How to create custom shader chunks

I’m interested in creating my own shader chunks to benefit from using custom #include statements in my glsl code, but I haven’t found a way to make it work. I’ve seen a few references to this, like in this Github issue: Custom Shader Chunk includes broken since THREEjs v. 138 · Issue #23580 · mrdoob/three.js · GitHub, but I’m struggling to find much other information on how to properly set this up.

I’ve tried importing ShaderChunk and adding a new string similar to the code snippit in the Github issue:

`import noise3D from ‘./noise.glsl’;
import { ShaderChunk } from ‘three/src/renderers/shaders/ShaderChunk.js’

ShaderChunk[‘noise3D’] = noise3D;`

I continue to get an error: “Can not resolve #include ” when adding the #include to my shader code.

If anyone knows the proper workflow to make this work, or a different way to use custom #include statements, I would be grateful if you would point me in the right direction.

Why not onBeforeCompile + .replace :thinking: ? (example, line 57) Seems like a safer, more flexible (ex. you can expand other includes before using replace, to access their variables), and simpler solution.

1 Like

I’m familiar with that workflow, but honestly it seems a bit messy compared to just using #include inside a shader. Also, my goal with this isn’t necessarily modifying built in shaders, but more adding my own shader chunks to custom shader materials

Why not use your own method to parse the includes?

If you look at this code youll find about 3 lines with a regular expression that goes through this string and replaces #include <whatever>.

You don’t havde to look up ShaderChunks you can look up any object you desire, like SponeBobSquarePants[ 'my_shader_chunk' ].

What you are asking is an excellent idea, it was proposed many years ago, but decided not to be implemented.

(one of many issues filed)

It is not allowed to pass your own Record<string,string> , you can only use the one that three.js designated, namely THREE.ShaderChunks . I never understood why, i think this is a valid approach.

This used to work:

Appreciate your answer. That definitely clears things up. Seems like it would be a great feature. That repo no longer works with current versions of Three.js?

Yeah probably not :frowning: but the idea that you can take care of all the shader chunks before three has had a chance to us still valid.