Closed andretchen0 closed 8 months ago
Brilliant catch @andretchen0 thanks for the detailed reproduction!
Every new instance of TresCanvas could create a new nodeOps instance that contains a unique TresContext (i.e., with the appropriate Scene) within its scope.
This was the original purpose, but it seems we didn't implement it correctly, I think your idea about refactoring nodeOps
to a function will potentially solve this, but I will need to test it
The weirdest thing is that I managed to reproduce the behavior only in stackblitz, in the playground we have a demo for multiple canvases, and it is not happening @andretchen0.
I'm using a v-if
to show/hide the box, here is working as expected
https://github.com/Tresjs/tres/assets/4699008/8c9a313a-47a8-4d70-9a92-a4b1f10c478a
I spent more time reproducing it and the only reason why was working on the playground it was because it was wrapped with Suspense
wtf 😂
This was the original purpose, but it seems we didn't implement it correctly
No worries. Bugs happen.
In the hope that it's helpful to mention: looking at the code, I have a hunch that some of the Vue SFC model has rubbed off on the way some plain ES modules were written. (It happens to me, so I'm assuming others, too.) Like the code in src/core/renderer.ts:
import * as THREE from 'three'
import { createRenderer } from 'vue'
import { extend } from './catalogue'
import { nodeOps } from './nodeOps'
export const { render } = createRenderer(nodeOps)
If one has the Vue <script setup>
mental model, it might look like render
will be unique every time the script is imported. Because every time you create <MyVueComponent>
, its <script setup>
is run again.
But ES modules are something like singletons. They're only evaluated the first time they're imported. In this case, it means all render
are the same.
Mostly that wasn't a problem because mostly the Vue renderer (nodeOps) functions just work on the arguments passed to them ... just not in the case of let scene
. Lol.
Bug
NodeOps accidentally shares
scene
across multipleTresCanvas
s.See the StackBlitz reproduction for details.
Problem
NodeOps's
let scene
is set whenever a newScene
is added to anyTresCanvas
– i.e., the variable points to the lastScene
added to aTresCanvas
. If elements from anotherTresCanvas
readscene
in nodeOps, the code expects that they will find theirScene
, but they do not.Solution?
Solution A
We could refactor nodeOps as
(context: TresContext) => NodeOps
.Every new instance of
TresCanvas
could create a new nodeOps instance which contains a uniqueTresContext
(i.e., with the appropriateScene
) within its scope.Solution B
Otherwise, we could simply recurse up the parent chain until we reach a
Scene
or run out of parents.Reproduction
https://stackblitz.com/edit/tresjs-basic-e6uzmm?file=src%2FApp.vue
System Info
Used Package Manager
npm
Code of Conduct