FarazzShaikh / THREE-CustomShaderMaterial

Extend Three.js standard materials with your own shaders!
Other
846 stars 54 forks source link

CustomShaderMaterial does not support clone() #19

Closed vincent-lecrubier-skydio closed 2 years ago

vincent-lecrubier-skydio commented 2 years ago

Problem

Trying to clone() CustomShaderMaterial does not work currently and gives this error:

TypeError: Cannot destructure property 'baseMaterial' of 'undefined' as it is undefined.

Cause

The reason is that the clone method is inherited from THREE.Material and looks like this

    clone() {
        return new this.constructor().copy( this );
    }

But the constructor looks like this (it destructures its first argument, which is not provided by clone).

  constructor({
    baseMaterial,
    fragmentShader,
    vertexShader,
    uniforms,
    patchMap,
    cacheKey,
    ...opts
  }) {
    ...
  }

Workaround

/**
 * This class is a workaround to make CustomShaderMaterial support clone.
 */
class CustomShaderMaterial2 extends CustomShaderMaterial {
  parameters: iCSMParams;
  constructor(parameters: iCSMParams) {
    super(parameters);
    this.parameters = parameters;
  }
  clone() {
    return new this.constructor(this.parameters).copy(this);
  }
}
FarazzShaikh commented 2 years ago

Thanks for the report, will fix!