timeline.js 89,2 КБ
Newer Older
Nikitos's avatar
ф  
Nikitos включено в состав коммита
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
// ===========================================================================
// AnimatedTimelineScene2d — сцена-таймлайн для диалогов и визуальных новелл.
//
// Модуль даёт `$` одну новую сущность: **анимированную таймлайн-сцену 2D** —
// описание того, что происходит на экране, одним массивом «битов» (beats):
//
//   $.timeline.define('russi', {
//       locations: { room: { bg: 'art/room.png', music: 'music/room.ogg' } },
//       cast: { russi: { name: 'Руси-тян', poses: { neutral: 'art/neutral.png' } } },
//       script: [
//           { location: 'room' },
//           { show: 'russi', from: 'left' },
//           { say: 'Бака! Ты не понимаешь, как прекрасен JS.', pose: 'angry' },
//           { shake: 10, ms: 400 },
//           { choose: [
//               { text: 'Согласен', goto: 'love', add: { trust: 1 } },
//               { text: 'Python лучше', goto: 'hate' },
//           ] },
//           { label: 'love' },
//           { ending: { id: 'love', title: 'Хорошая концовка', text: '…' } },
//       ],
//   });
//
//   $.timeline.play('russi');
//
// Что модуль берёт на себя, а что отдаёт другим подсистемам:
//
// | Слой | Кто отвечает |
// |---|---|
// | текст, печатная машинка, выборы, клавиатура | `$.dialog` (таймлайн только листает реплики) |
// | фон и локации | свои узлы-спрайты в мире + перекрёстное затухание |
// | герои, позы, вход/выход, дыхание, акценты | свой «риг» на персонажа + `$.tween` |
// | тряска экрана | `$.camera.shake` |
// | вспышки и затемнения | свои `ui.panel` поверх интерфейса |
// | музыка и звуки | `$.sound` |
// | флаги и концовки | `$.store` |
// | время и паузы | покадровый `tickTimeline(dt)`, как у `$.dialog` |
//
// Почему камера, а не `ui.*`: и фон, и герои живут в мире, а камера приколота
// к центру окна — тогда мировые координаты совпадают с экранными, но тряска
// камеры двигает всю картинку разом. Интерфейс (панель диалога, затемнение)
// остаётся недвижим: текст не должен прыгать.
//
// Таймлайн — не сценарий на рельсах: у битов есть метки, переходы (`goto`),
// условия (`if`) и вложенные ветки, поэтому на нём собираются и линейные
// новеллы, и развилки с концовками. Всё состояние прогона отдаётся наружу
// через `$.timeline.state()` — его видно тестам и агенту.
// ===========================================================================

Nikitos's avatar
Nikitos включено в состав коммита
50
import { engine } from './native.js';
51
import { ctx, wrap, wrapOne, query, spriteSize, fxRandom } from './core.js';
Nikitos's avatar
ф  
Nikitos включено в состав коммита
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000

// --- Реестр -----------------------------------------------------------------
// Определения (то, что объявила игра) и подписки на события модуля. Прогон
// один на процесс, как и диалог: две новеллы одновременно — это уже не новелла.
const definitions = new Map();
const listeners = new Map();
let api = null;
let run = null;
let ending_view = null;      // карточка концовки: живёт, когда прогон уже завершён
// След последнего прогона: после концовки `state()` обязан рассказать, чем
// всё кончилось, — иначе агенту и тестам нечего читать.
const last_run = { id: null, scene: null, ended: false, ending: null, location: null, beats: 0, ticks: 0, time: 0 };
const runtime = { auto: 0 };

// Длительности по умолчанию, мс.
const DEFAULTS = {
    fade: 450,          // перекрёстное затухание локации
    show: 320,          // выход персонажа на сцену
    hide: 260,
    flash: 220,
    shake: 380,
    ending: 700,
    auto: 1400,         // авто-режим: пауза после допечатанной реплики
};

// Встроенные акценты героя: имя → шаги твина по полям рига.
//   [поле, целевое значение, секунды]
// Поля рига: dx/dy — сдвиг от точки стояния, hop — подскок, scale — масштаб,
// angle — наклон. Акцент не трогает точку стояния: после него герой там же,
// где был, — иначе позы и входы «уезжали» бы после каждого «бака!».
const ACCENTS = {
    pop: [['scale', 1.07, 0.10], ['scale', 1, 0.16], ['dy', -6, 0.10], ['dy', 0, 0.16]],
    bounce: [['hop', 34, 0.12], ['hop', 0, 0.14], ['hop', 20, 0.10], ['hop', 0, 0.13]],
    nod: [['hop', -12, 0.12], ['hop', 0, 0.16]],
    lean: [['dx', 26, 0.18], ['dx', 0, 0.24]],
    away: [['dx', -30, 0.20], ['dx', 0, 0.26]],
    sigh: [['scale', 0.975, 0.30], ['scale', 1, 0.36], ['hop', -4, 0.30], ['hop', 0, 0.36]],
    step: [['dy', -4, 0.10], ['dy', 0, 0.12]],
};

