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,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
+ }
@@ -0,0 +1,114 @@
1
+ // place a splat lifted from one filled view into the world: fit its scale on the pixels the world already
2
+ // covers, keep only the gaussians that land in the hole, move them from the view's camera to world axes
3
+ import { F, STRIDE, type Splat, type SplatCamera } from './ply.ts'
4
+ import { IDENTITY, matToQuat, render, type Pose, type Render } from './raster.ts'
5
+
6
+ type Quat = [number, number, number, number]
7
+
8
+ function quatMul(a: Quat, b: Quat): Quat {
9
+ return [
10
+ a[0] * b[0] - a[1] * b[1] - a[2] * b[2] - a[3] * b[3],
11
+ a[0] * b[1] + a[1] * b[0] + a[2] * b[3] - a[3] * b[2],
12
+ a[0] * b[2] - a[1] * b[3] + a[2] * b[0] + a[3] * b[1],
13
+ a[0] * b[3] + a[1] * b[2] - a[2] * b[1] + a[3] * b[0],
14
+ ]
15
+ }
16
+
17
+ function quantile(sorted: Float64Array, q: number): number {
18
+ if (sorted.length === 0) return Number.NaN
19
+ return sorted[Math.min(sorted.length - 1, Math.max(0, Math.round(q * (sorted.length - 1))))] ?? Number.NaN
20
+ }
21
+
22
+ export type ScaleFit = {
23
+ /** world metres per lifted metre */
24
+ scale: number
25
+ /** the 25 % and 75 % quantiles of the per pixel ratio: how much the two depths disagree in shape */
26
+ spread: [number, number]
27
+ /** how many pixels the fit used */
28
+ pixels: number
29
+ }
30
+
31
+ /** the scale that best maps the lifted depth onto the world's depth, on pixels both cover well (median of ratios) */
32
+ export function fitScale(world: Render, lifted: Render, minCover = 0.95): ScaleFit {
33
+ const logs: number[] = []
34
+ for (let i = 0; i < world.alpha.length; i++) {
35
+ if (world.alpha[i]! < minCover || lifted.alpha[i]! < minCover) continue
36
+ const a = world.depth[i]!
37
+ const b = lifted.depth[i]!
38
+ if (a > 0 && b > 0) logs.push(Math.log(a / b))
39
+ }
40
+ if (logs.length < 1000) throw new Error(`scale fit: only ${logs.length} pixels covered by both splats, the views do not overlap enough`)
41
+ const sorted = Float64Array.from(logs).sort()
42
+ return {
43
+ scale: Math.exp(quantile(sorted, 0.5)),
44
+ spread: [Math.exp(quantile(sorted, 0.25)), Math.exp(quantile(sorted, 0.75))],
45
+ pixels: logs.length,
46
+ }
47
+ }
48
+
49
+ /** only the gaussians whose centre falls inside the picture: SHARP pushes some past its border, where nothing
50
+ * was seen, and from a turned camera they show as a dark smudge beyond the picture's edge */
51
+ export function trimToFrame(s: Splat, cam: SplatCamera): Splat {
52
+ const keep: number[] = []
53
+ for (let g = 0; g < s.n; g++) {
54
+ const b = g * STRIDE
55
+ const z = s.data[b + 2]!
56
+ if (z <= 0) continue
57
+ const u = (cam.f * s.data[b]!) / z + cam.cx
58
+ const v = (cam.f * s.data[b + 1]!) / z + cam.cy
59
+ if (u >= 0 && v >= 0 && u < cam.width && v < cam.height) keep.push(g)
60
+ }
61
+ const data = new Float32Array(keep.length * STRIDE)
62
+ keep.forEach((g, k) => data.set(s.data.subarray(g * STRIDE, (g + 1) * STRIDE), k * STRIDE))
63
+ return { n: keep.length, data, camera: s.camera }
64
+ }
65
+
66
+ export type Placed ={ kept: Splat; fit: ScaleFit; total: number }
67
+
68
+ /**
69
+ * `lifted` is SHARP's splat of the filled view, in that view's camera axes; `world` is the render of the grown
70
+ * splat from the same pose. Its gaussians whose centre lands where the world covered less than `keepBelow` are kept,
71
+ * scaled by the fit, and moved to world axes.
72
+ */
73
+ export function place(p: { lifted: Splat; world: Render; cam: SplatCamera; pose: Pose; keepBelow: number; minCover?: number }): Placed {
74
+ const lc = p.lifted.camera
75
+ if (lc == null) throw new Error('place: the lifted splat has no camera (intrinsic, image_size): not a SHARP ply')
76
+ if (Math.abs(lc.f - p.cam.f) > 0.01 * p.cam.f || lc.width !== p.cam.width || lc.height !== p.cam.height)
77
+ throw new Error(`place: the lifted splat was made for f=${lc.f} ${lc.width}x${lc.height}, the view is f=${p.cam.f} ${p.cam.width}x${p.cam.height}`)
78
+ const liftedView = render(p.lifted, p.cam, { R: IDENTITY, C: [0, 0, 0] })
79
+ const fit = fitScale(p.world, liftedView, p.minCover)
80
+ const s = fit.scale
81
+ const logS = Math.log(s)
82
+ const R = p.pose.R
83
+ const qR = matToQuat(R)
84
+ const src = p.lifted.data
85
+ const keep: number[] = []
86
+ const W = p.cam.width
87
+ const H = p.cam.height
88
+ for (let g = 0; g < p.lifted.n; g++) {
89
+ const b = g * STRIDE
90
+ const z = src[b + 2]!
91
+ if (z <= 0) continue
92
+ const u = Math.floor((p.cam.f * src[b]!) / z + p.cam.cx)
93
+ const v = Math.floor((p.cam.f * src[b + 1]!) / z + p.cam.cy)
94
+ if (u < 0 || v < 0 || u >= W || v >= H) continue
95
+ if (p.world.alpha[v * W + u]! < p.keepBelow) keep.push(g)
96
+ }
97
+ const data = new Float32Array(keep.length * STRIDE)
98
+ keep.forEach((g, k) => {
99
+ const b = g * STRIDE
100
+ const o = k * STRIDE
101
+ const x = src[b]! * s
102
+ const y = src[b + 1]! * s
103
+ const z = src[b + 2]! * s
104
+ data[o] = R[0] * x + R[1] * y + R[2] * z + p.pose.C[0]
105
+ data[o + 1] = R[3] * x + R[4] * y + R[5] * z + p.pose.C[1]
106
+ data[o + 2] = R[6] * x + R[7] * y + R[8] * z + p.pose.C[2]
107
+ for (let c = 0; c < 3; c++) data[o + F.dc + c] = src[b + F.dc + c]!
108
+ data[o + F.opacity] = src[b + F.opacity]!
109
+ for (let c = 0; c < 3; c++) data[o + F.scale + c] = src[b + F.scale + c]! + logS
110
+ const q = quatMul(qR, [src[b + F.rot]!, src[b + F.rot + 1]!, src[b + F.rot + 2]!, src[b + F.rot + 3]!])
111
+ for (let c = 0; c < 4; c++) data[o + F.rot + c] = q[c]!
112
+ })
113
+ return { kept: { n: keep.length, data, camera: null }, fit, total: p.lifted.n }
114
+ }
@@ -0,0 +1,198 @@
1
+ // grow a one picture splat into a world, round after round: render it from a new camera, let the image model fill
2
+ // what is empty (20-grow-splat.cflow.ts), lift the filled view with SHARP, keep only its new part at the world's
3
+ // scale, merge. The world folder holds `splat.ply` (SHARP's splat of the picture, OpenCV axes, metres); the loop
4
+ // writes `splat-grown.ply` beside it and the pictures of each round under `grow/`.
5
+ //
6
+ // bun examples/rvion/grow-splat/grow.ts <world folder> [--rounds "30 -30 60 -60"] [--extend "<what lies beyond>"]
7
+ // [--seed 1] [--fresh] [--reuse] [--views]
8
+ // a round is `<yaw>[@<x>,<z>]`: turn left by yaw degrees (negative turns right), standing at x metres right and
9
+ // z metres forward of the picture's camera. Without --fresh the rounds go on from the last grown splat; --reuse
10
+ // takes a round's filled view and lifted splat from an earlier run when they exist (tuning the merge alone).
11
+ // --views only draws the grown splat (and the picture's) from a fixed set of cameras, into grow/views.png
12
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
13
+ import { join, resolve } from 'pathe'
14
+ import sharp from 'sharp'
15
+ import { FILL_PROMPT, growSplatFill } from '../20-grow-splat.cflow.ts'
16
+ import { place, trimToFrame } from './align.ts'
17
+ import { concatSplats, readSplat, writeSplat, type Splat, type SplatCamera } from './ply.ts'
18
+ import { render, turn, type Pose, type Render } from './raster.ts'
19
+ import { sharpPredict } from './sharp.ts'
20
+
21
+ /** a pixel covered less than this is painted by the model */
22
+ const COVERED = 0.9
23
+ /** a lifted gaussian is kept where the world covered less than this */
24
+ const KEEP_BELOW = 0.6
25
+
26
+ type Round = { yaw: number; x: number; z: number }
27
+ type RoundLog = Round & { round: number; seed: number; seconds: number; scale: number; spread: [number, number]; fitPixels: number; hole: number; kept: number; total: number; gaussians: number }
28
+
29
+ function parseRound(token: string): Round {
30
+ const m = /^(-?\d+(?:\.\d+)?)(?:@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?))?$/.exec(token)
31
+ if (m == null) throw new Error(`a round is <yaw>[@<x>,<z>], got '${token}'`)
32
+ return { yaw: Number(m[1]), x: Number(m[2] ?? 0), z: Number(m[3] ?? 0) }
33
+ }
34
+
35
+ const poseOf = (r: Round): Pose => ({ R: turn(r.yaw), C: [r.x, 0, r.z] })
36
+ const roundName = (r: Round): string => `${r.yaw >= 0 ? 'l' : 'r'}${Math.abs(r.yaw)}${r.x !== 0 || r.z !== 0 ? `-at${r.x},${r.z}` : ''}`
37
+
38
+ const to8 = (x: number): number => Math.max(0, Math.min(255, Math.round(x * 255)))
39
+
40
+ /** the render as a png: rgb over black, alpha = how much the splat covers (LoadImage's mask is 1 − alpha) */
41
+ async function writeRender(path: string, r: Render, withAlpha: boolean, width = r.width): Promise<void> {
42
+ const px = Buffer.alloc(r.width * r.height * 4)
43
+ for (let i = 0; i < r.width * r.height; i++) {
44
+ px[i * 4] = to8(r.color[i * 3]!)
45
+ px[i * 4 + 1] = to8(r.color[i * 3 + 1]!)
46
+ px[i * 4 + 2] = to8(r.color[i * 3 + 2]!)
47
+ px[i * 4 + 3] = withAlpha ? to8(r.alpha[i]!) : 255
48
+ }
49
+ await sharp(px, { raw: { width: r.width, height: r.height, channels: 4 } }).resize(width).png().toFile(path)
50
+ }
51
+
52
+ async function writeMask(path: string, r: Render): Promise<number> {
53
+ const px = Buffer.alloc(r.width * r.height)
54
+ let hole = 0
55
+ for (let i = 0; i < px.length; i++) {
56
+ const empty = r.alpha[i]! < COVERED
57
+ px[i] = empty ? 255 : 0
58
+ if (empty) hole++
59
+ }
60
+ await sharp(px, { raw: { width: r.width, height: r.height, channels: 1 } }).png().toFile(path)
61
+ return hole / px.length
62
+ }
63
+
64
+ async function fill(renderPng: string, seed: number, extend: string): Promise<Uint8Array> {
65
+ growSplatFill.vars.render.set(renderPng)
66
+ growSplatFill.vars.seed.set(seed)
67
+ growSplatFill.vars.prompt.set(extend === '' ? FILL_PROMPT : `${FILL_PROMPT} Beyond the picture: ${extend}`)
68
+ const execution = await growSplatFill.run({ log: false })
69
+ const filled = execution.images.find((i) => i.tags.includes('filled'))
70
+ if (filled == null) throw new Error(`the fill run gave no 'filled' image (${execution.images.length} images)`)
71
+ return filled.buffer
72
+ }
73
+
74
+ /** the camera rounds are drawn with: the picture's own */
75
+ function cameraOf(s: Splat): SplatCamera {
76
+ if (s.camera == null) throw new Error('the world splat has no camera (intrinsic, image_size): grow needs a SHARP ply')
77
+ return s.camera
78
+ }
79
+
80
+ /** a round at a glance: the render, its empty part, the filled view, the world after the merge (2 × 2, 768 px each) */
81
+ async function sheet(path: string, pictures: string[]): Promise<void> {
82
+ const W = 768
83
+ const H = 512
84
+ const tiles = await Promise.all(
85
+ pictures.map(async (p, i) => ({
86
+ input: await sharp(p).flatten({ background: '#000000' }).resize(W, H).png().toBuffer(),
87
+ left: (i % 2) * (W + 8),
88
+ top: Math.floor(i / 2) * (H + 8),
89
+ })),
90
+ )
91
+ await sharp({ create: { width: 2 * W + 8, height: 2 * H + 8, channels: 3, background: '#ffffff' } }).composite(tiles).webp().toFile(path)
92
+ }
93
+
94
+ async function grow(dir: string, rounds: Round[], extend: string, seed0: number, fresh: boolean, reuse: boolean): Promise<void> {
95
+ const out = join(dir, 'grow')
96
+ mkdirSync(out, { recursive: true })
97
+ const grownPath = join(dir, 'splat-grown.ply')
98
+ const logPath = join(out, 'rounds.json')
99
+ const resume = !fresh && existsSync(grownPath) && existsSync(logPath)
100
+ const log: RoundLog[] = resume ? (JSON.parse(readFileSync(logPath, 'utf8')) as RoundLog[]) : []
101
+ const picture = readSplat(join(dir, 'splat.ply'))
102
+ const cam = cameraOf(picture)
103
+ let world = resume ? readSplat(grownPath) : trimToFrame(picture, cam)
104
+ console.log(`${resume ? 'resume' : 'start'}: ${world.n} gaussians, ${log.length} rounds done`)
105
+ for (const r of rounds) {
106
+ const t0 = performance.now()
107
+ const n = log.length + 1
108
+ const tag = `r${String(n).padStart(2, '0')}-${roundName(r)}`
109
+ const pose = poseOf(r)
110
+ const view = render(world, cam, pose)
111
+ const renderPng = join(out, `${tag}-render.png`)
112
+ await writeRender(renderPng, view, true)
113
+ const hole = await writeMask(join(out, `${tag}-mask.png`), view)
114
+ console.log(`${tag}: ${(hole * 100).toFixed(1)} % empty, filling`)
115
+ const seedN = seed0 + n
116
+ const filledPng = join(out, `${tag}-filled.png`)
117
+ if (!(reuse && existsSync(filledPng))) await sharp(await fill(renderPng, seedN, extend)).removeAlpha().png().toFile(filledPng)
118
+ const liftedPly = join(out, `${tag}-lifted.ply`)
119
+ const tf = performance.now()
120
+ console.log(`${tag}: filled in ${Math.round((tf - t0) / 1000)} s, lifting`)
121
+ if (!(reuse && existsSync(liftedPly))) sharpPredict(filledPng, liftedPly)
122
+ const tl = performance.now()
123
+ const placed = place({ lifted: readSplat(liftedPly), world: view, cam, pose, keepBelow: KEEP_BELOW })
124
+ world = concatSplats([world, placed.kept])
125
+ await writeRender(join(out, `${tag}-after.png`), render(world, cam, pose), false)
126
+ await sheet(join(out, `${tag}-sheet.webp`), [renderPng, join(out, `${tag}-mask.png`), filledPng, join(out, `${tag}-after.png`)])
127
+ writeSplat(grownPath, world)
128
+ const seconds = Math.round((performance.now() - t0) / 1000)
129
+ log.push({ ...r, round: n, seed: seedN, seconds, scale: placed.fit.scale, spread: placed.fit.spread, fitPixels: placed.fit.pixels, hole, kept: placed.kept.n, total: placed.total, gaussians: world.n })
130
+ writeFileSync(logPath, `${JSON.stringify(log, null, 3)}\n`)
131
+ console.log(
132
+ `${tag}: ${seconds} s (fill ${Math.round((tf - t0) / 1000)} s, SHARP ${Math.round((tl - tf) / 1000)} s), scale ×${placed.fit.scale.toFixed(3)} ` +
133
+ `(half the pixels within ×${placed.fit.spread[0].toFixed(2)}..×${placed.fit.spread[1].toFixed(2)}), kept ${placed.kept.n} of ${placed.total}, world ${world.n}`,
134
+ )
135
+ }
136
+ }
137
+
138
+ /** the cameras a grown world is judged from: turns to each side, then steps forward */
139
+ const VIEW_ROUNDS: Round[] = [
140
+ { yaw: 90, x: 0, z: 0 },
141
+ { yaw: 60, x: 0, z: 0 },
142
+ { yaw: 30, x: 0, z: 0 },
143
+ { yaw: 0, x: 0, z: 0 },
144
+ { yaw: -30, x: 0, z: 0 },
145
+ { yaw: -60, x: 0, z: 0 },
146
+ { yaw: -90, x: 0, z: 0 },
147
+ { yaw: 0, x: 0, z: 1.5 },
148
+ { yaw: 0, x: 0, z: 3 },
149
+ { yaw: 30, x: 0, z: 2 },
150
+ { yaw: -30, x: 0, z: 2 },
151
+ { yaw: 0, x: 1, z: 1 },
152
+ ]
153
+
154
+ /** one sheet: a row per camera, the picture's splat on the left and the grown one on the right */
155
+ async function views(dir: string): Promise<void> {
156
+ const out = join(dir, 'grow')
157
+ mkdirSync(out, { recursive: true })
158
+ const seedSplat = readSplat(join(dir, 'splat.ply'))
159
+ const grown = readSplat(join(dir, 'splat-grown.ply'))
160
+ const cam = cameraOf(seedSplat)
161
+ const W = 640
162
+ const H = Math.round((W * cam.height) / cam.width)
163
+ const tiles: { input: string; left: number; top: number }[] = []
164
+ for (const [i, r] of VIEW_ROUNDS.entries()) {
165
+ for (const [j, s] of [seedSplat, grown].entries()) {
166
+ const p = join(out, `view-${roundName(r)}-${j === 0 ? 'seed' : 'grown'}.png`)
167
+ await writeRender(p, render(s, cam, poseOf(r)), false, W)
168
+ tiles.push({ input: p, left: j * (W + 8), top: i * (H + 8) })
169
+ }
170
+ }
171
+ const sheet = join(out, 'views.png')
172
+ await sharp({ create: { width: 2 * W + 8, height: VIEW_ROUNDS.length * (H + 8), channels: 3, background: '#ffffff' } })
173
+ .composite(tiles)
174
+ .png()
175
+ .toFile(sheet)
176
+ console.log(`🟢 ${sheet} (rows: ${VIEW_ROUNDS.map(roundName).join(' ')})`)
177
+ }
178
+
179
+ if (import.meta.main) {
180
+ const args = process.argv.slice(2)
181
+ const flag = (name: string): string | null => {
182
+ const i = args.indexOf(name)
183
+ return i >= 0 ? (args[i + 1] ?? null) : null
184
+ }
185
+ const dirArg = args[0]
186
+ if (dirArg == null || dirArg.startsWith('--')) throw new Error('usage: grow.ts <world folder holding splat.ply> [--rounds "30 -30"] [--extend "…"] [--seed n] [--fresh] [--views]')
187
+ const dir = resolve(dirArg)
188
+ if (!existsSync(join(dir, 'splat.ply'))) throw new Error(`${dir} has no splat.ply`)
189
+ try {
190
+ if (args.includes('--views')) await views(dir)
191
+ else {
192
+ const rounds = (flag('--rounds') ?? '30 -30 60 -60').trim().split(/\s+/).map(parseRound)
193
+ await grow(dir, rounds, flag('--extend') ?? '', Number(flag('--seed') ?? 1), args.includes('--fresh'), args.includes('--reuse'))
194
+ }
195
+ } finally {
196
+ growSplatFill.host.disconnect()
197
+ }
198
+ }