Python3.11 で 簿記3級 の勉強

今回はPython3.11.5を使った。

https://www.python.org/downloads/windows/

python-3.11.5-amd64.exe

まあまあ時間かかる。。。。

システム環境変数追加なんで再起動して下さい。

F:\Python311に入れた

C:\Users\furcr>F:

F:>cd F:\Python311

F:\Python311>pip

動いたら

pip install pandas

動いたら

https://qiita.com/et47/items/ec05beb03c09d79a9f09

をやっていく

とりま


#仕訳をPandasのDataFrame形式で、仕訳帳 df_siwake に入力します。
#Siwakeクラスの関数 entry を呼び出すことで、df_siwakeに仕訳データの行を追加し、更新します。
#仕訳ルール①:借方(左側)、貸方(右側)に勘定科目と金額を記載する
#に従い、仕訳を入力するための空のDataFrameとして仕訳帳 df_siwake を作成します。


import pandas as pd
df_siwake = pd.DataFrame(index=[],columns=['仕訳番号', '日付', '借方科目', '借方金額', '貸方科目', '貸方金額'])
print("df_siwake= "+str(df_siwake))



#仕訳入力時に必ず貸借が一致していることにより、後ほど残高試算表を作るときにも、
#貸借金額が一致することが保証されます。

#そこで仕訳入力用のクラス Siwake を定義し、まずは①複合仕訳の入力に対応する形で
#関数 entry を定義します。

#※最終的には Siwake 内に②データ型チェック、③貸借一致チェックの関数を実装しますが、
#コードが長くなるため、末尾に補足として追記します。

class Siwake:
    def __init__(self):
        self.siwake_no = 0
        print("self.siwake_no= "+str(self.siwake_no))

    def entry(self, df, date, kari, kashi): 
        self.siwake_no += 1 # ...仕訳番号を更新
        print("self.siwake_no= "+str(self.siwake_no))

        for i in range(len(kari)): # ...複合仕訳に対応するため[借方科目、借方金額]の数だけループを回す                    
            kari_entry = pd.Series([self.siwake_no] + [date] + kari[i] + ["", 0], index=df.columns)          
            print("kari_entry= "+str(kari_entry))
            df = df._append(kari_entry, ignore_index=True)

        for i in range(len(kashi)): # ...複合仕訳に対応するため[貸方科目、貸方金額]の数だけループを回す                    
            kashi_entry = pd.Series([self.siwake_no] + [date] + ["", 0] + kashi[i], index=df.columns)
            print("kashi_entry= "+str(kashi_entry))
            df = df._append(kashi_entry, ignore_index=True)

        return df
        
siwake = Siwake()


