comfy-ts 2.22.0 → 2.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-fsHtW5zG.js} +51 -17
  2. package/dist/ServeApp-fsHtW5zG.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-DZynSkZm.js} +405 -39
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +428 -46
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +147 -1
  11. package/dist/index.d.ts +147 -1
  12. package/dist/index.js +428 -47
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Y5ZI48vV.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve-CICU_wTL.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve-CICU_wTL.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-CViJXsHL.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-CViJXsHL.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BGYJZGMD.js} +18 -3
  21. package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/serve-web.js +46 -43
  23. package/dist/web.d.ts +147 -1
  24. package/dist/web.js +428 -47
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +1 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +6 -56
  29. package/examples/depth-explorer/serve.ts +12 -133
  30. package/examples/depth-explorer/web/App.tsx +20 -91
  31. package/examples/depth-explorer/web/index.html +1 -0
  32. package/examples/depth-explorer/web/state.ts +26 -109
  33. package/examples/depth-explorer/web/styles.css +1 -286
  34. package/examples/explorer-kit/catalog.ts +80 -0
  35. package/examples/explorer-kit/server.ts +167 -0
  36. package/examples/explorer-kit/web/base.css +289 -0
  37. package/examples/explorer-kit/web/runs.ts +160 -0
  38. package/examples/explorer-kit/web/ui.tsx +125 -0
  39. package/examples/rvion/17-relight.cflow.ts +2 -1
  40. package/examples/rvion/18-world.cflow.ts +101 -0
  41. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  42. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  43. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  44. package/examples/rvion/flythroughChain.ts +171 -0
  45. package/examples/rvion/flythroughColmap.ts +157 -0
  46. package/examples/rvion/flythroughFuse.ts +199 -0
  47. package/examples/rvion/flythroughGuide.ts +300 -0
  48. package/examples/rvion/flythroughPalette.ts +310 -0
  49. package/examples/rvion/flythroughPath.ts +177 -0
  50. package/examples/rvion/flythroughSplat.ts +73 -0
  51. package/examples/rvion/grow-splat/align.ts +114 -0
  52. package/examples/rvion/grow-splat/grow.ts +198 -0
  53. package/examples/rvion/grow-splat/ply.ts +166 -0
  54. package/examples/rvion/grow-splat/raster.ts +207 -0
  55. package/examples/rvion/grow-splat/sharp.ts +45 -0
  56. package/examples/rvion/splatDataset.ts +80 -0
  57. package/examples/rvion/splatEval.ts +380 -0
  58. package/examples/upscale-explorer/models.ts +341 -0
  59. package/examples/upscale-explorer/serve.ts +19 -0
  60. package/examples/upscale-explorer/web/App.tsx +250 -0
  61. package/examples/upscale-explorer/web/compare.tsx +285 -0
  62. package/examples/upscale-explorer/web/index.html +15 -0
  63. package/examples/upscale-explorer/web/main.tsx +12 -0
  64. package/examples/upscale-explorer/web/state.ts +279 -0
  65. package/examples/upscale-explorer/web/styles.css +241 -0
  66. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  67. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  68. package/examples/world-explorer/serve.ts +171 -0
  69. package/examples/world-explorer/web/index.html +14 -0
  70. package/examples/world-explorer/web/main.tsx +200 -0
  71. package/examples/world-explorer/web/state.ts +212 -0
  72. package/examples/world-explorer/web/styles.css +131 -0
  73. package/examples/world-explorer/web/thumb.ts +21 -0
  74. package/examples/world-explorer/web/tsconfig.json +11 -0
  75. package/examples/world-explorer/world-state.ts +40 -0
  76. package/package.json +7 -8
  77. package/src/cli/serve/ServeApp.ts +27 -2
  78. package/src/cli/serve/resultHistory.ts +22 -4
  79. package/src/cli/serve/thumbs.ts +19 -8
  80. package/src/cli/serve/web/api.ts +4 -0
  81. package/src/cli/serve/web/components/Gallery.tsx +24 -1
  82. package/src/cli/serve/web/styles.ts +3 -0
  83. package/src/coreExports.ts +6 -0
  84. package/src/graph/ComfyNode.ts +12 -2
  85. package/src/host/ComfyHost.ts +159 -2
  86. package/src/host/ResilientWebsocket.ts +10 -0
  87. package/src/manager/script-update-manager.bun.ts +0 -7
  88. package/src/runner/ComfyExecution.ts +185 -23
  89. package/src/runner/ComfyWorkflow.ts +22 -0
  90. package/src/runner/ComfyWsApi.ts +3 -1
  91. package/src/runner/comfyOrgApiKey.ts +44 -0
  92. package/src/runner/historyReplay.ts +53 -0
  93. package/src/runner/outputs3d.ts +18 -0
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  96. package/src/state.ts +2 -0
  97. package/src/vars/DefinedWorkflow.ts +1 -0
  98. package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
  99. package/dist/exampleAssets-1NHndnNB.js.map +0 -1
