ShaderMaterial constructor type safety

The ShaderMaterial constructor accepts “any” as the shaderPath Babylon.js/packages/dev/core/src/Materials/shaderMaterial.ts at 8e84566967e845745462e6029a1ff8e6f6ef5372 · BabylonJS/Babylon.js · GitHub

Would it be possible to change that to use a type like

/**
 * Defines the route to the shader code.
 *  * object: `{ vertexSource: "vertex shader code string", fragmentSource: "fragment shader code string" }` for directly passing the shader code
 *  * object: `{ vertex: "custom", fragment: "custom" }`, used with `Effect.ShadersStore["customVertexShader"]` and `Effect.ShadersStore["customFragmentShader"]`
 *  * object: `{ vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }`, used with shader code in script tags
 *  * string: `"./COMMON_NAME"`, used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
 */
type IShaderPath =
  | {
      /**
       * Directly pass the shader code
       */
      vertexSource: string;
      /**
       * Directly pass the shader code
       */
      fragmentSource: string;
    }
  | {
      /**
       * Used with Effect.ShadersStore. If the `vertex` is set to `"custom`, then
       * Babylon.js will read from Effect.ShadersStore["customVertexShader"]
       */
      vertex: string;
      /**
       * Used with Effect.ShadersStore. If the `fragment` is set to `"custom`, then
       * Babylon.js will read from Effect.ShadersStore["customFragmentShader"]
       */
      fragment: string;
    }
  | {
      /**
       * Used with shader code in script tags
       */
      vertexElement: string;
      /**
       * Used with shader code in script tags
       */
      fragmentElement: string;
    }
  | string;

(I liberally copy-pasted from the existing documentation to write that type. Thus, do feel free to simply copy this code if that’s useful.)

2 Likes

Good idea!

Do you want to create a PR for it?

2 Likes

Agreed this is great!

Here we go Add type to shader material constructor by stefnotch · Pull Request #14908 · BabylonJS/Babylon.js · GitHub

There’s one failure, and I’m not sure what the correct fix is.