#仕訳①:会社を設立
#現金1000を元手に会社を設立しました。
#この元手のことを資本金と呼び、仕訳は以下の通りです。
print(u"------------会社を設立-----------")
df_siwake = siwake.entry(df_siwake, 20200401,[['現金', 1000]],[['資本金', 1000]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

#仕訳②:商品の仕入
#商品500を外部業者より仕入れました。
#仕訳は以下の通りです。
print(u"------------商品の仕入-----------")
df_siwake = siwake.entry(df_siwake, 20200402,[['商品', 500]],[['買掛金', 500]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

#仕訳③:商品を売上
#仕入れた商品のうち200について、価格300で販売しました。
#売上についての仕訳は以下の通りです。
print(u"------------商品を売上-----------")
df_siwake = siwake.entry(df_siwake, 20200403,[['売掛金', 300]],[['売上', 300]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

#仕訳④:仕入代金を支払
#仕入代金500のうち300について、外部業者に支払いました。
#(残りの200は翌月支払の契約と仮定します)
#仕訳は以下の通りです。
print(u"------------仕入代金を支払-----------")
df_siwake = siwake.entry(df_siwake, 20200420,[['買掛金', 300]],[['現金', 300]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

#仕訳⑤:販売代金を回収
#販売代金200について、販売先から現金で回収しました。
#(残りの100は翌月回収の契約と仮定します)
#仕訳は以下の通りです。
print(u"------------販売代金を回収-----------")
df_siwake = siwake.entry(df_siwake, 20200430,[['現金', 200]],[['売掛金', 200]])
df_siwake[df_siwake['仕訳番号']==siwake.siwake_no]

参考URL

https://www.sejuku.net/blog/64370

UE4 きれいなグラデーションの虹色のレインボーのマテリアルが作りたい

正解はtexCoordの応用だった。

texCoordを縦のグラデーションと横グラデーションに分け

値をLerpのAlphaにつないでお好きな色をA,Bにつなぐ。

2つ作ってMultplyして縦横グラデーションになるようにMIXした。

さらに回転させたい

下の部分が見切れていたので追加しました。

参考

UE4]UMGで使えるでシンプルなグラデーションを作 …historia.co.jp

https://wgld.org/d/glsl/g008.html

https://wgld.org/d/glsl/g010.html

[UE5.1]Customノードが安定してきたので色々試した。

いろんな意味で成功はしなかったが、かなり成長した。

まず、こちらのサイトで

ここのサイトが唯一.ushファイルのincludeをうまくやっている。
// Copyright Epic Games, Inc. All Rights Reserved.

#include "KA_MatCustomNode.h"
#include "Modules/ModuleManager.h"

IMPLEMENT_PRIMARY_GAME_MODULE(FKA_MatCustomNode, KA_MatCustomNode, "KA_MatCustomNode" );

void FKA_MatCustomNode::StartupModule()
{
    FString ShaderDirectory = FPaths::Combine(FPaths::ProjectDir(), TEXT("Shader"));
    if (!AllShaderSourceDirectoryMappings().Contains("/Project"))
    {
        AddShaderSourceDirectoryMapping("/Project", ShaderDirectory);
    }
    FString EngineDirectory = FPaths::Combine(FPaths::EngineDir(), TEXT("Engine"));
    if (!AllShaderSourceDirectoryMappings().Contains("/Engine"))
    {
        AddShaderSourceDirectoryMapping("/Engine", EngineDirectory);
    }
}

void FKA_MatCustomNode::ShutdownModule()
{
}

/Project/ というパスを入力することでプロジェクトフォルダの/Shader/へのパスからインクルードできるようにしていたので

よくあるインクルードコードで

/Engine/というパスを入力する事で/Engine/のShaderをインクルードできるようにしてみた。↑のソースコード

ただ.ushからのインクルードは機能しないっぽい

別の話だが

https://zhuanlan.zhihu.com/p/100834351

で紹介されているコードは実際には動かなかったが動くようにした。

#pragma once
#include "CoreMinimal.h"
#include "HAL/IConsoleManager.h"
#include "RHI.h"
#include "ShaderParameters.h"
#include "Shader.h"
#include "HitProxies.h"
#include "RHIStaticStates.h"
#include "SceneManagement.h"
#include "Materials/Material.h"
#include "PostProcess/SceneRenderTargets.h"
#include "DBufferTextures.h"
#include "LightMapRendering.h"
#include "VelocityRendering.h"
#include "MeshMaterialShaderType.h"
#include "MeshMaterialShader.h"
#include "ShaderBaseClasses.h"
#include "FogRendering.h"
#include "TranslucentLighting.h"
#include "PlanarReflectionRendering.h"
#include "UnrealEngine.h"
#include "ReflectionEnvironment.h"
#include "Strata/Strata.h"
#include "OIT/OITParameters.h"
#include "VirtualShadowMaps/VirtualShadowMapArray.h"
#include "VolumetricCloudRendering.h"
#include "Nanite/NaniteMaterials.h"

/**
 * Scene renderer that implements a deferred shading pipeline and associated features.
 */
class FDeferredShadingSceneRenderer : public FSceneRenderer
{
public:

	void RenderMyMeshPass(FRHICommandListImmediate& RHICmdList, const TArrayView<const FViewInfo*> PassViews);
	EDepthDrawingMode EarlyZPassMode;

}

#include "RHICommandList.h"
#include "Shader.h"
#include "RHIStaticStates.h"


#include "MyGS.h"
//My VertexShader
class FMyGS_VS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FMyGS_VS, Global);

public:

	FMyGS_VS() {}
	FMyGS_VS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
		: FGlobalShader(Initializer)
	{

	}

	static void ModifyCompilationEnvironment(const FGlobalShaderPermutationParameters& Parameters, FShaderCompilerEnvironment& OutEnvironment)
	{

	}

	static bool ShouldCompilePermutation(const FGlobalShaderPermutationParameters& Parameters)
	{
		return IsFeatureLevelSupported(Parameters.Platform, ERHIFeatureLevel::SM5);
	}

	static bool ShouldCache(EShaderPlatform Platform)
	{
		return true;
	}

	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		//Ar << ;
		return bShaderHasOutdatedParameters;
	}
	void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View)
	{
		FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, GetVertexShader(), View.ViewUniformBuffer);
	}
};

IMPLEMENT_SHADER_TYPE(, FMyGS_VS, TEXT("/Engine/Private/MyGS/MyGS.usf"), TEXT("MainVS"), SF_Vertex);


//My PixleShader
class FMyGS_PS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FMyGS_PS, Global);

public:

	FMyGS_PS() {}
	FMyGS_PS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
		: FGlobalShader(Initializer)
	{

	}

	static void ModifyCompilationEnvironment(const FGlobalShaderPermutationParameters& Parameters, FShaderCompilerEnvironment& OutEnvironment)
	{

	}

	static bool ShouldCompilePermutation(const FGlobalShaderPermutationParameters& Parameters)
	{
		return IsFeatureLevelSupported(Parameters.Platform, ERHIFeatureLevel::SM5);
	}

	static bool ShouldCache(EShaderPlatform Platform)
	{
		return true;
	}

	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		//Ar << ;
		return bShaderHasOutdatedParameters;
	}
	void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View)
	{
		FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, GetVertexShader(), View.ViewUniformBuffer);
	}
};

