nadir/components.rs
1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The engine's components: where entities are, how they move, what they
16//! look like, what they collide with, and what they sound like (ADR-0014,
17//! ADR-0022).
18
19use nadir_assets::Handle;
20use nadir_audio::{Bus, Music, PlayParams, Sound};
21use nadir_collision::Shape;
22use nadir_core::{Color, Rect, Vec2};
23use nadir_ecs::{Component, Entity};
24use nadir_render::{AtlasSprite, Flip, SortMode, SpriteDraw, Texture};
25
26nadir_scene::reflect_struct! {
27 /// Where an entity is, in world pixels (+Y down), as the last tick left
28 /// it. For a sprite, it is where its pivot is: its feet.
29 #[derive(Clone, Copy, Debug, Default, PartialEq)]
30 pub struct Transform {
31 /// The entity's position.
32 pub position: Vec2,
33 }
34}
35
36impl Transform {
37 /// An entity at `position`.
38 pub const fn at(position: Vec2) -> Self {
39 Self { position }
40 }
41}
42
43/// Where an entity was at the start of the last tick: a frame between two
44/// ticks draws it part of the way from there to its [`Transform`], by the
45/// frame's `alpha`.
46///
47/// The engine keeps it. The system `nadir::snapshot` copies each
48/// `Transform` into it at the start of every tick. It also gives one to
49/// every entity with a [`Sprite`] that has none, and to the entity each
50/// drawn [`Parent`] chain ends at, so a game does not add it. To move an
51/// entity at once, with nothing drawn on the way (a teleport), write both
52/// its `Transform` and this, in a fixed system: a drawn entity has one
53/// from the start of its first tick.
54#[derive(Clone, Copy, Debug, PartialEq)]
55pub struct PrevTransform(pub Transform);
56
57nadir_scene::reflect_newtype! {
58 /// How fast an entity moves, in pixels a second. The system
59 /// `nadir::movement` moves it by `velocity × dt` each tick: with a
60 /// [`Collider`], it slides along what it meets.
61 #[derive(Clone, Copy, Debug, Default, PartialEq)]
62 pub struct Velocity(pub Vec2);
63}
64
65/// What an entity looks like: a sprite drawn at its [`Transform`], between
66/// ticks part of the way from its [`PrevTransform`].
67///
68/// It holds what [`SpriteDraw`] holds but the position. It is reflected by
69/// hand, its texture as its page's path, and prefabs may name a frame of a
70/// cooked atlas instead (`crate::reflected`, ADR-0038); a hash leaves out
71/// what `nadir::animate` writes, below.
72///
73/// On an entity with an [`Animator`](crate::Animator), the system
74/// `nadir::animate` writes its `texture` and `uv` each frame, and its `size`
75/// and `pivot` when the frame shown has a [`Placement`](crate::Placement), as
76/// a cooked atlas's clips' frames do; on one with a [`Facing`], its
77/// `flip.x`.
78#[derive(Clone, Copy, Debug, PartialEq)]
79pub struct Sprite {
80 /// The texture, usually an atlas page.
81 pub texture: Handle<Texture>,
82 /// The region of the texture, normalized: (0, 0) to (1, 1) is all of
83 /// it.
84 pub uv: Rect,
85 /// The size in world units.
86 pub size: Vec2,
87 /// The point of the sprite at the entity's position, normalized:
88 /// (0.5, 1) is the middle of its bottom edge, its feet.
89 pub pivot: Vec2,
90 /// Radians, clockwise on screen, about the pivot.
91 pub rotation: f32,
92 /// A tint, sRGB, multiplied with the texture in linear light.
93 pub color: Color,
94 /// Higher layers are drawn in front of lower ones.
95 pub layer: u8,
96 /// How it is ordered within its layer.
97 pub sort: SortMode,
98 /// Which way it is mirrored, about its pivot (render's
99 /// [`SpriteDraw::flip`]).
100 pub flip: Flip,
101}
102
103impl Sprite {
104 /// A sprite of all of `texture`, `size` large, with its feet at the
105 /// entity's position: untinted, unrotated, y-sorted in layer 0, as
106 /// [`SpriteDraw::new`] makes one.
107 pub fn new(texture: Handle<Texture>, size: Vec2) -> Self {
108 let draw = SpriteDraw::new(texture, Vec2::ZERO, size);
109 Self {
110 texture: draw.texture,
111 uv: draw.uv,
112 size: draw.size,
113 pivot: draw.pivot,
114 rotation: draw.rotation,
115 color: draw.color,
116 layer: draw.layer,
117 sort: draw.sort,
118 flip: draw.flip,
119 }
120 }
121
122 /// A sprite of frame `frame` of `sprite`, from a cooked
123 /// [`Atlas`](nadir_render::Atlas), in `texture`, which must be the
124 /// frame's page, with the sprite's pivot at the entity's position: the
125 /// frame's trimmed size, one world unit a pixel, placed so that its
126 /// pixels are where the untrimmed cell would have them, up to the
127 /// rounding of its normalized pivot; otherwise as [`Sprite::new`] makes
128 /// one. `None` if `sprite` has no such frame, or is a tile set.
129 ///
130 /// Flipped, it mirrors about its pivot, so the trimmed quad lands where
131 /// the mirrored cell's pixels would. Animated, by a clip of
132 /// [`Clips::add_atlas`](crate::Clips::add_atlas), each frame is placed
133 /// by its own trimmed size and pivot ([`ClipFrame::from_atlas`](crate::ClipFrame::from_atlas)).
134 pub fn from_atlas(
135 texture: Handle<Texture>,
136 sprite: &AtlasSprite,
137 frame: usize,
138 ) -> Option<Self> {
139 let pivot = sprite.pivot()?;
140 let frame = sprite.frame(frame)?;
141 let mut drawn = Self::new(texture, frame.size().as_vec2());
142 drawn.uv = frame.uv();
143 drawn.pivot = frame.pivot_in(pivot);
144 Some(drawn)
145 }
146
147 /// The sprite to draw with its pivot at `position`.
148 pub fn draw(&self, position: Vec2) -> SpriteDraw {
149 SpriteDraw {
150 texture: self.texture,
151 uv: self.uv,
152 position,
153 size: self.size,
154 pivot: self.pivot,
155 rotation: self.rotation,
156 color: self.color,
157 layer: self.layer,
158 sort: self.sort,
159 flip: self.flip,
160 }
161 }
162}
163
164/// What an entity collides with: a [`nadir_collision::Collider`], offset
165/// from its [`Transform`]. The engine builds the
166/// [`Collisions`](crate::Collisions) world from these each tick.
167///
168/// A child's solid collider ([`Parent`]) is in its own parent's way when
169/// the child's layer is in the parent's mask, as `Collider::solid` makes
170/// it: the parent moves while the child is still where the last tick left
171/// it, so a move toward the child stops at it, as at a wall. Give the child
172/// a layer outside its parent's mask, or make it a trigger, which stops
173/// nothing.
174///
175/// It is reflected by hand, its layers by the names
176/// [`App::collision_layers`](crate::App::collision_layers) gives them
177/// (`crate::reflected`, ADR-0038).
178#[derive(Clone, Copy, Debug, PartialEq)]
179pub struct Collider(pub nadir_collision::Collider);
180
181impl Collider {
182 /// A solid `shape`, on every layer, colliding with every layer.
183 pub fn solid(shape: Shape) -> Self {
184 Self(nadir_collision::Collider::solid(shape))
185 }
186
187 /// A trigger `shape`, on every layer, detecting every layer.
188 pub fn trigger(shape: Shape) -> Self {
189 Self(nadir_collision::Collider::trigger(shape))
190 }
191}
192
193impl From<nadir_collision::Collider> for Collider {
194 fn from(collider: nadir_collision::Collider) -> Self {
195 Self(collider)
196 }
197}
198
199nadir_scene::reflect_struct! {
200 /// The entity the player controls: a tag.
201 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
202 pub struct Player;
203}
204
205nadir_scene::reflect_enum! {
206 /// Which way an entity faces. Art is drawn facing right: the system
207 /// `nadir::animate` mirrors the [`Sprite`] of an entity that faces left
208 /// (`flip.x`), and unmirrors it whichever other way it faces. Only the
209 /// entity's own Sprite: a [`Parent`]'s children need their own.
210 ///
211 /// It is simulation state, reflected: set it in fixed systems. Set in a
212 /// frame system, it mirrors the Sprite from the next frame.
213 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
214 pub enum Facing {
215 /// Toward +Y, down the screen.
216 #[default]
217 Down,
218 /// Toward −Y, up the screen.
219 Up,
220 /// Toward −X: the Sprite is mirrored.
221 Left,
222 /// Toward +X, as the art is drawn.
223 Right,
224 }
225}
226
227/// Puts an entity at another's position plus `offset`: the system
228/// `nadir::parent_offsets` writes its [`Transform`] after each tick's
229/// movement, and frames draw it at its parent's drawn position plus the
230/// offset.
231///
232/// A parent may have a parent of its own: a child goes with the first
233/// entity up the chain that has none, its root, by the offsets along the
234/// way, up to 8 steps. Entities on the way need no `Transform`. A child
235/// whose chain is longer, or loops, or ends at an entity without a
236/// `Transform` (one that was despawned, say) is left where it is.
237///
238/// It is not reflected until saves bring the `Entity` encoding (roadmap
239/// M9.4, ADR-0020).
240#[derive(Clone, Copy, Debug, PartialEq)]
241pub struct Parent {
242 /// The entity it goes with.
243 pub entity: Entity,
244 /// Where it is from that entity, in pixels.
245 pub offset: Vec2,
246}
247
248nadir_scene::reflect_newtype! {
249 /// An entity's id in saves, which stays the same from one run to the
250 /// next, unlike its [`Entity`]. Saves (roadmap M9.4) store only
251 /// entities that have one.
252 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
253 pub struct SaveId(pub u64);
254}
255
256/// Where the game hears from: the first entity with one and a
257/// [`Transform`], where it is drawn, between ticks part of the way from its
258/// [`PrevTransform`]. With none, the camera's position
259/// ([`RenderFrame::camera`](nadir_render::RenderFrame::camera)) is.
260///
261/// It is not reflected: a game gives it in code, not in prefabs or levels.
262#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
263pub struct AudioListener;
264
265/// A sound that plays at its entity, and follows it as it moves: the system
266/// `nadir::sound` starts it once its sound has loaded, while the entity has
267/// a [`Transform`] and is within
268/// [`AudioConfig::max_dist`](nadir_audio::AudioConfig::max_dist) of the
269/// listener ([`AudioListener`]), 800 pixels, where it can be heard. It
270/// stops, fading out over 100 ms, when the entity is despawned or loses
271/// the emitter or its `Transform`, or is more than 64 pixels past that
272/// distance; back within it, it starts again. A sound that does not loop
273/// plays once each time it starts.
274///
275/// Changed, it follows: a new `sound`, `bus`, `looped`, `priority` or
276/// `max_instances` stops the voice and starts the new one, and a new
277/// `volume` or `pitch` reaches the voice as it plays. Its `pan` is not
278/// used: where it is pans it.
279///
280/// A voice taken for another when the voices run short stays silent until
281/// the emitter starts again. [`PlayParams::priority`] protects it only
282/// from plays of a lower priority: [`AudioEmitter::looped`]'s 192 from
283/// sounds played with the default, 128. A sound that failed to load, or
284/// that the asset server does not hold, is warned of once, with the entity
285/// and its path, and not tried again until the emitter changes.
286///
287/// It is not reflected: a game gives it in code, not in prefabs or levels.
288#[derive(Clone, Copy, Debug, PartialEq)]
289#[non_exhaustive]
290pub struct AudioEmitter {
291 /// The sound it plays.
292 pub sound: Handle<Sound>,
293 /// How it plays it.
294 pub params: PlayParams,
295}
296
297impl AudioEmitter {
298 /// An emitter of `sound`, played as `params` say.
299 pub const fn new(sound: Handle<Sound>, params: PlayParams) -> Self {
300 Self { sound, params }
301 }
302
303 /// An emitter of `sound` looped on [`Bus::Ambience`], for a sound of
304 /// the place, such as water or a fire: at priority 192, and with no
305 /// limit to the voices of the sound, so that the sound's limit does not
306 /// make its emitters take one another's voices; when all the mixer's
307 /// voices play, a play of the same priority or higher still takes the
308 /// oldest of them ([`Audio::play_sound`](nadir_audio::Audio::play_sound)).
309 /// Otherwise as [`PlayParams::default`] plays.
310 pub fn looped(sound: Handle<Sound>) -> Self {
311 Self::new(
312 sound,
313 PlayParams {
314 bus: Bus::Ambience,
315 looped: true,
316 priority: 192,
317 max_instances: u8::MAX,
318 ..PlayParams::default()
319 },
320 )
321 }
322}
323
324/// A box, its entity's position ± `half` in pixels, whose music plays
325/// while the listener ([`AudioListener`]) is in it: the system
326/// `nadir::sound` crossfades to `music` over `crossfade_ms` when the
327/// listener comes into it. Where areas overlap, the one playing stays
328/// while the listener is in it, and otherwise the first of them that holds
329/// it plays. Outside every area, the music plays on; coming back into the
330/// area of the track that plays, it goes on as it is (ADR-0046).
331///
332/// A track still loading plays once it has loaded. One that failed to
333/// load, or that the asset server does not hold, is warned of once, with
334/// the entity and its path, and not tried again until the area changes:
335/// the music plays on as it is.
336///
337/// It is not reflected: a game gives it in code, not in prefabs or levels.
338#[derive(Clone, Copy, Debug, PartialEq)]
339#[non_exhaustive]
340pub struct MusicArea {
341 /// The track it plays, looped, on [`Bus::Music`].
342 pub music: Handle<Music>,
343 /// Half its size, from its entity's position.
344 pub half: Vec2,
345 /// How long the crossfade to its track takes, in milliseconds.
346 pub crossfade_ms: u32,
347}
348
349impl MusicArea {
350 /// An area of `music`, its entity's position ± `half`, that crossfades
351 /// to it over 1,500 ms.
352 pub const fn new(music: Handle<Music>, half: Vec2) -> Self {
353 Self {
354 music,
355 half,
356 crossfade_ms: 1_500,
357 }
358 }
359}
360
361impl Component for Transform {}
362impl Component for PrevTransform {}
363impl Component for Velocity {}
364impl Component for Sprite {}
365impl Component for Collider {}
366impl Component for Player {}
367impl Component for Facing {}
368impl Component for Parent {}
369impl Component for SaveId {}
370impl Component for AudioListener {}
371impl Component for AudioEmitter {}
372impl Component for MusicArea {}
373
374#[cfg(test)]
375mod tests {
376 use nadir_assets::{Asset, DecodeCtx};
377 use nadir_codec::{Limits, json, kbj};
378 use nadir_render::Atlas;
379
380 use super::*;
381
382 #[test]
383 fn a_sprite_of_a_trimmed_frame_covers_the_pixels_of_its_cell() {
384 let text = r#"{ "version": 2,
385 "pages": [ { "path": "atlas/props_0.qoi", "w": 64, "h": 64 } ],
386 "sprites": [ { "name": "props/rock",
387 "frames": [ { "page": 0, "x": 3, "y": 5, "w": 14, "h": 10, "ox": 1, "oy": 2, "sw": 16, "sh": 12 } ],
388 "pivot": [8.0, 12.0] } ] }"#;
389 let value = json::parse(text, Limits::default()).expect("the test's JSON");
390 let bytes = kbj::encode(&value, Limits::default()).expect("encodable");
391 let atlas = Atlas::decode(
392 &bytes,
393 &DecodeCtx::new("atlas/props.kbj", Limits::default()),
394 )
395 .expect("an atlas");
396 let rock = atlas.sprite("props/rock").expect("the rock");
397 let texture = Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN));
398 assert!(Sprite::from_atlas(texture, rock, 1).is_none());
399 let sprite = Sprite::from_atlas(texture, rock, 0).expect("a frame");
400 assert_eq!(sprite.size, Vec2::new(14.0, 10.0));
401 assert_eq!(sprite.uv, rock.frames()[0].uv());
402 // At the rock's feet, the quad's corner is the cell's, moved by the
403 // trim.
404 let feet = Vec2::new(40.0, 30.0);
405 let draw = sprite.draw(feet);
406 let corner = draw.position - draw.pivot * draw.size;
407 assert_eq!(corner, feet - Vec2::new(8.0, 12.0) + Vec2::new(1.0, 2.0));
408 assert_eq!((sprite.layer, sprite.color), (0, Color::WHITE));
409 }
410
411 #[test]
412 fn a_looped_emitter_loops_on_the_ambience_bus_at_192_with_no_limit() {
413 let sound = Handle::new(nadir_core::GenIndex::new(0, std::num::NonZeroU32::MIN));
414 let params = PlayParams {
415 bus: Bus::Ambience,
416 looped: true,
417 priority: 192,
418 max_instances: u8::MAX,
419 ..PlayParams::default()
420 };
421 assert_eq!(
422 AudioEmitter::looped(sound),
423 AudioEmitter::new(sound, params)
424 );
425 }
426}