How to add shadows in case of ShaderMaterial usage

Hi!
I’m new in Three.js. I’m applying texture on a small area with a mouse click like this:

	function createShaderMaterial(textures, maskTexture) {
		const uniforms = { maskTex: { value: maskTexture } };
		const textureUniformNames = [];

		textures.forEach((tex, i) => {
			const name = `texture${i}`;
			tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
			tex.repeat.set(10, 10);
			uniforms[name] = { value: tex };
			textureUniformNames.push(name);
		});

		const fragmentShader = `
			varying vec2 vUv;
			uniform sampler2D maskTex;
			${textureUniformNames.map(name => `uniform sampler2D ${name};`).join('\n')}
			void main() {
				vec4 mask = texture2D(maskTex, vUv);
				int idx = int(mask.r * 255.0 + 0.5);
				vec4 color = vec4(0.0);
				${textureUniformNames.map((name, i) => `
					if (idx == ${i}) color = texture2D(${name}, vUv * 10.0);
				`).join('')}
				gl_FragColor = color;
			}
		`;

		const vertexShader = `
			varying vec2 vUv;
			void main() {
				vUv = uv;
				gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
			}
		`;

		const material = new THREE.ShaderMaterial({
			uniforms,
			vertexShader,
			fragmentShader
		});
        
		return { material, uniforms };
	}

but ShaderMaterial does not work with shadows by default.
How I can add shadows support here (will be good if you can provide code with explanations)?
Thanks.

1 Like

This site helps explore the shaderlib shaders:

three-shaderlib-skim

As for basic shadows, you could create a grayscale texture made with radial fills, and multiply it against your other textures.

2 Likes

Can you show me how I can import this plugin to the project?

Are you using react three fiber?

I use it to directly edit shaders with hot reloading.