Skip to content

Instantly share code, notes, and snippets.

@ShopifyEng
Last active December 4, 2020 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShopifyEng/5a0c15b0c83ed00b66267b93994714cf to your computer and use it in GitHub Desktop.
Save ShopifyEng/5a0c15b0c83ed00b66267b93994714cf to your computer and use it in GitHub Desktop.
A World Rendered Beautifully: The Making of the BFCM 3D Data Visualization - CustomMeshStandardMaterial.ts
import {
MeshStandardMaterial,
MeshStandardMaterialParameters,
Shader,
IUniform,
WebGLRenderer,
} from 'three';
interface CustomUniforms {
[uniform: string]: IUniform;
}
export interface CustomShader {
uniforms?: CustomUniforms;
vertexShader?: string;
fragmentShader?: string;
}
class CustomMeshStandardMaterial extends MeshStandardMaterial {
private customUniforms: CustomUniforms;
private customVertexShader: string;
private customFragmentShader: string;
constructor(
params: MeshStandardMaterialParameters,
customShader: CustomShader,
) {
super(params);
this.customVertexShader = customShader.vertexShader;
this.customFragmentShader = customShader.fragmentShader;
this.customUniforms = customShader.uniforms;
}
onBeforeCompile(shader: Shader, _renderer: WebGLRenderer): void {
for (const [key, value] of Object.entries(this.customUniforms)) {
shader.uniforms[key] = value;
}
shader.vertexShader = this.customVertexShader || shader.vertexShader;
shader.fragmentShader = this.customFragmentShader || shader.fragmentShader;
}
protected setCustomUniform(key: string, value: any) {
this.initializeCustomUniforms();
this.customUniforms[key].value = value;
}
protected getCustomUniform(key: string): any {
this.initializeCustomUniforms();
return this.customUniforms[key] && this.customUniforms[key].value;
}
protected initializeCustomUniforms() {
if (!this.customUniforms) {
this.customUniforms = {};
}
}
}
export {CustomMeshStandardMaterial};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment