nightshade 0.38.0

A cross-platform data-oriented game engine.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
use crate::ecs::primitives::EasingFunction;
use nalgebra_glm::{Quat, Vec3};
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct CutsceneShot {
    pub eye: Vec3,
    pub target: Vec3,
    pub field_of_view_degrees: f32,
    pub roll_degrees: f32,
}

impl CutsceneShot {
    pub fn new(eye: Vec3, target: Vec3) -> Self {
        Self {
            eye,
            target,
            field_of_view_degrees: 45.0,
            roll_degrees: 0.0,
        }
    }

    pub fn with_field_of_view(mut self, field_of_view_degrees: f32) -> Self {
        self.field_of_view_degrees = field_of_view_degrees;
        self
    }

    pub fn with_roll(mut self, roll_degrees: f32) -> Self {
        self.roll_degrees = roll_degrees;
        self
    }

    pub fn interpolate(self, other: CutsceneShot, factor: f32) -> CutsceneShot {
        CutsceneShot {
            eye: self.eye + (other.eye - self.eye) * factor,
            target: self.target + (other.target - self.target) * factor,
            field_of_view_degrees: self.field_of_view_degrees
                + (other.field_of_view_degrees - self.field_of_view_degrees) * factor,
            roll_degrees: self.roll_degrees + (other.roll_degrees - self.roll_degrees) * factor,
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum CutsceneAction {
    CameraMove {
        from: CutsceneShot,
        to: CutsceneShot,
    },
    CameraFollow {
        actor: String,
        eye_offset: Vec3,
        look_height: f32,
        field_of_view_degrees: f32,
    },
    CameraPath {
        waypoints: Vec<CutsceneShot>,
    },
    CameraShake {
        amplitude: f32,
        frequency: f32,
    },
    Handheld {
        position_amplitude: f32,
        target_amplitude: f32,
        frequency: f32,
    },
    ActorMove {
        actor: String,
        from: Vec3,
        to: Vec3,
    },
    ActorTurn {
        actor: String,
        from_yaw_radians: f32,
        to_yaw_radians: f32,
    },
    ActorVisible {
        actor: String,
        visible: bool,
    },
    ActorAnimation {
        actor: String,
        clip: String,
        looping: bool,
        speed: f32,
        blend: f32,
    },
    CameraLookAt {
        actor: String,
        look_height: f32,
        damping: f32,
    },
    Dialogue {
        speaker: Option<String>,
        line: String,
    },
    Title {
        line: String,
    },
    Fade {
        from: f32,
        to: f32,
        color: Vec3,
    },
    Letterbox {
        from: f32,
        to: f32,
    },
    FocusPull {
        from_distance: f32,
        to_distance: f32,
        range: f32,
    },
    Grade {
        exposure_ev: (f32, f32),
        saturation: (f32, f32),
        contrast: (f32, f32),
    },
    /// Fires a named marker the host app drains and reacts to. Keeps cutscenes
    /// pure data: the timeline names an event, the game decides what it means.
    Trigger {
        id: String,
    },
    /// Plays a one-shot sound registered with the audio engine under `clip`.
    Sound {
        clip: String,
        volume: f32,
    },
    /// Starts looping music registered with the audio engine under `track`.
    Music {
        track: String,
        volume: f32,
    },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CutsceneEvent {
    pub start: f32,
    pub duration: f32,
    pub easing: EasingFunction,
    pub action: CutsceneAction,
}

impl CutsceneEvent {
    pub fn end(&self) -> f32 {
        self.start + self.duration
    }

    pub fn eased_progress(&self, time: f32) -> f32 {
        if self.duration <= 0.0 {
            return if time >= self.start { 1.0 } else { 0.0 };
        }
        let raw = ((time - self.start) / self.duration).clamp(0.0, 1.0);
        self.easing.evaluate(raw)
    }
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Cutscene {
    pub name: String,
    pub events: Vec<CutsceneEvent>,
}

impl Cutscene {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            events: Vec::new(),
        }
    }

    pub fn duration(&self) -> f32 {
        self.events
            .iter()
            .map(CutsceneEvent::end)
            .fold(0.0, f32::max)
    }

    fn push(
        mut self,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        action: CutsceneAction,
    ) -> Self {
        self.events.push(CutsceneEvent {
            start,
            duration,
            easing,
            action,
        });
        self
    }

    pub fn camera(
        self,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        from: CutsceneShot,
        to: CutsceneShot,
    ) -> Self {
        self.push(
            start,
            duration,
            easing,
            CutsceneAction::CameraMove { from, to },
        )
    }

    pub fn camera_follow(
        self,
        start: f32,
        duration: f32,
        actor: impl Into<String>,
        eye_offset: Vec3,
        look_height: f32,
        field_of_view_degrees: f32,
    ) -> Self {
        self.push(
            start,
            duration,
            EasingFunction::Linear,
            CutsceneAction::CameraFollow {
                actor: actor.into(),
                eye_offset,
                look_height,
                field_of_view_degrees,
            },
        )
    }

    pub fn camera_look_at(
        self,
        start: f32,
        duration: f32,
        actor: impl Into<String>,
        look_height: f32,
        damping: f32,
    ) -> Self {
        self.push(
            start,
            duration,
            EasingFunction::Linear,
            CutsceneAction::CameraLookAt {
                actor: actor.into(),
                look_height,
                damping,
            },
        )
    }

    pub fn camera_path(
        self,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        waypoints: Vec<CutsceneShot>,
    ) -> Self {
        self.push(
            start,
            duration,
            easing,
            CutsceneAction::CameraPath { waypoints },
        )
    }

    pub fn handheld(
        self,
        start: f32,
        duration: f32,
        position_amplitude: f32,
        target_amplitude: f32,
        frequency: f32,
    ) -> Self {
        self.push(
            start,
            duration,
            EasingFunction::Linear,
            CutsceneAction::Handheld {
                position_amplitude,
                target_amplitude,
                frequency,
            },
        )
    }

    pub fn camera_shake(self, start: f32, duration: f32, amplitude: f32, frequency: f32) -> Self {
        self.push(
            start,
            duration,
            EasingFunction::Linear,
            CutsceneAction::CameraShake {
                amplitude,
                frequency,
            },
        )
    }

    pub fn camera_cut(self, start: f32, shot: CutsceneShot) -> Self {
        self.push(
            start,
            0.0,
            EasingFunction::Linear,
            CutsceneAction::CameraMove {
                from: shot,
                to: shot,
            },
        )
    }

    pub fn actor_move(
        self,
        actor: impl Into<String>,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        from: Vec3,
        to: Vec3,
    ) -> Self {
        self.push(
            start,
            duration,
            easing,
            CutsceneAction::ActorMove {
                actor: actor.into(),
                from,
                to,
            },
        )
    }

    pub fn actor_turn(
        self,
        actor: impl Into<String>,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        from_yaw_radians: f32,
        to_yaw_radians: f32,
    ) -> Self {
        self.push(
            start,
            duration,
            easing,
            CutsceneAction::ActorTurn {
                actor: actor.into(),
                from_yaw_radians,
                to_yaw_radians,
            },
        )
    }

    pub fn actor_animation(
        self,
        actor: impl Into<String>,
        start: f32,
        clip: impl Into<String>,
        looping: bool,
        speed: f32,
    ) -> Self {
        self.actor_animation_blended(actor, start, clip, looping, speed, 0.2)
    }

    pub fn actor_animation_blended(
        self,
        actor: impl Into<String>,
        start: f32,
        clip: impl Into<String>,
        looping: bool,
        speed: f32,
        blend: f32,
    ) -> Self {
        self.push(
            start,
            0.0,
            EasingFunction::Linear,
            CutsceneAction::ActorAnimation {
                actor: actor.into(),
                clip: clip.into(),
                looping,
                speed,
                blend,
            },
        )
    }

    pub fn actor_place(self, actor: impl Into<String>, time: f32, position: Vec3) -> Self {
        self.push(
            time,
            0.0,
            EasingFunction::Linear,
            CutsceneAction::ActorMove {
                actor: actor.into(),
                from: position,
                to: position,
            },
        )
    }

    pub fn actor_face(self, actor: impl Into<String>, time: f32, yaw_radians: f32) -> Self {
        self.push(
            time,
            0.0,
            EasingFunction::Linear,
            CutsceneAction::ActorTurn {
                actor: actor.into(),
                from_yaw_radians: yaw_radians,
                to_yaw_radians: yaw_radians,
            },
        )
    }

    pub fn actor_visible(self, actor: impl Into<String>, time: f32, visible: bool) -> Self {
        self.push(
            time,
            0.0,
            EasingFunction::Linear,
            CutsceneAction::ActorVisible {
                actor: actor.into(),
                visible,
            },
        )
    }

    pub fn dialogue(
        self,
        start: f32,
        duration: f32,
        speaker: Option<&str>,
        line: impl Into<String>,
    ) -> Self {
        self.push(
            start,
            duration,
            EasingFunction::Linear,
            CutsceneAction::Dialogue {
                speaker: speaker.map(str::to_string),
                line: line.into(),
            },
        )
    }

    pub fn title(self, start: f32, duration: f32, line: impl Into<String>) -> Self {
        self.push(
            start,
            duration,
            EasingFunction::Linear,
            CutsceneAction::Title { line: line.into() },
        )
    }

    pub fn fade(
        self,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        from: f32,
        to: f32,
        color: Vec3,
    ) -> Self {
        self.push(
            start,
            duration,
            easing,
            CutsceneAction::Fade { from, to, color },
        )
    }

    pub fn fade_in(self, start: f32, duration: f32) -> Self {
        self.fade(
            start,
            duration,
            EasingFunction::QuadOut,
            1.0,
            0.0,
            Vec3::zeros(),
        )
    }

    pub fn fade_out(self, start: f32, duration: f32) -> Self {
        self.fade(
            start,
            duration,
            EasingFunction::QuadIn,
            0.0,
            1.0,
            Vec3::zeros(),
        )
    }

    pub fn letterbox(
        self,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        from: f32,
        to: f32,
    ) -> Self {
        self.push(
            start,
            duration,
            easing,
            CutsceneAction::Letterbox { from, to },
        )
    }

    pub fn letterbox_in(self, start: f32, duration: f32) -> Self {
        self.letterbox(start, duration, EasingFunction::CubicOut, 0.0, 1.0)
    }

    pub fn letterbox_out(self, start: f32, duration: f32) -> Self {
        self.letterbox(start, duration, EasingFunction::CubicIn, 1.0, 0.0)
    }

    pub fn focus_pull(
        self,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        from_distance: f32,
        to_distance: f32,
        range: f32,
    ) -> Self {
        self.push(
            start,
            duration,
            easing,
            CutsceneAction::FocusPull {
                from_distance,
                to_distance,
                range,
            },
        )
    }

    pub fn grade(
        self,
        start: f32,
        duration: f32,
        easing: EasingFunction,
        exposure_ev: (f32, f32),
        saturation: (f32, f32),
        contrast: (f32, f32),
    ) -> Self {
        self.push(
            start,
            duration,
            easing,
            CutsceneAction::Grade {
                exposure_ev,
                saturation,
                contrast,
            },
        )
    }

    pub fn trigger(self, start: f32, id: impl Into<String>) -> Self {
        self.push(
            start,
            0.0,
            EasingFunction::Linear,
            CutsceneAction::Trigger { id: id.into() },
        )
    }

    pub fn sound(self, start: f32, clip: impl Into<String>, volume: f32) -> Self {
        self.push(
            start,
            0.0,
            EasingFunction::Linear,
            CutsceneAction::Sound {
                clip: clip.into(),
                volume,
            },
        )
    }

    pub fn music(self, start: f32, track: impl Into<String>, volume: f32) -> Self {
        self.push(
            start,
            0.0,
            EasingFunction::Linear,
            CutsceneAction::Music {
                track: track.into(),
                volume,
            },
        )
    }

    /// Appends an action that begins `gap` seconds after everything authored so
    /// far ends. Lets a scene be written as a sequence without hand counting
    /// timestamps.
    pub fn then(
        self,
        gap: f32,
        duration: f32,
        easing: EasingFunction,
        action: CutsceneAction,
    ) -> Self {
        let start = self.duration() + gap;
        self.push(start, duration, easing, action)
    }

    pub fn then_dialogue(
        self,
        gap: f32,
        duration: f32,
        speaker: Option<&str>,
        line: impl Into<String>,
    ) -> Self {
        let start = self.duration() + gap;
        self.dialogue(start, duration, speaker, line)
    }

    /// Pushes a back to back run of dialogue lines, each `(speaker, line,
    /// duration)`, separated by `gap` seconds, starting at `start`.
    pub fn dialogue_sequence(
        mut self,
        start: f32,
        gap: f32,
        lines: &[(Option<&str>, &str, f32)],
    ) -> Self {
        let mut cursor = start;
        for (speaker, line, duration) in lines {
            self = self.dialogue(cursor, *duration, *speaker, *line);
            cursor += duration + gap;
        }
        self
    }
}

fn catmull_rom(p0: f32, p1: f32, p2: f32, p3: f32, t: f32) -> f32 {
    let t2 = t * t;
    let t3 = t2 * t;
    0.5 * ((2.0 * p1)
        + (-p0 + p2) * t
        + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2
        + (-p0 + 3.0 * p1 - 3.0 * p2 + p3) * t3)
}

fn catmull_rom_vec3(p0: Vec3, p1: Vec3, p2: Vec3, p3: Vec3, t: f32) -> Vec3 {
    Vec3::new(
        catmull_rom(p0.x, p1.x, p2.x, p3.x, t),
        catmull_rom(p0.y, p1.y, p2.y, p3.y, t),
        catmull_rom(p0.z, p1.z, p2.z, p3.z, t),
    )
}

pub fn sample_camera_path(waypoints: &[CutsceneShot], progress: f32) -> CutsceneShot {
    match waypoints.len() {
        0 => CutsceneShot::new(Vec3::zeros(), -Vec3::z()),
        1 => waypoints[0],
        _ => {
            let segments = waypoints.len() - 1;
            let scaled = (progress.clamp(0.0, 1.0) * segments as f32).min(segments as f32 - 1e-4);
            let index = scaled.floor() as usize;
            let local = scaled - index as f32;
            let point = |offset: isize| -> CutsceneShot {
                let clamped = (index as isize + offset).clamp(0, waypoints.len() as isize - 1);
                waypoints[clamped as usize]
            };
            let p0 = point(-1);
            let p1 = point(0);
            let p2 = point(1);
            let p3 = point(2);
            CutsceneShot {
                eye: catmull_rom_vec3(p0.eye, p1.eye, p2.eye, p3.eye, local),
                target: catmull_rom_vec3(p0.target, p1.target, p2.target, p3.target, local),
                field_of_view_degrees: catmull_rom(
                    p0.field_of_view_degrees,
                    p1.field_of_view_degrees,
                    p2.field_of_view_degrees,
                    p3.field_of_view_degrees,
                    local,
                ),
                roll_degrees: catmull_rom(
                    p0.roll_degrees,
                    p1.roll_degrees,
                    p2.roll_degrees,
                    p3.roll_degrees,
                    local,
                ),
            }
        }
    }
}

pub fn camera_look_rotation(eye: Vec3, target: Vec3, roll_degrees: f32) -> Quat {
    let direction = target - eye;
    if direction.magnitude_squared() < f32::EPSILON {
        return Quat::identity();
    }
    let direction = direction.normalize();
    let yaw = (-direction.x).atan2(-direction.z);
    let pitch = (-direction.y).clamp(-1.0, 1.0).asin();
    let yaw_rotation = nalgebra_glm::quat_angle_axis(yaw, &Vec3::y());
    let pitch_rotation = nalgebra_glm::quat_angle_axis(-pitch, &Vec3::x());
    let look = yaw_rotation * pitch_rotation;
    if roll_degrees.abs() < f32::EPSILON {
        return look;
    }
    let roll = nalgebra_glm::quat_angle_axis(roll_degrees.to_radians(), &direction);
    roll * look
}