// Дрожь — не твин, а затухающая синусоида: у неё десятки колебаний за секунду,
// и ключами твина её описывать бессмысленно.
const TREMORS = {
    tremble: { ms: 420, amp: 5, angle: 0.012 },
    shiver: { ms: 700, amp: 2.4, angle: 0.006 },
};

// --- Мелкие помощники -------------------------------------------------------

function num(value, fallback) {
    const v = Number(value);
    return Number.isFinite(v) ? v : fallback;
}

function ms(value, fallback) {
    if (value === undefined || value === null || value === true) return fallback;
    if (value === false) return 0;
    const v = Number(value);
    return Number.isFinite(v) ? Math.max(0, v) : fallback;
}

function report(where, error) {
    if (api && api.ctx && typeof api.ctx.reportError === 'function') api.ctx.reportError(where, error);
    else if (ctx && typeof ctx.log === 'function') ctx.log(`${where}: ${error}`);
}

function screenSize() {
    if (api && api.gfx && typeof api.gfx.size === 'function') {
        const size = api.gfx.size();
        if (size && size.w > 0) return size;
    }
    return { w: engine.width || 1280, h: engine.height || 720 };
}

/** Подписки модуля: $.timeline.on('ending', …) — как у $.dialog. */
function emit(name, data) {
    const list = listeners.get(name);
    if (list) {
        for (const fn of list.slice()) {
            try { fn(data); } catch (e) { report(`$.timeline "${name}"`, e); }
        }
    }
    if (api && typeof api._dispatchGlobal === 'function') {
        try { api._dispatchGlobal(null, 'timeline:' + name, data); } catch (e) { report('timeline:emit', e); }
    }
}

/** Значение условия: функция, булево, флаг ('!flag') или сравнение ('trust >= 2'). */
export function conditionValue(cond) {
    if (cond === undefined || cond === null) return true;
    if (typeof cond === 'function') {
        try { return !!cond(api, run && run.control); } catch (e) { report('$.timeline: условие', e); return false; }
    }
    if (typeof cond === 'string') {
        const text = cond.trim();
        if (!text) return false;

        // Сравнение: `trust >= 2`, `route == 'love'`. Пишется прямо в сценарии,
        // поэтому сценаристу не нужен JS — а нам не нужен eval.
        const compare = /^([A-Za-z_][\w.:]*)\s*(>=|<=|==|!=|>|<)\s*(.+)$/.exec(text);
        if (compare) {
            const left = readFlag(compare[1]);
            let right = compare[3].trim();
            if ((right.startsWith("'") && right.endsWith("'")) ||
                (right.startsWith('"') && right.endsWith('"'))) {
                right = right.slice(1, -1);
            }
            const right_num = Number(right);
            const both_numbers = Number.isFinite(right_num) && Number.isFinite(Number(left));
            const a = both_numbers ? Number(left) : (left === undefined || left === null ? '' : String(left));
            const b = both_numbers ? right_num : right;
            switch (compare[2]) {
            case '>=': return a >= b;
            case '<=': return a <= b;
            case '>': return a > b;
            case '<': return a < b;
            case '==': return a === b;
            case '!=': return a !== b;
            default: return false;
            }
        }

        const negated = text.startsWith('!');
        const key = negated ? text.slice(1).trim() : text;
        const value = readFlag(key);
        return negated ? !value : !!value;
    }
    return !!cond;
}

function readFlag(key) {
    if (!api || !api.store) return undefined;
    if (typeof api.store.get === 'function') return api.store.get(key, undefined);
    return undefined;
}

function writeFlag(key, value) {
    if (!api || !api.store || typeof api.store.set !== 'function') return;
    api.store.set(key, value);
}

function applyFlags(beat, mode) {
    const source = beat[mode];
    if (!source || typeof source !== 'object') return;
    for (const key of Object.keys(source)) {
        const value = source[key];
        if (mode === 'add') writeFlag(key, num(readFlag(key), 0) + num(value, 0));
        else writeFlag(key, value);
    }
}

// ===========================================================================
// Установка подсистемы
// ===========================================================================

