Skip to content

Commit

Permalink
Add SceneObserver
Browse files Browse the repository at this point in the history
  • Loading branch information
gkjohnson authored Jan 30, 2025
1 parent ec84e00 commit 7321aa7
Showing 1 changed file with 98 additions and 0 deletions.
98 changes: 98 additions & 0 deletions src/r3f/utilities/SceneObserver.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { EventDispatcher } from 'three';

function traverse( root, callback ) {

if ( callback( root ) ) {

return;

}

root.children.forEach( c => {

traverse( c, callback );

} );

}
class SceneWatcher extends EventDispatcher {

Check failure on line 18 in src/r3f/utilities/SceneObserver.js

View workflow job for this annotation

GitHub Actions / build (18.x)

'SceneWatcher' is defined but never used

Check failure on line 18 in src/r3f/utilities/SceneObserver.js

View workflow job for this annotation

GitHub Actions / build (20.x)

'SceneWatcher' is defined but never used

constructor() {

super();

this.objects = new Set();
this.observed = new Set();
this._addedCallback = ( { child } ) => {

traverse( child, c => {

if ( this.observed.has( c ) ) {

return true;

} else {

this.objects.add( c );
c.addEventListener( 'childadded', this._addedCallback );
c.addEventListener( 'childremoved', this._removedCallback );
this.dispatchEvent( { type: 'childadded', child } );
return false;

}

} );

};

this._removedCallback = ( { child } ) => {

traverse( child, c => {

if ( this.observed.has( c ) ) {

return true;

} else {

this.objects.delete( c );
c.removeEventListener( 'childadded', this._addedCallback );
c.removeEventListener( 'childremoved', this._removedCallback );
this.dispatchEvent( { type: 'childremoved', child } );
return false;

}

} );

};

}

observe( root ) {

const { observed } = this;
this._addedCallback( { child: root } );
observed.add( root );

}

unobserve( root ) {

const { observed } = this;
observed.delete( root );
this._removedCallback( { child: root } );

}

dispose() {

this.observed.forEach( root => {

this.unobserve( root );

} );

}

}

0 comments on commit 7321aa7

Please sign in to comment.