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.
- package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-fsHtW5zG.js} +51 -17
- package/dist/ServeApp-fsHtW5zG.js.map +1 -0
- package/dist/cli.js +5 -5
- package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-DZynSkZm.js} +405 -39
- package/dist/exampleAssets-DZynSkZm.js.map +1 -0
- package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
- package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
- package/dist/index.cjs +428 -46
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +147 -1
- package/dist/index.d.ts +147 -1
- package/dist/index.js +428 -47
- package/dist/index.js.map +1 -1
- package/dist/{run-run-Y5ZI48vV.js → run-run-Cn2JzKlE.js} +5 -5
- package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cn2JzKlE.js.map} +1 -1
- package/dist/{run-serve-CICU_wTL.js → run-serve-BhGegaCI.js} +4 -4
- package/dist/{run-serve-CICU_wTL.js.map → run-serve-BhGegaCI.js.map} +1 -1
- package/dist/{run-tui-CViJXsHL.js → run-tui-CrM4ijkH.js} +4 -4
- package/dist/{run-tui-CViJXsHL.js.map → run-tui-CrM4ijkH.js.map} +1 -1
- package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BGYJZGMD.js} +18 -3
- package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
- package/dist/serve-web.js +46 -43
- package/dist/web.d.ts +147 -1
- package/dist/web.js +428 -47
- package/dist/web.js.map +1 -1
- package/examples/README.md +1 -0
- package/examples/comfy-cloud/sdk.d.ts +102 -1
- package/examples/depth-explorer/models.ts +6 -56
- package/examples/depth-explorer/serve.ts +12 -133
- package/examples/depth-explorer/web/App.tsx +20 -91
- package/examples/depth-explorer/web/index.html +1 -0
- package/examples/depth-explorer/web/state.ts +26 -109
- package/examples/depth-explorer/web/styles.css +1 -286
- package/examples/explorer-kit/catalog.ts +80 -0
- package/examples/explorer-kit/server.ts +167 -0
- package/examples/explorer-kit/web/base.css +289 -0
- package/examples/explorer-kit/web/runs.ts +160 -0
- package/examples/explorer-kit/web/ui.tsx +125 -0
- package/examples/rvion/17-relight.cflow.ts +2 -1
- package/examples/rvion/18-world.cflow.ts +101 -0
- package/examples/rvion/19-flythrough.cflow.ts +312 -0
- package/examples/rvion/20-grow-splat.cflow.ts +88 -0
- package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
- package/examples/rvion/flythroughChain.ts +171 -0
- package/examples/rvion/flythroughColmap.ts +157 -0
- package/examples/rvion/flythroughFuse.ts +199 -0
- package/examples/rvion/flythroughGuide.ts +300 -0
- package/examples/rvion/flythroughPalette.ts +310 -0
- package/examples/rvion/flythroughPath.ts +177 -0
- package/examples/rvion/flythroughSplat.ts +73 -0
- package/examples/rvion/grow-splat/align.ts +114 -0
- package/examples/rvion/grow-splat/grow.ts +198 -0
- package/examples/rvion/grow-splat/ply.ts +166 -0
- package/examples/rvion/grow-splat/raster.ts +207 -0
- package/examples/rvion/grow-splat/sharp.ts +45 -0
- package/examples/rvion/splatDataset.ts +80 -0
- package/examples/rvion/splatEval.ts +380 -0
- package/examples/upscale-explorer/models.ts +341 -0
- package/examples/upscale-explorer/serve.ts +19 -0
- package/examples/upscale-explorer/web/App.tsx +250 -0
- package/examples/upscale-explorer/web/compare.tsx +285 -0
- package/examples/upscale-explorer/web/index.html +15 -0
- package/examples/upscale-explorer/web/main.tsx +12 -0
- package/examples/upscale-explorer/web/state.ts +279 -0
- package/examples/upscale-explorer/web/styles.css +241 -0
- package/examples/upscale-explorer/web/tsconfig.json +16 -0
- package/examples/upscale-explorer/web/viewport.tsx +130 -0
- package/examples/world-explorer/serve.ts +171 -0
- package/examples/world-explorer/web/index.html +14 -0
- package/examples/world-explorer/web/main.tsx +200 -0
- package/examples/world-explorer/web/state.ts +212 -0
- package/examples/world-explorer/web/styles.css +131 -0
- package/examples/world-explorer/web/thumb.ts +21 -0
- package/examples/world-explorer/web/tsconfig.json +11 -0
- package/examples/world-explorer/world-state.ts +40 -0
- package/package.json +7 -8
- package/src/cli/serve/ServeApp.ts +27 -2
- package/src/cli/serve/resultHistory.ts +22 -4
- package/src/cli/serve/thumbs.ts +19 -8
- package/src/cli/serve/web/api.ts +4 -0
- package/src/cli/serve/web/components/Gallery.tsx +24 -1
- package/src/cli/serve/web/styles.ts +3 -0
- package/src/coreExports.ts +6 -0
- package/src/graph/ComfyNode.ts +12 -2
- package/src/host/ComfyHost.ts +159 -2
- package/src/host/ResilientWebsocket.ts +10 -0
- package/src/manager/script-update-manager.bun.ts +0 -7
- package/src/runner/ComfyExecution.ts +185 -23
- package/src/runner/ComfyWorkflow.ts +22 -0
- package/src/runner/ComfyWsApi.ts +3 -1
- package/src/runner/comfyOrgApiKey.ts +44 -0
- package/src/runner/historyReplay.ts +53 -0
- package/src/runner/outputs3d.ts +18 -0
- package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
- package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
- package/src/state.ts +2 -0
- package/src/vars/DefinedWorkflow.ts +1 -0
- package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
- package/dist/exampleAssets-1NHndnNB.js.map +0 -1
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// one picture to a textured 3D model on windows-1: SAM 3 cuts the subject out by its name (one name a
|
|
2
|
+
// line, the masks joined), TRELLIS 2 builds one object with its back by construction (structure, shape,
|
|
3
|
+
// upsample, texture), then the mesh is remeshed, unwrapped and baked to a textured glb.
|
|
4
|
+
// source template: 3d_pixal3d_trellis2_image_to_model.json (its Trellis 2 branch)
|
|
5
|
+
// run directly: bun examples/rvion/21-photo-to-model.cflow.ts [path/to/image.png] ["subject"] [seed]
|
|
6
|
+
import { ComfyTS, exampleImagePath, v } from 'comfy-ts'
|
|
7
|
+
|
|
8
|
+
const comfy = ComfyTS.create()
|
|
9
|
+
const host = comfy.host({ id: 'windows-1' })
|
|
10
|
+
await host.loadSchemaFromCache()
|
|
11
|
+
|
|
12
|
+
const image = v.image(exampleImagePath('bear_1024x1024.jpg'), {
|
|
13
|
+
presets: {
|
|
14
|
+
bear: exampleImagePath('bear_1024x1024.jpg'),
|
|
15
|
+
walrus: exampleImagePath('walrus_1344x768.jpg'),
|
|
16
|
+
lioness: exampleImagePath('lioness_768x768.jpg'),
|
|
17
|
+
},
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
export const photoToModel = host.defineWorkflow({
|
|
21
|
+
id: 'photo-to-model',
|
|
22
|
+
vars: {
|
|
23
|
+
image,
|
|
24
|
+
/** what to cut out, one SAM 3 name a line; empty: the image already is the subject on black */
|
|
25
|
+
subject: v.text('bear'),
|
|
26
|
+
/** textured: the whole pipeline; shape: the untextured mesh only, about a third of the time */
|
|
27
|
+
model: v.choice(['textured', 'shape'], 'textured', 'model'),
|
|
28
|
+
seed: v.seed(42),
|
|
29
|
+
},
|
|
30
|
+
build: async (b, vars, wf) => {
|
|
31
|
+
const picture = await image.loadInWorkflow(wf)
|
|
32
|
+
const names = vars.subject.split('\n').map((s) => s.trim()).filter((s) => s !== '')
|
|
33
|
+
const masks = names.map(
|
|
34
|
+
(prompt) => b['rmbg.SAM3Segment']({ image: picture, model_name: 'sam3', prompt, output_mode: 'Merged', confidence_threshold: 0.2 }).outputs.MASK,
|
|
35
|
+
)
|
|
36
|
+
type Mask = (typeof masks)[number] | ReturnType<typeof b.MaskComposite>['outputs']['MASK']
|
|
37
|
+
const first = masks[0]
|
|
38
|
+
// the template's preprocessing: a square crop round the subject, 1.1 margin, on black
|
|
39
|
+
const cutout =
|
|
40
|
+
first == null
|
|
41
|
+
? picture.outputs.IMAGE
|
|
42
|
+
: b.ImageCropToMask({
|
|
43
|
+
images: picture,
|
|
44
|
+
masks: masks.slice(1).reduce<Mask>((acc, m) => b.MaskComposite({ destination: acc, source: m, x: 0, y: 0, operation: 'or' }).outputs.MASK, first),
|
|
45
|
+
width: 1024,
|
|
46
|
+
height: 1024,
|
|
47
|
+
pad_factor: 1.1,
|
|
48
|
+
grow_mask: 0,
|
|
49
|
+
background: '#000000',
|
|
50
|
+
}).outputs.images
|
|
51
|
+
b.SaveImageWebsocket({ images: cutout }, { tag: 'cutout' })
|
|
52
|
+
|
|
53
|
+
const unet = b.UNETLoader({ unet_name: 'trellis_2_int8_convrot.safetensors', weight_dtype: 'default' })
|
|
54
|
+
const shapeVae = b.VAELoader({ vae_name: 'trellis_2_shape_vae_bf16.safetensors' })
|
|
55
|
+
const cond = b.Trellis2Conditioning({
|
|
56
|
+
clip_vision_model: b.CLIPVisionLoader({ clip_name: 'dino_v3_L_naf_fp32.safetensors' }),
|
|
57
|
+
image: cutout,
|
|
58
|
+
})
|
|
59
|
+
// cfg override and rescale match the upstream pipeline's defaults (the template's own note)
|
|
60
|
+
const guided = (start: number, rescale: number) =>
|
|
61
|
+
b.RescaleCFG({ model: b.CFGOverride({ model: unet, cfg: 1, start_percent: start, end_percent: 1 }), multiplier: rescale })
|
|
62
|
+
const structure = b.KSampler({
|
|
63
|
+
model: b.ModelSamplingSD3({ model: guided(0.667, 0.7), shift: 5 }),
|
|
64
|
+
positive: cond.outputs.positive,
|
|
65
|
+
negative: cond.outputs.negative,
|
|
66
|
+
latent_image: b.EmptyTrellis2LatentStructure({ batch_size: 1 }),
|
|
67
|
+
seed: vars.seed + 14,
|
|
68
|
+
steps: 12,
|
|
69
|
+
cfg: 7.5,
|
|
70
|
+
sampler_name: 'euler',
|
|
71
|
+
scheduler: 'normal',
|
|
72
|
+
denoise: 1,
|
|
73
|
+
})
|
|
74
|
+
const shapeStage = b.Trellis2ShapeStage({
|
|
75
|
+
positive: cond.outputs.positive,
|
|
76
|
+
negative: cond.outputs.negative,
|
|
77
|
+
voxel: b.VaeDecodeStructureTrellis2({ samples: structure, vae: shapeVae, resolution: '32' }),
|
|
78
|
+
})
|
|
79
|
+
const shapeModel = guided(0.769, 0.5)
|
|
80
|
+
const shape512 = b.KSampler({
|
|
81
|
+
model: shapeModel,
|
|
82
|
+
positive: shapeStage.outputs.positive,
|
|
83
|
+
negative: shapeStage.outputs.negative,
|
|
84
|
+
latent_image: shapeStage.outputs.LATENT,
|
|
85
|
+
seed: vars.seed,
|
|
86
|
+
steps: 20,
|
|
87
|
+
cfg: 7.5,
|
|
88
|
+
sampler_name: 'euler',
|
|
89
|
+
scheduler: 'normal',
|
|
90
|
+
denoise: 1,
|
|
91
|
+
})
|
|
92
|
+
const upsample = b.Trellis2UpsampleStage({
|
|
93
|
+
positive: shapeStage.outputs.positive,
|
|
94
|
+
negative: shapeStage.outputs.negative,
|
|
95
|
+
shape_latent: shape512,
|
|
96
|
+
vae: shapeVae,
|
|
97
|
+
target_resolution: 1536,
|
|
98
|
+
})
|
|
99
|
+
const shapeHi = b.KSampler({
|
|
100
|
+
model: shapeModel,
|
|
101
|
+
positive: upsample.outputs.positive,
|
|
102
|
+
negative: upsample.outputs.negative,
|
|
103
|
+
latent_image: upsample.outputs.LATENT,
|
|
104
|
+
seed: vars.seed,
|
|
105
|
+
steps: 12,
|
|
106
|
+
cfg: 7.5,
|
|
107
|
+
sampler_name: 'euler',
|
|
108
|
+
scheduler: 'simple',
|
|
109
|
+
denoise: 1,
|
|
110
|
+
})
|
|
111
|
+
const shape = b.VaeDecodeShapeTrellis({ samples: shapeHi, vae: shapeVae })
|
|
112
|
+
// the raw shape, before remesh: what a geometry refiner aligned to the cutout takes
|
|
113
|
+
b.SaveGLB({ mesh: shape.outputs.mesh, filename_prefix: 'comfy-ts/photo-to-model-shape' }, { tag: 'shape' })
|
|
114
|
+
// four sides and the top, as the model is (views) and as clay (shape), to judge the geometry alone
|
|
115
|
+
const views = (mesh: typeof shape.outputs.mesh, modes: ('auto' | 'solid')[]) => {
|
|
116
|
+
const first = b.CreateCameraInfo({ mode: 'orbit', 'mode.yaw': 0, 'mode.pitch': 15, 'mode.distance': 1.15, camera_type: 'perspective', mesh })
|
|
117
|
+
const cameras = b.CreateCameraOrbit({ camera_info: first, count: 4, yaw: 360, pitch: 0, poles: 'top' })
|
|
118
|
+
for (const mode of modes) {
|
|
119
|
+
const render = b.RenderMesh({ mesh, mode, width: 768, height: 768, background: '#808080', camera_info: cameras })
|
|
120
|
+
b.SaveImageWebsocket({ images: render.outputs.image }, { tag: mode === 'auto' ? 'views' : 'clay' })
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (vars.model === 'shape') return views(shape.outputs.mesh, ['solid'])
|
|
124
|
+
|
|
125
|
+
const texture = b.Trellis2TextureStage({ positive: upsample.outputs.positive, negative: upsample.outputs.negative, shape_latent: shapeHi })
|
|
126
|
+
const textureLatent = b.KSampler({
|
|
127
|
+
model: unet,
|
|
128
|
+
positive: texture.outputs.positive,
|
|
129
|
+
negative: texture.outputs.negative,
|
|
130
|
+
latent_image: texture.outputs.LATENT,
|
|
131
|
+
seed: vars.seed + 1,
|
|
132
|
+
steps: 12,
|
|
133
|
+
cfg: 1,
|
|
134
|
+
sampler_name: 'euler',
|
|
135
|
+
scheduler: 'normal',
|
|
136
|
+
denoise: 1,
|
|
137
|
+
})
|
|
138
|
+
const colors = b.VaeDecodeTextureTrellis({
|
|
139
|
+
samples: textureLatent,
|
|
140
|
+
vae: b.VAELoader({ vae_name: 'trellis_2_texture_vae_bf16.safetensors' }),
|
|
141
|
+
shape_subdivides: shape.outputs.shape_subdivides,
|
|
142
|
+
})
|
|
143
|
+
const remeshed = b.RemeshMesh({
|
|
144
|
+
mesh: b.GetMeshInfo({ mesh: shape.outputs.mesh }).outputs.mesh,
|
|
145
|
+
resolution: 768,
|
|
146
|
+
sign_mode: 'solid',
|
|
147
|
+
'sign_mode.fill': 20,
|
|
148
|
+
'sign_mode.qef': false,
|
|
149
|
+
band: 1,
|
|
150
|
+
project_back: 0,
|
|
151
|
+
fix_poles: false,
|
|
152
|
+
smooth_iters: 20,
|
|
153
|
+
drop_small_components: 0.01,
|
|
154
|
+
precluster_max_verts: 20000000,
|
|
155
|
+
})
|
|
156
|
+
const decimated = b.DecimateMesh({ mesh: remeshed, target_face_count: 700000, placement_mode: 'midpoint' })
|
|
157
|
+
const unwrapped = b.UnwrapMesh({
|
|
158
|
+
mesh: b.MeshSmoothNormals({ mesh: decimated, crease_angle: 180 }),
|
|
159
|
+
segmenter: 'pec',
|
|
160
|
+
resolution: 4096,
|
|
161
|
+
padding: 1,
|
|
162
|
+
weld_distance: 0.0002,
|
|
163
|
+
})
|
|
164
|
+
const baked = b.BakeTextureFromVoxel({ mesh: unwrapped, voxel_colors: colors, texture_size: 4096, reference_mesh: shape.outputs.mesh })
|
|
165
|
+
const textured = b.MeshSmoothNormals({
|
|
166
|
+
mesh: b.ApplyTextureToMesh({
|
|
167
|
+
mesh: unwrapped,
|
|
168
|
+
base_color: baked.outputs.base_color,
|
|
169
|
+
metallic: baked.outputs.metallic,
|
|
170
|
+
roughness: baked.outputs.roughness,
|
|
171
|
+
occlusion: b.BakeAmbientOcclusion({ low_poly: unwrapped, high_poly: remeshed, resolution: 1024, samples: 64, max_distance: 0.71, strength: 1, bias: 0.01 }),
|
|
172
|
+
normal_map: b.BakeNormalMapFromMesh({ low_poly: unwrapped, high_poly: remeshed, resolution: 2048, cage_distance: 0.05, ignore_backfaces: true }),
|
|
173
|
+
}),
|
|
174
|
+
crease_angle: 180,
|
|
175
|
+
})
|
|
176
|
+
b.SaveGLB({ mesh: textured, filename_prefix: 'comfy-ts/photo-to-model' }, { tag: 'model' })
|
|
177
|
+
views(textured.outputs.mesh, ['auto', 'solid'])
|
|
178
|
+
},
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
export default photoToModel
|
|
182
|
+
|
|
183
|
+
if (import.meta.main) {
|
|
184
|
+
if (process.argv[2]) photoToModel.vars.image.set(process.argv[2])
|
|
185
|
+
if (process.argv[3] != null) photoToModel.vars.subject.set(process.argv[3])
|
|
186
|
+
if (process.argv[4]) photoToModel.vars.seed.set(Number(process.argv[4]))
|
|
187
|
+
const execution = await photoToModel.run({ log: true, save: { prefix: 'comfy-ts-example/photo-to-model' } })
|
|
188
|
+
for (const img of execution.images) console.log(`🟢 ${img.tags.join(',')} ${img.absPath}`)
|
|
189
|
+
for (const m of execution.models3d) console.log(`🟢 ${m.tags.join(',')} ${m.absPath}`)
|
|
190
|
+
host.disconnect()
|
|
191
|
+
}
|
|
@@ -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
|
+
}
|