IMPLEMENT_SHADER_TYPE(, FMyGS_PS, TEXT("/Engine/Private/MyGS/MyGS.usf"), TEXT("MainPS"), SF_Pixel);

//My Geomertry shader
class FMyGS_GS : public FGlobalShader
{
	DECLARE_SHADER_TYPE(FMyGS_GS, Global);

public:

	FMyGS_GS() {}
	FMyGS_GS(const ShaderMetaType::CompiledShaderInitializerType& Initializer)
		: FGlobalShader(Initializer)
	{

	}

	static void ModifyCompilationEnvironment(const FGlobalShaderPermutationParameters& Parameters, FShaderCompilerEnvironment& OutEnvironment)
	{

	}

	static bool ShouldCompilePermutation(const FGlobalShaderPermutationParameters& Parameters)
	{
		return IsFeatureLevelSupported(Parameters.Platform, ERHIFeatureLevel::SM5);
	}

	static bool ShouldCache(EShaderPlatform Platform)
	{
		return true;
	}

	virtual bool Serialize(FArchive& Ar) override
	{
		bool bShaderHasOutdatedParameters = FGlobalShader::Serialize(Ar);
		//Ar << ;
		return bShaderHasOutdatedParameters;
	}

	void SetParameters(FRHICommandList& RHICmdList, const FViewInfo& View)
	{
		FGlobalShader::SetParameters<FViewUniformShaderParameters>(RHICmdList, GetGeometryShader(), View.ViewUniformBuffer);
	}
};

IMPLEMENT_SHADER_TYPE(, FMyGS_GS, TEXT("/Engine/Private/MyGS/MyGS.usf"), TEXT("MainGS"), SF_Geometry);



class FDebugPane
{
public:

	FDebugPane();
	~FDebugPane();
	void FillRawData();
	void EmptyRawData();
	void Init();

	TArray<FVector> VerBuffer;
	TArray<uint16> InBuffer;

	uint32 Stride;

	bool Initialized;

	uint32 VertexCount;
	uint32 PrimitiveCount;

	FVertexBufferRHIRef VertexBufferRHI;
	FIndexBufferRHIRef IndexBufferRHI;

};
FDebugPane DebugMesh;

void FDeferredShadingSceneRenderer::RenderMyMeshPass(FRHICommandListImmediate& RHICmdList, const TArrayView<const FViewInfo*> PassViews)
{
	check(RHICmdList.IsOutsideRenderPass());

	TShaderMap<FGlobalShaderType>* ShaderMap = GetGlobalShaderMap(FeatureLevel);

	FSceneRenderTargets& SceneContext = FSceneRenderTargets::Get(RHICmdList);
	SceneContext.BeginRenderingSceneColor(RHICmdList, ESimpleRenderTargetMode::EExistingColorAndDepth, FExclusiveDepthStencil::DepthRead_StencilWrite, true);

	FGraphicsPipelineStateInitializer PSOInit;
	RHICmdList.ApplyCachedRenderTargets(PSOInit);

	PSOInit.RasterizerState = TStaticRasterizerState<FM_Wireframe, CM_None, false, false>::GetRHI();
	PSOInit.BlendState = TStaticBlendState<>::GetRHI();
	PSOInit.DepthStencilState = TStaticDepthStencilState<false, CF_GreaterEqual>::GetRHI();
	PSOInit.PrimitiveType = EPrimitiveType::PT_TriangleList;
	PSOInit.BoundShaderState.VertexDeclarationRHI = GetVertexDeclarationFVector3();

	TShaderMapRef<FMyGS_VS> Vs(ShaderMap);
	TShaderMapRef<FMyGS_PS> Ps(ShaderMap);
	TShaderMapRef<FMyGS_GS> Gs(ShaderMap);
	PSOInit.BoundShaderState.VertexShaderRHI = GETSAFERHISHADER_VERTEX(*Vs);
	PSOInit.BoundShaderState.PixelShaderRHI = GETSAFERHISHADER_PIXEL(*Ps);
	PSOInit.BoundShaderState.GeometryShaderRHI = GETSAFERHISHADER_GEOMETRY(*Gs);

	SetGraphicsPipelineState(RHICmdList, PSOInit);

	for (int i = 0; i < PassViews.Num(); ++i)
	{
		const FViewInfo* View = PassViews[i];

		if (DebugMesh.Initialized == false)
		{
			DebugMesh.Init();
		}
		RHICmdList.SetViewport(View->ViewRect.Min.X, View->ViewRect.Min.Y, 0.0f, View->ViewRect.Max.X, View->ViewRect.Max.Y, 1.0f);
		Gs->SetParameters(RHICmdList, *View);
		//Vs->SetParameters(RHICmdList, *View);

		RHICmdList.SetStreamSource(0, DebugMesh.VertexBufferRHI, 0);
		RHICmdList.DrawIndexedPrimitive(DebugMesh.IndexBufferRHI, PT_TriangleList, 0, DebugMesh.VertexCount, 0, DebugMesh.PrimitiveCount, 1);
	}
	SceneContext.FinishRenderingSceneColor(RHICmdList);
}