@@ -0,0 +1,310 @@
1
+ // how far a fly-through drifts from its picture's palette, and the pull back. Each frame is measured
2
+ // in CIE Lab against the picture cover-cropped to the frame: the mean colour (ΔE between the means,
3
+ // the lightness and the green-red and blue-yellow axes alone), the spread of the lightness (contrast),
4
+ // the mean chroma (saturation) and a chroma weighted hue histogram (Hellinger distance, 0 = the same
5
+ // hues). The match moves each frame's Lab mean and spread to the picture's, with stats smoothed over
6
+ // time so the pull never flickers.
7
+ //
8
+ // run: bun examples/rvion/flythroughPalette.ts measure <picture> <out.png> <label>=<video> …
9
+ // bun examples/rvion/flythroughPalette.ts match <picture> <in.mp4> <out.mp4> [strength]
10
+ import { $ } from 'bun'
11
+ import { writeFileSync } from 'node:fs'
12
+ import sharp from 'sharp'
13
+
14
+ /** sRGB 0..255 to linear, once per byte */
15
+ const LINEAR = Float64Array.from({ length: 256 }, (_, i) => {
16
+ const c = i / 255
17
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
18
+ })
19
+ const D65 = [0.95047, 1, 1.08883] as const
20
+ const f = (t: number) => (t > 216 / 24389 ? Math.cbrt(t) : (24389 / 27) * t / 116 + 16 / 116)
21
+ const fInv = (t: number) => (t ** 3 > 216 / 24389 ? t ** 3 : (116 * t - 16) / (24389 / 27))
22
+ const toByte = (c: number) => {
23
+ const s = c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055
24
+ return Math.max(0, Math.min(255, Math.round(s * 255)))
25
+ }
26
+
27
+ /** one sRGB pixel to Lab (D65) */
28
+ export function rgbToLab(r: number, g: number, b: number): [number, number, number] {
29
+ const R = LINEAR[r]!
30
+ const G = LINEAR[g]!
31
+ const B = LINEAR[b]!
32
+ const x = f((0.4124564 * R + 0.3575761 * G + 0.1804375 * B) / D65[0])
33
+ const y = f(0.2126729 * R + 0.7151522 * G + 0.072175 * B)
34
+ const z = f((0.0193339 * R + 0.119192 * G + 0.9503041 * B) / D65[2])
35
+ return [116 * y - 16, 500 * (x - y), 200 * (y - z)]
36
+ }
37
+
38
+ /** one Lab colour back to sRGB bytes */
39
+ export function labToRgb(L: number, a: number, b: number): [number, number, number] {
40
+ const fy = (L + 16) / 116
41
+ const X = D65[0] * fInv(fy + a / 500)
42
+ const Y = fInv(fy)
43
+ const Z = D65[2] * fInv(fy - b / 200)
44
+ return [
45
+ toByte(3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z),
46
+ toByte(-0.969266 * X + 1.8760108 * Y + 0.041556 * Z),
47
+ toByte(0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z),
48
+ ]
49
+ }
50
+
51
+ const HUE_BINS = 24
52
+ /** the chroma below which a pixel counts as grey */
53
+ const GREY = 1.5
54
+
55
+ /** a frame's palette: Lab mean and spread per channel, mean chroma, the chroma weighted hue histogram */
56
+ export type Palette = { mean: [number, number, number]; spread: [number, number, number]; chroma: number; hues: Float64Array }
57
+
58
+ export function paletteOf(rgb: Uint8Array): Palette {
59
+ const n = rgb.length / 3
60
+ const sum = [0, 0, 0]
61
+ const sq = [0, 0, 0]
62
+ let chroma = 0
63
+ const hues = new Float64Array(HUE_BINS)
64
+ for (let i = 0; i < n; i++) {
65
+ const lab = rgbToLab(rgb[i * 3]!, rgb[i * 3 + 1]!, rgb[i * 3 + 2]!)
66
+ for (let c = 0; c < 3; c++) {
67
+ const x = lab[c]!
68
+ sum[c]! += x
69
+ sq[c]! += x * x
70
+ }
71
+ const C = Math.hypot(lab[1], lab[2])
72
+ chroma += C
73
+ // a near grey pixel's hue is noise (compression, the VAE): only the chroma past that counts,
74
+ // shared between the two nearest bins so a hue on a bin's edge does not flip the distance
75
+ const w = Math.max(0, C - GREY)
76
+ if (w === 0) continue
77
+ const h = ((Math.atan2(lab[2], lab[1]) + Math.PI) / (2 * Math.PI)) * HUE_BINS - 0.5
78
+ const lo = Math.floor(h)
79
+ const t = h - lo
80
+ hues[(lo + HUE_BINS) % HUE_BINS]! += w * (1 - t)
81
+ hues[(lo + 1) % HUE_BINS]! += w * t
82
+ }
83
+ // and smoothed once over the circle (1, 2, 1): a few degrees of turn is a small distance
84
+ const soft = hues.map((x, k) => x * 2 + hues[(k + HUE_BINS - 1) % HUE_BINS]! + hues[(k + 1) % HUE_BINS]!)
85
+ const total = soft.reduce((a, b) => a + b, 0) || 1
86
+ for (let k = 0; k < HUE_BINS; k++) hues[k] = soft[k]! / total
87
+ const mean = sum.map((s) => s / n) as [number, number, number]
88
+ const spread = sq.map((s, c) => Math.sqrt(Math.max(0, s / n - mean[c]! ** 2))) as [number, number, number]
89
+ return { mean, spread, chroma: chroma / n, hues }
90
+ }
91
+
92
+ /** a frame's drift from the picture, each in its own unit */
93
+ export type Drift = {
94
+ /** ΔE (CIE76) between the two mean colours */
95
+ dE: number
96
+ /** lightness of the mean, frame minus picture (positive: brighter) */
97
+ dL: number
98
+ /** the green (−) to red (+) axis of the mean */
99
+ da: number
100
+ /** the blue (−) to yellow (+) axis of the mean */
101
+ db: number
102
+ /** the frame's lightness spread over the picture's (above 1: more contrast) */
103
+ contrast: number
104
+ /** the frame's mean chroma over the picture's (above 1: more saturated) */
105
+ saturation: number
106
+ /** Hellinger distance of the hue histograms, 0 = the same hues, 1 = none shared */
107
+ hue: number
108
+ }
109
+
110
+ export function driftOf(frame: Palette, picture: Palette): Drift {
111
+ let bc = 0
112
+ for (let k = 0; k < HUE_BINS; k++) bc += Math.sqrt(frame.hues[k]! * picture.hues[k]!)
113
+ const d = frame.mean.map((m, c) => m - picture.mean[c]!) as [number, number, number]
114
+ return {
115
+ dE: Math.hypot(...d),
116
+ dL: d[0],
117
+ da: d[1],
118
+ db: d[2],
119
+ contrast: frame.spread[0] / Math.max(picture.spread[0], 1e-6),
120
+ saturation: frame.chroma / Math.max(picture.chroma, 1e-6),
121
+ hue: Math.sqrt(Math.max(0, 1 - bc)),
122
+ }
123
+ }
124
+
125
+ /** palettes smoothed over time: a gaussian of `sigma` frames over each mean and spread */
126
+ export function smoothPalettes(list: Palette[], sigma: number): Palette[] {
127
+ const r = Math.ceil(sigma * 3)
128
+ return list.map((_, i) => {
129
+ const mean = [0, 0, 0]
130
+ const spread = [0, 0, 0]
131
+ let w = 0
132
+ for (let j = Math.max(0, i - r); j <= Math.min(list.length - 1, i + r); j++) {
133
+ const k = Math.exp(-((j - i) ** 2) / (2 * sigma * sigma))
134
+ for (let c = 0; c < 3; c++) {
135
+ mean[c]! += k * list[j]!.mean[c]!
136
+ spread[c]! += k * list[j]!.spread[c]!
137
+ }
138
+ w += k
139
+ }
140
+ const own = list[i]!
141
+ return { ...own, mean: mean.map((x) => x / w) as Palette['mean'], spread: spread.map((x) => x / w) as Palette['spread'] }
142
+ })
143
+ }
144
+
145
+ /** the frame moved toward the picture's Lab mean and spread, per channel, `strength` of the way
146
+ * (1 = all of it); the spread gain stays within 0.5 to 2, so a frame of one material is not blown up */
147
+ export function matchFrame(rgb: Uint8Array, from: Palette, to: Palette, strength: number): Uint8Array {
148
+ const gain = [0, 1, 2].map((c) => Math.min(2, Math.max(0.5, to.spread[c]! / Math.max(from.spread[c]!, 1e-6))))
149
+ const out = new Uint8Array(rgb.length)
150
+ for (let i = 0; i < rgb.length; i += 3) {
151
+ const lab = rgbToLab(rgb[i]!, rgb[i + 1]!, rgb[i + 2]!)
152
+ const moved = lab.map((x, c) => {
153
+ const matched = (x - from.mean[c]!) * gain[c]! + to.mean[c]!
154
+ return x + (matched - x) * strength
155
+ }) as [number, number, number]
156
+ const back = labToRgb(moved[0], moved[1], moved[2])
157
+ out[i] = back[0]
158
+ out[i + 1] = back[1]
159
+ out[i + 2] = back[2]
160
+ }
161
+ return out
162
+ }
163
+
164
+ /** a picture cover-cropped to `width` × `height`, as raw rgb */
165
+ export async function pictureAt(picture: string, width: number, height: number): Promise<Uint8Array> {
166
+ return new Uint8Array(await sharp(picture).removeAlpha().resize(width, height, { fit: 'cover' }).raw().toBuffer())
167
+ }
168
+
169
+ /** a video's width and height */
170
+ export async function videoSize(file: string): Promise<{ width: number; height: number }> {
171
+ const out = await $`ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 ${file}`.text()
172
+ const [width, height] = out.trim().split(',').map(Number) as [number, number]
173
+ return { width, height }
174
+ }
175
+
176
+ /** every frame of a video, `width` × `height` rgb, streamed to `each` */
177
+ export async function eachFrame(file: string, width: number, height: number, each: (rgb: Uint8Array, i: number) => void | Promise<void>): Promise<number> {
178
+ const proc = Bun.spawn(['ffmpeg', '-loglevel', 'error', '-i', file, '-vf', `scale=${width}:${height}`, '-pix_fmt', 'rgb24', '-f', 'rawvideo', '-'], { stdout: 'pipe' })
179
+ const size = width * height * 3
180
+ let buf = new Uint8Array(size)
181
+ let fill = 0
182
+ let i = 0
183
+ for await (const chunk of proc.stdout) {
184
+ let off = 0
185
+ while (off < chunk.length) {
186
+ const take = Math.min(size - fill, chunk.length - off)
187
+ buf.set(chunk.subarray(off, off + take), fill)
188
+ fill += take
189
+ off += take
190
+ if (fill === size) {
191
+ await each(buf, i++)
192
+ buf = new Uint8Array(size)
193
+ fill = 0
194
+ }
195
+ }
196
+ }
197
+ if ((await proc.exited) !== 0) throw new Error(`eachFrame: ffmpeg failed on ${file}`)
198
+ return i
199
+ }
200
+
201
+ /** the drift of every frame of a video from the picture, measured at a small size */
202
+ export async function measureVideo(picture: string, file: string): Promise<Drift[]> {
203
+ const size = await videoSize(file)
204
+ const width = 192
205
+ const height = Math.round((size.height / size.width) * width / 2) * 2
206
+ const ref = paletteOf(await pictureAt(picture, width, height))
207
+ const out: Drift[] = []
208
+ await eachFrame(file, width, height, (rgb) => void out.push(driftOf(paletteOf(rgb), ref)))
209
+ return out
210
+ }
211
+
212
+ /** every frame of a video matched to the picture (its stats smoothed over a sixth of a second: wider, a drifting start pulls frame 0 off the picture), into an mp4 at its fps */
213
+ export async function matchVideo(p: { picture: string; input: string; output: string; strength: number }): Promise<void> {
214
+ const size = await videoSize(p.input)
215
+ const fps = (await $`ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of csv=p=0 ${p.input}`.text()).trim()
216
+ const small = { width: 192, height: Math.round((size.height / size.width) * 96) * 2 }
217
+ const ref = paletteOf(await pictureAt(p.picture, small.width, small.height))
218
+ const own: Palette[] = []
219
+ await eachFrame(p.input, small.width, small.height, (rgb) => void own.push(paletteOf(rgb)))
220
+ const fpsValue = fps.split('/').map(Number).reduce((a, b) => a / b)
221
+ const smooth = smoothPalettes(own, fpsValue / 6)
222
+ const enc = Bun.spawn(
223
+ ['ffmpeg', '-loglevel', 'error', '-y', '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-s', `${size.width}x${size.height}`, '-r', fps, '-i', '-', '-c:v', 'libx264', '-crf', '12', '-pix_fmt', 'yuv420p', p.output],
224
+ { stdin: 'pipe' },
225
+ )
226
+ await eachFrame(p.input, size.width, size.height, (rgb, i) => {
227
+ const from = smooth[i]
228
+ if (from == null) throw new Error(`matchVideo: frame ${i} was not measured`)
229
+ enc.stdin.write(matchFrame(rgb, from, ref, p.strength))
230
+ })
231
+ await enc.stdin.end()
232
+ if ((await enc.exited) !== 0) throw new Error(`matchVideo: the encoder failed on ${p.output}`)
233
+ }
234
+
235
+ /** the drift curves of several videos as one picture: a panel per measure, a line per video */
236
+ export async function driftChart(series: { label: string; drift: Drift[] }[], out: string): Promise<void> {
237
+ const panels: { key: keyof Drift; title: string; lo: number; hi: number; mark?: number }[] = [
238
+ { key: 'dE', title: 'ΔE of the mean colour (0 = the picture)', lo: 0, hi: 20 },
239
+ { key: 'dL', title: 'lightness of the mean, against the picture', lo: -25, hi: 25, mark: 0 },
240
+ { key: 'saturation', title: 'saturation, against the picture (1 = the same)', lo: 0, hi: 3, mark: 1 },
241
+ { key: 'contrast', title: 'contrast, against the picture (1 = the same)', lo: 0, hi: 3, mark: 1 },
242
+ { key: 'hue', title: 'hue histogram distance (0 = the same hues)', lo: 0, hi: 0.6 },
243
+ { key: 'da', title: 'green (−) to red (+), against the picture', lo: -8, hi: 8, mark: 0 },
244
+ { key: 'db', title: 'blue (−) to yellow (+), against the picture', lo: -8, hi: 8, mark: 0 },
245
+ ]
246
+ const colours = ['#e6550d', '#3182bd', '#31a354', '#756bb1', '#d6616b', '#8c6d31', '#17becf']
247
+ const W = 520
248
+ const H = 190
249
+ const pad = { l: 44, r: 12, t: 26, b: 20 }
250
+ const cols = 2
251
+ const legend = 28
252
+ const width = W * cols
253
+ const height = legend + H * Math.ceil(panels.length / cols)
254
+ const frames = Math.max(...series.map((s) => s.drift.length), 2)
255
+ const parts: string[] = [`<rect width="${width}" height="${height}" fill="#ffffff"/>`]
256
+ series.forEach((s, i) => {
257
+ const x = 12 + i * 170
258
+ parts.push(`<rect x="${x}" y="9" width="14" height="4" fill="${colours[i % colours.length]}"/><text x="${x + 20}" y="16" font-size="13" font-family="Helvetica" fill="#222">${s.label}</text>`)
259
+ })
260
+ panels.forEach((panel, k) => {
261
+ const ox = (k % cols) * W
262
+ const oy = legend + Math.floor(k / cols) * H
263
+ const pw = W - pad.l - pad.r
264
+ const ph = H - pad.t - pad.b
265
+ const X = (i: number) => ox + pad.l + (i / (frames - 1)) * pw
266
+ const Y = (v: number) => oy + pad.t + (1 - (Math.max(panel.lo, Math.min(panel.hi, v)) - panel.lo) / (panel.hi - panel.lo)) * ph
267
+ parts.push(`<text x="${ox + pad.l}" y="${oy + 16}" font-size="13" font-family="Helvetica" fill="#222">${panel.title}</text>`)
268
+ parts.push(`<rect x="${ox + pad.l}" y="${oy + pad.t}" width="${pw}" height="${ph}" fill="none" stroke="#ccc"/>`)
269
+ for (const v of [panel.lo, panel.hi]) parts.push(`<text x="${ox + pad.l - 4}" y="${Y(v) + 4}" font-size="11" text-anchor="end" font-family="Helvetica" fill="#666">${v}</text>`)
270
+ if (panel.mark != null) parts.push(`<line x1="${X(0)}" x2="${X(frames - 1)}" y1="${Y(panel.mark)}" y2="${Y(panel.mark)}" stroke="#999" stroke-dasharray="3 3"/>`)
271
+ series.forEach((s, i) => {
272
+ const d = s.drift.map((x, j) => `${j === 0 ? 'M' : 'L'}${X(j).toFixed(1)},${Y(x[panel.key]).toFixed(1)}`).join('')
273
+ parts.push(`<path d="${d}" fill="none" stroke="${colours[i % colours.length]}" stroke-width="1.6"/>`)
274
+ })
275
+ })
276
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">${parts.join('')}</svg>`
277
+ await sharp(Buffer.from(svg)).png().toFile(out)
278
+ }
279
+
280
+ /** one line per video: the mean of each measure over its frames, and its worst ΔE */
281
+ export function driftSummary(label: string, drift: Drift[]): string {
282
+ const avg = (k: keyof Drift) => drift.reduce((a, d) => a + d[k], 0) / Math.max(drift.length, 1)
283
+ const worst = Math.max(...drift.map((d) => d.dE))
284
+ return `${label}: ΔE ${avg('dE').toFixed(1)} (worst ${worst.toFixed(1)}), L ${avg('dL').toFixed(1)}, a ${avg('da').toFixed(1)}, b ${avg('db').toFixed(1)}, contrast ${avg('contrast').toFixed(2)}, saturation ${avg('saturation').toFixed(2)}, hue ${avg('hue').toFixed(3)}`
285
+ }
286
+
287
+ if (import.meta.main) {
288
+ const [mode, picture, ...rest] = process.argv.slice(2)
289
+ if (mode === 'measure' && picture != null && rest.length >= 2) {
290
+ const [out, ...pairs] = rest
291
+ const series: { label: string; drift: Drift[] }[] = []
292
+ for (const pair of pairs) {
293
+ const at = pair.indexOf('=')
294
+ const label = at < 0 ? pair : pair.slice(0, at)
295
+ const drift = await measureVideo(picture, at < 0 ? pair : pair.slice(at + 1))
296
+ series.push({ label, drift })
297
+ console.log(driftSummary(label, drift))
298
+ }
299
+ await driftChart(series, out!)
300
+ writeFileSync(`${out}.json`, JSON.stringify(series.map((s) => ({ label: s.label, summary: driftSummary(s.label, s.drift), drift: s.drift }))))
301
+ console.log(`🟢 ${out}`)
302
+ } else if (mode === 'match' && picture != null && rest.length >= 2) {
303
+ const [input, output, strength] = rest
304
+ await matchVideo({ picture, input: input!, output: output!, strength: Number(strength ?? 1) })
305
+ console.log(`🟢 ${output}`)
306
+ } else
307
+ throw new Error(
308
+ 'usage: bun examples/rvion/flythroughPalette.ts measure <picture> <out.png> <label>=<video> … | match <picture> <in.mp4> <out.mp4> [strength]',
309
+ )
310
+ }
@@ -0,0 +1,177 @@
1
+ // the camera paths of 19-flythrough, pure numbers: no host, so a test or a script loads them alone
2
+
3
+ /** one camera of the walk, in the render's world (three.js: y up, the picture's camera at the
4
+ * origin looking down -z, as MoGe's mesh is placed) */
5
+ export type PathCamera = { position: [number, number, number]; target: [number, number, number] }
6
+
7
+ /**
8
+ * the walk: `distance` metres forward with an eased speed (still at both ends, so frame 0 is the
9
+ * picture), the heading turning `turn` degrees (positive = right) and the eye rising `rise` metres
10
+ * on the same ease. The camera always looks along its heading, one metre ahead, `pitch` degrees down
11
+ */
12
+ export function walkPath(p: { frames: number; distance: number; turn: number; rise: number; pitch?: number }): PathCamera[] {
13
+ const down = ((p.pitch ?? 0) * Math.PI) / 180
14
+ const ease = (t: number) => t * t * (3 - 2 * t)
15
+ const out: PathCamera[] = []
16
+ let x = 0
17
+ let z = 0
18
+ let prev = 0
19
+ for (let i = 0; i < p.frames; i++) {
20
+ const s = p.frames === 1 ? 0 : ease(i / (p.frames - 1))
21
+ const heading = (p.turn * s * Math.PI) / 180
22
+ // integrate along the heading at the middle of the step, so a turn bends the path
23
+ const mid = (p.turn * ((s + prev) / 2) * Math.PI) / 180
24
+ x += (s - prev) * p.distance * Math.sin(mid)
25
+ z -= (s - prev) * p.distance * Math.cos(mid)
26
+ prev = s
27
+ const y = p.rise * s
28
+ out.push({ position: [x, y, z], target: [x + Math.sin(heading) * Math.cos(down), y - Math.sin(down), z - Math.cos(heading) * Math.cos(down)] })
29
+ }
30
+ return out
31
+ }
32
+
33
+ /**
34
+ * around a thing: fly from the picture's camera toward `center` (x, z on the floor of the render's
35
+ * world), bend into a circle of `radius` metres around it and sweep `sweep` degrees (positive = the
36
+ * camera goes round by the right), the eye at its height and the thing centred. One steady speed over the whole path, eased
37
+ * only at its two ends, so clips cut from it (`frames` per clip, the last frame of one the first of
38
+ * the next) join without a jump. `centerY` is the thing's height against the eye (below: negative),
39
+ * `pitch` the degrees the first frame looks down, as the picture did
40
+ */
41
+ export function orbitPath(p: { frames: number; center: [number, number]; radius: number; sweep: number; centerY?: number; pitch?: number }): PathCamera[] {
42
+ const [cx, cz] = p.center
43
+ const cy = p.centerY ?? 0
44
+ const down = ((p.pitch ?? 0) * Math.PI) / 180
45
+ const dist = Math.hypot(cx, cz)
46
+ if (dist <= p.radius) throw new Error(`orbitPath: the camera starts inside the circle (${dist.toFixed(2)} m from its centre, radius ${p.radius} m)`)
47
+ // the circle starts where the line from the centre to the camera meets it
48
+ const phi0 = Math.atan2(-cx, -cz)
49
+ const onCircle = (phi: number): [number, number] => [cx + p.radius * Math.sin(phi), cz + p.radius * Math.cos(phi)]
50
+ const sweep = (p.sweep * Math.PI) / 180
51
+ const dir = Math.sign(sweep) || 1
52
+ // the approach: a cubic curve leaving straight ahead (-z) and landing on the circle along its tangent
53
+ const [ex, ez] = onCircle(phi0)
54
+ const approach = Math.hypot(ex, ez)
55
+ const tangent: [number, number] = [dir * Math.cos(phi0), -dir * Math.sin(phi0)]
56
+ const k = approach / 2.5
57
+ const ctrl: [number, number][] = [[0, 0], [0, -k], [ex - tangent[0] * k, ez - tangent[1] * k], [ex, ez]]
58
+ const bezier = (t: number): [number, number] => {
59
+ const u = 1 - t
60
+ const w = [u * u * u, 3 * u * u * t, 3 * u * t * t, t * t * t] as const
61
+ return [0, 1].map((a) => ctrl.reduce((acc, c, i) => acc + w[i]! * c[a]!, 0)) as [number, number]
62
+ }
63
+ // dense samples of the whole path: position, then where it looks
64
+ const samples: { at: [number, number]; look: [number, number, number] }[] = []
65
+ const N = 4000
66
+ for (let i = 0; i <= N; i++) {
67
+ const t = i / N
68
+ const at = bezier(t)
69
+ // the look turns from straight ahead to the centre over the approach
70
+ const ease = t * t * (3 - 2 * t)
71
+ const ahead: [number, number, number] = [at[0], -dist * Math.sin(down), at[1] - dist * Math.cos(down)]
72
+ samples.push({ at, look: [ahead[0] + (cx - ahead[0]) * ease, ahead[1] + (cy - ahead[1]) * ease, ahead[2] + (cz - ahead[2]) * ease] })
73
+ }
74
+ for (let i = 1; i <= N; i++) samples.push({ at: onCircle(phi0 + (sweep * i) / N), look: [cx, cy, cz] })
75
+ const cum = [0]
76
+ for (let i = 1; i < samples.length; i++) {
77
+ const a = samples[i - 1]!.at
78
+ const b = samples[i]!.at
79
+ cum.push(cum[i - 1]! + Math.hypot(b[0] - a[0], b[1] - a[1]))
80
+ }
81
+ const total = cum.at(-1) ?? 0
82
+ // steady speed, its ramp up and down over the first and last tenth of the path's time
83
+ const ramp = 0.1
84
+ const along = (t: number): number => {
85
+ const v = 1 / (1 - ramp)
86
+ if (t < ramp) return (v * t * t) / (2 * ramp)
87
+ if (t > 1 - ramp) return 1 - (v * (1 - t) * (1 - t)) / (2 * ramp)
88
+ return v * (t - ramp / 2)
89
+ }
90
+ const out: PathCamera[] = []
91
+ let j = 0
92
+ for (let f = 0; f < p.frames; f++) {
93
+ const want = along(p.frames === 1 ? 0 : f / (p.frames - 1)) * total
94
+ while (j < cum.length - 2 && cum[j + 1]! < want) j++
95
+ const a = samples[j]!
96
+ const b = samples[j + 1] ?? a
97
+ const span = cum[j + 1]! - cum[j]!
98
+ const r = span > 0 ? Math.min(1, Math.max(0, (want - cum[j]!) / span)) : 0
99
+ const mix = (x: number, y: number) => x + (y - x) * r
100
+ out.push({
101
+ position: [mix(a.at[0], b.at[0]), 0, mix(a.at[1], b.at[1])],
102
+ target: [mix(a.look[0], b.look[0]), mix(a.look[1], b.look[1]), mix(a.look[2], b.look[2])],
103
+ })
104
+ }
105
+ return out
106
+ }
107
+
108
+ /** the settings that place every camera of a fly-through, all its clips together */
109
+ export type PathSettings = {
110
+ path: 'walk' | 'orbit'
111
+ /** frames of one clip; clips share their joining frame */
112
+ length: number
113
+ clips: number
114
+ fovX: number
115
+ distance: number
116
+ turn: number
117
+ rise: number
118
+ aim: number
119
+ /** the aimed thing's row in the picture, 0 = top edge, 1 = bottom edge */
120
+ aimRow: number
121
+ /** the picture's height over its width: the aimed row's angle */
122
+ aspect: number
123
+ aimDistance: number
124
+ radius: number
125
+ sweep: number
126
+ /** degrees the picture's camera looks down at its floor. The path's world is levelled by it: y is
127
+ * the floor's up, the orbit circles round that vertical, and frame 0 still looks down as the
128
+ * picture did. A mesh in the picture's camera axes takes the same turn (levelPoint) */
129
+ pitch: number
130
+ }
131
+
132
+ /** every camera of the whole path, `clips × (length - 1) + 1` of them; clip `k` is frames
133
+ * `k × (length - 1)` to `(k + 1) × (length - 1)` */
134
+ export function pathCameras(p: PathSettings): PathCamera[] {
135
+ const frames = p.clips * (p.length - 1) + 1
136
+ if (p.path === 'walk') return walkPath({ frames, distance: p.distance, turn: p.turn, rise: p.rise, pitch: p.pitch })
137
+ // the aimed thing: the picture's pixel (`aim`, `aimRow`), `aimDistance` along its ray, levelled
138
+ const half = Math.tan((p.fovX * Math.PI) / 360)
139
+ const ray: [number, number, number] = [(p.aim - 0.5) * 2 * half, (0.5 - p.aimRow) * 2 * half * p.aspect, -1]
140
+ const length = Math.hypot(...ray)
141
+ const [cx, cy, cz] = levelPoint(
142
+ ray.map((x) => (x / length) * p.aimDistance) as [number, number, number],
143
+ p.pitch,
144
+ )
145
+ return orbitPath({ frames, center: [cx, cz], centerY: cy, radius: p.radius, sweep: p.sweep, pitch: p.pitch })
146
+ }
147
+
148
+ /** a point of the picture's camera axes (y up, -z ahead) in the path's levelled world: turned
149
+ * `pitch` degrees about x, so the picture's view axis points that much below the horizon */
150
+ export function levelPoint(q: [number, number, number], pitch: number): [number, number, number] {
151
+ const a = (pitch * Math.PI) / 180
152
+ return [q[0], q[1] * Math.cos(a) + q[2] * Math.sin(a), -q[1] * Math.sin(a) + q[2] * Math.cos(a)]
153
+ }
154
+
155
+ /** the vertical field of view of the frame Wan sees: the picture cover-cropped to `size`, its
156
+ * focal length set by its horizontal field of view */
157
+ export function frameFovY(p: { picture: { width: number; height: number }; fovX: number; size: { width: number; height: number } }): number {
158
+ const focal = p.picture.width / 2 / Math.tan((p.fovX * Math.PI) / 360)
159
+ const aspect = p.size.width / p.size.height
160
+ const croppedWidth = p.picture.width / p.picture.height > aspect
161
+ const visibleHeight = croppedWidth ? p.picture.height : p.picture.width / aspect
162
+ return (2 * Math.atan(visibleHeight / 2 / focal) * 180) / Math.PI
163
+ }
164
+
165
+ /** the video models a fly-through can use: their frame rate, and the frame counts they take */
166
+ export const ENGINES = {
167
+ /** Wan 2.2 Fun Control 14B: 16 fps, 4n+1 frames */
168
+ wan: { fps: 16, frames: (n: number) => Math.max(5, Math.round((n - 1) / 4) * 4 + 1) },
169
+ /** MiniMax H3 with its Fun ControlNet: 24 fps, 17k+5 frames (snapped up, as its own template) */
170
+ h3: { fps: 24, frames: (n: number) => Math.max(5, n) + ((5 - (Math.max(5, n) % 17) + 17) % 17) },
171
+ } as const
172
+ export type Engine = keyof typeof ENGINES
173
+
174
+ /** the frames of one clip of `seconds` for an engine */
175
+ export function clipFrames(engine: Engine, seconds: number): number {
176
+ return ENGINES[engine].frames(Math.round(seconds * ENGINES[engine].fps))
177
+ }
@@ -0,0 +1,73 @@
1
+ // a splat trained on a fly-through (Brush, on flythroughColmap.ts's export) into the axes the world
2
+ // viewers read, SHARP's: x right, y down, z ahead, the picture's camera. The fly-through's world is
3
+ // y up, -z ahead, levelled by the picture's pitch, so every splat turns 180° + pitch about x (at
4
+ // pitch 0: positions (x, -y, -z), rotations q' = (0, 1, 0, 0) ⊗ q). The view dependent colour
5
+ // (f_rest) is dropped rather than turned: the base colour stays exact.
6
+ //
7
+ // run: bun examples/rvion/flythroughSplat.ts <trained.ply> <out.ply> [pitch]
8
+ import { readFileSync, writeFileSync } from 'node:fs'
9
+
10
+ /** a binary 3DGS ply of float properties, its header and one Float32Array row per splat */
11
+ export function readSplatPly(bytes: Uint8Array): { names: string[]; count: number; data: Float32Array } {
12
+ const head = new TextDecoder('latin1').decode(bytes.subarray(0, Math.min(bytes.length, 65536)))
13
+ const end = head.indexOf('end_header\n')
14
+ if (end < 0) throw new Error('readSplatPly: no end_header')
15
+ const header = head.slice(0, end)
16
+ if (!header.includes('format binary_little_endian')) throw new Error('readSplatPly: not a binary little endian ply')
17
+ const count = Number(/element vertex (\d+)/.exec(header)?.[1] ?? Number.NaN)
18
+ if (!Number.isFinite(count)) throw new Error('readSplatPly: no vertex count')
19
+ const lines = header.split('\n')
20
+ const vertexAt = lines.findIndex((l) => l.startsWith('element vertex'))
21
+ const names: string[] = []
22
+ for (const line of lines.slice(vertexAt + 1)) {
23
+ if (line.startsWith('element')) break
24
+ const m = /^property (\S+) (\S+)$/.exec(line)
25
+ if (m == null) continue
26
+ if (m[1] !== 'float') throw new Error(`readSplatPly: property ${m[2]} is ${m[1]}, only float is read`)
27
+ names.push(m[2]!)
28
+ }
29
+ const start = end + 'end_header\n'.length
30
+ const data = new Float32Array(bytes.slice(start, start + count * names.length * 4).buffer)
31
+ return { names, count, data }
32
+ }
33
+
34
+ /** the turned splats, as a ply with the standard property order; `pitch` the path's (degrees) */
35
+ export function toViewerAxes(ply: { names: string[]; count: number; data: Float32Array }, pitch = 0): Uint8Array {
36
+ const angle = Math.PI + (pitch * Math.PI) / 180
37
+ const cos = Math.cos(angle)
38
+ const sin = Math.sin(angle)
39
+ // the turn as a quaternion (w, x): (cos, sin) of the half angle about x
40
+ const hw = Math.cos(angle / 2)
41
+ const hx = Math.sin(angle / 2)
42
+ const at = (name: string) => {
43
+ const i = ply.names.indexOf(name)
44
+ if (i < 0) throw new Error(`toViewerAxes: no property ${name}`)
45
+ return i
46
+ }
47
+ const src = ['x', 'y', 'z', 'f_dc_0', 'f_dc_1', 'f_dc_2', 'opacity', 'scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3'].map(at)
48
+ const P = ply.names.length
49
+ const out = new Float32Array(ply.count * 14)
50
+ for (let i = 0; i < ply.count; i++) {
51
+ const v = src.map((k) => ply.data[i * P + k]!)
52
+ const [x, y, z, r, g, b, o, s0, s1, s2, w, qx, qy, qz] = v as [number, number, number, number, number, number, number, number, number, number, number, number, number, number]
53
+ // (hw, hx, 0, 0) ⊗ (w, qx, qy, qz)
54
+ const rot = [hw * w - hx * qx, hw * qx + hx * w, hw * qy - hx * qz, hw * qz + hx * qy]
55
+ out.set([x, y * cos - z * sin, y * sin + z * cos, r, g, b, o, s0, s1, s2, ...rot], i * 14)
56
+ }
57
+ const props = ['x', 'y', 'z', 'f_dc_0', 'f_dc_1', 'f_dc_2', 'opacity', 'scale_0', 'scale_1', 'scale_2', 'rot_0', 'rot_1', 'rot_2', 'rot_3']
58
+ const header = new TextEncoder().encode(
59
+ `ply\nformat binary_little_endian 1.0\nelement vertex ${ply.count}\n${props.map((p) => `property float ${p}`).join('\n')}\nend_header\n`,
60
+ )
61
+ const bytes = new Uint8Array(header.length + out.byteLength)
62
+ bytes.set(header)
63
+ bytes.set(new Uint8Array(out.buffer), header.length)
64
+ return bytes
65
+ }
66
+
67
+ if (import.meta.main) {
68
+ const [input, output, pitch] = process.argv.slice(2)
69
+ if (input == null || output == null) throw new Error('usage: bun examples/rvion/flythroughSplat.ts <trained.ply> <out.ply> [pitch]')
70
+ const ply = readSplatPly(new Uint8Array(readFileSync(input)))
71
+ writeFileSync(output, toViewerAxes(ply, Number(pitch ?? 0)))
72
+ console.log(`🟢 ${ply.count} splats turned to the viewer's axes: ${output}`)
73
+ }