1use crate::activity::{Activity, Catalog, builtin_catalog};
8use crate::glyphs::{self, EMPTY};
9use crate::graph::{Cell, Glow, Lighting, SceneGraph, grid_for};
10use crate::hash::hash_label;
11use crate::math::pm;
12use crate::palette::{self, PaletteFamily, Theme};
13use crate::particles::{
14 CALM_PACE, Emitter, EmitterKind, LOOP_MS, WeatherKind, ember_set, hero_time, weather_set,
15};
16use crate::recipe::{GENERATOR_VERSION, OLDEST_GENERATOR_VERSION, SceneRecipe, TimeOfDay};
17use crate::rng::Rng;
18use crate::{focal, terrain};
19use std::fmt;
20
21pub const MIN_WIDTH: u32 = 160;
23pub const MIN_HEIGHT: u32 = 90;
24
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub struct BuildOptions {
28 pub width: u32,
29 pub height: u32,
30 pub theme: Theme,
31 pub buddy: bool,
33}
34
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub enum BuildError {
37 UnsupportedVersion(u32),
38 UnknownArchetype(String),
39 UnknownActivity(String),
40 UnknownPalette(String),
41 ThemeLocked(Theme),
43 TooSmall {
44 width: u32,
45 height: u32,
46 },
47}
48
49impl fmt::Display for BuildError {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 match self {
52 BuildError::UnsupportedVersion(v) => write!(
53 f,
54 "recipe generator_version {v} is not supported (this build is version {GENERATOR_VERSION})"
55 ),
56 BuildError::UnknownArchetype(a) => write!(f, "unknown archetype `{a}`"),
57 BuildError::UnknownActivity(a) => write!(f, "unknown activity `{a}`"),
58 BuildError::UnknownPalette(p) => write!(f, "unknown palette family `{p}`"),
59 BuildError::ThemeLocked(t) => {
60 write!(f, "this scene has no {} variant (theme-locked)", t.as_str())
61 }
62 BuildError::TooSmall { width, height } => write!(
63 f,
64 "{width}x{height} is too small; the minimum is {MIN_WIDTH}x{MIN_HEIGHT}"
65 ),
66 }
67 }
68}
69
70impl std::error::Error for BuildError {}
71
72pub fn build(recipe: &SceneRecipe, opts: &BuildOptions) -> Result<SceneGraph, BuildError> {
74 build_with(builtin_catalog(), recipe, opts)
75}
76
77pub fn build_with(
80 catalog: &Catalog,
81 recipe: &SceneRecipe,
82 opts: &BuildOptions,
83) -> Result<SceneGraph, BuildError> {
84 if !(OLDEST_GENERATOR_VERSION..=GENERATOR_VERSION).contains(&recipe.generator_version) {
85 return Err(BuildError::UnsupportedVersion(recipe.generator_version));
86 }
87 if opts.width < MIN_WIDTH || opts.height < MIN_HEIGHT {
88 return Err(BuildError::TooSmall {
89 width: opts.width,
90 height: opts.height,
91 });
92 }
93 let tod = recipe
94 .tod_for(opts.theme)
95 .ok_or(BuildError::ThemeLocked(opts.theme))?;
96 let family_id = match opts.theme {
97 Theme::Light => &recipe.palette.light,
98 Theme::Dark => &recipe.palette.dark,
99 };
100 let family =
101 *palette::family(family_id).ok_or_else(|| BuildError::UnknownPalette(family_id.clone()))?;
102 let activity = match &recipe.activity {
103 Some(id) => Some(
104 catalog
105 .get(id)
106 .ok_or_else(|| BuildError::UnknownActivity(id.clone()))?,
107 ),
108 None => None,
109 };
110 if !terrain::PAINTED.contains(&recipe.archetype.as_str()) {
111 return Err(BuildError::UnknownArchetype(recipe.archetype.clone()));
112 }
113 Ok(build_scene(recipe, activity, opts, tod, family))
114}
115
116pub use crate::focal::sprite_scale;
117
118fn tod_glow(tod: TimeOfDay) -> f64 {
119 match tod {
120 TimeOfDay::Night => 1.0,
121 TimeOfDay::DeepDusk => 0.95,
122 TimeOfDay::Dusk => 0.85,
123 TimeOfDay::GoldenHour => 0.7,
124 TimeOfDay::Morning => 0.55,
125 TimeOfDay::Noon => 0.5,
126 }
127}
128
129fn build_scene(
132 recipe: &SceneRecipe,
133 activity: Option<&Activity>,
134 opts: &BuildOptions,
135 tod: TimeOfDay,
136 family: PaletteFamily,
137) -> SceneGraph {
138 let pace = if recipe.generator_version >= 4 {
141 CALM_PACE
142 } else {
143 0
144 };
145 let (w, h) = (opts.width, opts.height);
146 let (wf, hf) = (f64::from(w), f64::from(h));
147 let aspect = wf / hf;
148 let unit = wf.min(hf);
150 let zoom = recipe.zoom_factor();
151 let grid = grid_for(w, h, zoom);
152 let comp = &recipe.composition;
153 let seed = recipe.seed;
154 let (cols, rows) = (grid.cols, grid.rows);
155 let mut cells = vec![Cell::default(); (cols * rows) as usize];
156
157 let horizon = pm(comp.horizon_pm);
159 let platform_row = ((horizon * f64::from(rows)).round() as u32).clamp(rows / 3, rows - 4);
160 let ground_y = (grid.origin_y + platform_row * grid.cell_h) as i32;
161 let focal = focal::layout(recipe, activity, w, h, ground_y, grid.cell_w, grid.cell_h);
162 let (gx0, gx1, group_h) = (focal.x0, focal.x1, focal.height);
163 let group_cx = f64::from(gx0 + gx1) * 0.5;
164
165 let ctx = terrain::Ctx {
166 recipe,
167 co: terrain::Coords {
168 g: grid,
169 w: wf,
170 h: hf,
171 },
172 aspect,
173 unit,
174 cols,
175 rows,
176 horizon,
177 platform_row,
178 terrain: hash_label(seed, "terrain"),
179 gx0,
180 gx1,
181 group_cx,
182 tod,
183 unsheltered: std::cell::RefCell::new(vec![None; cols as usize]),
184 };
185 let co = &ctx.co;
186
187 let journeying = recipe.is_journey()
191 && activity.is_some_and(|a| a.motion.kind == crate::activity::MotionKind::Journey);
192 let journeyed = if journeying {
193 terrain::journey(&recipe.archetype, &ctx, &mut cells)
194 } else {
195 None
196 };
197 let sky_limit = match &journeyed {
198 Some(j) => j.sky_limit.clone(),
199 None => terrain::background(&recipe.archetype, &ctx, &mut cells),
200 };
201
202 let dome_cx = (group_cx - f64::from(grid.origin_x)) / f64::from(grid.cell_w);
204 let dome_a = f64::from(gx1 - gx0) * 0.5 / f64::from(grid.cell_w) + 3.0;
205 let dome_b = f64::from(group_h) / f64::from(grid.cell_h) + 2.0;
206 let dome = |col: u32, row: u32| -> f64 {
207 let u = (f64::from(col) + 0.5 - dome_cx) / dome_a;
208 let v = (f64::from(row) + 0.5 - f64::from(platform_row)) / dome_b;
209 let (u2, v2) = (u * u, v * v);
210 u2 * u2 + v2 * v2
211 };
212 let dome_rows = if journeyed.is_some() { 0 } else { platform_row };
214 let flight = activity
217 .and_then(|a| a.motion.altitude)
218 .filter(|_| journeyed.is_some());
219 if let (Some(alt), Some(track)) = (flight, focal.character) {
220 let cw = f64::from(crate::graph::CHARACTER_BOX.0 * track.scale);
221 let fx = f64::from(track.x_range().0) + cw * 0.5;
222 let fy = alt * hf - f64::from(group_h) * 0.5;
223 let a = (cw * 0.5 + 3.0 * f64::from(grid.cell_w)) / f64::from(grid.cell_w);
224 let b = (f64::from(group_h) * 0.5 + 0.03 * hf) / f64::from(grid.cell_h) + 2.0;
225 let (ccx, ccy) = (
226 (fx - f64::from(grid.origin_x)) / f64::from(grid.cell_w),
227 (fy - f64::from(grid.origin_y)) / f64::from(grid.cell_h),
228 );
229 for row in 0..rows {
230 for col in 0..cols {
231 let u = (f64::from(col) + 0.5 - ccx) / a;
232 let v = (f64::from(row) + 0.5 - ccy) / b;
233 let s = u * u * u * u + v * v * v * v;
234 let cell = &mut cells[(row * cols + col) as usize];
235 if s <= 1.0 {
236 *cell = Cell::default();
237 } else if s <= 2.4 {
238 cell.shade = (f64::from(cell.shade) * 0.55).round() as u8;
239 }
240 }
241 }
242 }
243 for row in 0..dome_rows {
244 for col in 0..cols {
245 let s = dome(col, row);
246 let cell = &mut cells[(row * cols + col) as usize];
247 if s <= 1.0 {
248 *cell = Cell::default();
249 } else if s <= 2.4 {
250 cell.shade = (f64::from(cell.shade) * 0.55).round() as u8;
251 }
252 }
253 }
254
255 let before_platform = (recipe.look == "dither").then(|| cells.clone());
260 if journeyed.is_none() {
261 terrain::platform(&recipe.archetype, &ctx, &mut cells);
262 }
263 if let (Some(a), Some(track)) = (activity, focal.character)
265 && a.trail.as_deref() == Some("ski_tracks")
266 && platform_row + 1 < rows
267 {
268 let (lo, hi) = track.x_range();
269 let cw = (crate::graph::CHARACTER_BOX.0 * track.scale) as i32;
270 let c0 = co.col_of(f64::from(lo)).max(0) as u32;
271 let c1 = (co.col_of(f64::from(hi + cw)).max(0) as u32).min(cols - 1);
272 for col in c0..=c1 {
273 let glyph = if col % 5 == 0 {
274 glyphs::id('-')
275 } else {
276 glyphs::id('=')
277 };
278 cells[((platform_row + 1) * cols + col) as usize] = Cell {
279 glyph,
280 shade: terrain::shade_u8(0.55),
281 };
282 }
283 }
284 let water = (recipe.archetype == "shore").then(|| terrain::shore::open_water(&ctx));
285
286 let (per_aspect, set, lo, hi): (f64, &[u8], f64, f64) = match tod {
289 TimeOfDay::Night => (150.0, &glyphs::STARS, 0.25, 0.75),
290 TimeOfDay::DeepDusk => (95.0, &glyphs::STARS, 0.20, 0.60),
291 TimeOfDay::Dusk => (50.0, &glyphs::STARS, 0.18, 0.50),
292 _ => (35.0, &glyphs::SKY_DUST, 0.12, 0.30),
293 };
294 let star_weights: &[u32] = if set.len() == glyphs::STARS.len() {
295 &[6, 4, 4, 3, 2, 1]
296 } else {
297 &[4, 3, 2, 2]
298 };
299 let mut sky = Rng::stream(seed, "sky");
300 let count = (per_aspect * aspect).round() as u32;
301 for _ in 0..count {
302 let x = sky.unit();
303 let y = sky.unit() * horizon;
304 let gi = sky.weighted_index(star_weights);
305 let shade = sky.range_f64(lo, hi);
306 let col = co.col_of(x * wf);
307 let row = ((y * hf - f64::from(grid.origin_y)) / f64::from(grid.cell_h)).floor() as i64;
308 if col < 0 || row < 0 || col >= i64::from(cols) || row >= i64::from(platform_row) {
309 continue;
310 }
311 let (col, row) = (col as u32, row as u32);
312 let idx = (row * cols + col) as usize;
313 if cells[idx].glyph != EMPTY
314 || co.ny(row) > sky_limit[col as usize] - 0.02
315 || (journeyed.is_none() && dome(col, row) <= 2.4)
316 {
317 continue;
318 }
319 let bright = gi == set.len() - 1;
320 cells[idx] = Cell {
321 glyph: set[gi],
322 shade: terrain::shade_u8(if bright { hi } else { shade }),
323 };
324 }
325
326 if recipe.look == "dither" {
328 let land_line = ctx.land_line(&sky_limit);
329 let ground: Vec<bool> = match &before_platform {
330 Some(before) => before.iter().zip(&cells).map(|(a, b)| a != b).collect(),
331 None => vec![false; cells.len()],
332 };
333 crate::look::dither(
334 &ctx,
335 &mut cells,
336 &crate::look::Dither {
337 sky_limit: &land_line,
338 theme: opts.theme,
339 tod,
340 contrast: &recipe.contrast,
341 dome: &dome,
342 sea_top: terrain::sea_line(&recipe.archetype, &ctx),
343 ground: &ground,
344 standing: crate::archetype::archetype(&recipe.archetype)
345 .is_some_and(|a| a.silhouettes)
346 .then_some(sky_limit.as_slice()),
347 },
348 );
349 } else {
350 crate::look::line_contrast(&mut cells, &recipe.contrast);
351 }
352
353 let lighting = Lighting {
355 vignette_cx: wf * 0.5,
356 vignette_cy: hf * 0.5,
357 vignette_rx: wf * 0.75,
358 vignette_ry: hf * 0.75,
359 glow: focal.light.map(|l| Glow {
360 cx: l.cx,
361 cy: l.cy,
362 radius: 0.417 * unit * zoom * tod_glow(tod) * l.strength,
363 }),
364 };
365
366 let embers = ember_set(seed, pace);
369 let t_hero_ms = hero_time(&embers);
370 let emitters = focal
371 .embers_at
372 .map(|(x, y)| Emitter {
373 kind: EmitterKind::Embers,
374 origin_x: x,
375 origin_y: y,
376 unit: unit * zoom,
378 intensity: match opts.theme {
379 Theme::Dark => 1.0,
380 Theme::Light => 0.85,
381 },
382 embers,
383 drops: Vec::new(),
384 size: (wf, hf),
385 pace,
386 })
387 .into_iter()
388 .collect();
389 let mut emitters: Vec<Emitter> = emitters;
392 if let Some(kind) = WeatherKind::from_id(&recipe.weather)
393 && (kind != WeatherKind::Confetti || recipe.generator_version >= 4)
395 && kind.shows_at(tod)
396 {
397 emitters.push(Emitter {
398 kind: EmitterKind::Weather(kind),
399 origin_x: 0.0,
400 origin_y: 0.0,
401 unit,
402 intensity: 1.0,
403 embers: Vec::new(),
404 drops: weather_set(kind, seed, aspect, pace),
405 size: (wf, hf),
406 pace,
407 });
408 }
409
410 let journey = journeyed.zip(focal.character).map(|(j, track)| {
413 let cw = (crate::graph::CHARACTER_BOX.0 * track.scale) as i64;
414 let feet_x = track.x_range().0 + (cw / 2) as i32;
415 let half = (cw * 3 / 10).max(1);
416 let n = j.surface.len() as i64;
417 let under = |x: i64| {
418 (x - half..=x + half)
419 .map(|k| j.surface[k.rem_euclid(n) as usize])
420 .fold(f64::INFINITY, f64::min)
421 };
422 let ground = match activity.and_then(|a| a.motion.altitude) {
423 Some(alt) => {
426 let clear = 0.05 * hf;
427 (0..n)
428 .map(|x| {
429 let wave =
430 crate::math::sin(crate::math::TAU * 2.0 * x as f64 / n.max(1) as f64);
431 let line = alt * hf + 0.012 * hf * wave;
432 line.min(under(x) - clear).max(f64::from(group_h)).round() as i32
433 })
434 .collect()
435 }
436 None => (0..n).map(|x| under(x).round() as i32).collect(),
437 };
438 let mut layers = j.layers;
439 for l in &mut layers {
440 if recipe.look == "dither" {
441 crate::look::dither_strip(&mut l.cells, l.cols, opts.theme, &recipe.contrast);
442 } else {
443 crate::look::line_contrast(&mut l.cells, &recipe.contrast);
444 }
445 }
446 let loop_ms = if comp.journey_pace_c > 0 {
450 let near = layers.last().map_or(0, |l| u64::from(l.cols * l.turns));
451 let ms = near * 100_000 / u64::from(comp.journey_pace_c);
452 let step = LOOP_MS;
453 ((ms + step / 2) / step).max(2) * step
454 } else {
455 u64::from(comp.journey_ms)
456 };
457 crate::graph::Journey {
458 loop_ms,
459 layers,
460 ground,
461 feet_x,
462 }
463 });
464
465 SceneGraph {
466 width: w,
467 height: h,
468 theme: opts.theme,
469 tod,
470 buddy: opts.buddy,
471 seed: recipe.seed,
472 family,
473 grid,
474 cells,
475 lighting,
476 activity: recipe.activity.clone(),
477 props: focal.props,
478 unattended: focal.unattended,
479 character: focal.character,
480 emitters,
481 ground_y,
482 t_hero_ms,
483 loop_ms: LOOP_MS,
484 pace,
485 generator: recipe.generator_version,
486 letters: if recipe.letters == "text" {
487 String::new()
488 } else {
489 recipe.letters.clone()
490 },
491 water,
492 journey,
493 zoom,
494 }
495}
496
497#[cfg(test)]
498mod tests {
499 use super::*;
500 use crate::compose::compose;
501 use crate::graph::SpriteKind;
502 use crate::graph::grid_spec;
503 use crate::recipe::{Aspect, ContentContext};
504
505 fn graph(seed: u64, w: u32, h: u32, theme: Theme, buddy: bool) -> SceneGraph {
506 let r = compose(seed, Aspect::from_size(w, h), &ContentContext::default());
507 let theme = if r.tod_for(theme).is_some() {
509 theme
510 } else {
511 match theme {
512 Theme::Dark => Theme::Light,
513 Theme::Light => Theme::Dark,
514 }
515 };
516 build(
517 &r,
518 &BuildOptions {
519 width: w,
520 height: h,
521 theme,
522 buddy,
523 },
524 )
525 .unwrap()
526 }
527
528 #[test]
529 fn grid_matches_plan_at_4k() {
530 let g = grid_spec(3840, 2160);
531 assert_eq!((g.cell_w, g.cell_h), (11, 20));
532 assert_eq!(g.rows, 108);
533 let small = grid_spec(640, 360);
534 assert_eq!((small.cell_w, small.cell_h), (6, 11));
535 }
536
537 #[test]
538 fn buddy_toggle_keeps_landscape() {
539 let a = graph(7, 960, 540, Theme::Dark, true);
540 let b = graph(7, 960, 540, Theme::Dark, false);
541 assert_eq!(a.cells, b.cells);
542 assert_eq!(a.lighting, b.lighting);
543 assert_ne!(a.sprites_at(0), b.sprites_at(0));
544 }
545
546 #[test]
547 fn feet_on_platform_top_at_all_times() {
548 for seed in 0..30 {
549 let g = graph(seed, 1280, 720, Theme::Dark, true);
551 let archetype = compose(
552 seed,
553 Aspect::from_size(1280, 720),
554 &ContentContext::default(),
555 )
556 .archetype;
557 let row = ((g.ground_y as u32) - g.grid.origin_y) / g.grid.cell_h;
558 for t in (0..20_000).step_by(1_250) {
559 let c = g
560 .sprites_at(t)
561 .into_iter()
562 .find(|s| s.kind == SpriteKind::Character)
563 .unwrap();
564 if g.character.is_some_and(|t| t.flies()) {
565 assert!(c.y >= 0 && c.y + c.height() as i32 <= g.height as i32);
567 continue;
568 }
569 if let Some(j) = &g.journey {
570 let ground = j.ground_at(g.grid.cell_w, g.grid.origin_x, t).unwrap();
572 assert_eq!(c.y + c.height() as i32, ground, "seed {seed} t {t}");
573 assert!(c.y >= 0 && ground < g.height as i32);
574 continue;
575 }
576 assert_eq!(c.y + c.height() as i32, g.ground_y);
577 assert!(c.x >= 0 && c.x + c.width() as i32 <= g.width as i32);
578 let col = ((c.x + c.width() as i32 / 2) as u32 - g.grid.origin_x) / g.grid.cell_w;
580 assert_eq!(
581 g.cell(col, row).glyph,
582 terrain::platform_top(&archetype),
583 "seed {seed} t {t}"
584 );
585 }
586 }
587 }
588
589 #[test]
590 fn theme_locked_scenes_refuse_the_other_theme() {
591 let ctx = ContentContext {
592 enabled_activities: vec!["stargaze".into()],
593 ..ContentContext::default()
594 };
595 let r = compose(4, Aspect::from_size(16, 9), &ctx);
596 let opts = BuildOptions {
597 width: 640,
598 height: 360,
599 theme: Theme::Light,
600 buddy: true,
601 };
602 assert_eq!(
603 build(&r, &opts).unwrap_err(),
604 BuildError::ThemeLocked(Theme::Light)
605 );
606 assert!(
607 build(
608 &r,
609 &BuildOptions {
610 theme: Theme::Dark,
611 ..opts
612 }
613 )
614 .is_ok()
615 );
616 }
617
618 #[test]
619 fn props_never_overlap_the_character() {
620 for seed in 0..30 {
621 let g = graph(seed, 1920, 1080, Theme::Dark, true);
622 let track = g.character.unwrap();
623 if track.flies() {
624 continue; }
626 let (lo, hi) = track.x_range();
627 let cw = track.at(0).width() as i32;
628 for p in &g.props {
629 let (px0, px1) = (p.x, p.x + p.width() as i32);
630 assert!(
631 px1 <= lo || px0 >= hi + cw,
632 "seed {seed}: {:?} overlaps the character's range",
633 p.kind
634 );
635 }
636 }
637 }
638
639 #[test]
640 fn rejects_tiny_sizes_and_unknown_archetypes() {
641 let mut r = compose(1, Aspect::from_size(16, 9), &ContentContext::default());
642 let theme = if r.tod_for(Theme::Dark).is_some() {
644 Theme::Dark
645 } else {
646 Theme::Light
647 };
648 let opts = BuildOptions {
649 width: 100,
650 height: 50,
651 theme,
652 buddy: true,
653 };
654 assert!(matches!(build(&r, &opts), Err(BuildError::TooSmall { .. })));
655 r.archetype = "atlantis".into();
656 let opts = BuildOptions {
657 width: 640,
658 height: 360,
659 ..opts
660 };
661 assert!(matches!(
662 build(&r, &opts),
663 Err(BuildError::UnknownArchetype(_))
664 ));
665 }
666}