export function installTimeline($) {    api = $;

    const timeline = {
        /**
         * Объявить таймлайн-сцену.
         *   $.timeline.define('russi', spec)
         * Возвращает объект управления прогоном (он же — значение `$`),
         * у которого есть `.play()`, `.state()`, `.hero()`.
         */
        define(id, spec) { return defineTimeline(id, spec); },

        has(id) { return definitions.has(String(id)); },
        list() { return [...definitions.keys()].sort(); },
        remove(id) {
            const key = String(id);
            const def = definitions.get(key);
            if (!def) return false;
            if (run && run.def === def) timeline.stop('removed');
            if (api.scene && typeof api.scene.remove === 'function') api.scene.remove(def.scene);
            if (api.dialog && typeof api.dialog.remove === 'function') api.dialog.remove(def.dialog);
            definitions.delete(key);
            return true;
        },

        /**
         * Запустить таймлайн: `$.timeline.play('russi', { at: 'metka' })`.
         * Сцена загрузится сама, если игра сейчас в другой сцене.
         */
        play(id, opts) { return playTimeline(String(id), opts); },

        /** Остановить прогон (диалог закроется, сцена останется жить). */
        stop(reason) { return stopRun(reason || 'manual'); },

        /** Дальше: допечатать реплику или перейти к следующей. */
        next() { return api && api.dialog ? api.dialog.next() : false; },
        skip() { return api && api.dialog ? api.dialog.skip() : false; },
        /** Выбрать вариант по номеру видимого списка. */
        choose(index) { return api && api.dialog ? api.dialog.choose(index) : false; },
        chooseByText(text) { return api && api.dialog ? api.dialog.chooseByText(text) : false; },
        choices() { return api && api.dialog ? api.dialog.choices() : []; },

        /** Прыгнуть на метку — тем же путём, что и бит `goto`. */
        goto(label) { gotoLabel(label); return timeline; },

        /** Сменить локацию вручную (то же, что бит `{ location }`). */
        location(name, opts) { startLocation(Object.assign({ location: name }, opts || {})); return timeline; },

        /** Сменить позу вручную: `$.timeline.pose('russi', 'angry')`. */
        pose(who, name, opts) { poseBeat(Object.assign({ pose: name, who: who }, opts || {})); return timeline; },

        /** Узел персонажа — для своих эффектов и проверок. */
        hero(who) {
            if (!run) return wrap([]);
            const rig = run.rigs.get(who === undefined ? run.def.hero : String(who));
            return rig ? wrapOne(rig.node) : wrap([]);
        },

        /** Авто-режим: мс паузы после реплики; `auto(false)` — выключить. */
        auto(value) {
            if (value === undefined) return runtime.auto;
            if (value === false || value === null) runtime.auto = 0;
            else if (value === true) runtime.auto = DEFAULTS.auto;
            else runtime.auto = Math.max(0, num(value, DEFAULTS.auto));
            if (run) run.auto_timer = 0;
            return runtime.auto;
        },

        /** Скорость печатной машинки (символов в секунду) — как $.dialog.speed. */
        speed(value) { return api && api.dialog ? api.dialog.speed(value) : 0; },

        /**
         * Реплики таймлайна по порядку: `[{ id, speaker, text, choices }]`.
         * id — он же имя файла озвучки (`<dir>/<id>.mp3`), поэтому список
         * заодно служит сценарием записи голоса.
         */
        lines(id) {
            const key = id === undefined || id === null ? (run ? run.def.id : last_run.id) : String(id);
            const def = definitions.get(key);
            if (!def) return [];
            return Object.keys(def.nodes)
                .sort((a, b) => num(a.slice(2), 0) - num(b.slice(2), 0))
                .map((node) => ({
                    id: node,
                    speaker: def.nodes[node].speaker || '',
                    text: def.nodes[node].text || '',
                    choices: Array.isArray(def.nodes[node].choices) ? def.nodes[node].choices.length : 0,
                }));
        },

        /** Снимок прогона: для тестов, отладки и агента. */
        state() { return runState(); },

        running() { return !!run; },
        /** Имя таймлайна: после концовки — имя последнего прогона, а не null. */
        current() { return run ? run.def.id : last_run.id; },
        /** Прогон дошёл до конца (концовка или конец скрипта). */
        ended() { return run ? !!run.ended : !!last_run.ended; },
        definition() { return run ? run.def : null; },

        on(name, fn) {
            const key = String(name);
            if (!listeners.has(key)) listeners.set(key, []);
            listeners.get(key).push(fn);
            return timeline;
        },
        off(name, fn) {
            const key = String(name);
            if (!listeners.has(key)) return timeline;
            if (!fn) listeners.delete(key);
            else listeners.set(key, listeners.get(key).filter((f) => f !== fn));
            return timeline;
        },
        emit(name, data) { emit(String(name), data); return timeline; },
        listenerCount(name) { return (listeners.get(String(name)) || []).length; },
    };

    $.timeline = timeline;

    /**
     * Литеральное имя из задания: `$.animatedTimelineScene2d(spec)` —
     * то же, что `$.timeline.define(spec.id, spec)`. Оставлено как синоним,
     * чтобы тип сцены читался в коде игры буквально.
     */
    $.animatedTimelineScene2d = function (spec) {
        const id = spec && (spec.id || spec.name);
        if (!id) {
            if (ctx && typeof ctx.log === 'function') {
                ctx.log('$.animatedTimelineScene2d: в описании нужен id — { id: "russi", script: [...] }');
            }
            return timeline;
        }
        return defineTimeline(String(id), spec);
    };

    // Реплики новеллы листает сам таймлайн: как только диалог закрылся или
    // игрок выбрал вариант — прогон продолжается. Продолжение откладывается
    // до кадра (см. requestStep): запускать следующий бит прямо из обработчика
    // `$.dialog` нельзя — диалог в этот момент ещё жив и «перезапуск» съел бы
    // только что открытую реплику.
    if ($.dialog && typeof $.dialog.on === 'function') {
        $.dialog.on('choice', (event) => {
            if (!run || !run.wait || run.wait.kind !== 'say') return;
            const beat = run.wait.beat;
            const options = beatChoices(beat) || [];
            const entry = options[event.index] || null;
            run.wait = null;
            if (entry) {
                applyFlags(entry, 'set');
                applyFlags(entry, 'add');
                if (typeof entry.do === 'function') {
                    try { entry.do(api, run.control); } catch (e) { report('$.timeline: выбор do()', e); }
                }
            }
            emit('choice', { beat, index: event.index, text: event.text, entry });
            const target = entry && (entry.goto !== undefined ? entry.goto : entry.to);
            if (target !== undefined && target !== null) gotoLabel(target);
            requestStep();
        });

        const finishSay = () => {
            if (!run || !run.wait || run.wait.kind !== 'say') return;
            run.wait = null;
            requestStep();
        };
        $.dialog.on('end', finishSay);
    }

    return timeline;
}

