[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