Skip to main content

three_rs/core/
events.rs

1//! The scene graph's events and render callbacks: three.js'
2//! `EventDispatcher` as it is used on an `Object3D`, and the
3//! `onBeforeRender` / `onAfterRender` callbacks.
4//!
5//! three.js dispatches by string (`'added'`, `'childadded'`, ...) with an
6//! untyped event object. The port has a closed [`SceneEvent`] enum instead,
7//! because the four events an `Object3D` dispatches are the whole set and
8//! each carries known data; `docs/api.md` decision 12 says why there is no
9//! string-keyed dispatcher. The listener list lives on the [`Object3D`] and
10//! the methods that add, remove and dispatch are on [`ObjectRef`], next to the
11//! tree methods that dispatch.
12
13use std::cell::Cell;
14use std::fmt;
15use std::rc::Rc;
16
17use crate::cameras::RenderCamera;
18use crate::core::{Group, ObjectRef};
19use crate::objects::Scene;
20use crate::renderer::{RenderTarget, Renderer};
21
22#[cfg(doc)]
23use crate::core::Object3D;
24
25/// An event an `Object3D` dispatches to its listeners, the `event` argument
26/// of three.js' `dispatchEvent( event )`.
27///
28/// The set is closed: these are the four events three's `Object3D` dispatches
29/// from `add()`, `remove()` and `attach()`. three's `event.target` is the
30/// second argument every listener receives, not a field here.
31#[derive(Clone, Debug)]
32pub enum SceneEvent {
33    /// `{ type: 'added' }` — dispatched on an object once it has a new parent.
34    Added,
35    /// `{ type: 'removed' }` — dispatched on an object once it has lost its
36    /// parent.
37    Removed,
38    /// `{ type: 'childadded', child }` — dispatched on the parent after
39    /// [`Added`](Self::Added) has been dispatched on the child.
40    ChildAdded(ObjectRef),
41    /// `{ type: 'childremoved', child }` — dispatched on the old parent after
42    /// [`Removed`](Self::Removed) has been dispatched on the child.
43    ChildRemoved(ObjectRef),
44}
45
46/// The `type` string of a [`SceneEvent`], which is what a listener is
47/// registered for: three's `addEventListener( 'added', ... )` is
48/// `add_event_listener(SceneEventType::Added, ...)`.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
50pub enum SceneEventType {
51    /// `'added'`.
52    Added,
53    /// `'removed'`.
54    Removed,
55    /// `'childadded'`.
56    ChildAdded,
57    /// `'childremoved'`.
58    ChildRemoved,
59}
60
61impl SceneEvent {
62    /// `event.type`.
63    pub fn event_type(&self) -> SceneEventType {
64        match self {
65            Self::Added => SceneEventType::Added,
66            Self::Removed => SceneEventType::Removed,
67            Self::ChildAdded(_) => SceneEventType::ChildAdded,
68            Self::ChildRemoved(_) => SceneEventType::ChildRemoved,
69        }
70    }
71
72    /// `event.child` — the child of a [`ChildAdded`](Self::ChildAdded) or
73    /// [`ChildRemoved`](Self::ChildRemoved) event; `None` for the others.
74    pub fn child(&self) -> Option<&ObjectRef> {
75        match self {
76            Self::ChildAdded(child) | Self::ChildRemoved(child) => Some(child),
77            Self::Added | Self::Removed => None,
78        }
79    }
80}
81
82/// What [`ObjectRef::add_event_listener`] returns, and what
83/// [`ObjectRef::remove_event_listener`] and [`ObjectRef::has_event_listener`] take in
84/// place of three's listener function.
85///
86/// A JS function has an identity a Rust closure lacks, so the handle stands
87/// for it. Every handle is distinct, which is also why three's "can't add one
88/// listener twice" check has nothing to compare: a closure is moved into the
89/// list and cannot be added a second time. Opaque, per decision 11 of
90/// `docs/api.md`.
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
92pub struct ListenerHandle(u64);
93
94impl ListenerHandle {
95    fn next() -> Self {
96        thread_local! {
97            static NEXT: Cell<u64> = const { Cell::new(0) };
98        }
99        NEXT.with(|next| {
100            let value = next.get();
101            next.set(value + 1);
102            Self(value)
103        })
104    }
105}
106
107/// A listener: called with the event and three's `event.target`, the node the
108/// event was dispatched on.
109///
110/// `Fn` rather than `FnMut` because dispatch is re-entrant: a listener that
111/// adds a child dispatches again from inside its own call, which may reach
112/// the same listener. Keep mutable state in a `Cell` or `RefCell`. Getting the
113/// target as an argument, rather than capturing the node, is what keeps a
114/// listener from holding its own node alive.
115pub type SceneEventListener = Rc<dyn Fn(&SceneEvent, &ObjectRef)>;
116
117/// three's `object._listeners`: the listeners of one object, in the order
118/// they were added. Opaque — it is a public field of [`Object3D`] only so
119/// `Object3D { .., ..Default::default() }` keeps working outside the crate;
120/// the methods that use it are on [`ObjectRef`].
121#[derive(Clone, Default)]
122pub struct SceneEventListeners {
123    entries: Vec<(SceneEventType, ListenerHandle, SceneEventListener)>,
124}
125
126impl fmt::Debug for SceneEventListeners {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        f.debug_list()
129            .entries(self.entries.iter().map(|(ty, handle, _)| (ty, handle)))
130            .finish()
131    }
132}
133
134impl SceneEventListeners {
135    pub(crate) fn add(
136        &mut self,
137        ty: SceneEventType,
138        listener: SceneEventListener,
139    ) -> ListenerHandle {
140        let handle = ListenerHandle::next();
141        self.entries.push((ty, handle, listener));
142        handle
143    }
144
145    pub(crate) fn has(&self, ty: SceneEventType, handle: ListenerHandle) -> bool {
146        self.entries
147            .iter()
148            .any(|(t, h, _)| *t == ty && *h == handle)
149    }
150
151    pub(crate) fn remove(&mut self, ty: SceneEventType, handle: ListenerHandle) {
152        if let Some(index) = self
153            .entries
154            .iter()
155            .position(|(t, h, _)| *t == ty && *h == handle)
156        {
157            self.entries.remove(index);
158        }
159    }
160
161    /// `listenerArray.slice( 0 )`: the listeners of `ty`, copied out so the
162    /// caller can drop its borrow of the object before calling them.
163    pub(crate) fn snapshot(&self, ty: SceneEventType) -> Vec<SceneEventListener> {
164        self.entries
165            .iter()
166            .filter(|(t, _, _)| *t == ty)
167            .map(|(_, _, listener)| listener.clone())
168            .collect()
169    }
170
171    pub(crate) fn is_empty(&self) -> bool {
172        self.entries.is_empty()
173    }
174}
175
176/// `object.onBeforeRender` / `object.onAfterRender`, as a boxed closure in an
177/// `Option` field of [`Object3D`].
178///
179/// three passes `( renderer, scene, camera, geometry, material, group )` with
180/// the object as `this`. Here the first argument is the object's own [`ObjectRef`],
181/// not borrowed, so the hook can borrow it (or any other node) as it likes;
182/// the geometry and material are on its payload. The renderer is shared:
183/// the hook runs inside a render, and the port records every draw of a pass
184/// after all of its before-hooks have run, so a hook cannot draw. `group` is
185/// the `geometry.groups` entry the draw uses, `None` for a single-material
186/// object. See `docs/api.md` decision 12.
187///
188/// The renderer takes the hook out of the field for the call and puts it back
189/// afterwards unless the hook stored a new one there, so a hook can replace
190/// itself but not clear itself: clearing the field from inside the call is
191/// undone. Clear it outside a render instead.
192pub type ObjectRenderHook =
193    Box<dyn FnMut(&ObjectRef, &Renderer, &Scene, &dyn RenderCamera, Option<&Group>)>;
194
195/// `scene.onBeforeRender` / `scene.onAfterRender`, as a boxed closure in an
196/// `Option` field of [`Scene`].
197///
198/// three passes `( renderer, scene, camera, renderTarget )`, where
199/// `renderTarget` is the target the scene is drawn into: the internal
200/// framebuffer target when one is used, else the renderer's render target, so
201/// `None` means the canvas. `Fn`, because the renderer reaches the scene
202/// shared — a pass or a reflector renders it again from inside its own render
203/// — so keep mutable state in a `Cell` or `RefCell`.
204pub type SceneRenderHook = Box<dyn Fn(&Renderer, &Scene, &dyn RenderCamera, Option<&RenderTarget>)>;