npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

three-extended-material

v0.3.0

Published

Easily extend native three.js materials with modular and composable shader units and effects, available as a vanilla or React component.

Downloads

748

Readme

three-extended-material

Easily extend native three.js materials with modular and composable shader units and effects, available as a vanilla or React component.

image

Usage

npm install three-extended-material

Then, create your extended material:

import { ExtendedMaterial } from "three-extended-material"

const material = new ExtendedMaterial(

    superMaterial,  // the threejs material class to extend

    extensions,     // the extension (or an array of extensions) 
                    // object to extend the material with

    parameters,     // the properties to pass the material 
                    // (can be either properties from the original material, 
                    // or uniforms from the extensions)

    options         // additional options (explained later)
)

An extension is a simple object with the following signature:

const extension = {

  name: "",         // string defining the name of the extension
                    // used to generate a unique shader program code

  uniforms: {},     // uniforms to pass to the materials, in a { uniform: value } format.
                    // note that uniforms are not automatically prepended to the shader code.
                    // be careful about not repeating uniform names when chaining extensions

  defines: {},      // defines to pass to the materials, in a { define: 1 or 0 } format.

  vertexShader: (shader, type) => shader,    // a function which takes the original vertex
                                            // shader code, and returns the modified cone

  fragmentShader: (shader, type) => shader,   // a function which takes the original fragment
                                              // shader code, and returns the modified cone
};

The name of each extension is hashed alongside the name of the original material in order to generate a unique shader program cache key for that combination.

The ExtendedMaterial will provide property accessors to all uniforms, so you can use extension.myUniform to set or get the value. This means that when using multiple extension, each uniform name should be unique.

The vertexShader and fragmentShader functions provide you with the original material shaders code, and should return the modified shader code to replace the original shaders code with. A common pattern is to prepend the uniforms definition to the code, and then run a string replace function to add extra shader code in specific places. The second argument type will be the type of the shader, and can be useful to support multiple SuperMaterials at once, by monkey-patch specific bits of thhe shader if the type is of MeshBasicMaterial, some other for MeshPhysicalMaterial, and so on.

Note that when chaining multiple extensions, the shader code is modified for each extension, and passed to the next one - so be careful about not removing pieces of shader which might be queried by later extensions.

You can also pass an options object with any of the following parameters to the ExtendedMaterial constructor as the last argument:

{
  debug: false,           // if true, prints the material's shader code after being patched
  programCacheKey: null   // if not null, sets the customProgramCacheKey 
                          // for the material to this value instead of hashing it.
}

three.js materials' shaders are pretty opinionated - a good starting point would be to use the debug option to print the original shader code, then exploring the ShaderChunks definitions on GitHub to figure out a good injection point for your logic.

Example

Here's a basic setup where we extend the MeshStandardMaterial with an extension which overlays a screen-space checkerboard:

const checkerBoardExtension = {
  name: "checkerboard",
  uniforms: {
    checkersSize: 5.0,
  },
  // no defines or vertex shader modifications needed
  // in this extension, so we can leave them out
  fragmentShader: (shader, type) => {
    shader = `
      uniform float checkersSize;
      ${shader.replace(
        "#include <opaque_fragment>",
        // here we inject the checkerboard logic right before the <opaque_fragment>,
        // where gl_FragColor is set according to the lighting calculation
        // https://github.com/mrdoob/three.js/blob/master/src/renderers/shaders/ShaderChunk/output_fragment.glsl.js
        `
        vec2 pos = floor(gl_FragCoord.xy / checkersSize);
        float pattern = mod(pos.x + mod(pos.y, 2.0), 2.0);
  
        outgoingLight = outgoingLight * pattern;
        #include <opaque_fragment>
        `
      )}
    `;
    return shader;
  },
};

const material = new ExtendedMaterial(MeshStandardMaterial, [checkerBoardExtension], {
  color: 0x00aaff,
  checkersSize: 8.0, // we can pass different values than the default one...
});

const box = new Mesh(new BoxGeometry(), material);
box.material.checkersSize: 10.0; //... or use the property accessor to set / get its value

React

ExtendedMaterial is also exported as a react-three-fiber-friendly component to be used in React projects:

import { ExtendedMaterial } from "three-extended-material/react"
import { MeshStandardMaterial } from 'three';

function Box() {
  return (
    <mesh
      <boxGeometry args={[1, 1, 1]} />
      <ExtendedMaterial 
        superMaterial={MeshStandardMaterial} 
        extensions={[checkerBoardExtension]} 
        color={0x00aaff}
        checkersSize={8.0}
      /> 
    </mesh>
  )
}

In this case, just pass the ExtendedMaterial's parameters to as props to the component, in the classic react declarative style. Its properties will be updated reactively, and the Material will be re-created only if the superMaterial or its extensions changes.

Demos

Support Buy me a coffee

If this tool has proven useful to you, consider buying me a coffee to support development of this and many other projects.