void FDebugPane::FillRawData()
{
	VerBuffer = {
		FVector(0.0f, 0.0f, 0.0f),
		FVector(100.0f, 0.0f, 0.0f),
		FVector(100.0f, 100.0f, 0.0f),
		FVector(0.0f, 100.0f, 0.0f)
	};

	InBuffer = {
		0, 1, 2,
		0, 2, 3
	};
}

FDebugPane::FDebugPane()
{
	Initialized = false;
}

FDebugPane::~FDebugPane()
{
	VertexBufferRHI.SafeRelease();
	IndexBufferRHI.SafeRelease();
}

void FDebugPane::EmptyRawData()
{
	VerBuffer.Empty();
	InBuffer.Empty();
}

void FDebugPane::Init()
{
	FillRawData();

	VertexCount = static_cast<uint32>(VerBuffer.Num());
	PrimitiveCount = static_cast<uint32>(InBuffer.Num() / 3);

	//GPU Vertex Buffer
	{
		TStaticMeshVertexData<FVector> VertexData(false);
		Stride = VertexData.GetStride();

		VertexData.ResizeBuffer(VerBuffer.Num());

		uint8* Data = VertexData.GetDataPointer();
		const uint8* InData = (const uint8*)&(VerBuffer[0]);
		FMemory::Memcpy(Data, InData, Stride * VerBuffer.Num());

		FResourceArrayInterface* ResourceArray = VertexData.GetResourceArray();
		FRHIResourceCreateInfo CreateInfo(ResourceArray);
		VertexBufferRHI = RHICreateVertexBuffer(ResourceArray->GetResourceDataSize(), BUF_Static, CreateInfo);
	}

	{
		TResourceArray<uint16, INDEXBUFFER_ALIGNMENT> IndexBuffer;
		IndexBuffer.AddUninitialized(InBuffer.Num());
		FMemory::Memcpy(IndexBuffer.GetData(), (void*)(&(InBuffer[0])), InBuffer.Num() * sizeof(uint16));

		// Create index buffer. Fill buffer with initial data upon creation
		FRHIResourceCreateInfo CreateInfo(&IndexBuffer);
		IndexBufferRHI = RHICreateIndexBuffer(sizeof(uint16), IndexBuffer.GetResourceDataSize(), BUF_Static, CreateInfo);
	}

	EmptyRawData();

	Initialized = true;
}

これでコンパイルは通る

また、別の話だが

これを移植しようとして

https://www.shadertoy.com/view/XsfGWN

コンパイルは通せた。

ちゃんと動かない。

const static float4 MyFloat = float4(1.0,0.0,0.0,1.0);

//const float uvScale = 1.0;
const float uvScale = 1.0;
//const float colorUvScale = 0.1;
const float colorUvScale = 1.0;
const float furDepth = 0.2;
const int furLayers = 64;
const float rayStep = 0.00625;
const float furThreshold = 0.4;
const float shininess = 50.0;
float iTime;

Texture2D<float4> Tex0;
Texture2D<float4> Tex1;
sampler Tex0Sampler;
sampler Tex1Sampler;

float2 UV;

//float3 blur = Texture2DSample(Tex0, Tex0Sampler, UV).rgb;

//bool intersectSphere(float3 ro, float3 rd, float r, out float t)
bool intersectSphere(float3 ro, float3 rd, float r,float t)
{
    //float t;
    float b = dot(-ro, rd);
	float det = b*b - dot(ro, ro) + r*r;
	if (det < 0.0) return false;
	det = sqrt(det);
	t = b - det;
	return t > 0.0;
}

float3 rotateX(float3 p, float a)
{
    float sa = sin(a);
    float ca = cos(a);
    return float3(p.x, ca*p.y - sa*p.z, sa*p.y + ca*p.z);
}
float3 rotateY(float3 p, float a)
{
    float sa = sin(a);
    float ca = cos(a);
    return float3(ca*p.x + sa*p.z, p.y, -sa*p.x + ca*p.z);
}

float2 cartesianToSpherical(float3 p)
{		
	float r = length(p);

	float t = (r - (1.0 - furDepth)) / furDepth;	
	p = rotateX(p.zyx, -cos(iTime*1.5)*t*t*0.4).zyx;	// curl

	p /= r;	
	float2 uv = float2(atan2(p.y, p.x), acos(p.z));

	//uv.x += cos(iTime*1.5)*t*t*0.4;	// curl
	//uv.y += sin(iTime*1.7)*t*t*0.2;
	uv.y -= t*t*0.1;	// curl down
	return uv;
}


