comfy-ts 2.23.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 (76) hide show
  1. package/dist/{ServeApp-DolRCMHj.js → ServeApp-fsHtW5zG.js} +3 -3
  2. package/dist/{ServeApp-DolRCMHj.js.map → ServeApp-fsHtW5zG.js.map} +1 -1
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-Duneoq6r.js → exampleAssets-DZynSkZm.js} +79 -15
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-DjoJA8y7.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-DjoJA8y7.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +80 -14
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +53 -19
  11. package/dist/index.d.ts +53 -19
  12. package/dist/index.js +80 -15
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Cr0L9lCK.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Cr0L9lCK.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve---qA7o_m.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve---qA7o_m.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-DxXiWo5J.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-DxXiWo5J.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-BTxdABHi.js → schemaDrift-BGYJZGMD.js} +3 -2
  21. package/dist/{schemaDrift-BTxdABHi.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/web.d.ts +53 -19
  23. package/dist/web.js +80 -15
  24. package/dist/web.js.map +1 -1
  25. package/examples/README.md +1 -0
  26. package/examples/depth-explorer/models.ts +6 -56
  27. package/examples/depth-explorer/serve.ts +12 -133
  28. package/examples/depth-explorer/web/App.tsx +20 -91
  29. package/examples/depth-explorer/web/index.html +1 -0
  30. package/examples/depth-explorer/web/state.ts +26 -109
  31. package/examples/depth-explorer/web/styles.css +1 -286
  32. package/examples/explorer-kit/catalog.ts +80 -0
  33. package/examples/explorer-kit/server.ts +167 -0
  34. package/examples/explorer-kit/web/base.css +289 -0
  35. package/examples/explorer-kit/web/runs.ts +160 -0
  36. package/examples/explorer-kit/web/ui.tsx +125 -0
  37. package/examples/rvion/17-relight.cflow.ts +2 -1
  38. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  39. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  40. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  41. package/examples/rvion/flythroughChain.ts +171 -0
  42. package/examples/rvion/flythroughColmap.ts +157 -0
  43. package/examples/rvion/flythroughFuse.ts +199 -0
  44. package/examples/rvion/flythroughGuide.ts +300 -0
  45. package/examples/rvion/flythroughPalette.ts +310 -0
  46. package/examples/rvion/flythroughPath.ts +177 -0
  47. package/examples/rvion/flythroughSplat.ts +73 -0
  48. package/examples/rvion/grow-splat/align.ts +114 -0
  49. package/examples/rvion/grow-splat/grow.ts +198 -0
  50. package/examples/rvion/grow-splat/ply.ts +166 -0
  51. package/examples/rvion/grow-splat/raster.ts +207 -0
  52. package/examples/rvion/grow-splat/sharp.ts +45 -0
  53. package/examples/rvion/splatDataset.ts +80 -0
  54. package/examples/rvion/splatEval.ts +380 -0
  55. package/examples/upscale-explorer/models.ts +341 -0
  56. package/examples/upscale-explorer/serve.ts +19 -0
  57. package/examples/upscale-explorer/web/App.tsx +250 -0
  58. package/examples/upscale-explorer/web/compare.tsx +285 -0
  59. package/examples/upscale-explorer/web/index.html +15 -0
  60. package/examples/upscale-explorer/web/main.tsx +12 -0
  61. package/examples/upscale-explorer/web/state.ts +279 -0
  62. package/examples/upscale-explorer/web/styles.css +241 -0
  63. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  64. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  65. package/examples/world-explorer/web/main.tsx +2 -2
  66. package/package.json +4 -3
  67. package/src/coreExports.ts +5 -0
  68. package/src/host/ComfyHost.ts +6 -0
  69. package/src/runner/ComfyExecution.ts +22 -5
  70. package/src/runner/ComfyWorkflow.ts +22 -0
  71. package/src/runner/ComfyWsApi.ts +1 -1
  72. package/src/runner/comfyOrgApiKey.ts +44 -0
  73. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  74. package/src/state.ts +2 -0
  75. package/src/vars/DefinedWorkflow.ts +1 -0
  76. package/dist/exampleAssets-Duneoq6r.js.map +0 -1
@@ -0,0 +1,171 @@
1
+ // a long fly-through, clip by clip: 19-flythrough cut along one camera path, each clip started
2
+ // from the last frame of the clip before. The picture's MoGe mesh is made once on the box and kept,
3
+ // the guide of every clip is drawn here (flythroughGuide.ts), so the box only runs Wan.
4
+ // Writes into <out>: mesh.glb, clip-<k>.mp4 with its guide, colour render and coverage beside it,
5
+ // cameras.json (every frame's camera), and flythrough.mp4, the clips joined. Each clip is the video
6
+ // model's (clip-<k>-raw.mp4) pulled back to the picture's palette frame by frame, so the colours
7
+ // hold across the clips and the frames a splat trainer reads agree.
8
+ //
9
+ // run: bun examples/rvion/flythroughChain.ts <picture> <settings.json> <out> [from] [to]
10
+ // settings.json holds 19-flythrough's vars ({ "path": "orbit", "clips": 7, "fov": 62, … })
11
+ import { $ } from 'bun'
12
+ import { mkdirSync, existsSync, readFileSync, writeFileSync } from 'node:fs'
13
+ import { join, resolve } from 'pathe'
14
+ import sharp from 'sharp'
15
+ import { ComfyTS } from 'comfy-ts'
16
+ import flythrough, { chainStart, premadeCoverage, premadeGuide, premadeRender } from './19-flythrough.cflow.ts'
17
+ import { dropStretched, levelMesh, readGlb, renderGuideFrame, type GuideMesh } from './flythroughGuide.ts'
18
+ import { matchFrame, matchVideo, paletteOf, pictureAt } from './flythroughPalette.ts'
19
+ import { clipFrames, ENGINES, frameFovY, pathCameras } from './flythroughPath.ts'
20
+
21
+ const [picture, settingsPath, out, fromArg, toArg] = process.argv.slice(2)
22
+ if (picture == null || settingsPath == null || out == null)
23
+ throw new Error('usage: bun examples/rvion/flythroughChain.ts <picture> <settings.json> <out> [from] [to]')
24
+ mkdirSync(out, { recursive: true })
25
+ const settings = JSON.parse(readFileSync(settingsPath, 'utf8')) as Record<string, unknown>
26
+ for (const [key, value] of Object.entries(settings)) {
27
+ const slot = Object.entries(flythrough.vars).find(([name]) => name === key)?.[1]
28
+ if (slot == null) throw new Error(`settings: no var '${key}' on 19-flythrough`)
29
+ if (!slot.parse(typeof value === 'string' ? value : JSON.stringify(value)))
30
+ throw new Error(`settings: '${key}' does not take ${JSON.stringify(value)}`)
31
+ }
32
+ flythrough.vars.image.set(picture)
33
+ const v = flythrough.vars
34
+
35
+ // the mesh, once: MoGe of the picture on the box, saved as a glb
36
+ const host = ComfyTS.create().host({ id: 'windows-1' })
37
+ await host.loadSchemaFromCache()
38
+ const meshPath = join(out, 'mesh.glb')
39
+ if (!existsSync(meshPath)) {
40
+ const fov = v.fov.value
41
+ const meshFlow = host.defineWorkflow({
42
+ id: 'flythrough-mesh',
43
+ vars: {},
44
+ build: async (b, _vars, wf) => {
45
+ const geometry = b.MoGeInference({
46
+ moge_model: b.LoadMoGeModel({ model_name: 'moge_2_vitl_normal_fp16.safetensors' }),
47
+ image: await v.image.loadInWorkflow(wf),
48
+ fov_x_degrees: fov,
49
+ })
50
+ b.SaveGLB({ mesh: b.MoGePointMapToMesh({ moge_geometry: geometry }), filename_prefix: 'comfy-ts-example/flythrough-mesh' })
51
+ },
52
+ })
53
+ const made = await meshFlow.run({})
54
+ const glb = made.models3d[0]
55
+ if (glb == null) throw new Error('flythrough chain: the box sent no mesh back')
56
+ writeFileSync(meshPath, glb.bytes)
57
+ }
58
+ const parsed = readGlb(new Uint8Array(readFileSync(meshPath)))
59
+ const decoded = await sharp(parsed.textureBytes).removeAlpha().raw().toBuffer({ resolveWithObject: true })
60
+ // without its curtains (dropStretched): seen from the side they are streaks Wan would copy; in the
61
+ // path's levelled world (the picture's pitch)
62
+ const mesh: GuideMesh = levelMesh(
63
+ dropStretched({ ...parsed, texture: { width: decoded.info.width, height: decoded.info.height, rgb: new Uint8Array(decoded.data) } }, 3),
64
+ v.pitch.value,
65
+ )
66
+
67
+ // the whole path, every camera, written once
68
+ const source = v.size.imageSize()
69
+ if (source == null) throw new Error(`flythrough chain: cannot read the size of ${picture}`)
70
+ const length = clipFrames(v.engine.value, v.seconds.value)
71
+ const fps = ENGINES[v.engine.value].fps
72
+ const cameras = pathCameras({
73
+ path: v.path.value,
74
+ length,
75
+ clips: v.clips.value,
76
+ fovX: v.fov.value,
77
+ distance: v.distance.value,
78
+ turn: v.turn.value,
79
+ rise: v.rise.value,
80
+ aim: v.aim.value,
81
+ aimRow: v.aimRow.value,
82
+ aspect: source.height / source.width,
83
+ aimDistance: v.aimDistance.value,
84
+ radius: v.radius.value,
85
+ sweep: v.sweep.value,
86
+ pitch: v.pitch.value,
87
+ })
88
+ const size = v.size.value
89
+ const fovY = frameFovY({ picture: source, fovX: v.fov.value, size })
90
+ writeFileSync(join(out, 'cameras.json'), JSON.stringify({ fovY, pitch: v.pitch.value, width: size.width, height: size.height, length, cameras }, null, 1))
91
+
92
+ /** frames of raw rgb into an mp4 at the engine's fps */
93
+ const encode = async (frames: Uint8Array[], file: string) => {
94
+ const dir = `${file}.frames`
95
+ mkdirSync(dir, { recursive: true })
96
+ await Promise.all(
97
+ frames.map((rgb, i) =>
98
+ sharp(rgb, { raw: { width: size.width, height: size.height, channels: 3 } })
99
+ .png({ compressionLevel: 1 })
100
+ .toFile(join(dir, `${String(i).padStart(4, '0')}.png`)),
101
+ ),
102
+ )
103
+ await $`ffmpeg -loglevel error -y -framerate ${fps} -i ${join(dir, '%04d.png')} -c:v libx264 -crf 12 -pix_fmt yuv420p ${file}`
104
+ await $`rm -rf ${dir}`
105
+ }
106
+
107
+ /** a chained clip starts from the last frame of the one before, and each clip drifts a little in
108
+ * colour: before it seeds the next clip, that frame moves to the picture's Lab mean and spread
109
+ * (flythroughPalette.ts), so the drift cannot add up from clip to clip */
110
+ async function matchColours(frame: string, reference: string): Promise<string> {
111
+ const img = await sharp(frame).removeAlpha().raw().toBuffer({ resolveWithObject: true })
112
+ const own = new Uint8Array(img.data)
113
+ const target = paletteOf(await pictureAt(reference, img.info.width, img.info.height))
114
+ const data = matchFrame(own, paletteOf(own), target, 1)
115
+ const outFile = frame.replace(/\.png$/, '-matched.png')
116
+ await sharp(data, { raw: { width: img.info.width, height: img.info.height, channels: 3 } }).png().toFile(outFile)
117
+ return outFile
118
+ }
119
+
120
+ const from = Number(fromArg ?? 0)
121
+ const to = Number(toArg ?? v.clips.value - 1)
122
+ for (let k = from; k <= to; k++) {
123
+ const t0 = Date.now()
124
+ const own = cameras.slice(k * (length - 1), k * (length - 1) + length)
125
+ const frames = own.map((camera) => renderGuideFrame({ mesh, camera, width: size.width, height: size.height, fovY, fill: v.holes.value === 'filled' }))
126
+ const guide = join(out, `clip-${k}-guide.mp4`)
127
+ await encode(frames.map((f) => (v.guide.value === 'depth' ? f.depth : f.color)), guide)
128
+ const render = join(out, `clip-${k}-render.mp4`)
129
+ const coverage = join(out, `clip-${k}-coverage.mp4`)
130
+ await encode(frames.map((f) => f.color), render)
131
+ await encode(frames.map((f) => f.coverage), coverage)
132
+ const drawn = ((Date.now() - t0) / 1000).toFixed(1)
133
+
134
+ premadeGuide.set(guide)
135
+ premadeRender.set(render)
136
+ premadeCoverage.set(coverage)
137
+ if (k === 0) chainStart.set('')
138
+ else {
139
+ const last = join(out, `clip-${k - 1}-last.png`)
140
+ await $`ffmpeg -loglevel error -y -sseof -0.3 -i ${join(out, `clip-${k - 1}.mp4`)} -update 1 -frames:v 1 ${last}`
141
+ chainStart.set(await matchColours(last, picture))
142
+ }
143
+ v.clip.set(k)
144
+ const t1 = Date.now()
145
+ const execution = await flythrough.run({})
146
+ const clip = execution.videos.find((x) => x.tags.includes('clip'))
147
+ if (clip == null) throw new Error(`flythrough chain: clip ${k} came back without its video`)
148
+ const raw = join(out, `clip-${k}-raw.mp4`)
149
+ writeFileSync(raw, clip.bytes)
150
+ await matchVideo({ picture, input: raw, output: join(out, `clip-${k}.mp4`), strength: 1 })
151
+ console.log(`🟢 clip ${k}: guide drawn in ${drawn} s, ${v.engine.value} in ${((Date.now() - t1) / 1000).toFixed(0)} s`)
152
+ }
153
+
154
+ // the joined video: every clip after the first loses its first frame, the last frame of the one before
155
+ const parts: string[] = []
156
+ for (let k = 0; k < v.clips.value; k++) {
157
+ const file = join(out, `clip-${k}.mp4`)
158
+ if (!existsSync(file)) break
159
+ if (k === 0) parts.push(file)
160
+ else {
161
+ const trimmed = join(out, `clip-${k}-trimmed.mp4`)
162
+ const dropFirst = `select=gte(n\\,1),setpts=N/${fps}/TB`
163
+ await $`ffmpeg -loglevel error -y -i ${file} -vf ${dropFirst} -r ${fps} -c:v libx264 -crf 14 -pix_fmt yuv420p ${trimmed}`
164
+ parts.push(trimmed)
165
+ }
166
+ }
167
+ writeFileSync(join(out, 'parts.txt'), parts.map((p) => `file '${resolve(p)}'`).join('\n'))
168
+ await $`ffmpeg -loglevel error -y -f concat -safe 0 -i ${join(out, 'parts.txt')} -c copy ${join(out, 'flythrough.mp4')}`
169
+ console.log(`🟢 ${parts.length} clips joined: ${join(out, 'flythrough.mp4')}`)
170
+ host.disconnect()
171
+ process.exit(0)
@@ -0,0 +1,157 @@
1
+ // a fly-through as a COLMAP text model, for a 3D gaussian splat trainer that reads one (Brush,
2
+ // gsplat, nerfstudio): every `every`-th frame of the clips as an image, the camera we chose for it
3
+ // as its pose (retimed to the guide frame it matches best, as the video runs a little ahead or
4
+ // behind), and the picture's MoGe mesh as the starting points. Reads what flythroughChain.ts wrote into <out>.
5
+ //
6
+ // run: bun examples/rvion/flythroughColmap.ts <out> [every]
7
+ // writes <out>/colmap/images/*.png and <out>/colmap/sparse/0/{cameras,images,points3D}.txt
8
+ import { $ } from 'bun'
9
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
10
+ import { join } from 'pathe'
11
+ import sharp from 'sharp'
12
+ import { readGlb } from './flythroughGuide.ts'
13
+ import { levelPoint, type PathCamera } from './flythroughPath.ts'
14
+
15
+ /** world to camera, COLMAP axes (x right, y down, z ahead), as a quaternion and a translation */
16
+ export function colmapPose(c: PathCamera): { q: [number, number, number, number]; t: [number, number, number] } {
17
+ const f = [c.target[0] - c.position[0], c.target[1] - c.position[1], c.target[2] - c.position[2]]
18
+ const fl = Math.hypot(f[0]!, f[1]!, f[2]!)
19
+ const fw = f.map((x) => x / fl) as [number, number, number]
20
+ const rl = Math.hypot(fw[2], fw[0])
21
+ const r: [number, number, number] = [-fw[2] / rl, 0, fw[0] / rl]
22
+ const u: [number, number, number] = [r[1] * fw[2] - r[2] * fw[1], r[2] * fw[0] - r[0] * fw[2], r[0] * fw[1] - r[1] * fw[0]]
23
+ // rows: camera x, y (down), z in world axes
24
+ const R = [r, [-u[0], -u[1], -u[2]], fw] as const
25
+ const t = R.map((row) => -(row[0] * c.position[0] + row[1] * c.position[1] + row[2] * c.position[2])) as [number, number, number]
26
+ const [m00, m01, m02] = R[0]
27
+ const [m10, m11, m12] = R[1]
28
+ const [m20, m21, m22] = R[2]
29
+ const trace = m00 + m11 + m22
30
+ let q: [number, number, number, number]
31
+ if (trace > 0) {
32
+ const s = 0.5 / Math.sqrt(trace + 1)
33
+ q = [0.25 / s, (m21 - m12) * s, (m02 - m20) * s, (m10 - m01) * s]
34
+ } else if (m00 > m11 && m00 > m22) {
35
+ const s = 2 * Math.sqrt(1 + m00 - m11 - m22)
36
+ q = [(m21 - m12) / s, 0.25 * s, (m01 + m10) / s, (m02 + m20) / s]
37
+ } else if (m11 > m22) {
38
+ const s = 2 * Math.sqrt(1 + m11 - m00 - m22)
39
+ q = [(m02 - m20) / s, (m01 + m10) / s, 0.25 * s, (m12 + m21) / s]
40
+ } else {
41
+ const s = 2 * Math.sqrt(1 + m22 - m00 - m11)
42
+ q = [(m10 - m01) / s, (m02 + m20) / s, (m12 + m21) / s, 0.25 * s]
43
+ }
44
+ return { q, t }
45
+ }
46
+
47
+ /** small grey frames of a video, for matching */
48
+ const SMALL = { width: 104, height: 60 }
49
+ const greyFrames = async (file: string): Promise<Uint8Array> =>
50
+ new Uint8Array(await $`ffmpeg -loglevel error -i ${file} -vf scale=${SMALL.width}:${SMALL.height} -pix_fmt gray -f rawvideo -`.arrayBuffer())
51
+
52
+ /**
53
+ * which guide frame a clip frame shows: the video model runs a little ahead of or behind the path,
54
+ * so the frame takes the camera of the guide frame it matches best (correlation over the pixels the
55
+ * guide covers) within `window` frames; it keeps its own when the match is weak
56
+ */
57
+ export function retime(p: { clip: Uint8Array; render: Uint8Array; coverage: Uint8Array; frame: number; window: number }): { frame: number; score: number } {
58
+ const size = SMALL.width * SMALL.height
59
+ const frames = Math.min(p.render.length, p.coverage.length) / size
60
+ const ncc = (b: number) => {
61
+ let sa = 0
62
+ let sb = 0
63
+ let k = 0
64
+ const ao = p.frame * size
65
+ const bo = b * size
66
+ for (let i = 0; i < size; i++)
67
+ if (p.coverage[bo + i]! > 128) {
68
+ sa += p.clip[ao + i]!
69
+ sb += p.render[bo + i]!
70
+ k++
71
+ }
72
+ if (k < size / 10) return -1
73
+ const ma = sa / k
74
+ const mb = sb / k
75
+ let num = 0
76
+ let da = 0
77
+ let db = 0
78
+ for (let i = 0; i < size; i++)
79
+ if (p.coverage[bo + i]! > 128) {
80
+ const x = p.clip[ao + i]! - ma
81
+ const y = p.render[bo + i]! - mb
82
+ num += x * y
83
+ da += x * x
84
+ db += y * y
85
+ }
86
+ return num / Math.sqrt(da * db || 1)
87
+ }
88
+ let best = { frame: p.frame, score: ncc(Math.min(p.frame, frames - 1)) }
89
+ for (let b = Math.max(0, p.frame - p.window); b <= Math.min(frames - 1, p.frame + p.window); b++) {
90
+ const score = ncc(b)
91
+ if (score > best.score) best = { frame: b, score }
92
+ }
93
+ return best.score < 0.3 ? { frame: p.frame, score: best.score } : best
94
+ }
95
+
96
+ if (import.meta.main) {
97
+ const [out, everyArg] = process.argv.slice(2)
98
+ if (out == null) throw new Error('usage: bun examples/rvion/flythroughColmap.ts <out> [every]')
99
+ const every = Number(everyArg ?? 4)
100
+ const rig = JSON.parse(readFileSync(join(out, 'cameras.json'), 'utf8')) as {
101
+ fovY: number
102
+ pitch?: number
103
+ width: number
104
+ height: number
105
+ length: number
106
+ cameras: PathCamera[]
107
+ }
108
+ const root = join(out, 'colmap')
109
+ const sparse = join(root, 'sparse', '0')
110
+ const imagesDir = join(root, 'images')
111
+ mkdirSync(sparse, { recursive: true })
112
+ mkdirSync(imagesDir, { recursive: true })
113
+
114
+ const focal = rig.height / 2 / Math.tan((rig.fovY * Math.PI) / 360)
115
+ writeFileSync(join(sparse, 'cameras.txt'), `# CAMERA_ID MODEL WIDTH HEIGHT PARAMS[]\n1 PINHOLE ${rig.width} ${rig.height} ${focal} ${focal} ${rig.width / 2} ${rig.height / 2}\n`)
116
+
117
+ const lines = ['# IMAGE_ID QW QX QY QZ TX TY TZ CAMERA_ID NAME', '# POINTS2D (none)']
118
+ let id = 1
119
+ const timing: { clip: number; frame: number; camera: number; score: number }[] = []
120
+ for (let k = 0; existsSync(join(out, `clip-${k}.mp4`)); k++) {
121
+ const dir = join(out, `clip-${k}.frames`)
122
+ mkdirSync(dir, { recursive: true })
123
+ await $`ffmpeg -loglevel error -y -i ${join(out, `clip-${k}.mp4`)} ${join(dir, '%04d.png')}`
124
+ const [clipGrey, renderGrey, coverageGrey] = await Promise.all(
125
+ ['', '-render', '-coverage'].map((tag) => greyFrames(join(out, `clip-${k}${tag}.mp4`))),
126
+ )
127
+ // frame 0 of a later clip is the last frame of the one before: kept once
128
+ for (let j = k === 0 ? 0 : every; j < rig.length; j += every) {
129
+ const match = retime({ clip: clipGrey!, render: renderGrey!, coverage: coverageGrey!, frame: j, window: 12 })
130
+ timing.push({ clip: k, frame: j, camera: match.frame, score: Number(match.score.toFixed(2)) })
131
+ const cam = rig.cameras[k * (rig.length - 1) + match.frame]
132
+ if (cam == null) continue
133
+ const name = `c${k}-f${String(j).padStart(3, '0')}.png`
134
+ await $`cp ${join(dir, `${String(j + 1).padStart(4, '0')}.png`)} ${join(imagesDir, name)}`
135
+ const { q, t } = colmapPose(cam)
136
+ lines.push(`${id++} ${q.join(' ')} ${t.join(' ')} 1 ${name}`, '')
137
+ }
138
+ await $`rm -rf ${dir}`
139
+ }
140
+ writeFileSync(join(sparse, 'images.txt'), `${lines.join('\n')}\n`)
141
+ writeFileSync(join(root, 'retime.json'), JSON.stringify(timing))
142
+
143
+ // starting points: the mesh's vertices, one in 8, coloured from its texture, in the path's levelled world
144
+ const mesh = readGlb(new Uint8Array(readFileSync(join(out, 'mesh.glb'))))
145
+ const tex = await sharp(mesh.textureBytes).removeAlpha().raw().toBuffer({ resolveWithObject: true })
146
+ const pts = ['# POINT3D_ID X Y Z R G B ERROR TRACK[]']
147
+ for (let i = 0, n = 1; i < mesh.positions.length / 3; i += 8) {
148
+ const [x, y, z] = levelPoint([mesh.positions[i * 3]!, mesh.positions[i * 3 + 1]!, mesh.positions[i * 3 + 2]!], rig.pitch ?? 0)
149
+ if (!Number.isFinite(x + y + z)) continue
150
+ const u = Math.round(mesh.uvs[i * 2]! * (tex.info.width - 1))
151
+ const v = Math.round(mesh.uvs[i * 2 + 1]! * (tex.info.height - 1))
152
+ const o = (v * tex.info.width + u) * 3
153
+ pts.push(`${n++} ${x} ${y} ${z} ${tex.data[o]} ${tex.data[o + 1]} ${tex.data[o + 2]} 0`)
154
+ }
155
+ writeFileSync(join(sparse, 'points3D.txt'), `${pts.join('\n')}\n`)
156
+ console.log(`🟢 ${id - 1} images, ${pts.length - 1} points: ${root}`)
157
+ }
@@ -0,0 +1,199 @@
1
+ // a fly-through back into 3D: MoGe (or DA3) measures the depth of every few frames of the clips (on
2
+ // the box), each frame's depth is scaled to the frame before it (the first to the picture's own mesh)
3
+ // where they overlap, set at the camera we chose for it, and all of them become one cloud of
4
+ // small gaussians (a 3DGS ply the world viewers open). Wider than one viewpoint: what the video
5
+ // model invented beyond the picture gets a place too. Reads what flythroughChain.ts wrote into <out>.
6
+ //
7
+ // run: bun examples/rvion/flythroughFuse.ts <out> [every] [points] [moge|da3]
8
+ // writes <out>/fused.ply and <out>/fuse.json (each frame's scale and how much of it the guide covered)
9
+ import { $ } from 'bun'
10
+ import { mkdirSync, readFileSync, existsSync, writeFileSync } from 'node:fs'
11
+ import { join } from 'pathe'
12
+ import sharp from 'sharp'
13
+ import { ComfyTS, v } from 'comfy-ts'
14
+ import { dropStretched, readGlb, renderGuideFrame, type GuideMesh } from './flythroughGuide.ts'
15
+ import type { PathCamera } from './flythroughPath.ts'
16
+
17
+ /** a frame's mesh (its camera space: y up, -z ahead) scaled, turned to the camera's heading and moved there */
18
+ export function placeMesh(positions: Float32Array, scale: number, camera: PathCamera): Float32Array {
19
+ const fx = camera.target[0] - camera.position[0]
20
+ const fz = camera.target[2] - camera.position[2]
21
+ const psi = Math.atan2(fx, -fz)
22
+ const c = Math.cos(psi)
23
+ const s = Math.sin(psi)
24
+ const out = new Float32Array(positions.length)
25
+ for (let i = 0; i < out.length; i += 3) {
26
+ const x = positions[i]! * scale
27
+ const y = positions[i + 1]! * scale
28
+ const z = positions[i + 2]! * scale
29
+ out[i] = c * x - s * z + camera.position[0]
30
+ out[i + 1] = y + camera.position[1]
31
+ out[i + 2] = s * x + c * z + camera.position[2]
32
+ }
33
+ return out
34
+ }
35
+
36
+ /** points as a 3DGS ply: each a small round gaussian of its colour */
37
+ export function gaussianPly(p: { xyz: number[]; rgb: number[]; size: number }): Uint8Array {
38
+ const n = p.xyz.length / 3
39
+ 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']
40
+ const header = `ply\nformat binary_little_endian 1.0\nelement vertex ${n}\n${props.map((x) => `property float ${x}`).join('\n')}\nend_header\n`
41
+ const head = new TextEncoder().encode(header)
42
+ const body = new Float32Array(n * props.length)
43
+ const SH0 = 0.28209479177387814
44
+ const logScale = Math.log(p.size)
45
+ for (let i = 0; i < n; i++) {
46
+ const o = i * props.length
47
+ body.set([p.xyz[i * 3]!, p.xyz[i * 3 + 1]!, p.xyz[i * 3 + 2]!], o)
48
+ for (let c = 0; c < 3; c++) body[o + 3 + c] = (p.rgb[i * 3 + c]! / 255 - 0.5) / SH0
49
+ body[o + 6] = 4.6 // opacity logit: 0.99
50
+ body.set([logScale, logScale, logScale, 1, 0, 0, 0], o + 7)
51
+ }
52
+ const out = new Uint8Array(head.length + body.byteLength)
53
+ out.set(head)
54
+ out.set(new Uint8Array(body.buffer), head.length)
55
+ return out
56
+ }
57
+
58
+ const loadMesh = async (bytes: Uint8Array): Promise<GuideMesh> => {
59
+ const g = readGlb(bytes)
60
+ const t = await sharp(g.textureBytes).removeAlpha().raw().toBuffer({ resolveWithObject: true })
61
+ return { ...g, positions: new Float32Array(g.positions), texture: { width: t.info.width, height: t.info.height, rgb: new Uint8Array(t.data) } }
62
+ }
63
+
64
+ if (import.meta.main) {
65
+ const [out, everyArg, pointsArg, depthArg] = process.argv.slice(2)
66
+ if (out == null) throw new Error('usage: bun examples/rvion/flythroughFuse.ts <out> [every] [points] [moge|da3]')
67
+ const depthModel = depthArg ?? 'moge'
68
+ if (depthModel !== 'moge' && depthModel !== 'da3') throw new Error(`fuse: depth model '${depthModel}', not moge or da3`)
69
+ const every = Number(everyArg ?? 10)
70
+ const budget = Number(pointsArg ?? 1_500_000)
71
+ const rig = JSON.parse(readFileSync(join(out, 'cameras.json'), 'utf8')) as {
72
+ fovY: number
73
+ width: number
74
+ height: number
75
+ length: number
76
+ cameras: PathCamera[]
77
+ }
78
+ const fovX = (2 * Math.atan((Math.tan((rig.fovY * Math.PI) / 360) * rig.width) / rig.height) * 180) / Math.PI
79
+
80
+ // the frames, and the camera of each
81
+ const frames: { file: string; camera: PathCamera; index: number }[] = []
82
+ const framesDir = join(out, 'fuse-frames')
83
+ mkdirSync(framesDir, { recursive: true })
84
+ for (let k = 0; existsSync(join(out, `clip-${k}.mp4`)); k++) {
85
+ await $`ffmpeg -loglevel error -y -i ${join(out, `clip-${k}.mp4`)} ${join(framesDir, `c${k}-%04d.png`)}`
86
+ for (let j = k === 0 ? 0 : every; j < rig.length; j += every) {
87
+ const index = k * (rig.length - 1) + j
88
+ const camera = rig.cameras[index]
89
+ if (camera != null) frames.push({ file: join(framesDir, `c${k}-${String(j + 1).padStart(4, '0')}.png`), camera, index })
90
+ }
91
+ }
92
+
93
+ // depth of every frame, one prompt, one glb each, kept in <out>/fuse-meshes so a new fusion
94
+ // costs no box time
95
+ const meshesDir = join(out, 'fuse-meshes')
96
+ mkdirSync(meshesDir, { recursive: true })
97
+ const cached = (i: number) => join(meshesDir, `${depthModel}-${frames[i]!.index}.glb`)
98
+ const missing = frames.map((_, i) => i).filter((i) => !existsSync(cached(i)))
99
+ if (missing.length > 0) {
100
+ const host = ComfyTS.create().host({ id: 'windows-1' })
101
+ await host.loadSchemaFromCache()
102
+ const inputs = missing.map((i) => v.image(frames[i]!.file))
103
+ const measure = host.defineWorkflow({
104
+ id: 'flythrough-fuse',
105
+ vars: {},
106
+ build: async (b, _vars, wf) => {
107
+ // one loader each, made on first use
108
+ let mogeModel: ReturnType<typeof b.LoadMoGeModel> | undefined
109
+ let da3Model: ReturnType<typeof b.LoadDA3Model> | undefined
110
+ const moge = () => (mogeModel ??= b.LoadMoGeModel({ model_name: 'moge_2_vitl_normal_fp16.safetensors' }))
111
+ const da3 = () => (da3Model ??= b.LoadDA3Model({ model_name: 'depth_anything_3_mono_large.safetensors' }))
112
+ for (const [j, input] of inputs.entries()) {
113
+ const image = await input.loadInWorkflow(wf)
114
+ const mesh =
115
+ depthModel === 'moge'
116
+ ? b.MoGePointMapToMesh({
117
+ moge_geometry: b.MoGeInference({ moge_model: moge(), image, fov_x_degrees: fovX, resolution_level: 6 }),
118
+ decimation: 2,
119
+ })
120
+ : b.DA3GeometryToMesh({
121
+ // DA3's mono model knows no field of view: it unprojects at about 60°
122
+ da3_geometry: b.DA3Inference({ da3_model: da3(), image, mode: 'mono' }),
123
+ decimation: 2,
124
+ })
125
+ b.SaveGLB({ mesh, filename_prefix: 'comfy-ts-example/flythrough-fuse' }, { tag: `frame-${missing[j]}` })
126
+ }
127
+ },
128
+ })
129
+ const t0 = Date.now()
130
+ const measured = await measure.run({})
131
+ console.log(`🟢 ${depthModel} on ${missing.length} frames in ${((Date.now() - t0) / 1000).toFixed(0)} s`)
132
+ host.disconnect()
133
+ for (const i of missing) {
134
+ const glb = measured.models3d.find((m) => m.tags.includes(`frame-${i}`))
135
+ if (glb == null) throw new Error(`fuse: no mesh came back for frame ${frames[i]!.index}`)
136
+ writeFileSync(cached(i), glb.bytes)
137
+ }
138
+ }
139
+
140
+ // scale: the first frame to the picture's mesh (the guide), each next one to the frame before it,
141
+ // where they overlap; the picture's mesh is only right near the picture's own view, the frame
142
+ // before is right wherever the camera has just been
143
+ const source = await loadMesh(new Uint8Array(readFileSync(join(out, 'mesh.glb'))))
144
+ const origin: PathCamera = { position: [0, 0, 0], target: [0, 0, -1] }
145
+ const W = Math.round(rig.width / 2)
146
+ const H = Math.round(rig.height / 2)
147
+ const median = (reference: Float32Array, own: Float32Array) => {
148
+ const ratios: number[] = []
149
+ for (let k = 0; k < W * H; k++) if (Number.isFinite(reference[k]!) && Number.isFinite(own[k]!)) ratios.push(reference[k]! / own[k]!)
150
+ ratios.sort((x, y) => x - y)
151
+ return { scale: ratios[Math.floor(ratios.length / 2)] ?? Number.NaN, covered: ratios.length / (W * H) }
152
+ }
153
+ const fused: { mesh: GuideMesh; placed: GuideMesh; scale: number; covered: number; against: string; camera: PathCamera; index: number }[] = []
154
+ for (const [i, f] of frames.entries()) {
155
+ const mesh = dropStretched(await loadMesh(new Uint8Array(readFileSync(cached(i)))), 3)
156
+ const own = renderGuideFrame({ mesh, camera: origin, width: W, height: H, fovY: rig.fovY }).metres
157
+ const before = fused.at(-1)
158
+ const reference = before == null ? source : before.placed
159
+ let fit = median(renderGuideFrame({ mesh: reference, camera: f.camera, width: W, height: H, fovY: rig.fovY }).metres, own)
160
+ let against = before == null ? 'picture' : 'previous'
161
+ if (!(fit.covered > 0.15) && before != null) {
162
+ fit = { scale: before.scale, covered: fit.covered }
163
+ against = 'previous scale'
164
+ }
165
+ if (!Number.isFinite(fit.scale)) throw new Error(`fuse: frame ${f.index} overlaps nothing to set its scale`)
166
+ const placed = { ...mesh, positions: placeMesh(mesh.positions, fit.scale, f.camera) }
167
+ fused.push({ mesh, placed, scale: fit.scale, covered: fit.covered, against, camera: f.camera, index: f.index })
168
+ }
169
+
170
+ // the cloud: every frame's vertices, thinned to the budget
171
+ const total = fused.reduce((n, f) => n + f.mesh.positions.length / 3, 0)
172
+ const stride = Math.max(1, Math.ceil(total / budget))
173
+ const xyz: number[] = []
174
+ const rgb: number[] = []
175
+ for (const f of fused) {
176
+ const placed = f.placed.positions
177
+ const tex = f.mesh.texture
178
+ for (let i = 0; i < placed.length / 3; i += stride) {
179
+ const x = placed[i * 3]!
180
+ const y = placed[i * 3 + 1]!
181
+ const z = placed[i * 3 + 2]!
182
+ if (!Number.isFinite(x + y + z)) continue
183
+ const u = Math.round(f.mesh.uvs[i * 2]! * (tex.width - 1))
184
+ const w = Math.round(f.mesh.uvs[i * 2 + 1]! * (tex.height - 1))
185
+ const o = (w * tex.width + u) * 3
186
+ // written in the axes of SHARP's splats (x right, y down, z ahead), as the world viewers expect
187
+ xyz.push(x, -y, -z)
188
+ rgb.push(tex.rgb[o]!, tex.rgb[o + 1]!, tex.rgb[o + 2]!)
189
+ }
190
+ }
191
+ writeFileSync(join(out, 'fused.ply'), gaussianPly({ xyz, rgb, size: 0.03 }))
192
+ writeFileSync(
193
+ join(out, 'fuse.json'),
194
+ JSON.stringify(fused.map((f) => ({ frame: f.index, scale: f.scale, against: f.against, covered: Number(f.covered.toFixed(3)) })), null, 1),
195
+ )
196
+ await $`rm -rf ${framesDir}`
197
+ console.log(`🟢 ${xyz.length / 3} points from ${fused.length} frames: ${join(out, 'fused.ply')}`)
198
+ process.exit(0)
199
+ }