Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Side effects in constructor cause problems when used as a custom React Three Fiber component #27

Open
itsdouges opened this issue Nov 16, 2022 · 0 comments

Comments

@itsdouges
Copy link
Contributor

itsdouges commented Nov 16, 2022

Heya! I've been setting up three-csm to work as a r3f component and I've mostly got it working but unfortunately there is one friction point - the side effects during class construction. This has been a friction point in other three classes, for example OrbitControls (see: mrdoob/three.js#20575 if you're interested).

The solution would be to separate out the side effects from the constructor, adding them into a new function called attach or something similar. If the side effects are desirable for vanilla threejs scenes or ergonomics we could also keep the current behaviour and add the new behaviour under a constructor arg.

mrdoob looks to be keen on separating out side effects from constructors mrdoob/three.js#20575 (comment)

Happy to contribute, let me know what you think.


Edit: I have been able to work around this for now by creating a proxy class:

class CSMProxy {
  instance: CSM | undefined;
  args: Params;

  constructor(args: Params) {
    this.args = args;
  }

  set fade(fade: boolean) {
    if (this.instance) {
      this.instance.fade = fade;
    }
  }

  set camera(camera: Camera) {
    if (this.instance) {
      this.instance.camera = camera;
    }
  }

  set lightDirection(vector: Vector3 | Vector3Tuple) {
    if (this.instance) {
      this.instance.lightDirection = Array.isArray(vector)
        ? new Vector3().fromArray(vector).normalize()
        : vector;
    }
  }

  attach() {
    this.instance = new CSM(this.args);
  }

  dispose() {
    if (this.instance) {
      this.instance.dispose();
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant