Skip to main content

three_rs/objects/
sprite.rs

1//! Port of `three.js/src/objects/Sprite.js`.
2//!
3//! A sprite is a quad that always faces the camera. The facing is done in the
4//! vertex shader by [`SpriteNodeMaterial`](crate::materials::SpriteNodeMaterial)'s
5//! `setupPositionView()`; the object itself only carries the material, the
6//! `center` anchor, and a geometry every sprite shares.
7
8use std::rc::Rc;
9
10use crate::core::{BufferAttribute, BufferGeometry, Intersection, Object3D, ObjectRef, Raycaster};
11use crate::materials::{MeshBasicNodeMaterial, SpriteNodeMaterial};
12use crate::math::{Matrix4, Sphere, Triangle, Vector2, Vector3};
13use crate::objects::Payload;
14
15thread_local! {
16    /// `Sprite.js`' module-level `_geometry`, built by the first `new Sprite()`
17    /// and shared by every sprite after it. Thread-local because the scene is
18    /// single-threaded (`docs/api.md` §1) and `Rc` cannot be a `static`.
19    static GEOMETRY: Rc<BufferGeometry> = Rc::new(sprite_geometry());
20}
21
22/// The unit quad, `-0.5 … 0.5` in `x` and `y`, two triangles.
23///
24/// three.js packs `position` and `uv` into one `InterleavedBuffer` of stride
25/// 5; the port has no interleaved attributes on `BufferGeometry` yet (see
26/// `docs/webgpu_lines_fat-progress.md`), so they are two plain attributes. The
27/// WGSL is the same either way — the stride is vertex-buffer layout, not
28/// shader — and the values are three's, in three's order.
29fn sprite_geometry() -> BufferGeometry {
30    #[rustfmt::skip]
31    let interleaved: [f32; 20] = [
32        -0.5, -0.5, 0.0, 0.0, 0.0,
33         0.5, -0.5, 0.0, 1.0, 0.0,
34         0.5,  0.5, 0.0, 1.0, 1.0,
35        -0.5,  0.5, 0.0, 0.0, 1.0,
36    ];
37    let position: Vec<f32> = interleaved
38        .chunks(5)
39        .flat_map(|v| [v[0], v[1], v[2]])
40        .collect();
41    let uv: Vec<f32> = interleaved.chunks(5).flat_map(|v| [v[3], v[4]]).collect();
42
43    let mut geometry = BufferGeometry::new();
44    geometry.set_index(&[0, 1, 2, 0, 2, 3]);
45    geometry.set_attribute("position", BufferAttribute::new(position, 3));
46    geometry.set_attribute("uv", BufferAttribute::new(uv, 2));
47    geometry
48}
49
50/// The state `Sprite` adds to `Object3D`. It lives in a node's [`Payload`], as
51/// `Mesh`'s does — see `docs/scene-graph.md`.
52#[derive(Clone)]
53pub struct Sprite {
54    /// `Sprite.geometry` — the shared quad, the same `Rc` for every sprite.
55    pub geometry: Rc<BufferGeometry>,
56    /// `Sprite.material`.
57    pub material: SpriteNodeMaterial,
58    /// `Sprite.center` — the sprite's anchor point in its own quad, `( 0.5,
59    /// 0.5 )` being the middle and `( 0, 0 )` the bottom left. Read by the
60    /// vertex shader through a `reference( 'center', 'vec2', object )` uniform,
61    /// by `raycast()`, and by `Frustum.intersectsSprite()`.
62    pub center: Vector2,
63    /// `Sprite.count` — the number of instances drawn, `1` by default. A
64    /// larger count draws the one quad that many times, and the material
65    /// tells the instances apart with `instanceIndex` or an instanced
66    /// attribute (`webgpu_instance_sprites`).
67    pub count: usize,
68}
69
70impl Sprite {
71    /// `new Sprite( material )`, as a scene-graph [`ObjectRef`].
72    ///
73    /// `None` is three's default argument, `new SpriteMaterial()`, which under
74    /// `WebGPURenderer` is a `SpriteNodeMaterial`.
75    #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
76    pub fn new(material: impl Into<Option<SpriteNodeMaterial>>) -> ObjectRef {
77        let mut object = Object3D {
78            object_type: "Sprite",
79            ..Default::default()
80        };
81        object.payload = Payload::Sprite(Self::of(material.into()));
82        object.into_node()
83    }
84
85    /// The `Sprite` state alone, for a caller that already has the node.
86    pub fn of(material: Option<SpriteNodeMaterial>) -> Self {
87        Self {
88            geometry: GEOMETRY.with(Rc::clone),
89            material: material.unwrap_or_else(MeshBasicNodeMaterial::sprite),
90            center: Vector2::new(0.5, 0.5),
91            count: 1,
92        }
93    }
94
95    /// The sphere `Frustum.intersectsSprite( sprite )` tests: radius
96    /// `√½` — the quad's half diagonal — grown by how far `center` is from the
97    /// middle, at the object's origin, pushed through `matrixWorld`.
98    pub(crate) fn bounding_sphere_in(&self, matrix_world: &Matrix4) -> Sphere {
99        let default_center = Vector2::new(0.5, 0.5);
100        let offset = default_center.distance_to(&self.center);
101
102        let mut sphere = Sphere::new(
103            Vector3::new(0.0, 0.0, 0.0),
104            std::f64::consts::FRAC_1_SQRT_2 + offset,
105        );
106        sphere.apply_matrix4(matrix_world);
107        sphere
108    }
109
110    /// `Sprite.raycast( raycaster, intersects )` — the quad as the vertex
111    /// shader places it, facing `raycaster.camera`, tested as two triangles
112    /// with no backface culling.
113    ///
114    /// three.js logs an error when `raycaster.camera` is `null` and then
115    /// throws on reading it; the port logs the same message and hits nothing.
116    pub fn raycast(
117        &self,
118        matrix_world: &Matrix4,
119        object: &ObjectRef,
120        raycaster: &Raycaster,
121        intersects: &mut Vec<Intersection>,
122    ) {
123        let Some(camera) = &raycaster.camera else {
124            eprintln!(
125                "THREE.Sprite: \"Raycaster.camera\" needs to be set in order to raycast against sprites."
126            );
127            return;
128        };
129
130        let mut world_scale = Vector3::ZERO;
131        world_scale.set_from_matrix_scale(matrix_world);
132        let view_world_matrix = camera.matrix_world;
133        let mut model_view_matrix = Matrix4::identity();
134        model_view_matrix.multiply_matrices(&camera.matrix_world_inverse, matrix_world);
135        let mut mv_position = Vector3::ZERO;
136        mv_position.set_from_matrix_position(&model_view_matrix);
137
138        if camera.is_perspective_camera && !self.material.size_attenuation {
139            world_scale.multiply_scalar(-mv_position.z);
140        }
141
142        let rotation = self.material.rotation;
143        let sin_cos = (rotation != 0.0).then(|| (rotation.sin(), rotation.cos()));
144
145        let center = self.center;
146        let vertex = |x: f64, y: f64| {
147            transform_vertex(
148                Vector2::new(x, y),
149                &mv_position,
150                &center,
151                &world_scale,
152                sin_cos,
153                &view_world_matrix,
154            )
155        };
156        let v_a = vertex(-0.5, -0.5);
157        let mut v_b = vertex(0.5, -0.5);
158        let v_c = vertex(0.5, 0.5);
159        let uv_a = Vector3::new(0.0, 0.0, 0.0);
160        let mut uv_b = Vector3::new(1.0, 0.0, 0.0);
161        let uv_c = Vector3::new(1.0, 1.0, 0.0);
162
163        // Check the first triangle, then the second.
164        let intersect_point = match raycaster.ray.intersect_triangle(&v_a, &v_b, &v_c, false) {
165            Some(point) => point,
166            None => {
167                v_b = vertex(-0.5, 0.5);
168                uv_b = Vector3::new(0.0, 1.0, 0.0);
169                match raycaster.ray.intersect_triangle(&v_a, &v_c, &v_b, false) {
170                    Some(point) => point,
171                    None => return,
172                }
173            }
174        };
175
176        let distance = raycaster.ray.origin.distance_to(&intersect_point);
177        if distance < raycaster.near || distance > raycaster.far {
178            return;
179        }
180
181        let mut intersection = Intersection::new(distance, intersect_point, object.clone());
182        intersection.uv = Triangle::static_get_interpolation(
183            &intersect_point,
184            &v_a,
185            &v_b,
186            &v_c,
187            &uv_a,
188            &uv_b,
189            &uv_c,
190        )
191        .map(|uv| Vector2::new(uv.x, uv.y));
192        intersects.push(intersection);
193    }
194}
195
196/// `Sprite.js`' `transformVertex( vertexPosition, mvPosition, center, scale,
197/// sin, cos )`: a quad corner to world space, the way
198/// `SpriteNodeMaterial.setupPositionView()` places it in view space.
199fn transform_vertex(
200    vertex_position: Vector2,
201    mv_position: &Vector3,
202    center: &Vector2,
203    scale: &Vector3,
204    sin_cos: Option<(f64, f64)>,
205    view_world_matrix: &Matrix4,
206) -> Vector3 {
207    // Compute the position in camera space.
208    let aligned_x = (vertex_position.x - center.x + 0.5) * scale.x;
209    let aligned_y = (vertex_position.y - center.y + 0.5) * scale.y;
210
211    let (rotated_x, rotated_y) = match sin_cos {
212        Some((sin, cos)) => (
213            cos * aligned_x - sin * aligned_y,
214            sin * aligned_x + cos * aligned_y,
215        ),
216        None => (aligned_x, aligned_y),
217    };
218
219    let mut position = *mv_position;
220    position.x += rotated_x;
221    position.y += rotated_y;
222
223    // Transform to world space.
224    position.apply_matrix4(view_world_matrix);
225    position
226}