Could Someone help me out with implementing custom shaders?

Hello there,

I am currently working on a project where I need to implement some custom shaders, but I am having trouble getting started. I am fairly new to shaders and could use some guidance on how to integrate them into my Three.js project.

Specifically, I want to achieve a certain effect using shaders, but I am not sure how to write the shader code or how to integrate it into my existing Three.js scene.

Also, I have gone through this post: which definitely helped me out a lot.

If anyone could provide some resources, tutorials, or even just some general advice on how to get started with custom shaders in Three.js, I would greatly appreciate it.

Thanks in advance for your help and assistance.

Best introduction I’ve seen is this one (incomplete guide only covering the basics)

Next you need to understand three.js shader chunk system
long story short:

  • native materials are fragmented into chunks (small pieces of GLSL code)
  • each chunk is dedicated to a feature, you can combine them to tweak existing/new shaders.
  • this system is part of the core and can be called anytime as long three main module is imported.

to visualize this, look at the native shader’s code here:

as you can see, they barely contain any code. It’s all chunks added using #include
the whole library containing the actual code of each chunks is here:

Finally check this very basic example here:
it take the most basic shader, inject additional code with .onBeforeCompile to apply vertex fragment distortion. The nice part is you don’t need to rewrite the whole shader, you only inject cool stuff at the specific chunk, and you done.

Disclaimer: This system is probably fated to be replaced by node materials in the future. It just doesn’t scale very well with all the evolutions three went trough


What about:

Creating a custom shader in Three.js - DEV Community

You can assign a ShaderMaterial to a Mesh.

It must have a vertex shader and fragment shader, eg the ones defining MeshBasicMaterial here:

three.js/src/renderers/shaders/ShaderLib/meshbasic.glsl.js at 232b4eac8cfd002fbd4dbb665bd9e77372e13ffc · mrdoob/three.js · GitHub

You can comment out lines from the above shaders and see what happens. You can understand the #include’s by looking in their respective files (in same directory).

1 Like