//float furDensity(float3 pos, out float2 uv,Texture2D<float4> Tex0A,sampler Tex0ASampler)
float furDensity(float3 pos,float2 uv,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
{
	uv = cartesianToSpherical(pos.xzy);	
	//float3 tex = Texture2DSample(Tex0,Tex0Sampler,uv*uvScale);
	float3 tex = Texture2DSample(Tex0A,Tex0ASampler,uv*uvScale);

	// thin out hair
	float density = smoothstep(furThreshold, 1.0, tex.x);
	
	float r = length(pos);
	float t = (r - (1.0 - furDepth)) / furDepth;
	
	// fade out along length
	float len = tex.y;
	density *= smoothstep(len, len-0.2, t);

	return density;	
}


// calculate normal from density
float3 furNormal(float3 pos, float density,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
{
    float eps = 0.01;
    float3 n;
	float2 uv;
    n.x = furDensity( float3(pos.x+eps, pos.y, pos.z), uv ,Tex0A,Tex0ASampler,UV0) - density;
    n.y = furDensity( float3(pos.x, pos.y+eps, pos.z), uv ,Tex0A,Tex0ASampler,UV0) - density;
    n.z = furDensity( float3(pos.x, pos.y, pos.z+eps), uv ,Tex0A,Tex0ASampler,UV0) - density;
    return normalize(n);
}


//float3 furShade(Texture2D<float4> Tex1A,sampler Tex1ASampler,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
float3 furShade(float3 pos, float2 uv, float3 ro, float density,Texture2D<float4> Tex1A,sampler Tex1ASampler,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
{
    /*
    float2 iResolution = float2(2048,2048);
    float2 fragCoord = float2(640,360);
    
    float2 uv = fragCoord.xy / iResolution.xy;
	uv = uv*2.0-1.0;
	uv.x *= iResolution.x / iResolution.y;
    //uv =UV;
    
    float3 ro = float3(0.0, 0.0, 2.5);
	float3 rd = normalize(float3(uv, -2.0));
    float t2=1.0;
    float3 pos = ro + rd*t2;
    float density = furDensity(pos, uv,Tex0A,Tex0ASampler,UV0);
    */
    //----------------------------------------------------
	// lighting
	const float3 L = float3(0, 1, 0);
	float3 V = normalize(ro - pos);
	float3 H = normalize(V + L);

	float3 N = -furNormal(pos, density,Tex0A,Tex0ASampler,UV0);
	//float diff = max(0.0, dot(N, L));
	float diff = max(0.0, dot(N, L)*0.5+0.5);
	float spec = pow(max(0.0, dot(N, H)), shininess);
	
	// base color
	//float3 color = Texture2DSample(Tex1,Tex1Sampler, uv*colorUvScale).xyz;
	//float3 color = Texture2DSample(Tex1A,Tex1ASampler, UV0*colorUvScale).xyz;
	float3 color = Texture2DSample(Tex1A,Tex1ASampler, UV0*1.5).xyz;
    
	// darken with depth
	float r = length(pos);
	float t = (r - (1.0 - furDepth)) / furDepth;
	t = clamp(t, 0.0, 1.0);
	float i = t*0.5+0.5;
		
	//return color*diff*i + float3(spec*i,spec*i,spec*i);
    return color;
}	

float GetRandomNumber(float2 texCoord, int Seed)
{
    return frac(sin(dot(texCoord.xy, float2(12.9898, 78.233)) + Seed) * 43758.5453);
}

//float4 scene(float3 ro,float3 rd)
float4 scene(Texture2D<float4> Tex1A,sampler Tex1ASampler,Texture2D<float4> Tex0A,sampler Tex0ASampler,float2 UV0)
{
    float2 iResolution = float2(2048,2048);
    float2 fragCoord = float2(640,360);
    
    float2 uv = fragCoord.xy / iResolution.xy;
	uv = uv*2.0-1.0;
	uv.x *= iResolution.x / iResolution.y;
    uv=UV;
    float3 ro = float3(0.0, 0.0, 2.5);
	float3 rd = normalize(float3(uv, -2.0));
    
	//-------------------------------------------
	float3 p = float3(0.0,0.0,0.0);
	//const float r = 1.0;
	const float r = 1.1;
	float t=1.0;				  
	bool hit = intersectSphere(ro - p, rd, r, t);
	
	float4 c = float4(0.0,0.0,0.0,0.0);
    float4 sampleCol= float4(0.0,0.0,0.0,0.0);
    
    float rayStepA = furDepth*2.0 / float(furLayers);
    //float2 uv;
    float density;
    //float2 uv =float2(0.5,0.5);
	if (hit) {
		float3 pos = ro + rd*t;

		// ray-march into volume
		//for(int i=0; i<furLayers; i++) {
        for(int i=0; i<91; i++) {

			sampleCol.a = furDensity(pos, uv,Tex0A,Tex0ASampler,UV0)+0.5;
			//sampleCol.a = furDensity(pos, UV,Tex0A,Tex0ASampler,UV0)+0.5;
			//sampleCol.a = GetRandomNumber(UV,  5);
			//sampleCol.a = Texture2DSample(Tex0A,Tex0ASampler,UV*uvScale).y;
            
			//sampleCol.a = 1.0;
            density = sampleCol.a;
			if (sampleCol.a > 0.0) {
                sampleCol.rgb = furShade( pos,  uv,  ro, density, Tex1A, Tex1ASampler, Tex0A, Tex0ASampler, UV0);
                //sampleCol.rgb = furShade( pos,  UV,  ro, density, Tex1A, Tex1ASampler, Tex0A, Tex0ASampler, UV0);

				// pre-multiply alpha
				sampleCol.rgb *= sampleCol.a;
				c = c + sampleCol*(1.0 - c.a);
				if (c.a > 0.95) break;
			}
			
			pos += rd*rayStepA;
		}

	}
	
	return c;
	//return sampleCol;
}

/*
//float4 mainImage( out float4 fragColor, in float2 fragCoord )
//float4 mainImage(float2 fragCoord )
float4 mainImage( )
{
    //-----------------------------------------
    float2 iResolution = float2(256,256);
    float2 fragCoord = float2(256,256);
    float3 iMouse = float3(128,128,128);

	float2 uv = fragCoord.xy / iResolution.xy;
	uv = uv*2.0-1.0;
	uv.x *= iResolution.x / iResolution.y;
	
	float3 ro = float3(0.0, 0.0, 2.5);
	float3 rd = normalize(float3(uv, -2.0));
	
	float2 mouse = iMouse.xy / iResolution.xy;
	float roty = 0.0;
	float rotx = 0.0;
	if (iMouse.z > 0.0) {
		rotx = (mouse.y-0.5)*3.0;
		roty = -(mouse.x-0.5)*6.0;
	} else {
		roty = sin(iTime*1.5);
	}
	
    ro = rotateX(ro, rotx);	
    ro = rotateY(ro, roty);	
    rd = rotateX(rd, rotx);
    rd = rotateY(rd, roty);
	//--------------------------------------------------
    
    float2 iResolution = float2(256,256);
    float2 fragCoord = float2(256,256);
    
    float2 uv = fragCoord.xy / iResolution.xy;
	uv = uv*2.0-1.0;
	uv.x *= iResolution.x / iResolution.y;
    
    float3 ro = float3(0.0, 0.0, 2.5);
	float3 rd = normalize(float3(uv, -2.0));
    
	//fragColor = scene(ro, rd);
    //return fragColor;
    return scene(ro, rd);
}
*/

//float4 MyFunction(float2 UV,float iTime,Texture2D<float4> Tex0,Texture2D<float4> Tex1,sampler Tex0Sampler,sampler Tex1Sampler)
float4 MyFunction()

{
	return float4(0.0,1.0,0.0,1.0);
}

プロジェクトのダウンロード

https://drive.google.com/file/d/1RZ5TCEDluJOAzsGnDZp6nwCpN8u2we2U/view?usp=sharing

[UE5] SubSystemの種類

https://docs.unrealengine.com/4.26/ja/ProgrammingAndScripting/Subsystems/

このページにもあるがUE5には多くのサブシステムがあるみたい。
もうちょっと前からあったみたいスクショは4.25.4。

全部BluePrintからアクセスできる。

・ただでさえ入り組んだクラスにさらに API を追加しなくてすむ。

とあるように、中にはすごいAPIがたくさん詰まってる。

できないと思ってたことができることもある。

ここにあるだけで

EngineSubsystem 

EditorSubsystem 

GameInstanceSubsystem 

LocalPlayerSubsystem 

AssetEditorSubsystem

で肝心のAPIが

BrushEditingSubsystem

EditorUtilitySubsystem

で肝心のAPIが

ImportSubsystem

LayersSubsystem

MoviepipelineQueueSubsystem

PanelExtentionSubsystem

AssetTagsSubsystem

AutoDestroySubsystem

LandscapeSubsystem

ObjectTraceWorldSubsystem

参考URL

https://www.docswell.com/s/EpicGamesJapan/KY18EZ-UE4_AllStudy04_Subsystem#p1

アンリアルクエスト5で勉強したProcedural Meshでオブジェクトを切るについて

プロジェクトのサンプルはアンリアルクエスト5のプロジェクトを使いました。

https://historia.co.jp/unrealquest05 のDiscordから #プロジェクトデータ配布のチャンネルからDLできます。Discordサーバーが消えた場合はあとで考えます。

使用バージョンは
UE5.2.0

切られるオブジェクトを用意する

ブループリントクラス>Actorで作成します。

名前はBP_ProceduralMesh_Actor としました。

作成したブループリントを開き

DefaultSceneRootの下に

ProceduralMeshとCubeまたはキューブを追加します。

Cubeコンポーネントの設定

M_Procedralというマテリアルを作って

/Game/UnrealQuest5/Props/LevelPrototyping/Meshes/SM_Cubeをコピーしてきて
CubeコンポーネントのスタティックメッシュをSM_Cubeに変更

コピーしてきたSM_Cubeの設定を行います。

AllowCPUAccess にチェックを入れてCPUからでもメッシュ情報にアクセスできるようにします。

Procedural Meshコンポーネントの設定
Procedural Meshコンポーネントの Use Complex as Simple Collisionのチェックを外します。

コンストラクタのノードを設定する
ProceduralMeshに対してCube情報をコピーしてCubeコンポーネントを削除します。

コピーしてきたレベルに作成したBPをおいてみました。

BP_UQ5_Playerを開いて

BladeMeshのOnConponentBeginOverlapをクリックしてノードを作ります。

これ動くのSet Simulate Physics だけだったので、結局

ファーストパーソン を追加

/Game/FirstPerson/Blueprints/BP_FirstPersonProjectile をコピーして

BP_ProceduralBulletとする

On Component Hit をこのように改造する

BP_UQ5_PlayerにBullet_Spawnのカスタムイベントを追加

通常攻撃をコンボにカスタムしてあるけど、こんな感じでSequenceでBullet_Spawnを呼ぶ

BP_ProceduralBulletの当たり判定がデカくなるようにスケールをデカくした

できたのがこちら

アンリアルクエスト5のDiscordでこのページを見た兎月さんがもっとすごい実装方法をしていたので許可を頂いたので、こちらに張らせていただきます
https://uq5.netlify.app/UE5-1-1_Cut_with_a_blade.png

兎月さんに感謝!できたのがこれ。

きもちいですねカットした法線どおりに切れると!

参考サイト

SkeltalMeshをカット?
https://www.unrealengine.com/marketplace/en-US/product/slice-skeletal-mesh-vr?sessionInvalidated=true

[UE4/UE5]MasterPoseComponentの説明

ぷちコンでも乱用した

MasterPoseComponentの説明です。

これがあればぶっちゃけリターゲットとか必要なくない?

みたいなお話です。

大きいEnableMasterPose図はこれです。

アップのEnableMasterPoseはこれです。

UE5.1ではこうしないと

ブループリントランタイム エラー:”プロパティ SkeletalMeshComponent の読み取りを試行するためのアクセスはありません”。 ノード: ブランチ グラフ: EnableMasterPose 関数: Enable Master Pose ブループリント: BP_ThirdMetaHuman

のエラー出た から 最初からSkeletel Mesh Component をIsVaildしたら治った。

添わせたいスケルタルメッシュを以下のように設定するだけで

あたまがこれです。

そうびがこれです。

グレイマンはトランスペアレントなマテリアルで見せてません。

グレイマンはVisibleはTrueにしておかないと壊れます。

こうしているせいで全モーションはグレイマンに追加するだけででOKです。
どんどんグレーマンが鬼カスタムモーション化していくだけなので他のプロジェクトを作る際も鬼グレイマンさえ移行すればいいから簡単です。

以上でした。

5.1のバージョンはこんな感じでした。

Meshの下に入れ子にするのがポイント

参考

https://forums.unrealengine.com/t/topic/402278

ikソルバーとは?

ikつまり逆運動学の問題を解く計算方法のこと
たとえば

つま先から各関節の位置を決める計算方法のことで

ikハンドル(エンドエフェクタ)の位置や姿勢が与えられたときに、その位置や姿勢を達成するために必要な各関節の角度を求めます。

ソルバー計算で、この逆運動学問題を解くことで、3Dキャラクターやロボットアームなどの動きを制御することができます。

IKソルバー計算には、様々な種類があります。代表的なものには、運動学的制約を用いる数値的解法や、数学的最適化問題を解く方法などがあります。

IKソルバーは、3Dキャラクターやロボットアームなどの動きを制御するためのアルゴリズムのことです。
例えば、ロボットアームが目標の位置に移動するために、各関節の角度を計算して制御する際に使用されます。これにより、子供たちも楽しめるロボットの動きが実現されます。

MayaにChatGPT(openai)を追加インストールしてみる

Mayaのpip書き換えちゃうので自己責任でというかMayaの再インスト―ルもする余裕があるときにやること

とりあえずpipでインストールする前にpipのバージョンがふるいのでUpgradeしてる。

cd "C:\Program Files\Autodesk\Maya2023\bin\"
mayapy.exe -m pip install --upgrade pip

mayapy -m pip install openai
cmd /k

入った。

てかこの2フォルダをsitepackageにいれとくだけでも動くには動くはず
https://drive.google.com/file/d/12KGnpQAnkWn3wifXPsMehqZ5YFfeFhWe/view?usp=share_link

メインのPython

import os
import openai


print(os.getcwd())
#print(__file__)
MELpath=os.getcwd()
pythonPath= os.path.abspath(MELpath+"/../python/open_ai/")
pythonPath= pythonPath.replace('\\', '/')
print("pythonPath= "+pythonPath)

f = open(pythonPath+'/open_ai_api_key.txt', 'r', encoding='UTF-8')
open_ai_api_key = f.read()
f.close()

#openai.api_key = os.getenv("OPENAI_API_KEY")
openai.api_key = open_ai_api_key

# APIコールを行う関数
def completion(new_message_text:str, settings_text:str = '', past_messages:list = []):
    if len(past_messages) == 0 and len(settings_text) != 0:
        system = {"role": "system", "content": settings_text}
        past_messages.append(system)

    new_message = {"role": "user", "content": new_message_text}
    past_messages.append(new_message)

    result = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=past_messages
    )
    message_text = result.choices[0].message.content
    response_message = {"role": "assistant", "content": message_text}
    past_messages.append(response_message)
    
    return message_text, past_messages
    
    
    
import re
# 返答をPythonコードとその他の部分に分解
# reモジュールを使って```python~```で囲まれた部分とそれ以外の部分を切り出します。
def decompose_response(txt):
    pattern = r"```python([\s\S]*?)```"
    
    code_list = re.findall(pattern, txt)
    for i in range(int(len(code_list))):
        code_list[i] = re.sub('\A[\r?\n]', '', code_list[i])
        code_list[i] = re.sub('[\r?\n]\Z', '', code_list[i])
    
    comment = re.sub(pattern, '', txt)
    comment = re.sub('[\r?\n]+', '\n', comment)
    comment = re.sub('[\r?\n]\Z', '', comment)
    
    return comment, code_list
    
    
    


from maya import cmds

class ChatGPT_Maya(object):

    def __init__(self):
        self.system_settings = "質問に対して、MayaのPythonスクリプトを書いてください。スクリプト以外の文章は短めにまとめてください。"
        self.message_log = []
        self.at_first = True
        self.create_window()

    def reset_session(self, *args):
        self.message_log = []
        self.at_first = True
        cmds.scrollField(self.input_field, e=True, tx='')
        cmds.scrollField(self.ai_comment, e=True, tx='')
        cmds.cmdScrollFieldExecuter(self.script_field, e=True, t='')

    def call(self, *args):
        user_input = cmds.scrollField(self.input_field, q=True, tx=True)
        
        # APIコール
        if self.at_first:
            message_text, self.message_log = completion(user_input, self.system_settings, [])
            self.at_first = False
        else:
            message_text, self.message_log = completion(user_input, '', self.message_log)
            
        # 返答を分解
        comment, code_list = decompose_response(message_text)
        
        # Pythonコード以外の部分をai_commentに表示
        cmds.scrollField(self.ai_comment, e=True, tx=comment)

        # Pythonコードの1つ目をscript_fieldに表示。2つ目以降は無視(汗
        if code_list:
            cmds.cmdScrollFieldExecuter(self.script_field, e=True, t=code_list[0])
            # 実行
            if cmds.checkBox(self.script_exec, q=True, v=True):
                cmds.cmdScrollFieldExecuter(self.script_field, e=True, executeAll=True)
        else:
            cmds.cmdScrollFieldExecuter(self.script_field, e=True, t='')
    
    # UI作成
    def create_window(self, *args):
        cmds.window(title=u'ChatGPTがPythonスクリプトを書くよ!', width=600, sizeable=True)
        
        cmds.columnLayout(adj=True, cat=['both',5], rs=5)
        self.reset_button = cmds.button(label='Reset', c=self.reset_session) #セッションのリセット
        self.input_field = cmds.scrollField(h=50, ed=True, ww=True, tx='', ec=self.call) #テンキーのEnterで送信
        self.script_exec = cmds.checkBox(label=u'実行もする', align='left', v=True) #Checkが入っていたら返答と同時にスクリプトを実行
        cmds.separator(h=10, st='in')
        self.ai_comment = cmds.scrollField(h=100, ed=False, ww=True, tx='') #コードブロック以外の部分を表示する場所
        cmds.text(l='Script:', align='left')
        self.script_field = cmds.cmdScrollFieldExecuter(st='python', h=200) #Pythonコードを表示・実行する場所
        cmds.setParent('..')

        cmds.showWindow()
        
        
        
        
ChatGPT_Maya_ins=ChatGPT_Maya()

エラーが返ってくる

openai : error_code=None error_message=’You exceeded your current quota, please check your plan and billing details.’ error_param=None error_type=insufficient_quota message=’OpenAI API error received’ stream_error=False

エラー: RateLimitError: file C:\Program Files\Autodesk\Maya2023\Python\lib\site-packages\openai\api_requestor.py line 679: You exceeded your current quota, please check your plan and billing details.

このエラーは

https://platform.openai.com/account/billing/overview

で Payment methods と Billing preferencesPrimary business addressを設定したら動くようになった。

お世話になった記事

https://qiita.com/akasaki1211/items/34d0f89e0ae2c6efaf48

https://okumuralab.org/~okumura/python/openai_api.html

https://knowledge.autodesk.com/ja/support/maya/learn-explore/caas/CloudHelp/cloudhelp/2023/JPN/Maya-Scripting/files/GUID-72A245EC-CDB4-46AB-BEE0-4BBBF9791627-htm.html

https://qiita.com/sakasegawa/items/db2cff79bd14faf2c8e0

https://tomo-web.jp/chat-gpt-you-exceeded-your-current-quota/#index_id0