How to add shadows to custom shader material?

I found this short tutorial that includes the relevant shader chunks to calculate shadows on a custom shader material. The post is just under a year old so I was wondering if there is a better way to enable shadows for your material in newer versions (R3F or three)?

Depending on your shader, if it’s just a minor change/addition you could use onBeforeCompile on a built-in material. I also made a plugin to make extending material more easy and clean, also to replicate code to the depth/distance material required for shadows when doing vertex transformations.

Specifically this line from the example

// testMaterial is your ShaderMaterial you extended from a built-in
testMaterial.customDepthMaterial = THREE.extendMaterial( THREE.MeshDepthMaterial, {

	template: testMaterial

} );

You could also extend a minimal built-in material that suits your usecase and just remove the includes you don’t need, for instance:

fragment: {

	'@#include <alphamap_pars_fragment>': '',
	'@#include <alphamap_fragment>': '',
	'@#include <clearcoat_normal_fragment_begin>': '',
	'@#include <clearcoat_normal_fragment_maps>': '',
	'@#include <clearcoat_normalmap_pars_fragment>': '',
	'@#include <clipping_planes_fragment>': '',
	'@#include <clipping_planes_pars_fragment>': ''
	// etc..
}

But if you don’t need any other built-in feature you should just use the custom shader code, the relevant inlcudes for shadows aren’t too many.

3 Likes

Thanks for the various solutions! I am mainly wanting to create my own materials from scratch to better understand some concepts, so I think building with the shaderchunks is the best way for now. I will keep the other methods in mind though :+1:

1 Like