// ===========================================================================
// Объявление таймлайна
// ===========================================================================

function defineTimeline(id, spec) {
    if (!id) {
        if (ctx && typeof ctx.log === 'function') ctx.log('$.timeline.define: нужно непустое имя, например define("russi", { script: [...] })');
        return api.timeline;
    }
    if (!spec || typeof spec !== 'object' || !Array.isArray(spec.script)) {
        if (ctx && typeof ctx.log === 'function') {
            ctx.log(`$.timeline.define("${id}"): нужен массив script — [{ location: 'room' }, { say: '…' }]`);
        }
        return api.timeline;
    }

    const def = normalize(id, spec);
    definitions.set(def.id, def);

    // Реплики становятся обычным диалогом: печатная машинка, страницы,
    // выборы, i18n и клавиатура уже есть в $.dialog, дублировать их здесь
    // значило бы завести вторую правду о тексте.
    if (api.dialog && typeof api.dialog.define === 'function') {
        api.dialog.define(def.dialog, {
            nodes: def.nodes,
            start: def.nodes.start ? 'start' : Object.keys(def.nodes)[0],
            style: def.style,
            speed: def.speed,
        });
    }

    if (api.scene && typeof api.scene.add === 'function') {
        api.scene.add(def.scene, {
            enter($, opts) {
                buildStage(def);
                const pending = def.pending;
                def.pending = null;
                const start_opts = pending && pending.opts ? pending.opts : (opts || {});
                startRun(def, start_opts);
                // Хуки игры: HUD, свои узлы, подписки. Сцена таймлайна одна,
                // и без этих хуков игре пришлось бы регистрировать сцену с тем
                // же именем и затирать staging новеллы.
                if (def.onEnter) callHook('enter', def.onEnter, [api, def]);
            },
            exit() {
                if (def.onExit) callHook('exit', def.onExit, [api, def]);
                teardownStage(def);
                if (run && run.def === def) stopRun('scene');
            },
            update(dt) {
                if (def.onUpdate) callHook('update', def.onUpdate, [dt, api, def]);
            },
        });
    }

    return api.timeline;
}

function normalize(id, spec) {
    const locations = {};
    const raw_locations = spec.locations && typeof spec.locations === 'object' ? spec.locations : {};
    for (const key of Object.keys(raw_locations)) {
        const value = raw_locations[key];
        locations[key] = typeof value === 'string' ? { bg: value } : Object.assign({}, value);
    }

    const cast = {};
    const raw_cast = spec.cast && typeof spec.cast === 'object' ? spec.cast : {};
    for (const key of Object.keys(raw_cast)) {
        const value = raw_cast[key] || {};
        cast[key] = {
            who: key,
            name: value.name !== undefined ? String(value.name) : key,
            poses: value.poses && typeof value.poses === 'object' ? Object.assign({}, value.poses) : {},
            pose: value.pose ? String(value.pose) : null,
            x: num(value.x, 0.5),
            bottom: num(value.bottom, 1.0),        // 1 — низ кадра
            height: num(value.height, 0.92),       // доля высоты окна
            idle: value.idle !== false,
            mirror: value.mirror === true,
            tint: value.tint || null,
            layer: num(value.layer, 10),
        };
    }

    const script = spec.script;
    const nodes = {};
    const node_of = new Map();
    let serial = 0;

    // Проход по скрипту (включая вложенные ветки if) заводит реплики
    // в диалог и запоминает соответствие «бит → реплика».
    const walk = (list) => {
        if (!Array.isArray(list)) return;
        for (const beat of list) {
            if (beat && typeof beat === 'object') {
                const text = beat.choose !== undefined && beat.say === undefined && beat.narrate === undefined
                    ? '' : (beat.say !== undefined ? beat.say : beat.narrate);
                if (beat.say !== undefined || beat.narrate !== undefined || beat.choose !== undefined) {
                    const node_id = 'tl' + (++serial);
                    node_of.set(beat, node_id);
                    const raw_choices = beatChoices(beat);
                    nodes[node_id] = {
                        text: text === undefined ? '' : text,
                        speaker: speakerOf(beat, cast),
                        portrait: beat.portrait,
                        speed: beat.speed,
                        style: beat.style,
                        choices: raw_choices ? raw_choices.map(choiceNode) : undefined,
                        to: null,       // конец реплики = «игрок нажал дальше»
                    };
                }
                if (beat.then) walk(beat.then);
                if (beat.else) walk(beat.else);
            }
        }
    };
    walk(script);
    if (Object.keys(nodes).length === 0) nodes.start = { text: '', to: null };

    const labels = new Map();
    const collect_labels = (list) => {
        if (!Array.isArray(list)) return;
        for (const beat of list) {
            if (beat && typeof beat === 'object') {
                if (typeof beat.label === 'string') labels.set(beat.label, beat);
                if (beat.then) collect_labels(beat.then);
                if (beat.else) collect_labels(beat.else);
            }
        }
    };
    collect_labels(script);

    const cast_keys = Object.keys(cast);
    const hero = spec.hero ? String(spec.hero) : (cast_keys[0] || null);

    return {
        id: String(id),
        scene: spec.scene ? String(spec.scene) : String(id),
        dialog: spec.dialog ? String(spec.dialog) : '__timeline_' + id,
        title: spec.title ? String(spec.title) : String(id),
        backdrop: spec.backdrop || '#070a12',
        locations,
        location: spec.location ? String(spec.location) : Object.keys(locations)[0] || null,
        cast,
        hero,
        script,
        nodes,
        node_of,
        labels,
        speed: spec.speed,
        style: spec.style,
        exitScene: spec.exitScene ? String(spec.exitScene) : null,
        afterEnding: typeof spec.afterEnding === 'function' ? spec.afterEnding : null,
        onBeat: typeof spec.onBeat === 'function' ? spec.onBeat : null,
        dialog_theme: spec.dialogTheme && typeof spec.dialogTheme === 'object' ? spec.dialogTheme : null,
        // Чем рисовать реплику: узлами <ui.*> (по умолчанию) или документом
        // RmlUi. Во втором случае перенос строк, шрифт и рамку делает RmlUi,
        // а $.dialog остаётся мозгом — печатная машинка, выборы, клавиатура.
        dialog_view: normalizeDialogView(spec.dialogView),
        location_card: spec.locationCard !== false,
        // Озвучка реплик: файл на каждую реплику, имя = id её узла (tl12.mp3).
        // Нет файла — реплика просто идёт без голоса.
        voice: normalizeVoice(spec.voice, spec.hero ? String(spec.hero) : Object.keys(cast)[0]),
        onEnter: typeof spec.enter === 'function' ? spec.enter : null,
        onExit: typeof spec.exit === 'function' ? spec.exit : null,
        onUpdate: typeof spec.update === 'function' ? spec.update : null,
        pending: null,
    };
}

/**
 * Описание вида реплики. `dialogView: { kind: 'rml', doc: 'ui/vn-dialog.rml' }`
 * включает отрисовку через RmlUi; всё остальное (id элементов) имеет значения
 * по умолчанию и нужно только для нестандартной разметки.
 */
function normalizeDialogView(spec) {
    if (!spec || typeof spec !== 'object') return null;
    const kind = spec.kind || (spec.doc ? 'rml' : null);
    if (kind !== 'rml' || !spec.doc) return null;
    return {
        kind: 'rml',
        doc: String(spec.doc),
        speaker: spec.speaker ? String(spec.speaker) : 'vn-speaker',
        text: spec.text ? String(spec.text) : 'vn-text',
        choice_prefix: spec.choicePrefix ? String(spec.choicePrefix) : 'vn-choice-',
        choices: num(spec.choices, 6),
        off_class: spec.offClass ? String(spec.offClass) : 'off',
        selected_class: spec.selectedClass ? String(spec.selectedClass) : 'selected',
        handle: null,
        shown: null,
        last_speaker: undefined,
        last_text: undefined,
        last_choices: undefined,
    };
}

/**
 * Озвучка реплик.
 *
 * Раскладка нарочно простая: `<dir>/<id реплики>.<ext>`, где id — тот же, что
 * отдаёт `$.timeline.lines()`. Реплика без файла идёт молча, поэтому озвучку
 * можно дописывать по одной и в любом порядке.
 */
function normalizeVoice(spec, hero) {
    if (!spec) return null;
    const options = typeof spec === 'string' ? { dir: spec } : spec;
    if (!options || !options.dir) return null;
    return {
        dir: String(options.dir).replace(/\/+$/, ''),
        ext: options.ext ? String(options.ext) : 'mp3',
        volume: num(options.volume, 1),
        who: options.who ? String(options.who) : hero,
        channel: null,
    };
}

/** Играет ли сейчас озвучка: по ней авто-режим ждёт конца реплики. */
function voicePlaying(def) {
    const voice = def.voice;
    if (!voice || voice.channel === null || voice.channel < 0) return false;
    if (!api.sound || typeof api.sound.playing !== 'function') return false;
    return !!api.sound.playing(voice.channel);
}

/** Проиграть озвучку реплики, если файл есть. Предыдущий голос обрывается. */
function playVoice(def, who, node_id) {
    const voice = def.voice;
    if (!voice || !node_id) return;
    if (voice.who && who && voice.who !== who) return;
    if (!api.sound || !api.fs || typeof api.fs.exists !== 'function') return;
    const path = voice.dir + '/' + node_id + '.' + voice.ext;
    let exists = false;
    try { exists = api.fs.exists(path); } catch (e) { exists = false; }
    if (!exists) return;
    if (voice.channel !== null && voice.channel >= 0 && typeof api.sound.stop === 'function') {
        api.sound.stop(voice.channel, 60);
    }
    voice.channel = api.sound.play(path, { volume: voice.volume });
    emit('voice', { who, node: node_id, path });
}

function callHook(name, fn, args) {
    try {
        fn.apply(null, args);
    } catch (e) {
        report(`$.timeline: хук ${name}`, e);
    }
}

/**
 * Варианты ответа бита: `{ choose: [...] }` — основная форма,
 * `{ say: '…', choices: [...] }` — короткая запись реплики с выборами.
 * Один доступ на всех: объявление и обработчик выбора обязаны видеть одно и то же.
 */
function beatChoices(beat) {
    if (Array.isArray(beat.choose)) return beat.choose;
    if (Array.isArray(beat.choices)) return beat.choices;
    return null;
}

function speakerOf(beat, cast) {
    if (beat.who !== undefined && cast[beat.who]) return cast[beat.who].name;
    if (beat.speaker !== undefined) return beat.speaker;
    if (beat.narrate !== undefined) return '';
    const first = Object.keys(cast)[0];
    return first ? cast[first].name : '';
}

function choiceNode(entry) {
    return {
        text: entry && entry.text !== undefined ? entry.text : '',
        if: entry ? entry.if !== undefined ? entry.if : entry.when : undefined,
        action: entry ? entry.action : undefined,
        to: null,
    };
}

// ===========================================================================
// Прогон
// ===========================================================================

function startRun(def, opts) {
    stopRun('restart');
    // Карточка концовки — часть прошлого прогона: программный play() обязан
    // её убрать, иначе новый прогон идёт «под» финальным экраном.
    if (def.stage && def.stage.ending) {
        teardownEndingCard(def.stage.ending);
        def.stage.ending = null;
    }
    if (ending_view && ending_view.def === def) ending_view = null;
    const script = def.script;
    const start_at = opts && (opts.at || opts.label);
    let index = 0;
    if (start_at !== undefined && def.labels.has(String(start_at))) {
        index = script.indexOf(def.labels.get(String(start_at)));
        if (index < 0) index = 0;
    }

    run = {
        def,
        control: null,
        frames: [{ list: script, index }],
        wait: null,
        step_pending: true,
        timers: [],
        rigs: new Map(),
        location: null,
        loc_node: null,          // какой из двух фонов сейчас виден
        ending_view: null,
        auto_timer: 0,
        time: 0,
        ticks: 0,
        ended: false,
        ending: null,
        beats: 0,
    };

    buildCast(def);
    run.stage = def.stage;
    if (def.location) startLocation({ location: def.location, fade: 0 });

    emit('start', { id: def.id, scene: def.scene, at: start_at === undefined ? null : start_at });
    run.control = makeControl(def);
    return run.control;
}

function makeControl(def) {
    return {
        id: def.id,
        get location() { return run ? run.location : null; },
        state() { return runState(); },
        goto(label) { gotoLabel(label); return this; },
        next() { return api.timeline.next(); },
        choose(i) { return api.timeline.choose(i); },
        stop() { return stopRun('manual'); },
        hero(who) { return api.timeline.hero(who); },
    };
}

function stopRun(reason) {
    if (!run) return false;
    const def = run.def;
    const timers = run.timers;
    run.timers = [];
    const tweens = run.tween_handles || [];
    run.tween_handles = [];
    for (const handle of tweens) {
        try { if (handle && handle.kill) handle.kill(); } catch (e) { report('$.timeline: kill твина', e); }
    }
    if (timers.length) { /* таймеры живут в tickTimeline, достаточно очистить список */ }

    run.wait = null;
    run.step_pending = false;
    rememberRun(def, run);
    const was_ended = run.ended;
    const ending = run.ending;
    run = null;

    // Диалог закрываем после обнуления run: иначе его же событие 'end'
    // попыталось бы продолжить уже остановленный прогон.
    if (api && api.dialog && api.dialog.isOpen && api.dialog.isOpen()) api.dialog.close();

    if (!was_ended) emit('end', { id: def.id, reason: reason || 'manual', ending: ending });
    return true;
}

function gotoLabel(label) {
    if (!run || label === undefined || label === null) return false;
    const beat = run.def.labels.get(String(label));
    if (!beat) {
        if (ctx && typeof ctx.log === 'function') ctx.log(`$.timeline: метка "${label}" не найдена в "${run.def.id}"`);
        return false;
    }
    // Метка может стоять и внутри ветки `if` — тогда путь к ней собирается
    // из вложенных списков, чтобы после ветки прогон продолжился там же,
    // где продолжался бы без прыжка.
    const path = findPath(run.def.script, beat, []);
    if (!path) {
        if (ctx && typeof ctx.log === 'function') ctx.log(`$.timeline: метка "${label}" есть, но путь к ней не найден`);
        return false;
    }
    run.frames = path;
    run.wait = null;
    requestStep();
    return true;
}

function findPath(list, beat, stack) {
    for (let i = 0; i < list.length; i++) {
        const item = list[i];
        if (item === beat) return stack.concat([{ list, index: i }]);
        if (!item || typeof item !== 'object') continue;
        for (const key of ['then', 'else']) {
            if (!Array.isArray(item[key])) continue;
            const found = findPath(item[key], beat, stack.concat([{ list, index: i + 1 }]));
            if (found) return found;
        }
    }
    return null;
}

function requestStep() {
    if (run) run.step_pending = true;
}

/** Запомнить прогон: после концовки `state()` обязан рассказать, чем всё кончилось. */
function rememberRun(def, source) {
    if (!def) return;
    last_run.id = def.id;
    last_run.scene = def.scene;
    last_run.ended = !!source.ended;
    last_run.ending = source.ending ? (source.ending.id || null) : null;
    last_run.location = source.location || null;
    last_run.beats = source.beats || 0;
    last_run.ticks = source.ticks || 0;
    last_run.time = Math.round(source.time || 0);
}

/**
 * Отпустить ожидание и попросить следующий шаг.
 *
 * Именно парой: асинхронный источник (промис твина, событие диалога, дрожь)
 * срабатывает когда угодно, и «просто requestStep» не годится — шаг не
 * начнётся, пока в run.wait висит прежний hold. На этом уже ломался вход
 * героя: бит `{ show }` ждал твин, твин завершался, а прогон стоял.
 */
function releaseWait(kind) {
    if (!run) return;
    if (kind === undefined || (run.wait && run.wait.kind === kind)) run.wait = null;
    requestStep();
}

/** Продолжить прогон через wait: `run.wait.kind` — чего ждём. */
function hold(kind, data) {
    if (!run) return 'stop';
    run.wait = Object.assign({ kind }, data || {});
    return 'hold';
}

function step() {
    if (!run) return;
    let guard = 0;
    while (run && !run.wait) {
        if (++guard > 200000) {                    // защита от зацикливания скрипта
            if (ctx && typeof ctx.log === 'function') ctx.log('$.timeline: скрипт зациклился — прогон остановлен');
            stopRun('loop');
            return;
        }
        const frame = run.frames[run.frames.length - 1];
        if (!frame) { finishRun(); return; }
        if (frame.index >= frame.list.length) { run.frames.pop(); continue; }
        const beat = frame.list[frame.index++];
        run.beats++;
        const action = runBeat(beat);
        if (action === 'hold') return;
        if (action === 'stop') return;
    }
}

function finishRun() {
    if (!run) return;
    const def = run.def;
    run.ended = true;
    rememberRun(def, run);
    const ending = run.ending;
    run = null;                    // конец — значит конец: running() не врёт
    emit('end', { id: def.id, reason: 'end', ending: ending });
    if (api && api.dialog && api.dialog.isOpen && api.dialog.isOpen()) api.dialog.close();
}

// --- Биты -------------------------------------------------------------------

const NEXT = 'next';
const HOLD = 'hold';
const STOP = 'stop';

function runBeat(beat) {
    if (!run) return STOP;

    // Сахар: строка в скрипте — реплика героя по умолчанию. Так линейная
    // новелла читается как сценарий, а не как список объектов.
    if (typeof beat === 'string') return runBeat({ say: beat });
    if (typeof beat === 'function') {
        try { beat(api, run.control); } catch (e) { report('$.timeline: функция-бит', e); }
        return NEXT;
    }
    if (!beat || typeof beat !== 'object') return NEXT;

    if (run.def.onBeat) {
        try { run.def.onBeat(beat, run.control); } catch (e) { report('$.timeline: onBeat', e); }
    }
    emit('beat', { beat, count: run.beats, location: run.location });

    const flow = beat.say !== undefined || beat.narrate !== undefined || beat.choose !== undefined;

    // 1. Состояние и данные — они не занимают времени.
    applyFlags(beat, 'set');
    applyFlags(beat, 'add');

    // 2. Локация, музыка, звук.
    if (beat.location !== undefined) {
        const fade_ms = startLocation(beat);
        if (!flow && beat.wait !== false && fade_ms > 0 && beat.wait !== undefined) {
            return hold('wait', { ms: fade_ms });
        }
    }
    if (beat.music !== undefined) musicBeat(beat);
    if (beat.sfx !== undefined) sfxBeat(beat);

    // 3. Персонажи.
    if (beat.show !== undefined) return showBeat(beat);
    if (beat.hide !== undefined) return hideBeat(beat);
    if (beat.pose !== undefined) poseBeat(beat);
    if (beat.anim !== undefined) return animBeat(beat);

    // 4. Экран.
    if (beat.shake !== undefined) shakeBeat(beat);
    if (beat.flash !== undefined) flashBeat(beat);
    if (beat.fade !== undefined) {
        const fade_ms = fadeBeat(beat);
        if (!flow && fade_ms > 0) return hold('wait', { ms: fade_ms });
    }
    if (beat.zoom !== undefined) zoomBeat(beat);

    // 5. Произвольный код и события.
    if (typeof beat.do === 'function') {
        try { beat.do(api, run.control); } catch (e) { report('$.timeline: do()', e); }
    }
    if (beat.emit !== undefined) emit(String(beat.emit), beat.data || {});

    // 6. Ветвление и переходы.
    if (beat.if !== undefined) {
        const branch = conditionValue(beat.if) ? beat.then : beat.else;
        if (Array.isArray(branch) && branch.length) run.frames.push({ list: branch, index: 0 });
        return NEXT;
    }
    if (beat.goto !== undefined) { gotoLabel(beat.goto); return NEXT; }
    if (beat.ending !== undefined) return endingBeat(beat);

    // 7. Пауза и текст — то, ради чего всё остальное.
    if (beat.wait !== undefined && beat.wait !== false && !flow) return hold('wait', { ms: ms(beat.wait, 400) });
    if (beat.narrate !== undefined) return sayBeat(beat);
    if (beat.say !== undefined) return sayBeat(beat);
    if (beat.choose !== undefined) return sayBeat(beat);

    return NEXT;
}

// --- Текст ------------------------------------------------------------------

function sayBeat(beat) {
    const def = run.def;
    const node_id = def.node_of.get(beat);
    if (!node_id) return NEXT;                    // реплика без текста — не реплика
    if (!api.dialog || !api.dialog.play) return NEXT;

    const who = beat.who !== undefined ? String(beat.who) : def.hero;
    if (beat.pose !== undefined) poseBeat(beat);
    if (who && run.rigs.has(who)) {
        const rig = run.rigs.get(who);
        if (rig && !rig.el.visible) showBeat({ show: who, from: beat.from || 'fade' });
    }

    const opened = api.dialog.play(def.dialog, node_id);
    if (!opened) return NEXT;
    // Тема — украшение: если она не применилась, реплика обязана открыться.
    try { applyDialogTheme(def); } catch (e) { report('$.timeline: тема диалога', e); }
    playVoice(def, who, node_id);
    run.auto_timer = 0;
    emit('say', { who, text: typeof beat.say === 'string' ? beat.say : beat.narrate, node: node_id });
    return hold('say', { beat });
}

/**
 * Тема панели диалога: цвета, а не размеры.
 *
 * Геометрию панель пересчитывает сама каждый кадр (она растёт под число
 * вариантов), поэтому трогать x/y/w/h бессмысленно — а вот цвет фона, имя
 * говорящего и кнопки выбора живут до следующего play().
 */
function applyDialogTheme(def) {
    const theme = def.dialog_theme;
    if (!theme) return;
    // query() отдаёт массив узлов, а не обёртку: get(0) здесь — TypeError.
    const node = (id) => {
        const list = query('#' + id);
        return list && list.length ? list[0] : null;
    };
    const panel = node('__dialog');
    if (panel && theme.panel) panel.color = packColorSafe(theme.panel);
    const speaker = node('__dialog_speaker');
    if (speaker) {
        if (theme.speaker) speaker.color = packColorSafe(theme.speaker);
        if (theme.speakerSize) speaker.size = num(theme.speakerSize, speaker.size);
    }
    for (let i = 0; i < 4; i++) {
        const line = node('__dialog_line' + i);
        if (line && theme.text) line.color = packColorSafe(theme.text);
    }
    for (let i = 0; i < 6; i++) {
        const button = node('__dialog_choice' + i);
        if (!button) continue;
        // Цвет кнопок здесь НЕ ставим: $.dialog перекрашивает их каждый кадр
        // (подсветка выбранного варианта), поэтому их ведёт tickChoiceTheme.
        if (theme.choiceHover) button.hover_color = packColorSafe(theme.choiceHover);
        if (theme.choiceText) button.text_color = packColorSafe(theme.choiceText);
    }
}

/**
 * Панель диалога под крупный текст — каждый кадр, после `$.dialog`.
 *
 * `$.dialog` считает геометрию из своих констант: текстовая часть фиксированной
 * высоты, кнопки выбора стоят сразу под ней. Пока кегль был 20-22 px, это
 * сходилось; на 26 px строка перестаёт помещаться и налезает на кнопки.
 *
 * Тонкость: `updateView()` диалог зовёт не каждый кадр (пока текст печатается —
 * зовёт, после — нет). Поэтому правку нельзя ни накапливать, ни делать один раз
 * за реплику: нужна «родная» геометрия как база. База снимается при смене
 * реплики/страницы/размера окна, а дальше каждый кадр раскладка строится от неё
 * заново — тогда она идемпотентна.
 */
const dialog_layout = { key: null, base: null };
Для ускорения просмотра не вся история отображается Просмотреть всю вину