File size: 68,942 Bytes
4eecd03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
// Animated painting robot: replays the job's planned work order over the photo.
//
// It animates what the planner actually produced (job.work_order): sanding/scraping on the prep regions, spot priming, then the roller
// strokes in planned order and the trim strokes, leaving the paint it laid down. It is a visualisation of the plan, not a simulation of
// a machine: the robot is a generic mast-and-arm rig, its drive and reach are plausible motion, and nothing it shows is measured,
// approved or sent anywhere. A blocked or unplanned job has no strokes, so there is nothing to play and the button says why.
//
// What makes it read as real (all of it deterministic, so a replay or a scrub always looks the same):
//   * a two-link arm solved by inverse kinematics from a mast carriage that lags the roller, so the elbow bends and straightens as it reaches;
//   * the drive base keeps the roller inside its reach and rolls (wheel spin follows the distance driven);
//   * the roller is oriented the way a real one is: its axis is perpendicular to the stroke and its length IS the stripe it paints;
//   * the roller picks up paint at a tray (reload trips), and the paint it lays thins as the roller runs dry;
//   * fresh paint is wet (a sheen that dries to matt in ~2 s), has a faint nap texture, and now and then a drip runs from a stroke end;
//   * sanding raises dust that drifts down; arm, mast and roller cast a soft shadow on the wall.
//
// Two machines share one timeline: the ground robot above, and a tethered spray drone (like the hose-fed facade-washing drones): a quad with a boom
// nozzle, fed by a hose from a ground pump cart, so it never reloads. The drone is simulated as a spring-damper chasing the nozzle target with a
// deterministic wind sway and roll, lays a spray fan (soft overspray halo, dense core, speckle) instead of a roller stripe, and the tank on the cart
// empties as the job progresses. Still an illustration of the plan, not a flight simulation.
//
// Public surface (window.PVRobot, also used by the tests): buildTimeline(job), seek(t), play(), pause(), pose(), state(), setRig("ground"|"drone").
(() => {
  "use strict";
  const $ = (s) => document.querySelector(s);
  const REDUCED = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  const PHASE_STYLE = {
    prep: { label: "Prep: sanding and scraping", tint: "#d9a066", width: 0.55, alpha: 0.5 },
    prime: { label: "Spot priming", tint: "#e8e4dc", width: 0.7, alpha: 0.85 },
    paint: { label: "Rolling the wall", tint: null, width: 1, alpha: 0.84 },
    trim: { label: "Cutting in the edges", tint: null, width: 0.45, alpha: 0.9 },
    touch: { label: "Touch-up", tint: null, width: 0.8, alpha: 0.9 },
  };
  const DRONE_LABEL = { prep: "Prep: soft-washing the damage", prime: "Spot priming", paint: "Spraying the wall", trim: "Detail spray along the edges", touch: "Touch-up spray" };
  const els = {};
  let timeline = null;
  let t = 0, speed = 1, playing = false, raf = 0, lastTs = 0;
  let drawn = 0;
  let paintLayer = null, pctx = null, wetLayer = null, wctx = null, napPattern = null, mottlePattern = null;
  let rig = null, maskLayer = null, rollLayer = null, rctx = null, preLayer = null, qctx = null, tmpLayer = null, maskInfo = null;
  const RIG_DT = 1 / 30;
  let particles = [], lastPose = null, rigKind = "ground";

  const getJob = () => (typeof job !== "undefined" ? job : null);   // app.js declares `job` with let: a global binding, not window.job
  const dist = (a, b) => Math.hypot(b[0] - a[0], b[1] - a[1]);
  const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
  const lerp = (a, b, k) => a + (b - a) * k;
  const rng = (seed) => () => { seed |= 0; seed = (seed + 0x6D2B79F5) | 0; let r = Math.imul(seed ^ (seed >>> 15), 1 | seed); r = (r + Math.imul(r ^ (r >>> 7), 61 | r)) ^ r; return ((r ^ (r >>> 14)) >>> 0) / 4294967296; };

  // ---------------------------------------------------------------------- timeline from the work order
  function segmentsOf(strokes) {
    return (strokes || []).filter((s) => Array.isArray(s) && s.length === 2 && s.every((p) => Array.isArray(p) && p.length === 2))
      .map(([a, b]) => ({ kind: "seg", x0: a[0], y0: a[1], x1: b[0], y1: b[1], len: dist(a, b) }));
  }
  function reasonNoPlan(wo) {
    if (wo.status === "blocked") return "This job is blocked, so there is no paint plan to show. Resolve the reasons listed on the right first.";
    if (!(wo.steps || []).some((s) => s.step === "paint")) return "There is no paint step in this work order yet.";
    return "The plan has no roller strokes to animate.";
  }
  function buildTimeline(j, totalSeconds = 18, opts = {}) {
    const wo = (j && j.work_order) || {};
    const W = (j && j.width) || 800, H = (j && j.height) || 600, u = Math.max(W, H) / 900;
    const raw = [];
    const widthPx = (step) => Math.max(6, Number(step.plan && step.plan.plan && step.plan.plan.stroke_width_units) || 0.04 * W);
    for (const step of wo.steps || []) {
      if (step.step === "prep") raw.push({ kind: "prep", segs: (step.tasks || []).flatMap((x) => segmentsOf(x.strokes_px)) });
      else if (step.step === "spot_prime") raw.push({ kind: "prime", segs: (step.tasks || []).flatMap((x) => segmentsOf(x.strokes_px)) });
      else if (step.step === "paint" && step.plan && step.plan.plan) {
        raw.push({ kind: "paint", segs: segmentsOf(step.plan.plan.strokes), widthPx: widthPx(step) });
        raw.push({ kind: "trim", segs: segmentsOf((step.plan.plan.trim || {}).strokes), widthPx: widthPx(step) });
      } else if (step.step === "touch_up") raw.push({ kind: "touch", segs: (step.tasks || []).flatMap((x) => segmentsOf(x.strokes_px)) });
    }
    const phases = raw.filter((p) => p.segs.length);
    if (!phases.some((p) => p.kind === "paint")) return { phases: [], items: [], total: 0, reloads: 0, reason: reasonNoPlan(wo) };

    const tray = { x: 0.115 * W, y: H - 46 * u };           // a paint tray standing on the floor at the left of the picture
    let reloads = 0, cursor = null;
    const items = [];
    const rand = rng(1234), toneRand = rng(555);
    let segIdx = 0;
    for (const p of phases) {
      const rollerKind = p.kind === "paint" || p.kind === "trim" || p.kind === "touch";
      const every = opts.drone ? 1e9 : p.kind === "paint" ? Math.max(5, Math.ceil(p.segs.length / 5)) : p.kind === "trim" ? Math.max(14, Math.ceil(p.segs.length / 3)) : 1e9;
      p.track = [];
      p.width = (p.widthPx || Math.max(8, 0.022 * W)) * PHASE_STYLE[p.kind].width;
      let sinceLoad = 0;
      const addMove = (from, to, kind) => { const d = dist(from, to); if (d > 2) p.track.push({ kind, x0: from[0], y0: from[1], x1: to[0], y1: to[1], len: d, w: kind === "reload" ? 0.45 : 0.4 }); };
      p.segs.forEach((s) => {
        if (rollerKind && sinceLoad >= every) {          // run dry: go to the tray, dip, come back
          if (cursor) addMove(cursor, [tray.x, tray.y], "reload");
          p.track.push({ kind: "dip", x0: tray.x, y0: tray.y, x1: tray.x, y1: tray.y, len: 0, dip: true });
          cursor = [tray.x, tray.y]; sinceLoad = 0; reloads++;
        }
        if (cursor) addMove(cursor, [s.x0, s.y0], "move");
        s.load = rollerKind && !opts.drone ? 1 - 0.38 * (sinceLoad / Math.max(every, 1)) : 1;
        s.tone = 0.9 + 0.1 * toneRand(); s.idx = segIdx++;      // per-stroke tone, so overlaps and laps show
        // seeded, rare drips off the end of a heavily-loaded horizontal stroke
        if (!opts.drone && p.kind === "paint" && Math.abs(s.x1 - s.x0) > Math.abs(s.y1 - s.y0) && s.load > 0.92 && rand() < 0.09)
          s.drip = { x: lerp(s.x0, s.x1, 0.8 + 0.2 * rand()), y: s.y0 + p.width / 2, len: (16 + 24 * rand()) * u };
        p.track.push(s);
        cursor = [s.x1, s.y1];
        sinceLoad++;
      });
      p.track.forEach((x) => { x.phase = p; });
      items.push(...p.track);
    }
    // time: strokes by length; transits are quicker; a dip takes a fixed beat; prep passes are lighter
    const strokeLen = items.filter((x) => x.kind === "seg").reduce((a, x) => a + x.len, 0) || 1;
    const dipW = 0.045 * strokeLen;
    const weight = items.map((x) => (x.kind === "seg" ? x.len * (x.phase.kind === "prep" ? 0.6 : 1) : x.dip ? dipW : x.len * x.w));
    const gap = 0.55;
    const sum = weight.reduce((a, b) => a + b, 0);
    const budget = totalSeconds - gap * (phases.length - 1);
    let clock = 0, phaseOf = null;
    items.forEach((x, i) => {
      if (phaseOf && x.phase !== phaseOf) clock += gap;
      phaseOf = x.phase;
      x.t0 = clock; clock += budget * (weight[i] / sum); x.t1 = clock;
    });
    phases.forEach((p) => { p.segs = p.track.filter((x) => x.kind === "seg"); p.t0 = p.track[0].t0; p.t1 = p.track[p.track.length - 1].t1; p.label = opts.drone ? DRONE_LABEL[p.kind] : PHASE_STYLE[p.kind].label; });
    return { phases, items, total: clock, reloads, tray, W, drone: !!opts.drone };
  }

  // ---------------------------------------------------------------------- paint left behind (matt layer + wet sheen layer)
  function paintColour() {
    const c = (getJob() && getJob().paint_color) || {};
    const ref = c.reference;      // only a TARGET colour the job names; the wall's own detected colour would repaint it invisibly
    const rgb = ref && (ref.rgb || ref.srgb);
    return Array.isArray(rgb) ? [rgb[0] | 0, rgb[1] | 0, rgb[2] | 0] : [70, 150, 255];
  }
  function makeNap() {
    const c = document.createElement("canvas"); c.width = c.height = 96;
    const x = c.getContext("2d"), r = rng(77), img = x.createImageData(96, 96);
    for (let i = 0; i < img.data.length; i += 4) { const v = 120 + (r() * 90) | 0; img.data[i] = img.data[i + 1] = img.data[i + 2] = v; img.data[i + 3] = 255; }
    x.putImageData(img, 0, 0);
    return c;
  }
  function makeMottle() {                                  // low-frequency blotches: uneven film thickness
    const c = document.createElement("canvas"); c.width = c.height = 192;
    const x = c.getContext("2d"), r = rng(31);
    x.fillStyle = "#b4b4b4"; x.fillRect(0, 0, 192, 192);
    for (let i = 0; i < 160; i++) {
      const cx = r() * 192, cy = r() * 192, rad = 8 + r() * 26, v = 90 + (r() * 140) | 0;
      for (const ox of [-192, 0, 192]) for (const oy of [-192, 0, 192]) {
        const g = x.createRadialGradient(cx + ox, cy + oy, 0, cx + ox, cy + oy, rad); g.addColorStop(0, `rgba(${v},${v},${v},.55)`); g.addColorStop(1, `rgba(${v},${v},${v},0)`);
        x.fillStyle = g; x.fillRect(cx + ox - rad, cy + oy - rad, rad * 2, rad * 2);
      }
    }
    return c;
  }
  function resetLayers() {
    const j = getJob();
    for (const k of ["paint", "wet"]) {
      const c = document.createElement("canvas"); c.width = j.width; c.height = j.height;
      const x = c.getContext("2d"); x.lineCap = "round"; x.lineJoin = "round";
      if (k === "paint") { paintLayer = c; pctx = x; } else { wetLayer = c; wctx = x; }
    }
    napPattern = pctx.createPattern(makeNap(), "repeat");
    mottlePattern = pctx.createPattern(makeMottle(), "repeat");
    rollLayer = document.createElement("canvas"); rollLayer.width = j.width; rollLayer.height = j.height;
    rctx = rollLayer.getContext("2d"); rctx.lineCap = "round"; rctx.lineJoin = "round";
    preLayer = document.createElement("canvas"); preLayer.width = j.width; preLayer.height = j.height;
    qctx = preLayer.getContext("2d"); qctx.lineCap = "round"; qctx.lineJoin = "round";
    tmpLayer = document.createElement("canvas"); tmpLayer.width = j.width; tmpLayer.height = j.height;
    drawn = 0; particles = [];
  }
  // Rolled wall paint goes on its own layer so it can be clipped to where the plan says paint may go (a roller's round ends and the planner's stroke
  // width would otherwise paint over windows and keep-out areas); prep/prime sit under it; trim and touch-up sit over it and are not clipped (trim runs along the edges).
  const ctxOf = (s) => (s.phase.kind === "paint" ? rctx : s.phase.kind === "prep" || s.phase.kind === "prime" ? qctx : pctx);
  function buildMask(j) {
    const c = document.createElement("canvas"); c.width = j.width; c.height = j.height;
    const x = c.getContext("2d");
    const layer = (name) => document.querySelector(`#stage img.layer[data-layer="${name}"]:not(.edge)`);
    const grab = (img) => {
      if (!img || !img.complete || !img.naturalWidth) return null;
      const t = document.createElement("canvas"); t.width = j.width; t.height = j.height;
      const tx = t.getContext("2d"); tx.drawImage(img, 0, 0, j.width, j.height);
      return tx.getImageData(0, 0, j.width, j.height).data;
    };
    const paint = grab(layer("paint")), keep = grab(layer("keepout"));
    if (!paint) return null;                                           // no paint layer to clip to: paint unclipped rather than hide everything
    const out = x.createImageData(j.width, j.height), d = out.data;
    let allowed = 0;
    for (let i = 0; i < d.length; i += 4) {
      const ok = paint[i + 3] > 0 && !(keep && keep[i + 3] > 0);
      d[i + 3] = ok ? 255 : 0; if (ok) allowed++;
    }
    x.putImageData(out, 0, 0);
    maskInfo = { allowed_px: allowed, total_px: j.width * j.height };
    return c;
  }
  // One stretch of a stroke with hard (butt) ends, so consecutive slices abut without a darker bead where translucent round caps would overlap. A round
  // end cap is added only at the true start or end of the stroke, as a half disc facing outward so it never doubles up on the body.
  function seg(c, ax, ay, bx, by, w, capStart, capEnd) {
    const dx = bx - ax, dy = by - ay, m = Math.hypot(dx, dy), th = Math.atan2(dy, dx);
    c.lineCap = "butt"; c.lineWidth = w;
    if (m > 1e-6) { const ux = dx / m, uy = dy / m, e = capStart ? 0 : 0.6; c.beginPath(); c.moveTo(ax - ux * e, ay - uy * e); c.lineTo(bx, by); c.stroke(); }
    if (capStart || capEnd) {
      c.fillStyle = c.strokeStyle;
      if (m <= 1e-6) { c.beginPath(); c.arc(ax, ay, w / 2, 0, Math.PI * 2); c.fill(); return; }
      if (capStart) { c.beginPath(); c.arc(ax, ay, w / 2, th + Math.PI / 2, th + 1.5 * Math.PI); c.fill(); }
      if (capEnd) { c.beginPath(); c.arc(bx, by, w / 2, th - Math.PI / 2, th + Math.PI / 2); c.fill(); }
    }
  }
  // Split [a,b] (fractions of a stroke) into pieces whose edges do not depend on how the time slices fall: fine cells near each end, where a roller
  // or fan tails off, and one piece between. fn(p0, p1, taper) gets the fractions and an ink multiplier from 0.55 at the very end to 1 inside.
  function pieces(len, a, b, u, fn) {
    const tail = Math.min(0.07 * len, 30 * u), step = 3.5 * u, cuts = [0];
    if (tail > step * 2) { for (let d = step; d < tail; d += step) cuts.push(d / len); cuts.push(tail / len, 1 - tail / len); for (let d = tail - step; d > 0; d -= step) cuts.push(1 - d / len); }
    cuts.push(1);
    for (let k = 0; k + 1 < cuts.length; k++) {
      const p0 = Math.max(cuts[k], a), p1 = Math.min(cuts[k + 1], b);
      if (p1 <= p0 + 1e-9) continue;
      const pm = (cuts[k] + cuts[k + 1]) / 2 * len, e = tail > 0 ? Math.min(pm / tail, (len - pm) / tail, 1) : 1, sm = e * e * (3 - 2 * e);
      fn(p0, p1, 0.55 + 0.45 * sm);
    }
  }
  function bake(from, to) {
    const rgb = paintColour();
    const col = (a) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${a})`;
    const u = Math.max(timeline.W || 800, 1) / 900;
    for (const s of timeline.items) {
      if (s.kind !== "seg" || s.t1 <= from || s.t0 >= to) continue;
      const st = PHASE_STYLE[s.phase.kind];
      const pctx = ctxOf(s);
      const span = Math.max(s.t1 - s.t0, 1e-9);
      const a = clamp((from - s.t0) / span, 0, 1), b = clamp((to - s.t0) / span, 0, 1);
      const w = s.phase.width, kind = s.phase.kind, len = Math.max(s.len, 1e-6);
      const dx = s.x1 - s.x0, dy = s.y1 - s.y0;
      const at = (f) => [s.x0 + dx * f, s.y0 + dy * f];
      pctx.globalCompositeOperation = "source-over"; pctx.globalAlpha = 1;
      if (timeline.drone && !st.tint) { sprayBake(pctx, s, a, b, w, rgb); }
      else pieces(len, a, b, u, (p0, p1, tp) => {
        const [ax, ay] = at(p0), [bx, by] = at(p1), flat = kind === "paint" && !timeline.drone;          // a roller stops with a straight edge; a brush or fan rounds off
        const cs = !flat && p0 <= 1e-9, ce = !flat && p1 >= 1 - 1e-9;
        pctx.strokeStyle = st.tint ? st.tint : col(st.alpha * s.load * s.tone * tp * (kind === "prep" ? 0.6 : 1));
        seg(pctx, ax, ay, bx, by, w, cs, ce);
        if (!st.tint || kind === "prime") {         // a soft lighter core, the nap texture and a blotchy mottle: a roller does not lay a flat colour
          pctx.strokeStyle = "rgba(255,255,255,0.10)"; seg(pctx, ax, ay, bx, by, w * 0.55, cs, ce);
          pctx.globalCompositeOperation = "multiply";
          pctx.strokeStyle = napPattern; pctx.globalAlpha = 0.16; seg(pctx, ax, ay, bx, by, w * 0.92, cs, ce);
          if (mottlePattern) { pctx.strokeStyle = mottlePattern; pctx.globalAlpha = 0.12; seg(pctx, ax, ay, bx, by, w * 0.98, cs, ce); }
          pctx.globalCompositeOperation = "source-over"; pctx.globalAlpha = 1;
        }
        if (kind === "paint") ridges(pctx, ax, ay, bx, by, w);
        if (kind === "trim") bristles(pctx, s, p0, p1, w, rgb, u);
        if (kind === "paint" || kind === "trim") wetStreak(s, ax, ay, bx, by, w, u, cs, ce);
      });
      if (timeline.drone && (kind === "paint" || kind === "trim")) pieces(len, a, b, u, (p0, p1) => { const [ax, ay] = at(p0), [bx, by] = at(p1); wetStreak(s, ax, ay, bx, by, w * 0.8, u, p0 <= 1e-9, p1 >= 1 - 1e-9); });
    }
    for (const s of timeline.items) {                                    // drips grow after their stroke ends
      if (!s.drip) continue;
      const g0 = clamp((from - s.t1) / 1.6, 0, 1), g1 = clamp((to - s.t1) / 1.6, 0, 1);
      if (g1 <= g0) continue;
      const pctx = rctx;
      pctx.strokeStyle = col(0.8 * s.load); pctx.lineWidth = 2.6 * u; pctx.lineCap = "round";
      pctx.beginPath(); pctx.moveTo(s.drip.x, s.drip.y + s.drip.len * g0); pctx.lineTo(s.drip.x, s.drip.y + s.drip.len * g1); pctx.stroke();
      pctx.fillStyle = col(0.85 * s.load); pctx.beginPath(); pctx.arc(s.drip.x, s.drip.y + s.drip.len * g1, 2.4 * u, 0, Math.PI * 2); pctx.fill();
      pctx.fillStyle = "rgba(255,255,255,0.22)"; pctx.beginPath(); pctx.arc(s.drip.x - 0.7 * u, s.drip.y + s.drip.len * g1 - 0.8 * u, 0.9 * u, 0, Math.PI * 2); pctx.fill();   // glint on the bead
    }
    rctx.globalAlpha = 1; qctx.globalAlpha = 1; pctx.globalAlpha = 1;
  }
  // Wet paint catches the light: a broad sheen plus a thin hard highlight toward the light (up and left). Both dry away in render().
  function wetStreak(s, ax, ay, bx, by, w, u, cs, ce) {
    const dx = bx - ax, dy = by - ay, m = Math.hypot(dx, dy) || 1;
    let nx = -dy / m, ny = dx / m; if (nx + ny > 0) { nx = -nx; ny = -ny; }
    wctx.globalAlpha = 1;
    wctx.strokeStyle = "rgba(255,255,255,0.24)"; seg(wctx, ax, ay, bx, by, w * 0.7, cs, ce);
    wctx.strokeStyle = "rgba(255,255,255,0.46)"; seg(wctx, ax + nx * w * 0.2, ay + ny * w * 0.2, bx + nx * w * 0.2, by + ny * w * 0.2, Math.max(1.4 * u, w * 0.14), cs, ce);
  }
  // A brush cutting in leaves bristle streaks: a few thin lines of varying density that follow the stroke, placed from a hash so they never change on replay.
  function bristles(c, s, p0, p1, w, rgb, u) {
    const dx = s.x1 - s.x0, dy = s.y1 - s.y0, len = Math.max(s.len, 1e-6), nx = -dy / len, ny = dx / len;
    for (let k = 0; k < 6; k++) {
      const r = rng((s.idx + 3) * 2654435 + k * 97), off = (r() - 0.5) * w * 0.86, dark = r() < 0.5;
      c.strokeStyle = dark ? `rgba(${rgb[0] * 0.7 | 0},${rgb[1] * 0.7 | 0},${rgb[2] * 0.7 | 0},${0.12 + 0.12 * r()})` : "rgba(255,255,255,0.14)";
      c.beginPath(); c.moveTo(s.x0 + dx * p0 + nx * off, s.y0 + dy * p0 + ny * off); c.lineTo(s.x0 + dx * p1 + nx * off, s.y0 + dy * p1 + ny * off);
      c.lineWidth = (0.7 + 0.9 * r()) * u; c.lineCap = "butt"; c.stroke();
    }
  }

  // A roller leaves a faint ridge of paint along both edges of its stripe; where stripes overlap these show as the lap marks you see on a rolled wall.
  function ridges(c, ax, ay, bx, by, w) {
    const dx = bx - ax, dy = by - ay, m = Math.hypot(dx, dy); if (m < 0.5) return;
    const nx = -dy / m, ny = dx / m, o = w * 0.49, u = Math.max(timeline.W || 800, 1) / 900;
    for (const side of [-1, 1]) {
      c.strokeStyle = "rgba(0,0,0,0.07)"; c.lineWidth = 1.5 * u;
      c.beginPath(); c.moveTo(ax + nx * o * side, ay + ny * o * side); c.lineTo(bx + nx * o * side, by + ny * o * side); c.stroke();
      c.strokeStyle = "rgba(255,255,255,0.09)"; c.lineWidth = 1 * u;
      c.beginPath(); c.moveTo(ax + nx * (o - 2 * u) * side, ay + ny * (o - 2 * u) * side); c.lineTo(bx + nx * (o - 2 * u) * side, by + ny * (o - 2 * u) * side); c.stroke();
    }
  }
  // Spray: a soft overspray halo, the fan itself, a dense core, and speckle placed on a fixed lattice along the stroke (hashed by stroke and step) so a
  // scrub or replay lays exactly the same droplets however the time slices fall.
  function sprayBake(c, s, a, b, w, rgb) {
    const col = (al) => `rgba(${rgb[0]},${rgb[1]},${rgb[2]},${al})`, u = Math.max(timeline.W || 800, 1) / 900;
    const k = s.load * s.tone, trim = s.phase.kind === "trim", len = Math.max(s.len, 1e-6), dx = s.x1 - s.x0, dy = s.y1 - s.y0;
    const nx = -dy / len, ny = dx / len, at = (f) => [s.x0 + dx * f, s.y0 + dy * f];
    c.globalCompositeOperation = "source-over"; c.globalAlpha = 1;
    pieces(len, a, b, u, (p0, p1, tp) => {                      // overspray halo, the fan itself, a dense core; all feather out at the ends of a pass
      const [ax, ay] = at(p0), [bx, by] = at(p1), cs = p0 <= 1e-9, ce = p1 >= 1 - 1e-9;
      c.strokeStyle = col(0.09 * k * tp); seg(c, ax, ay, bx, by, w * 1.55, cs, ce);
      c.strokeStyle = col((trim ? 0.62 : 0.5) * k * tp); seg(c, ax, ay, bx, by, w, cs, ce);
      c.strokeStyle = col(0.22 * k * tp); seg(c, ax, ay, bx, by, w * 0.5, cs, ce);
    });
    const sp = 4 * u, k0 = Math.ceil(a * len / sp), k1 = Math.floor(b * len / sp);        // speckle on a fixed lattice, hashed by stroke and step
    for (let q = k0; q <= k1; q++) {
      const r = rng((s.idx + 1) * 7919 + q * 104729), f = q * sp / len, cx = s.x0 + dx * f, cy = s.y0 + dy * f;
      for (let n = 0; n < 3; n++) {
        const off = (r() + r() - 1) * w * 0.95, rad = (0.5 + r() * 1.1) * u;
        c.fillStyle = col(0.35 + 0.4 * r());
        c.beginPath(); c.arc(cx + nx * off, cy + ny * off, rad, 0, Math.PI * 2); c.fill();
      }
    }
  }

  // ---------------------------------------------------------------------- where the roller is
  function headAt(time) {
    const items = timeline.items;
    let lo = 0, hi = items.length - 1, found = -1;
    while (lo <= hi) { const mid = (lo + hi) >> 1; if (items[mid].t0 <= time) { found = mid; lo = mid + 1; } else hi = mid - 1; }
    if (found < 0) return null;
    const s = items[found], ph = s.phase;
    if (time > s.t1 + 1e-9) return { x: s.x1, y: s.y1, kind: ph.kind, item: "idle", label: ph.label, vx: 0, vy: 0, idle: true, p: ph };
    const u = (time - s.t0) / Math.max(s.t1 - s.t0, 1e-9);
    const ease = s.kind === "seg" ? u : u * u * (3 - 2 * u);               // transits ease in and out; strokes are steady
    const label = s.kind === "reload" || s.kind === "dip" ? "Reloading the roller" : ph.label;
    return { x: lerp(s.x0, s.x1, ease), y: lerp(s.y0, s.y1, ease), kind: ph.kind, item: s.kind, label, vx: s.x1 - s.x0, vy: s.y1 - s.y0,
      idle: false, painting: s.kind === "seg", p: ph, seg: s, u };
  }

  // ---------------------------------------------------------------------- pose: drive base, mast carriage, two-link arm by IK
  // The rig's state (drive position, mast carriage height, wheel and roller spin) depends on where it has been, so it is simulated ONCE at open() into a
  // table at 30 Hz and looked up by time. That is what makes a scrub or a replay show exactly the same picture as playing straight through.
  function stepRig(st, head, W, H) {
    const u = Math.max(W, H) / 900;
    const floor = H - 14 * u;
    const L1 = 0.145 * W, L2 = 0.145 * W;
    const tx = head ? head.x : st.x + 80 * u, ty = head ? head.y : H * 0.55;
    const near = 0.30 * (L1 + L2), far = 0.82 * (L1 + L2);
    let want = st.x;
    if (tx - st.x > far) want = tx - far; else if (st.x - tx > far) want = tx + far; else if (Math.abs(tx - st.x) < near) want = st.x + (tx >= st.x ? -1 : 1) * 0.15 * near;
    want = clamp(want, 0.06 * W, 0.94 * W);
    const moved = (want - st.x) * 0.075;
    st.x += moved; st.wheel += moved / (9 * u);
    st.cy += (clamp(ty, 40 * u, floor - 70 * u) - st.cy) * 0.07;
    if (head && !head.idle && head.item === "seg") st.spin += RIG_DT * 90 * u;
  }
  function buildRig(j) {
    const st = { x: j.width * 0.14, cy: j.height * 0.5, wheel: 0, spin: 0 };
    const n = Math.ceil(timeline.total / RIG_DT) + 1, table = [];
    for (let i = 0; i <= n; i++) { stepRig(st, headAt(i * RIG_DT), j.width, j.height); table.push({ x: st.x, cy: st.cy, wheel: st.wheel, spin: st.spin }); }
    return table;
  }
  function rigAt(time) {
    const f = clamp(time / RIG_DT, 0, rig.length - 1), i = Math.floor(f), k = f - i, a = rig[i], b = rig[Math.min(i + 1, rig.length - 1)];
    return { x: lerp(a.x, b.x, k), cy: lerp(a.cy, b.cy, k), wheel: lerp(a.wheel, b.wheel, k), spin: lerp(a.spin, b.spin, k) };
  }

  function solvePose(head, W, H) {
    const u = Math.max(W, H) / 900;
    const floor = H - 14 * u;
    const L1 = 0.145 * W, L2 = 0.145 * W, maxReach = (L1 + L2) * 0.93;
    const st = rigAt(t);
    const tx = head ? head.x : st.x + 80 * u, ty = head ? head.y : H * 0.55;
    const sx = st.x, sy = st.cy;
    let dx = tx - sx, dy = ty - sy, d = Math.hypot(dx, dy);
    if (d > maxReach) { const k = maxReach / d; dx *= k; dy *= k; d = maxReach; }
    const wx = sx + dx, wy = sy + dy;                                    // wrist (the roller frame hangs from here)
    const dd = clamp(d, Math.abs(L1 - L2) + 1, L1 + L2 - 1);             // two-link IK by the law of cosines, elbow bent upward
    const a = (L1 * L1 - L2 * L2 + dd * dd) / (2 * dd), hgt = Math.sqrt(Math.max(L1 * L1 - a * a, 0));
    const ux = dx / (d || 1), uy = dy / (d || 1);
    const side = ux >= 0 ? 1 : -1;
    const ex = sx + ux * a + uy * hgt * side, ey = sy + uy * a - ux * hgt * side;
    return { u, floor, L1, L2, base: { x: st.x, y: floor }, shoulder: { x: sx, y: sy }, elbow: { x: ex, y: ey }, wrist: { x: wx, y: wy },
      head: { x: tx, y: ty }, reach: d, maxReach, wheel: st.wheel, spin: st.spin };
  }


  // ---------------------------------------------------------------------- the drone: simulated once, like the ground rig
  // Body hovers above its nozzle. A spring-damper (slightly under-damped, so it overshoots a little at stroke ends) chases the target, a slow
  // two-tone gust sways it, and it rolls into its acceleration the way a quad does.
  const droneTarget = (head, st, W, H, u) => ({ x: head ? head.x : W * 0.14, y: (head ? head.y : H * 0.5) - 52 * u });
  function buildDrone(j) {
    const W = j.width, H = j.height, u = Math.max(W, H) / 900, n = Math.ceil(timeline.total / RIG_DT) + 1, table = [];
    const g = droneTarget(headAt(0), null, W, H, u);
    const st = { x: g.x, y: g.y, vx: 0, vy: 0, roll: 0, rotor: 0, d: 1, kick: 0, wasSpraying: false };
    const k = 70, c = 11;
    for (let i = 0; i <= n; i++) {
      const tt = i * RIG_DT, tg = droneTarget(headAt(tt), st, W, H, u), wind = windAt(tt);
      const ax = k * (tg.x - st.x) - c * st.vx + wind.fx * u * 40, ay = k * (tg.y - st.y) - c * st.vy + wind.fy * u * 40;
      st.vx += ax * RIG_DT; st.vy += ay * RIG_DT; st.x += st.vx * RIG_DT; st.y += st.vy * RIG_DT;
      const wantRoll = clamp(st.vx / (260 * u) * 0.3 + wind.fx * 0.05, -0.32, 0.32);
      st.roll += (wantRoll - st.roll) * 0.18; st.rotor += RIG_DT * 55;
      const hd = headAt(tt), spraying = !!(hd && !hd.idle && hd.item === "seg");
      // The gun's recoil: at trigger open the jet shoves the airframe off the wall, then it settles (drone_path's kick).
      // Standoff: it closes on the wall to spray, backs off in transit, and rides a little further out while the jet runs.
      if (spraying && !st.wasSpraying) st.kick = 0.22;
      st.wasSpraying = spraying;
      st.kick *= Math.exp(-RIG_DT / 0.35);
      const dT = (spraying ? 0.4 : 1) + st.kick;
      st.d += (dT - st.d) * 0.09;
      table.push({ x: st.x, y: st.y, roll: st.roll, rotor: st.rotor, vx: st.vx, d: st.d, kick: st.kick });
    }
    return table;
  }
  const windAt = (tt) => ({ fx: Math.sin(tt * 0.9) * 0.6 + Math.sin(tt * 2.3 + 1) * 0.3, fy: Math.sin(tt * 1.3 + 2) * 0.35 });
  function droneAt(time) {
    const f = clamp(time / RIG_DT, 0, rig.length - 1), i = Math.floor(f), k = f - i, a = rig[i], b = rig[Math.min(i + 1, rig.length - 1)];
    return { x: lerp(a.x, b.x, k), y: lerp(a.y, b.y, k), roll: lerp(a.roll, b.roll, k), rotor: lerp(a.rotor, b.rotor, k), vx: lerp(a.vx, b.vx, k), d: lerp(a.d, b.d, k) };
  }
  function drawCart(ctx, u, H, rgb, frac, live, dr) {
    const cx = 0.085 * timeline.W, floor = H - 14 * u, w = 104 * u, h = 58 * u, x = cx - w / 2, y = floor - h - 12 * u;
    ctx.fillStyle = "rgba(0,0,0,.3)"; ctx.beginPath(); ctx.ellipse(cx, floor + 3 * u, w * 0.62, 6 * u, 0, 0, Math.PI * 2); ctx.fill();
    for (const wx of [x + 16 * u, x + w - 16 * u]) {                                          // wheels
      const g = ctx.createRadialGradient(wx - 2 * u, floor - 8 * u, 1, wx, floor - 6 * u, 11 * u); g.addColorStop(0, "#5b626d"); g.addColorStop(1, "#23272f");
      ctx.fillStyle = g; ctx.beginPath(); ctx.arc(wx, floor - 7 * u, 10 * u, 0, Math.PI * 2); ctx.fill();
      ctx.fillStyle = "#b9c0cb"; ctx.beginPath(); ctx.arc(wx, floor - 7 * u, 3.4 * u, 0, Math.PI * 2); ctx.fill();
    }
    const g = ctx.createLinearGradient(0, y, 0, y + h); g.addColorStop(0, "#fbfbfc"); g.addColorStop(0.6, "#dfe4ea"); g.addColorStop(1, "#aeb6c2");
    ctx.fillStyle = g; rr(ctx, x, y, w, h, 8 * u); ctx.fill(); ctx.strokeStyle = "rgba(0,0,0,.4)"; ctx.lineWidth = 1.5 * u; ctx.stroke();
    const tx = x + 8 * u, ty = y + 7 * u, tw = 38 * u, th = h - 14 * u;                         // paint tank with a level window
    ctx.fillStyle = "#1d2128"; rr(ctx, tx, ty, tw, th, 5 * u); ctx.fill();
    const lvl = th * (0.06 + 0.88 * (1 - 0.8 * frac));
    ctx.save(); rr(ctx, tx + 2 * u, ty + 2 * u, tw - 4 * u, th - 4 * u, 4 * u); ctx.clip();
    ctx.fillStyle = `rgb(${rgb[0]},${rgb[1]},${rgb[2]})`; ctx.fillRect(tx, ty + th - lvl, tw, lvl);
    ctx.fillStyle = "rgba(255,255,255,.28)"; ctx.fillRect(tx, ty + th - lvl, tw, 2.5 * u);
    ctx.fillStyle = "rgba(255,255,255,.14)"; ctx.fillRect(tx + 4 * u, ty, 5 * u, th);
    ctx.restore();
    const gx = x + 66 * u, gy = y + 20 * u, gr = 12 * u;                                       // pressure gauge: needle jitters while pumping
    ctx.fillStyle = "#f3f5f8"; ctx.beginPath(); ctx.arc(gx, gy, gr, 0, Math.PI * 2); ctx.fill(); ctx.strokeStyle = "#454c58"; ctx.lineWidth = 1.6 * u; ctx.stroke();
    const ang = (live ? -0.4 + 0.12 * Math.sin(dr.rotor * 0.9) : -1.9) + 0.6; ctx.strokeStyle = "#d0301f"; ctx.lineWidth = 1.8 * u;
    ctx.beginPath(); ctx.moveTo(gx, gy); ctx.lineTo(gx + Math.cos(ang) * gr * 0.8, gy + Math.sin(ang) * gr * 0.8); ctx.stroke();
    ctx.fillStyle = live ? "#0a84ff" : "#30d158"; ctx.globalAlpha = live ? 0.65 + 0.35 * Math.sin(performance.now() / 150) : 1;
    rr(ctx, x + 56 * u, y + 40 * u, 28 * u, 5 * u, 2.5 * u); ctx.fill(); ctx.globalAlpha = 1;
    ctx.fillStyle = "#1d1d1f"; ctx.font = `700 ${9 * u}px -apple-system, Helvetica, Arial, sans-serif`; ctx.fillText("PV-D", x + w - 28 * u, y + h - 5 * u);
    const rx = cx + 4 * u, ry = y - 9 * u, rrad = 15 * u;                                       // hose reel on top, spokes turn as hose pays out
    ctx.fillStyle = "#2b303a"; ctx.beginPath(); ctx.arc(rx, ry, rrad, 0, Math.PI * 2); ctx.fill();
    ctx.strokeStyle = "#7b8594"; ctx.lineWidth = 1.5 * u; ctx.stroke();
    for (let q = 0; q < 6; q++) { const a = dr.x * 0.012 + q * Math.PI / 3; ctx.beginPath(); ctx.moveTo(rx, ry); ctx.lineTo(rx + Math.cos(a) * rrad * 0.85, ry + Math.sin(a) * rrad * 0.85); ctx.stroke(); }
    return { x: rx + rrad * 0.2, y: ry - rrad * 0.6 };                                           // hose leaves the reel here
  }
  function drawHose(ctx, a, b, u, tt) {
    const L = Math.hypot(b.x - a.x, b.y - a.y), sag = 0.14 * L + 26 * u, bow = Math.sin(tt * 0.9) * 8 * u;
    const mx = (a.x + b.x) / 2 + bow, my = (a.y + b.y) / 2 + sag * 1.6;
    const path = () => { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.quadraticCurveTo(mx, my, b.x, b.y); };
    ctx.lineCap = "round";
    ctx.save(); ctx.translate(20 * u, 26 * u); ctx.strokeStyle = "rgba(0,0,0,.16)"; ctx.lineWidth = 7 * u; path(); ctx.stroke(); ctx.restore();   // shadow on the wall
    ctx.strokeStyle = "#1f2a35"; ctx.lineWidth = 6.2 * u; path(); ctx.stroke();
    ctx.strokeStyle = "#566a80"; ctx.lineWidth = 2 * u; ctx.save(); ctx.translate(-1 * u, -1.4 * u); path(); ctx.stroke(); ctx.restore();
    ctx.setLineDash([3 * u, 26 * u]); ctx.strokeStyle = "#ffcf3d"; ctx.lineWidth = 6.4 * u; path(); ctx.stroke(); ctx.setLineDash([]);   // tape bands every few metres
  }
  function drawDrone(ctx, u, dr, head, rgb, tt) {
    const sc = 0.9 + 0.14 * dr.d, nz = { x: 0, y: 56 * u };                    // nearer the camera (backed off the wall) reads bigger
    ctx.save(); ctx.translate(dr.x, dr.y); ctx.rotate(dr.roll); ctx.scale(sc, sc);
    ctx.shadowColor = `rgba(0,0,0,${0.46 - 0.16 * dr.d})`; ctx.shadowBlur = (4 + 18 * dr.d) * u; ctx.shadowOffsetX = (5 + 34 * dr.d) * u; ctx.shadowOffsetY = (7 + 44 * dr.d) * u;   // far from the wall: long, soft, faint shadow
    ctx.strokeStyle = "#20252d"; ctx.lineCap = "round"; ctx.lineWidth = 6 * u;                      // arms
    ctx.beginPath(); ctx.moveTo(-76 * u, -4 * u); ctx.lineTo(76 * u, -4 * u); ctx.stroke();
    ctx.lineWidth = 4 * u; ctx.beginPath(); ctx.moveTo(-44 * u, -10 * u); ctx.lineTo(44 * u, -10 * u); ctx.stroke();
    ctx.lineWidth = 2.4 * u; ctx.strokeStyle = "#454c58";                                           // landing skids
    ctx.beginPath(); ctx.moveTo(-26 * u, 14 * u); ctx.quadraticCurveTo(-34 * u, 30 * u, -48 * u, 30 * u); ctx.moveTo(26 * u, 14 * u); ctx.quadraticCurveTo(34 * u, 30 * u, 48 * u, 30 * u); ctx.stroke();
    ctx.lineWidth = 4.5 * u; ctx.strokeStyle = "#2b303a";                                           // spray boom + nozzle
    ctx.beginPath(); ctx.moveTo(0, 12 * u); ctx.lineTo(0, nz.y - 6 * u); ctx.stroke();
    ctx.fillStyle = "#c9d0da"; ctx.beginPath(); ctx.moveTo(-5 * u, nz.y - 6 * u); ctx.lineTo(5 * u, nz.y - 6 * u); ctx.lineTo(2.2 * u, nz.y + 4 * u); ctx.lineTo(-2.2 * u, nz.y + 4 * u); ctx.closePath(); ctx.fill();
    ctx.shadowColor = "transparent";
    const rotors = [[-76, -4, 1], [76, -4, 1], [-44, -10, 0.78], [44, -10, 0.78]];                  // far pair drawn first and a touch smaller
    rotors.sort((a, b) => a[2] - b[2]);
    const drawRotor = ([rx, ry, sc]) => {
      ctx.fillStyle = "#2b303a"; rr(ctx, (rx - 5) * u, (ry - 7) * u, 10 * u, 8 * u, 2 * u); ctx.fill();
      const wd = 40 * u * sc, ph = dr.rotor * (rx < 0 ? 1 : -1);
      const g = ctx.createRadialGradient(rx * u, (ry - 8) * u, 2, rx * u, (ry - 8) * u, wd); g.addColorStop(0, "rgba(40,46,56,.34)"); g.addColorStop(0.7, "rgba(40,46,56,.16)"); g.addColorStop(1, "rgba(40,46,56,0)");
      ctx.fillStyle = g; ctx.beginPath(); ctx.ellipse(rx * u, (ry - 8) * u, wd, 7 * u * sc, 0, 0, Math.PI * 2); ctx.fill();
      ctx.strokeStyle = "rgba(20,24,30,.55)"; ctx.lineWidth = 1.6 * u;                                    // blade tips seen edge-on, flickering
      ctx.beginPath(); ctx.moveTo(rx * u - Math.cos(ph) * wd * 0.95, (ry - 8) * u); ctx.lineTo(rx * u + Math.cos(ph) * wd * 0.95, (ry - 8) * u); ctx.stroke();
    };
    drawRotor(rotors[0]); drawRotor(rotors[1]);
    const g = ctx.createLinearGradient(0, -16 * u, 0, 18 * u); g.addColorStop(0, "#fbfbfc"); g.addColorStop(0.6, "#dfe4ea"); g.addColorStop(1, "#aeb6c2");
    ctx.fillStyle = g; rr(ctx, -30 * u, -16 * u, 60 * u, 32 * u, 10 * u); ctx.fill();                       // fuselage
    ctx.strokeStyle = "rgba(0,0,0,.4)"; ctx.lineWidth = 1.5 * u; ctx.stroke();
    ctx.fillStyle = "#ffd04a"; rr(ctx, -30 * u, -16 * u, 60 * u, 8 * u, 5 * u); ctx.fill();
    ctx.fillStyle = "#1d1d1f"; ctx.font = `700 ${8 * u}px -apple-system, Helvetica, Arial, sans-serif`; ctx.fillText("PV-D", -12 * u, 9 * u);
    ctx.fillStyle = "#15181d"; ctx.beginPath(); ctx.arc(20 * u, 0, 6.5 * u, 0, Math.PI * 2); ctx.fill();   // gimbal camera that watches the pass
    ctx.fillStyle = "#4a90ff"; ctx.beginPath(); ctx.arc(21.5 * u, -1.5 * u, 1.8 * u, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = "#8d98a8"; rr(ctx, -4 * u, -22 * u, 8 * u, 6 * u, 2 * u); ctx.fill();                  // hose port on top
    const blink = Math.sin(tt * 9) > 0.6;
    ctx.fillStyle = blink ? "#ff453a" : "#7a2a26"; ctx.beginPath(); ctx.arc(-76 * u, -9 * u, 2 * u, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = blink ? "#30d158" : "#1f6b34"; ctx.beginPath(); ctx.arc(76 * u, -9 * u, 2 * u, 0, Math.PI * 2); ctx.fill();
    drawRotor(rotors[2]); drawRotor(rotors[3]);
    ctx.restore();
    const cos = Math.cos(dr.roll), sin = Math.sin(dr.roll);
    return { nozzle: { x: dr.x + (nz.x * cos - nz.y * sin) * sc, y: dr.y + (nz.x * sin + nz.y * cos) * sc } };
  }
  // Two rangefinder dots either side of the spot, the way a standoff sensor reads the wall; they spread as the drone backs off.
  function drawStandoff(ctx, u, head, dr) {
    const gap = (22 + 22 * dr.d) * u;
    for (const sd of [-1, 1]) {
      const x = head.x + sd * gap, y = head.y - 12 * u, g = ctx.createRadialGradient(x, y, 0, x, y, 7 * u);
      g.addColorStop(0, "rgba(255,70,60,.95)"); g.addColorStop(0.35, "rgba(255,70,60,.45)"); g.addColorStop(1, "rgba(255,70,60,0)");
      ctx.fillStyle = g; ctx.beginPath(); ctx.arc(x, y, 7 * u, 0, Math.PI * 2); ctx.fill();
    }
  }
  function drawSpray(ctx, u, noz, head, rgb, standoff = 1) {
    const base = head.p ? head.p.width : 40 * u, w = base * Math.max(0.35, Math.min(1.2, standoff));   // fan width follows the standoff
    const m = Math.hypot(head.vx, head.vy) || 1, nx = -head.vy / m, ny = head.vx / m;
    const tint = head.kind === "prep" ? "200,225,245" : head.kind === "prime" ? "232,228,220" : `${rgb[0]},${rgb[1]},${rgb[2]}`;
    const ax = head.x + nx * w / 2, ay = head.y + ny * w / 2, bx = head.x - nx * w / 2, by = head.y - ny * w / 2;
    ctx.save();
    const g = ctx.createLinearGradient(noz.x, noz.y, head.x, head.y);                                    // jet from the nozzle to the wall
    g.addColorStop(0, `rgba(${tint},.0)`); g.addColorStop(0.35, `rgba(${tint},.28)`); g.addColorStop(1, `rgba(${tint},.5)`);
    ctx.fillStyle = g; ctx.beginPath(); ctx.moveTo(noz.x - 1.5 * u, noz.y); ctx.lineTo(ax, ay); ctx.lineTo(bx, by); ctx.lineTo(noz.x + 1.5 * u, noz.y); ctx.closePath(); ctx.fill();
    const rg = ctx.createRadialGradient(head.x, head.y, 1, head.x, head.y, w * 0.8);                       // wet spot where the fan meets the wall
    rg.addColorStop(0, `rgba(${tint},.5)`); rg.addColorStop(1, `rgba(${tint},0)`);
    ctx.fillStyle = rg; ctx.beginPath(); ctx.arc(head.x, head.y, w * 0.8, 0, Math.PI * 2); ctx.fill();
    ctx.restore();
  }
  function renderDrone(ctx, cvs, head, dtSim, rgb) {
    const u = Math.max(cvs.width, cvs.height) / 900, tt = t, dr = droneAt(t), H = cvs.height;
    const live = !!head && !head.idle, wind = windAt(tt).fx;
    if (live && head.item === "seg") {
      if (head.kind === "prep") spawnDust(head, u, Math.max(dtSim, 0.016), "rgba(190,215,235,.9)");
      else spawnPaintFlecks(head, u, Math.max(dtSim, 0.016), rgb, true, wind);
    }
    const frac = t / Math.max(timeline.total, 1e-6);
    const reel = drawCart(ctx, u, H, rgb, frac, live, dr);
    const cos = Math.cos(dr.roll), sin = Math.sin(dr.roll);
    if (live && head.item === "seg") drawStandoff(ctx, u, head, dr);
    drawHose(ctx, reel, { x: dr.x + 22 * u * sin, y: dr.y - 22 * u * cos }, u, tt);                  // hose first, so the drone sits on top of it
    const parts = drawDrone(ctx, u, dr, head, rgb, tt);
    if (live && head.item === "seg") drawSpray(ctx, u, parts.nozzle, head, rgb, dr.d);
    stepDust(ctx, Math.max(0.016, Math.min(dtSim, 0.1)), u);
    lastPose = { drone: dr, nozzle: parts.nozzle, head: { x: head ? head.x : 0, y: head ? head.y : 0 }, u };
  }


  // ---------------------------------------------------------------------- live job stats: wall painted, paint used and left, passes, reloads, time left
  // Everything is derived from the plan being replayed. Area and litres need a scale: the work order's measured one, or its ASSUMED one (then every
  // figure is tagged "scale assumed"). Paint is 10 m2 per litre per coat, two coats, the same figures the "how much paint" answer uses; this animation
  // lays one coat. Time left is an estimate at a typical machine speed, not a measurement.
  const COVER_M2_PER_L = 10, COATS = 2, SPEED_MM_S = { ground: 250, drone: 500 }, RELOAD_S = 20;
  let statsBase = null;
  function buildStats(j) {
    const wo = (j && j.work_order) || {}, sc = wo.scale || {}, mmpp = Number(sc.mm_per_px) > 0 ? Number(sc.mm_per_px) : null;
    const items = timeline.items, kinds = { paint: 1, trim: 1, touch: 1 };
    const cum = new Array(items.length), pass = new Array(items.length), dips = new Array(items.length);
    let a = 0, n = 0, d = 0;
    items.forEach((x, i) => { if (x.kind === "seg" && kinds[x.phase.kind]) { a += x.len * x.phase.width; n++; } if (x.dip) d++; cum[i] = a; pass[i] = n; dips[i] = d; });
    const lenPx = items.filter((x) => x.kind === "seg" && kinds[x.phase.kind]).reduce((s2, x) => s2 + x.len, 0);
    const areaFt2 = wo.summary && Number(wo.summary.paint_area_ft2) > 0 ? Number(wo.summary.paint_area_ft2) : null;
    const coatL = areaFt2 ? areaFt2 * 0.092903 / COVER_M2_PER_L : null;
    statsBase = { cum, pass, dips, totalArea: Math.max(a, 1e-9), totalPass: n, totalDips: d, areaFt2, coatL, mmpp, lenPx,
      assumed: /assumed/i.test(String(sc.source || "")) || !mmpp,
      travelMin: mmpp ? (lenPx * mmpp / SPEED_MM_S[rigKind] + d * RELOAD_S) / 60 : null };
    const root = els.stats; if (!root) return;
    root.textContent = "";
    const tile = (id, label) => {
      const t2 = document.createElement("div"), l = document.createElement("span"), v = document.createElement("strong"), s3 = document.createElement("small"), m = document.createElement("div"), f = document.createElement("i");
      t2.className = "rs-tile"; t2.dataset.id = id; l.className = "rs-label"; l.textContent = label; v.className = "rs-val"; s3.className = "rs-sub"; m.className = "rs-meter"; m.appendChild(f);
      t2.append(l, v, s3, m); root.appendChild(t2); return t2;
    };
    tile("wall", "Wall painted"); tile("paint", "Paint left"); tile("passes", "Passes");
    tile("machine", rigKind === "drone" ? "Supply" : "Reloads"); tile("time", "Time left");
  }
  function statsAt(time) {
    const b = statsBase; if (!b) return;
    const items = timeline.items;
    let lo = 0, hi = items.length - 1, k = -1;
    while (lo <= hi) { const mid = (lo + hi) >> 1; if (items[mid].t0 <= time) { k = mid; lo = mid + 1; } else hi = mid - 1; }
    let area = 0, pass = 0, dips = 0;
    if (k >= 0) {
      const it = items[k], u = clamp((time - it.t0) / Math.max(it.t1 - it.t0, 1e-9), 0, 1);
      const before = k > 0 ? b.cum[k - 1] : 0, bp = k > 0 ? b.pass[k - 1] : 0, bd = k > 0 ? b.dips[k - 1] : 0;
      const isPaint = it.kind === "seg" && b.cum[k] > before;
      area = isPaint ? before + (b.cum[k] - before) * u : before;
      pass = isPaint ? bp + (u >= 1 ? 1 : 0) : bp;
      dips = it.dip ? bd - 1 + (u >= 1 ? 1 : 0) : bd;
    }
    const f = clamp(area / b.totalArea, 0, 1), done = time >= timeline.total - 1e-6, tag = b.assumed ? " · scale assumed" : "";
    const set = (id, val, sub, frac, level) => {
      const t2 = els.stats.querySelector(`[data-id="${id}"]`); if (!t2) return;
      t2.querySelector(".rs-val").textContent = val; t2.querySelector(".rs-sub").textContent = sub;
      const m = t2.querySelector(".rs-meter"); m.hidden = frac == null; if (frac != null) m.firstChild.style.width = `${Math.round(100 * clamp(frac, 0, 1))}%`;
      t2.dataset.level = level || "";
    };
    set("wall", `${Math.round(100 * f)}%`, b.areaFt2 ? `${fmt1(f * b.areaFt2)} of ${fmt1(b.areaFt2)} sq ft${tag}` : "of the planned area", f);
    if (b.coatL) {
      const used = f * b.coatL, left = b.coatL - used, total = b.coatL * COATS;
      set("paint", `${fmt1(left)} L`, `${fmt1(used)} L used · coat 1 of ${COATS} · job ${fmt1(total)} L${tag}`, 1 - f, left / b.coatL < 0.12 && !done ? "low" : "");
    } else set("paint", `${Math.round(100 * (1 - f))}%`, "of this coat to go (no scale: litres unknown)", 1 - f);
    set("passes", `${Math.min(pass, b.totalPass)} / ${b.totalPass}`, "roller passes and cut-in strokes", b.totalPass ? pass / b.totalPass : 0);
    if (rigKind === "drone") set("machine", "Hose-fed", "no reloads: pump cart refills the line", null);
    else set("machine", `${Math.min(dips, b.totalDips)} / ${b.totalDips}`, "dips in the paint tray", b.totalDips ? dips / b.totalDips : 1);
    if (b.travelMin != null) { const left = b.travelMin * (1 - time / Math.max(timeline.total, 1e-9)); set("time", done ? "Done" : fmtMin(left), `of ~${fmtMin(b.travelMin)} at ${SPEED_MM_S[rigKind] / 1000} m/s (estimate)`, null); }
    else set("time", "—", "needs a scale to estimate", null);
  }
  const fmt1 = (v) => (v >= 10 ? Math.round(v) : Math.round(v * 10) / 10).toLocaleString();
  const fmtMin = (m) => (m < 1 ? "< 1 min" : m < 90 ? `${Math.round(m)} min` : `${Math.floor(m / 60)} h ${Math.round(m % 60)} min`);

  // ---------------------------------------------------------------------- drawing
  function rr(ctx, x, y, w, h, r) {
    ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r);
    ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath();
  }
  function link(ctx, a, b, w, c1, c2) {
    const ang = Math.atan2(b.y - a.y, b.x - a.x), len = Math.hypot(b.x - a.x, b.y - a.y);
    ctx.save(); ctx.translate(a.x, a.y); ctx.rotate(ang);
    const g = ctx.createLinearGradient(0, -w / 2, 0, w / 2); g.addColorStop(0, c1); g.addColorStop(0.5, c2); g.addColorStop(1, c1);
    ctx.fillStyle = g; rr(ctx, -w * 0.5, -w / 2, len + w, w, w / 2); ctx.fill();
    ctx.strokeStyle = "rgba(0,0,0,.38)"; ctx.lineWidth = Math.max(1, w * 0.07); ctx.stroke();
    ctx.restore();
  }
  function joint(ctx, p, r) {
    const g = ctx.createRadialGradient(p.x - r * 0.3, p.y - r * 0.3, r * 0.1, p.x, p.y, r);
    g.addColorStop(0, "#e9edf3"); g.addColorStop(1, "#6a7381");
    ctx.fillStyle = g; ctx.beginPath(); ctx.arc(p.x, p.y, r, 0, Math.PI * 2); ctx.fill();
    ctx.strokeStyle = "rgba(0,0,0,.45)"; ctx.lineWidth = r * 0.16; ctx.stroke();
    ctx.fillStyle = "#2b303a"; ctx.beginPath(); ctx.arc(p.x, p.y, r * 0.32, 0, Math.PI * 2); ctx.fill();
  }
  function drawRoller(ctx, pose, head, rgb) {
    const u = pose.u, p = pose.wrist, painting = head && head.painting;
    const kind = head ? head.kind : "paint";
    let ax = 0, ay = 1;                                                    // roller axis (unit): perpendicular to the way it is moving
    if (head && !head.idle && (head.vx || head.vy)) { const m = Math.hypot(head.vx, head.vy); ax = -head.vy / m; ay = head.vx / m; }
    if (ay < 0 || (Math.abs(ay) < 1e-6 && ax < 0)) { ax = -ax; ay = -ay; }
    const phaseW = head && head.p ? head.p.width : 40 * u;
    const length = clamp(kind === "prep" ? 36 * u : phaseW, 20 * u, 110 * u), dia = (kind === "trim" ? 11 : kind === "prep" ? 16 : 19) * u;
    ctx.save(); ctx.translate(p.x, p.y); ctx.rotate(Math.atan2(ay, ax));
    ctx.strokeStyle = "#444b57"; ctx.lineWidth = 2.4 * u; ctx.lineCap = "round";            // wire frame from the arm to the roller ends
    ctx.beginPath(); ctx.moveTo(-length / 2 + 3 * u, 0); ctx.lineTo(-length / 2 + 3 * u, -dia * 0.9); ctx.lineTo(0, -dia * 1.35); ctx.stroke();
    const dry = head && head.seg && head.seg.load < 1 ? clamp((1 - head.seg.load) / 0.38, 0, 1) * 0.55 : 0;       // a roller running dry fades toward bare nap
    const mix = (c, to) => Math.round(c + (to - c) * dry);
    ctx.fillStyle = kind === "prep" ? "#c99a5e" : kind === "trim" ? "#7b8794" : `rgb(${mix(rgb[0], 226)},${mix(rgb[1], 220)},${mix(rgb[2], 208)})`;
    rr(ctx, -length / 2, -dia / 2, length, dia, dia * 0.5); ctx.fill();
    const sh = ctx.createLinearGradient(0, -dia / 2, 0, dia / 2);
    sh.addColorStop(0, "rgba(255,255,255,.42)"); sh.addColorStop(0.45, "rgba(255,255,255,0)"); sh.addColorStop(1, "rgba(0,0,0,.34)");
    ctx.fillStyle = sh; rr(ctx, -length / 2, -dia / 2, length, dia, dia * 0.5); ctx.fill();
    ctx.save(); rr(ctx, -length / 2, -dia / 2, length, dia, dia * 0.5); ctx.clip();        // nap bands scroll as it rolls
    ctx.strokeStyle = "rgba(0,0,0,.16)"; ctx.lineWidth = 1 * u;
    const step = 5 * u, off = (pose.spin % step + step) % step;
    for (let k = -length / 2 - step; k < length / 2 + step; k += step) { ctx.beginPath(); ctx.moveTo(k + off, -dia / 2); ctx.lineTo(k + off, dia / 2); ctx.stroke(); }
    ctx.restore();
    ctx.strokeStyle = "rgba(0,0,0,.4)"; ctx.lineWidth = 1.2 * u; rr(ctx, -length / 2, -dia / 2, length, dia, dia * 0.5); ctx.stroke();
    if (painting) { ctx.strokeStyle = "rgba(255,255,255,.55)"; ctx.lineWidth = 1.4 * u; ctx.beginPath(); ctx.moveTo(-length / 2 + 4 * u, dia * 0.28); ctx.lineTo(length / 2 - 4 * u, dia * 0.28); ctx.stroke(); }
    ctx.restore();
  }
  function drawTray(ctx, u, rgb, tray, dipping) {
    ctx.save(); ctx.translate(tray.x, tray.y);
    ctx.fillStyle = "rgba(0,0,0,.25)"; ctx.beginPath(); ctx.ellipse(0, 22 * u, 52 * u, 6 * u, 0, 0, Math.PI * 2); ctx.fill();
    const g = ctx.createLinearGradient(0, -10 * u, 0, 24 * u); g.addColorStop(0, "#d8dde4"); g.addColorStop(1, "#8e98a6");
    ctx.fillStyle = g; ctx.beginPath(); ctx.moveTo(-50 * u, -4 * u); ctx.lineTo(50 * u, -4 * u); ctx.lineTo(40 * u, 22 * u); ctx.lineTo(-40 * u, 22 * u); ctx.closePath(); ctx.fill();
    ctx.strokeStyle = "rgba(0,0,0,.4)"; ctx.lineWidth = 1.2 * u; ctx.stroke();
    ctx.fillStyle = `rgb(${rgb[0]},${rgb[1]},${rgb[2]})`; ctx.beginPath(); ctx.ellipse(0, -2 * u, 44 * u, 5 * u, 0, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = "rgba(255,255,255,.35)"; ctx.beginPath(); ctx.ellipse(-12 * u, -3.5 * u, 14 * u, 1.8 * u, 0, 0, Math.PI * 2); ctx.fill();
    if (dipping) { ctx.strokeStyle = "rgba(255,255,255,.5)"; ctx.lineWidth = 1.5 * u; ctx.beginPath(); ctx.ellipse(0, -2 * u, 10 * u + 6 * u * Math.abs(Math.sin(performance.now() / 120)), 2.5 * u, 0, 0, Math.PI * 2); ctx.stroke(); }
    ctx.restore();
  }
  function drawBase(ctx, pose, head) {
    const u = pose.u, bx0 = pose.base.x, floor = pose.floor;
    const bw = 132 * u, bh = 44 * u, bx = bx0 - bw / 2, by = floor - bh - 14 * u;
    ctx.fillStyle = "rgba(0,0,0,.3)"; ctx.beginPath(); ctx.ellipse(bx0, floor + 3 * u, bw * 0.66, 7 * u, 0, 0, Math.PI * 2); ctx.fill();
    ctx.fillStyle = "#23272f"; rr(ctx, bx - 6 * u, by + bh - 6 * u, bw + 12 * u, 22 * u, 11 * u); ctx.fill();            // tracks
    for (let k = 0; k < 6; k++) {
      const wx = bx + 10 * u + k * ((bw - 20 * u) / 5), wy = by + bh + 5 * u;
      const g = ctx.createRadialGradient(wx - 1.5 * u, wy - 1.5 * u, 1, wx, wy, 7.5 * u); g.addColorStop(0, "#69717d"); g.addColorStop(1, "#343a44");
      ctx.fillStyle = g; ctx.beginPath(); ctx.arc(wx, wy, 7.2 * u, 0, Math.PI * 2); ctx.fill();
      ctx.strokeStyle = "#b9c0cb"; ctx.lineWidth = 1.3 * u;
      ctx.beginPath(); ctx.moveTo(wx, wy); ctx.lineTo(wx + Math.cos(pose.wheel + k) * 6 * u, wy + Math.sin(pose.wheel + k) * 6 * u); ctx.stroke();
    }
    const g = ctx.createLinearGradient(0, by, 0, by + bh); g.addColorStop(0, "#fbfbfc"); g.addColorStop(0.55, "#dfe4ea"); g.addColorStop(1, "#aeb6c2");
    ctx.fillStyle = g; rr(ctx, bx, by, bw, bh, 10 * u); ctx.fill();
    ctx.strokeStyle = "rgba(0,0,0,.4)"; ctx.lineWidth = 1.6 * u; ctx.stroke();
    ctx.fillStyle = "rgba(0,0,0,.12)"; rr(ctx, bx + 8 * u, by + bh * 0.62, bw - 16 * u, 4 * u, 2 * u); ctx.fill();
    const live = head && !head.idle;                                       // status strip: orange prep, blue paint, green idle
    const lamp = !live ? "#30d158" : head.kind === "prep" ? "#ff9f0a" : "#0a84ff";
    ctx.fillStyle = lamp; ctx.globalAlpha = live ? 0.65 + 0.35 * Math.sin(performance.now() / 150) : 1; rr(ctx, bx + 12 * u, by + 9 * u, 34 * u, 6 * u, 3 * u); ctx.fill(); ctx.globalAlpha = 1;
    ctx.fillStyle = "#1d1d1f"; ctx.font = `700 ${11 * u}px -apple-system, Helvetica, Arial, sans-serif`; ctx.fillText("PV-1", bx + bw - 44 * u, by + 17 * u);
    const top = pose.shoulder.y, mx = pose.base.x;                         // mast: fixed lower section + telescoping upper section
    ctx.save(); ctx.shadowColor = "rgba(0,0,0,.32)"; ctx.shadowBlur = 10 * u; ctx.shadowOffsetX = 7 * u; ctx.shadowOffsetY = 9 * u;
    const outerTop = Math.max(top + 20 * u, by - 150 * u);
    const g2 = ctx.createLinearGradient(mx - 7 * u, 0, mx + 7 * u, 0); g2.addColorStop(0, "#2d333d"); g2.addColorStop(0.5, "#7b8594"); g2.addColorStop(1, "#2d333d");
    ctx.fillStyle = g2; rr(ctx, mx - 7 * u, outerTop, 14 * u, by - outerTop + 4 * u, 3 * u); ctx.fill();
    const g3 = ctx.createLinearGradient(mx - 4.5 * u, 0, mx + 4.5 * u, 0); g3.addColorStop(0, "#3d4552"); g3.addColorStop(0.5, "#a3adbb"); g3.addColorStop(1, "#3d4552");
    ctx.fillStyle = g3; rr(ctx, mx - 4.5 * u, top - 8 * u, 9 * u, Math.max(outerTop - top + 40 * u, 10 * u), 2.5 * u); ctx.fill();
    ctx.restore();
  }
  // Mains umbilical from the drive base off the left edge: slack rises and falls with the distance driven, and it lies on the floor.
  function drawCable(ctx, pose) {
    const u = pose.u, a = { x: pose.base.x - 62 * u, y: pose.floor - 26 * u }, b = { x: -14 * u, y: pose.floor - 3 * u };
    const dip = Math.min(40 * u, 8 * u + Math.abs(a.x - b.x) * 0.05);
    ctx.save(); ctx.lineCap = "round";
    const path = () => { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.bezierCurveTo(a.x - 30 * u, a.y + dip, b.x + 60 * u, b.y + 2 * u, b.x, b.y); };
    ctx.strokeStyle = "rgba(0,0,0,.22)"; ctx.lineWidth = 5 * u; ctx.translate(0, 3 * u); path(); ctx.stroke(); ctx.translate(0, -3 * u);
    ctx.strokeStyle = "#e8742a"; ctx.lineWidth = 3.4 * u; path(); ctx.stroke();
    ctx.strokeStyle = "rgba(255,255,255,.35)"; ctx.lineWidth = 1 * u; ctx.translate(0, -1 * u); path(); ctx.stroke();
    ctx.restore();
  }
  function drawArm(ctx, pose) {
    const u = pose.u;
    ctx.save(); ctx.shadowColor = "rgba(0,0,0,.34)"; ctx.shadowBlur = 12 * u; ctx.shadowOffsetX = 9 * u; ctx.shadowOffsetY = 12 * u;
    const g = ctx.createLinearGradient(0, pose.shoulder.y - 13 * u, 0, pose.shoulder.y + 13 * u); g.addColorStop(0, "#ffd04a"); g.addColorStop(1, "#d89a10");
    ctx.fillStyle = g; rr(ctx, pose.shoulder.x - 15 * u, pose.shoulder.y - 13 * u, 30 * u, 26 * u, 6 * u); ctx.fill();   // carriage on the mast
    ctx.strokeStyle = "rgba(0,0,0,.4)"; ctx.lineWidth = 1.4 * u; ctx.stroke();
    link(ctx, pose.shoulder, pose.elbow, 14 * u, "#9aa4b2", "#e8ecf1");
    link(ctx, pose.elbow, pose.wrist, 11 * u, "#8b95a3", "#dfe4ea");
    ctx.restore();
    joint(ctx, pose.shoulder, 8 * u); joint(ctx, pose.elbow, 8.5 * u); joint(ctx, pose.wrist, 6.5 * u);
  }
  const dustRng = rng(9);
  function spawnDust(head, u, dt, colour) {
    const n = Math.floor(14 * dt * speed + dustRng() * 0.8);
    for (let k = 0; k < n; k++) particles.push({ x: head.x + (dustRng() - 0.5) * 22 * u, y: head.y + (dustRng() - 0.5) * 18 * u, vx: (dustRng() - 0.5) * 26 * u, vy: (-6 + dustRng() * 14) * u, life: 1, r: (1.2 + dustRng() * 2.2) * u, c: colour });
    if (particles.length > 320) particles.splice(0, particles.length - 320);
  }
  // Paint flung off a fast roller, and drifting spray mist from the drone's fan: small, short-lived, coloured like the paint.
  function spawnPaintFlecks(head, u, dt, rgb, mist, wind) {
    const rate = mist ? 70 : 9, n = Math.floor(rate * dt * speed + dustRng() * (mist ? 1.4 : 0.5));
    const sp = head.p ? head.p.width : 30 * u;
    for (let k = 0; k < n; k++) {
      const lateral = (dustRng() - 0.5) * sp * (mist ? 1.2 : 0.9);
      const m = Math.hypot(head.vx, head.vy) || 1, nx = -head.vy / m, ny = head.vx / m;
      particles.push({ x: head.x + nx * lateral, y: head.y + ny * lateral, vx: (mist ? wind * 14 * u : 0) + (dustRng() - 0.5) * (mist ? 22 : 60) * u, vy: (mist ? -4 : -20) * u + dustRng() * 14 * u,
        life: mist ? 0.55 + dustRng() * 0.45 : 1, r: (mist ? 0.8 + dustRng() * 1.6 : 0.9 + dustRng() * 1.4) * u, c: `rgb(${rgb[0]},${rgb[1]},${rgb[2]})`, g: mist ? 0.25 : 1, a: mist ? 0.5 : 0.85, d: mist ? 0.9 : 1.7 });
    }
    if (particles.length > 320) particles.splice(0, particles.length - 320);
  }
  function stepDust(ctx, dt, u) {
    particles.forEach((p) => { p.life -= dt / (p.d || 1.7); p.vy += 60 * (p.g == null ? 1 : p.g) * dt * u; p.x += p.vx * dt; p.y += p.vy * dt; });
    particles = particles.filter((p) => p.life > 0);
    for (const p of particles) { ctx.globalAlpha = Math.max(0, p.life) * (p.a || 0.7); ctx.fillStyle = p.c || "#e9dcc8"; ctx.beginPath(); ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2); ctx.fill(); }
    ctx.globalAlpha = 1;
  }

  function render() {
    const j = getJob(); if (!j || !timeline || !timeline.phases.length) return;
    const cvs = els.canvas, ctx = cvs.getContext("2d");
    if (t < drawn) resetLayers();
    const dtSim = clamp(t - drawn, 0, 2);
    bake(drawn, t); drawn = t;
    if (dtSim > 0) {                                                       // the wet sheen dries to matt in about two seconds
      wctx.globalCompositeOperation = "destination-out"; wctx.fillStyle = `rgba(0,0,0,${1 - Math.exp(-dtSim / 1.9)})`;
      wctx.fillRect(0, 0, wetLayer.width, wetLayer.height); wctx.globalCompositeOperation = "source-over";
    }
    ctx.clearRect(0, 0, cvs.width, cvs.height);
    ctx.drawImage(preLayer, 0, 0);
    if (maskLayer) {
      const tx = tmpLayer.getContext("2d");
      tx.globalCompositeOperation = "source-over"; tx.clearRect(0, 0, tmpLayer.width, tmpLayer.height);
      tx.drawImage(rollLayer, 0, 0); tx.globalCompositeOperation = "destination-in"; tx.drawImage(maskLayer, 0, 0); tx.globalCompositeOperation = "source-over";
      ctx.drawImage(tmpLayer, 0, 0);
    } else ctx.drawImage(rollLayer, 0, 0);
    ctx.drawImage(paintLayer, 0, 0);
    if (maskLayer) {
      const tx = tmpLayer.getContext("2d");
      tx.globalCompositeOperation = "source-over"; tx.clearRect(0, 0, tmpLayer.width, tmpLayer.height);
      tx.drawImage(wetLayer, 0, 0); tx.globalCompositeOperation = "destination-in"; tx.drawImage(maskLayer, 0, 0); tx.globalCompositeOperation = "source-over";
      ctx.drawImage(tmpLayer, 0, 0);
    } else ctx.drawImage(wetLayer, 0, 0);
    const head = headAt(t), rgb = paintColour();
    statsAt(t);
    if (rigKind === "drone") {
      renderDrone(ctx, cvs, head, dtSim, rgb);
      els.phase.textContent = t >= timeline.total - 1e-6 ? "Finished" : (head ? head.label : "Ready");
      const pctD = Math.round(100 * t / timeline.total);
      els.pct.textContent = `${pctD}%`; els.seek.value = String(Math.round(1000 * t / timeline.total)); els.root.dataset.progress = String(pctD);
      if (!playing) els.play.textContent = t >= timeline.total - 1e-6 ? "Replay" : "Play";
      return;
    }
    const pose = solvePose(head, cvs.width, cvs.height);
    lastPose = pose;
    if (head && !head.idle && head.kind === "prep" && head.item === "seg") spawnDust(head, pose.u, Math.max(dtSim, 0.016));
    else if (head && !head.idle && head.kind === "paint" && head.item === "seg") spawnPaintFlecks(head, pose.u, Math.max(dtSim, 0.016), rgb, false, 0);
    drawCable(ctx, pose);
    stepDust(ctx, Math.max(0.016, Math.min(dtSim, 0.1)), pose.u);
    drawTray(ctx, pose.u, rgb, timeline.tray, head && head.item === "dip" && !head.idle);
    drawBase(ctx, pose, head);
    drawArm(ctx, pose);
    if (head && !head.idle && head.item === "seg") {                         // the roller is pressed on the wall: tight dark contact shadow around it
      const w = Math.min(120 * pose.u, (head.p ? head.p.width : 40 * pose.u) * 0.9), g = ctx.createRadialGradient(pose.wrist.x, pose.wrist.y, 1, pose.wrist.x, pose.wrist.y, w);
      g.addColorStop(0, "rgba(0,0,0,.26)"); g.addColorStop(1, "rgba(0,0,0,0)");
      ctx.fillStyle = g; ctx.beginPath(); ctx.arc(pose.wrist.x, pose.wrist.y, w, 0, Math.PI * 2); ctx.fill();
    }
    ctx.save(); ctx.shadowColor = "rgba(0,0,0,.34)"; ctx.shadowBlur = 8 * pose.u; ctx.shadowOffsetX = 6 * pose.u; ctx.shadowOffsetY = 8 * pose.u;
    drawRoller(ctx, pose, head, rgb);
    ctx.restore();
    els.phase.textContent = t >= timeline.total - 1e-6 ? "Finished" : (head ? head.label : "Ready");
    const pct = Math.round(100 * t / timeline.total);
    els.pct.textContent = `${pct}%`;
    els.seek.value = String(Math.round(1000 * t / timeline.total));
    els.root.dataset.progress = String(pct);
    if (!playing) els.play.textContent = t >= timeline.total - 1e-6 ? "Replay" : "Play";
  }

  function frame(ts) {
    if (!playing) return;
    const dt = Math.min(0.05, (ts - lastTs) / 1000 || 0); lastTs = ts;
    t = Math.min(timeline.total, t + dt * speed);
    render();
    if (t >= timeline.total) { setPlaying(false); return; }
    raf = requestAnimationFrame(frame);
  }
  function setPlaying(on) {
    playing = on && !!timeline && timeline.total > 0;
    els.play.textContent = playing ? "Pause" : (t >= timeline.total - 1e-6 ? "Replay" : "Play");
    els.play.setAttribute("aria-pressed", playing ? "true" : "false");
    cancelAnimationFrame(raf);
    if (playing) { lastTs = performance.now(); if (t >= timeline.total - 1e-6) { t = 0; } raf = requestAnimationFrame(frame); }
  }
  function seek(time) {
    if (!timeline || !timeline.total) return;
    t = clamp(time, 0, timeline.total);
    render();
  }

  // ---------------------------------------------------------------------- open / close
  function open() {
    const j = getJob(); if (!j) return;
    timeline = buildTimeline(j, 18, { drone: rigKind === "drone" });
    if (!timeline.phases.length) { window.toast && window.toast(timeline.reason, "warn"); return; }
    els.root.hidden = false;
    els.canvas.hidden = false;
    els.canvas.width = j.width; els.canvas.height = j.height;
    maskLayer = buildMask(j);
    resetLayers();
    rig = rigKind === "drone" ? buildDrone(j) : buildRig(j);
    buildStats(j);
    t = 0; speed = Number(els.speed.value) || 1;
    document.querySelectorAll('#stage [data-layer="paint"], #stage [data-layer="touchup"]').forEach((e) => e.classList.add("robot-dim"));
    $("#robot-open").setAttribute("aria-pressed", "true");
    if (REDUCED) { t = timeline.total; render(); setPlaying(false); els.play.textContent = "Replay"; }
    else { render(); setPlaying(true); }
  }
  // Switch machine mid-watch: same plan, same fraction of the way through, same play state.
  function setRig(kind) {
    if (kind !== "ground" && kind !== "drone") return false;
    rigKind = kind;
    document.querySelectorAll("#robot-rig [data-rig]").forEach((b) => { const on = b.dataset.rig === kind; b.classList.toggle("on", on); b.setAttribute("aria-pressed", on ? "true" : "false"); });
    const j = getJob();
    if (!j || !els.root || els.root.hidden || !timeline) return true;
    const frac = timeline.total ? t / timeline.total : 0, was = playing;
    setPlaying(false);
    timeline = buildTimeline(j, 18, { drone: kind === "drone" });
    resetLayers(); rig = kind === "drone" ? buildDrone(j) : buildRig(j);
    buildStats(j);
    t = frac * timeline.total; particles = [];
    render(); if (was) setPlaying(true);
    return true;
  }
  function close() {
    setPlaying(false);
    els.root.hidden = true; els.canvas.hidden = true;
    document.querySelectorAll("#stage .robot-dim").forEach((e) => e.classList.remove("robot-dim"));
    $("#robot-open").setAttribute("aria-pressed", "false");
  }
  function refreshButton() {
    const btn = $("#robot-open"); if (!btn) return;
    const j = getJob();
    const tl = j ? buildTimeline(j) : { phases: [], reason: "Open a job first." };
    btn.disabled = false;                           // always clickable: a click on a blocked job explains why, instead of a dead button
    btn.title = tl.phases.length ? "Watch the robot work through this plan" : tl.reason;
    btn.dataset.ready = tl.phases.length ? "1" : "0";
    btn.textContent = els.root && !els.root.hidden ? "Stop watching" : "Watch it paint";
  }

  function init() {
    els.root = $("#robot-bar"); els.canvas = $("#robot-canvas"); els.play = $("#robot-play"); els.seek = $("#robot-seek");
    els.speed = $("#robot-speed"); els.stats = $("#robot-stats"); els.phase = $("#robot-phase"); els.pct = $("#robot-pct");
    if (!els.root || !els.canvas) return;
    $("#robot-open").addEventListener("click", () => { if (els.root.hidden) open(); else close(); });
    $("#robot-close").addEventListener("click", close);
    const rigSeg = $("#robot-rig");
    if (rigSeg) rigSeg.addEventListener("click", (e) => { const b = e.target.closest("[data-rig]"); if (b) setRig(b.dataset.rig); });
    els.play.addEventListener("click", () => setPlaying(!playing));
    els.seek.addEventListener("input", () => { setPlaying(false); seek(timeline.total * Number(els.seek.value) / 1000); els.play.textContent = "Play"; });
    els.speed.addEventListener("change", () => { speed = Number(els.speed.value) || 1; });
    document.addEventListener("keydown", (e) => {
      if (els.root.hidden || /INPUT|TEXTAREA|SELECT/.test((e.target || {}).tagName || "")) return;
      if (e.key === " ") { e.preventDefault(); setPlaying(!playing); }
      else if (e.key === "Escape") close();
    });
    let seen = getJob();                             // a job opened from the URL hash can load before this script runs: poll the job by identity
    setInterval(() => {
      const cur = getJob();
      if (cur !== seen) { seen = cur; if (!els.root.hidden) close(); }
      refreshButton();
    }, 400);
    refreshButton();
  }
  // Test/diagnostic: how much roller paint lies outside the allowed area before clipping, and how much of it is actually shown.
  function spill() {
    if (!maskLayer || !rollLayer) return null;
    const W = rollLayer.width, H = rollLayer.height, g = (c) => c.getContext("2d").getImageData(0, 0, W, H).data;
    const raw = g(rollLayer), m = g(maskLayer), tx = tmpLayer.getContext("2d");
    tx.globalCompositeOperation = "source-over"; tx.clearRect(0, 0, W, H); tx.drawImage(rollLayer, 0, 0); tx.globalCompositeOperation = "destination-in"; tx.drawImage(maskLayer, 0, 0);
    tx.globalCompositeOperation = "source-over";
    const shown = g(tmpLayer);
    let rawOut = 0, shownOut = 0, inside = 0;
    for (let i = 3; i < raw.length; i += 4) {
      const allowed = m[i] > 0;
      if (raw[i] > 12 && !allowed) rawOut++;
      if (shown[i] > 12 && !allowed) shownOut++;
      if (shown[i] > 12 && allowed) inside++;
    }
    return { raw_outside_px: rawOut, shown_outside_px: shownOut, inside_px: inside, allowed_px: maskInfo.allowed_px };
  }
  // Test hook: remove a rectangle (fractions of the picture) from the allowed area, as if a keep-out region sat there.
  function carveMask(fx, fy, fw, fh) {
    if (!maskLayer) return false;
    const x = maskLayer.getContext("2d"), W = maskLayer.width, H = maskLayer.height;
    x.globalCompositeOperation = "destination-out"; x.fillRect(fx * W, fy * H, fw * W, fh * H); x.globalCompositeOperation = "source-over";
    return true;
  }
  window.PVRobot = {
    spill, carveMask, setRig, rig: () => rigKind,
    buildTimeline, seek, play: () => setPlaying(true), pause: () => setPlaying(false), open, close,
    pose: () => lastPose && lastPose.shoulder && { shoulder: lastPose.shoulder, elbow: lastPose.elbow, wrist: lastPose.wrist, head: lastPose.head, L1: lastPose.L1, L2: lastPose.L2, reach: lastPose.reach, maxReach: lastPose.maxReach, base: lastPose.base },
    stats: () => { if (!statsBase) return null; const o = {}; els.stats.querySelectorAll(".rs-tile").forEach((t2) => { o[t2.dataset.id] = t2.querySelector(".rs-val").textContent; }); return o; },
    state: () => ({ clipped: !!maskLayer, mask: maskInfo, t, total: timeline ? timeline.total : 0, playing, reloads: timeline ? timeline.reloads : 0, particles: particles.length,
      phases: timeline ? timeline.phases.map((p) => ({ kind: p.kind, segs: p.segs.length, t0: p.t0, t1: p.t1 })) : [] }),
  };
  if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init); else init();
})();