-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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