comfy-ts 2.21.0 → 2.22.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 (85) hide show
  1. package/dist/{ServeApp-ByMobrWW.js → ServeApp-DuxYdaZZ.js} +142 -7
  2. package/dist/ServeApp-DuxYdaZZ.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-B5sMqNia.js → exampleAssets-1NHndnNB.js} +4 -17
  5. package/dist/exampleAssets-1NHndnNB.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-BNZgYIww.js → findDefinedWorkflow-CRsBTTJK.js} +2 -2
  7. package/dist/{findDefinedWorkflow-BNZgYIww.js.map → findDefinedWorkflow-CRsBTTJK.js.map} +1 -1
  8. package/dist/index.cjs +32 -1
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +71 -6
  11. package/dist/index.d.ts +71 -6
  12. package/dist/index.js +31 -2
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-CuBSygku.js → run-run-Y5ZI48vV.js} +5 -5
  15. package/dist/{run-run-CuBSygku.js.map → run-run-Y5ZI48vV.js.map} +1 -1
  16. package/dist/{run-serve-COk_G0Qz.js → run-serve-CICU_wTL.js} +4 -4
  17. package/dist/{run-serve-COk_G0Qz.js.map → run-serve-CICU_wTL.js.map} +1 -1
  18. package/dist/{run-tui-CB6i_x2y.js → run-tui-CViJXsHL.js} +4 -4
  19. package/dist/{run-tui-CB6i_x2y.js.map → run-tui-CViJXsHL.js.map} +1 -1
  20. package/dist/{schemaDrift-CHDVYlaj.js → schemaDrift-CzjaIwZX.js} +22 -2
  21. package/dist/schemaDrift-CzjaIwZX.js.map +1 -0
  22. package/dist/serve-web.js +204 -47
  23. package/dist/web.d.ts +71 -6
  24. package/dist/web.js +31 -2
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +2 -0
  27. package/examples/depth-explorer/models.ts +722 -0
  28. package/examples/depth-explorer/serve.ts +140 -0
  29. package/examples/depth-explorer/thumbs/bae.webp +0 -0
  30. package/examples/depth-explorer/thumbs/da3-mono-large.webp +0 -0
  31. package/examples/depth-explorer/thumbs/dav1-vitl.webp +0 -0
  32. package/examples/depth-explorer/thumbs/dav2-vitl.webp +0 -0
  33. package/examples/depth-explorer/thumbs/dsine.webp +0 -0
  34. package/examples/depth-explorer/thumbs/iid-albedo.webp +0 -0
  35. package/examples/depth-explorer/thumbs/iid-metalness.webp +0 -0
  36. package/examples/depth-explorer/thumbs/iid-roughness.webp +0 -0
  37. package/examples/depth-explorer/thumbs/iid-shading.webp +0 -0
  38. package/examples/depth-explorer/thumbs/iid-specular.webp +0 -0
  39. package/examples/depth-explorer/thumbs/leres.webp +0 -0
  40. package/examples/depth-explorer/thumbs/lotus-depth.webp +0 -0
  41. package/examples/depth-explorer/thumbs/marigold2-albedo.webp +0 -0
  42. package/examples/depth-explorer/thumbs/marigold2-depth.webp +0 -0
  43. package/examples/depth-explorer/thumbs/marigold2-normal.webp +0 -0
  44. package/examples/depth-explorer/thumbs/metric3d-depth.webp +0 -0
  45. package/examples/depth-explorer/thumbs/metric3d-normal.webp +0 -0
  46. package/examples/depth-explorer/thumbs/midas-normal.webp +0 -0
  47. package/examples/depth-explorer/thumbs/midas.webp +0 -0
  48. package/examples/depth-explorer/thumbs/moge2-depth.webp +0 -0
  49. package/examples/depth-explorer/thumbs/moge2-normal.webp +0 -0
  50. package/examples/depth-explorer/thumbs/zoe-da.webp +0 -0
  51. package/examples/depth-explorer/thumbs/zoe.webp +0 -0
  52. package/examples/depth-explorer/web/App.tsx +457 -0
  53. package/examples/depth-explorer/web/gl.ts +202 -0
  54. package/examples/depth-explorer/web/index.html +14 -0
  55. package/examples/depth-explorer/web/main.tsx +19 -0
  56. package/examples/depth-explorer/web/pixels.ts +86 -0
  57. package/examples/depth-explorer/web/state.ts +329 -0
  58. package/examples/depth-explorer/web/styles.css +366 -0
  59. package/examples/depth-explorer/web/tsconfig.json +16 -0
  60. package/examples/rvion/17-relight.cflow.ts +110 -0
  61. package/package.json +3 -2
  62. package/src/cli/serve/ServeApp.ts +79 -4
  63. package/src/cli/serve/describeVar.ts +12 -1
  64. package/src/cli/serve/resultHistory.ts +6 -1
  65. package/src/cli/serve/thumbs.ts +66 -0
  66. package/src/cli/serve/web/api.ts +5 -1
  67. package/src/cli/serve/web/components/Gallery.tsx +2 -0
  68. package/src/cli/serve/web/components/controls/BasicControls.tsx +14 -17
  69. package/src/cli/serve/web/components/controls/MediaControl.tsx +62 -9
  70. package/src/cli/serve/web/components/controls/RichSelect.tsx +262 -0
  71. package/src/cli/serve/web/state/RunSt.poll.test.ts +4 -1
  72. package/src/cli/serve/web/state/choiceButtons.ts +26 -2
  73. package/src/cli/serve/web/styles.ts +39 -0
  74. package/src/cli/serve/web/widgets/OutputWidgets.tsx +19 -0
  75. package/src/cli/serve/web/widgets/RelightSt.ts +113 -0
  76. package/src/cli/serve/web/widgets/RelightWidget.tsx +305 -0
  77. package/src/cli/serve/web/widgets/relightGl.ts +305 -0
  78. package/src/cli/serve/web/widgets/widgetStyles.ts +19 -0
  79. package/src/coreExports.ts +9 -0
  80. package/src/vars/ComfyVars.ts +32 -2
  81. package/src/vars/DefinedWorkflow.ts +4 -0
  82. package/src/vars/outputWidgets.ts +47 -0
  83. package/dist/ServeApp-ByMobrWW.js.map +0 -1
  84. package/dist/exampleAssets-B5sMqNia.js.map +0 -1
  85. package/dist/schemaDrift-CHDVYlaj.js.map +0 -1
@@ -0,0 +1,140 @@
1
+ // depth explorer: drop any image, run every depth / normal estimator the host has, compare them
2
+ // side by side, as a 3D relief or relit by the normals.
3
+ // bun examples/depth-explorer/serve.ts [--samples <dir>] → http://127.0.0.1:8292
4
+ // one ComfyUI prompt per model, so each card fills as its model finishes and one failure stays one card.
5
+ import { createHash } from 'node:crypto'
6
+ import { readdirSync } from 'node:fs'
7
+ import { ComfyTS, exampleImagePath, MediaImage } from 'comfy-ts'
8
+ import { basename, dirname, resolve } from 'pathe'
9
+ import { availability, MODELS, type HostId } from './models.ts'
10
+ import page from './web/index.html'
11
+
12
+ const HOST_ID: HostId = 'windows-1'
13
+ const PORT = Number(process.env.PORT ?? 8292)
14
+
15
+ const comfy = ComfyTS.create()
16
+ const host = comfy.host({ id: HOST_ID })
17
+ // a live schema: availability reads the loaders' file lists, and a weight downloaded since the
18
+ // cache was written must show up as runnable
19
+ await host.connect({ schema: 'refresh' })
20
+
21
+ /** uploaded source images, by content hash (the page sends each one once) */
22
+ const images = new Map<string, Uint8Array>()
23
+
24
+ /** the bundled example images, plus every `--samples <dir>` given: name → file */
25
+ const samplePaths = new Map<string, string>()
26
+ const sampleDirs = [dirname(exampleImagePath('dog_512x512.jpg'))]
27
+ for (let i = 2; i < process.argv.length; i++)
28
+ if (process.argv[i] === '--samples' && process.argv[i + 1] != null)
29
+ sampleDirs.push(resolve(String(process.argv[++i])))
30
+ for (const dir of sampleDirs)
31
+ for (const f of readdirSync(dir)) if (/\.(jpe?g|png|webp)$/i.test(f)) samplePaths.set(f, `${dir}/${f}`)
32
+ const samples = [...samplePaths.keys()]
33
+
34
+ const json = (data: unknown, status = 200): Response => Response.json(data, { status })
35
+
36
+ function modelsPayload(): unknown {
37
+ const info = host.schema.data.spec
38
+ return {
39
+ host: HOST_ID,
40
+ models: MODELS.map((m) => ({
41
+ id: m.id,
42
+ label: m.label,
43
+ family: m.family,
44
+ year: m.year,
45
+ kind: m.kind,
46
+ tier: m.tier,
47
+ blurb: m.blurb,
48
+ date: m.date,
49
+ size: m.size,
50
+ quality: m.quality,
51
+ speed: m.speed,
52
+ autoDownload: m.autoDownload === true,
53
+ ...availability(info, m),
54
+ })),
55
+ }
56
+ }
57
+
58
+ type RunBody = { image: string; model: string; detail: number }
59
+
60
+ function readRunBody(raw: unknown): RunBody {
61
+ const r = raw as Partial<RunBody> | null
62
+ if (r == null || typeof r.image !== 'string' || typeof r.model !== 'string' || typeof r.detail !== 'number')
63
+ throw new Error('body must be { image: string, model: string, detail: number }')
64
+ return { image: r.image, model: r.model, detail: Math.min(2048, Math.max(256, Math.round(r.detail))) }
65
+ }
66
+
67
+ async function run(body: RunBody): Promise<Response> {
68
+ const model = MODELS.find((m) => m.id === body.model)
69
+ if (model == null) return json({ error: `unknown model ${body.model}` }, 404)
70
+ const avail = availability(host.schema.data.spec, model)
71
+ if (!avail.ok) return json({ error: 'not on this host', ...avail }, 409)
72
+ const bytes = images.get(body.image)
73
+ if (bytes == null) return json({ error: 'unknown image, upload it again' }, 404)
74
+
75
+ const started = performance.now()
76
+ const wf = host.workflow({ id: `depth-explorer-${model.id}` })
77
+ const loaded = await new MediaImage({ buffer: bytes }).loadInWorkflow_viaLoadImageNode(wf)
78
+ const out = model.build(wf.builder, loaded, { detail: body.detail, wf })
79
+ const save = wf.builderBase.SaveImageWebsocket
80
+ if (save == null) throw new Error('this host has no SaveImageWebsocket node')
81
+ save({ images: out })
82
+ // SaveImageWebsocket: the result never touches the server disk; the source image is uploaded
83
+ // once (hash named) and reused by every model
84
+ const execution = await wf.run({ scrubHistory: true })
85
+ const ms = Math.round(performance.now() - started)
86
+ const first = execution.images[0]
87
+ if (execution.status !== 'Success' || first == null) {
88
+ // ComfyUI's own reason (a missing weight, an oom) sits in the error message's data
89
+ const err = execution.data.error
90
+ const message =
91
+ err != null && 'exception_message' in err.data
92
+ ? `${err.data.node_type ?? 'a node'}: ${err.data.exception_message}`
93
+ : `run ended ${execution.status}, no image`
94
+ console.error(`🔴 ${model.id}: ${message}`)
95
+ return json({ error: message, ms }, 500)
96
+ }
97
+ console.log(`🟢 ${model.id} ${ms} ms`)
98
+ return new Response(first.buffer as Uint8Array<ArrayBuffer>, {
99
+ headers: { 'content-type': `image/${first.metadata.type ?? 'png'}`, 'x-ms': String(ms) },
100
+ })
101
+ }
102
+
103
+ const server = Bun.serve({
104
+ port: PORT,
105
+ hostname: '127.0.0.1',
106
+ development: true,
107
+ idleTimeout: 255, // a cold model load on the GPU box takes minutes
108
+ routes: {
109
+ '/': page,
110
+ '/api/models': () => json(modelsPayload()),
111
+ '/api/samples': () => json(samples),
112
+ '/api/samples/:name': (req) => {
113
+ const path = samplePaths.get(basename(req.params.name))
114
+ if (path == null) return json({ error: 'no such sample' }, 404)
115
+ return new Response(Bun.file(path))
116
+ },
117
+ '/api/image': {
118
+ POST: async (req) => {
119
+ const bytes = new Uint8Array(await req.arrayBuffer())
120
+ if (bytes.length === 0) return json({ error: 'empty body' }, 400)
121
+ const key = createHash('sha1').update(bytes).digest('hex').slice(0, 16)
122
+ images.set(key, bytes)
123
+ return json({ key })
124
+ },
125
+ },
126
+ '/api/run': {
127
+ POST: async (req) => {
128
+ try {
129
+ return await run(readRunBody(await req.json()))
130
+ } catch (e) {
131
+ const message = e instanceof Error ? e.message : String(e)
132
+ console.error('🔴 run failed:', message)
133
+ return json({ error: message }, 500)
134
+ }
135
+ },
136
+ },
137
+ },
138
+ })
139
+
140
+ console.log(`depth explorer → http://127.0.0.1:${server.port}/ (host ${HOST_ID})`)
@@ -0,0 +1,457 @@
1
+ import { observer } from 'mobx-react-lite'
2
+ import { useEffect, useRef, useState, type ReactNode } from 'react'
3
+ import { GlView, type GlParams } from './gl.ts'
4
+ import { greyDepth, loadImage, paintDepth } from './pixels.ts'
5
+ import { RelightWidgetView } from '../../../src/cli/serve/web/widgets/RelightWidget.tsx'
6
+ import { widget, type RelightRoles } from '../../../src/vars/outputWidgets.ts'
7
+ import type { AppSt, ModelInfo } from './state.ts'
8
+
9
+ /** grey (optionally stretched) depth canvas per result url, shared by the card, the wipe and the 3D view */
10
+ const greyCache = new Map<string, Promise<HTMLCanvasElement>>()
11
+ function grey(url: string, stretch: boolean): Promise<HTMLCanvasElement> {
12
+ const k = `${url}|${stretch}`
13
+ let hit = greyCache.get(k)
14
+ if (hit == null) {
15
+ hit = loadImage(url).then((img) => greyDepth(img, stretch))
16
+ greyCache.set(k, hit)
17
+ }
18
+ return hit
19
+ }
20
+
21
+ /** a depth result in the picked colormap, a material map in stretched grey, a normal map as is */
22
+ const MapImage = observer(function MapImage(p: { st: AppSt; model: ModelInfo; url: string; className?: string }) {
23
+ const ref = useRef<HTMLCanvasElement>(null)
24
+ const { colormap, autoLevels } = p.st
25
+ useEffect(() => {
26
+ if (p.model.kind === 'normal') return
27
+ let live = true
28
+ const material = p.model.kind === 'material'
29
+ void grey(p.url, material || autoLevels).then((g) => {
30
+ if (live && ref.current != null) paintDepth(g, material ? 'gray' : colormap, ref.current)
31
+ })
32
+ return () => {
33
+ live = false
34
+ }
35
+ }, [p.url, colormap, autoLevels, p.model.kind])
36
+ if (p.model.kind === 'normal')
37
+ return <img className={p.className} src={p.url} alt={p.model.label} draggable={false} />
38
+ return <canvas className={p.className} ref={ref} />
39
+ })
40
+
41
+ const Card = observer(function Card(p: { st: AppSt; model: ModelInfo }) {
42
+ const { st, model } = p
43
+ const r = st.result(model.id)
44
+ const aspect = st.source != null ? `${st.source.width} / ${st.source.height}` : '1'
45
+ let body: ReactNode
46
+ if (!model.ok) {
47
+ body = (
48
+ <div className="missing">
49
+ <b>not on this host</b>
50
+ {model.missingNodes.length > 0 && <span>nodes: {model.missingNodes.join(', ')}</span>}
51
+ {model.missingFiles.map((f) => (
52
+ <a key={f.file} href={f.url} target="_blank" rel="noreferrer">
53
+ models/{f.folder}/{f.file}
54
+ </a>
55
+ ))}
56
+ </div>
57
+ )
58
+ } else if (r == null) {
59
+ body = (
60
+ <button className="ghost" onClick={() => st.enqueue(model.id)} disabled={st.source == null}>
61
+ run
62
+ </button>
63
+ )
64
+ } else if (r.status === 'queued') body = <span className="dim">queued</span>
65
+ else if (r.status === 'running')
66
+ body = (
67
+ <span className="dim">
68
+ <span className="spin" /> {((st.now - r.startedAt) / 1000).toFixed(1)} s
69
+ {model.autoDownload && st.now - r.startedAt > 8000 && <small>first run downloads the weights</small>}
70
+ </span>
71
+ )
72
+ else if (r.status === 'error')
73
+ body = (
74
+ <div className="err">
75
+ <span>{r.error}</span>
76
+ <button className="ghost" onClick={() => st.enqueue(model.id)}>
77
+ retry
78
+ </button>
79
+ </div>
80
+ )
81
+ else if (r.url != null) body = <MapImage st={st} model={model} url={r.url} />
82
+
83
+ const done = r?.status === 'done'
84
+ return (
85
+ <div className={`card ${done ? 'done' : ''} ${model.ok ? '' : 'off'}`}>
86
+ <div className="cardHead">
87
+ <span className="name">
88
+ {model.label} <span className="fam">{model.family}</span>
89
+ </span>
90
+ <span className="meta">
91
+ {r?.ms != null && done ? `${(r.ms / 1000).toFixed(1)} s · ` : ''}
92
+ {model.year}
93
+ </span>
94
+ </div>
95
+ <div className="frame" style={{ aspectRatio: aspect }} onClick={() => done && st.openFocus(model.id)}>
96
+ {body}
97
+ </div>
98
+ <div className="blurb">{model.blurb}</div>
99
+ </div>
100
+ )
101
+ })
102
+
103
+ const Section = observer(function Section(p: { st: AppSt; title: string; models: ModelInfo[] }) {
104
+ if (p.models.length === 0) return null
105
+ return (
106
+ <section>
107
+ <h2>{p.title}</h2>
108
+ <div className="grid">
109
+ {p.models.map((m) => (
110
+ <Card key={m.id} st={p.st} model={m} />
111
+ ))}
112
+ </div>
113
+ </section>
114
+ )
115
+ })
116
+
117
+ function Seg<T extends string | number>(p: { value: T; options: [T, string][]; onChange: (v: T) => void }) {
118
+ return (
119
+ <div className="seg">
120
+ {p.options.map(([v, label]) => (
121
+ <button key={String(v)} className={v === p.value ? 'on' : ''} onClick={() => p.onChange(v)}>
122
+ {label}
123
+ </button>
124
+ ))}
125
+ </div>
126
+ )
127
+ }
128
+
129
+ const Sidebar = observer(function Sidebar(p: { st: AppSt }) {
130
+ const { st } = p
131
+ const [drag, setDrag] = useState(false)
132
+ const fileRef = useRef<HTMLInputElement>(null)
133
+ const take = (f: File | undefined): void => {
134
+ if (f != null && f.type.startsWith('image/')) void st.setSource(f, f.name)
135
+ }
136
+ useEffect(() => {
137
+ const onPaste = (e: ClipboardEvent): void => {
138
+ const f = [...(e.clipboardData?.files ?? [])].find((x) => x.type.startsWith('image/'))
139
+ take(f)
140
+ }
141
+ window.addEventListener('paste', onPaste)
142
+ return () => window.removeEventListener('paste', onPaste)
143
+ })
144
+ return (
145
+ <aside>
146
+ <div
147
+ className={`drop ${drag ? 'over' : ''}`}
148
+ onDragOver={(e) => {
149
+ e.preventDefault()
150
+ setDrag(true)
151
+ }}
152
+ onDragLeave={() => setDrag(false)}
153
+ onDrop={(e) => {
154
+ e.preventDefault()
155
+ setDrag(false)
156
+ take(e.dataTransfer.files[0])
157
+ }}
158
+ onClick={() => fileRef.current?.click()}
159
+ >
160
+ {st.source != null ? <img src={st.source.url} alt={st.source.name} /> : <span>drop an image</span>}
161
+ <input ref={fileRef} type="file" accept="image/*" hidden onChange={(e) => take(e.target.files?.[0])} />
162
+ </div>
163
+ <div className="dim small">
164
+ {st.source != null ? `${st.source.name} · ${st.source.width}×${st.source.height}` : ''}
165
+ <br />
166
+ drop, click or paste an image
167
+ </div>
168
+ <div className="samples">
169
+ {st.samples.map((s) => (
170
+ <img key={s} src={`/api/samples/${s}`} alt={s} title={s} onClick={() => void st.loadSample(s)} />
171
+ ))}
172
+ </div>
173
+
174
+ <label>detail</label>
175
+ <Seg
176
+ value={st.detail}
177
+ options={[
178
+ [512, '512'],
179
+ [768, '768'],
180
+ [1024, '1024'],
181
+ ]}
182
+ onChange={(v) => st.set('detail', v)}
183
+ />
184
+ <label>depth colors</label>
185
+ <Seg
186
+ value={st.colormap}
187
+ options={[
188
+ ['turbo', 'turbo'],
189
+ ['gray', 'grey'],
190
+ ]}
191
+ onChange={(v) => st.set('colormap', v)}
192
+ />
193
+ <label className="check">
194
+ <input type="checkbox" checked={st.autoLevels} onChange={(e) => st.set('autoLevels', e.target.checked)} />
195
+ stretch each depth map (2 to 98 %)
196
+ </label>
197
+ <label className="check">
198
+ <input type="checkbox" checked={st.showClassic} onChange={(e) => st.set('showClassic', e.target.checked)} />
199
+ show classic baselines (2021 to 2023)
200
+ </label>
201
+ <label className="check">
202
+ <input type="checkbox" checked={st.showMissing} onChange={(e) => st.set('showMissing', e.target.checked)} />
203
+ show models this host lacks
204
+ </label>
205
+ <button
206
+ className="primary"
207
+ disabled={st.source == null || st.runnable.length === 0}
208
+ onClick={() => st.runAll()}
209
+ >
210
+ {st.busy ? 'running…' : `run all ${st.runnable.length}`}
211
+ </button>
212
+ <div className="dim small">one prompt at a time on {st.host}; click a finished card to inspect it</div>
213
+ </aside>
214
+ )
215
+ })
216
+
217
+ const Wipe = observer(function Wipe(p: { st: AppSt; model: ModelInfo; url: string }) {
218
+ const { st } = p
219
+ const x = st.wipeX
220
+ const against = st.wipeAgainst === 'source' ? null : st.model(st.wipeAgainst)
221
+ const againstUrl = against != null ? st.result(against.id)?.url : null
222
+ const src = st.source
223
+ if (src == null) return null
224
+ const move = (e: React.PointerEvent<HTMLDivElement>): void => {
225
+ const r = e.currentTarget.getBoundingClientRect()
226
+ st.set('wipeX', Math.min(100, Math.max(0, ((e.clientX - r.left) / r.width) * 100)))
227
+ }
228
+ return (
229
+ <div
230
+ className="wipe"
231
+ style={{
232
+ aspectRatio: `${src.width} / ${src.height}`,
233
+ width: `min(100%, calc((100vh - 140px) * ${src.width / src.height}))`,
234
+ }}
235
+ onPointerMove={move}
236
+ >
237
+ {against != null && againstUrl != null ? (
238
+ <MapImage st={st} model={against} url={againstUrl} className="layer" />
239
+ ) : (
240
+ <img className="layer" src={src.url} alt="source" draggable={false} />
241
+ )}
242
+ <div className="layer" style={{ clipPath: `inset(0 0 0 ${x}%)` }}>
243
+ <MapImage st={st} model={p.model} url={p.url} className="layer" />
244
+ </div>
245
+ <div className="handle" style={{ left: `${x}%` }} />
246
+ <span className="tag l">{against != null ? `${against.label} ${against.family}` : 'source'}</span>
247
+ <span className="tag r">
248
+ {p.model.label} {p.model.family}
249
+ </span>
250
+ </div>
251
+ )
252
+ })
253
+
254
+ /** the depth map as a textured 3D relief: drag to orbit, wheel to zoom */
255
+ const ReliefPanel = observer(function ReliefPanel(p: { st: AppSt; url: string }) {
256
+ const { st } = p
257
+ const ref = useRef<HTMLCanvasElement>(null)
258
+ const view = useRef<GlView | null>(null)
259
+ const params: GlParams = st.relief
260
+ const setParams = (v: GlParams): void => st.set('relief', v)
261
+ const [error, setError] = useState<string | null>(null)
262
+ const [ready, setReady] = useState(false)
263
+
264
+ useEffect(() => {
265
+ const c = ref.current
266
+ const src = st.source
267
+ if (c == null || src == null) return
268
+ let live = true
269
+ try {
270
+ view.current ??= new GlView(c)
271
+ } catch (e) {
272
+ setError(e instanceof Error ? e.message : String(e))
273
+ return
274
+ }
275
+ void Promise.all([loadImage(src.url), grey(p.url, st.autoLevels)]).then(([s, m]) => {
276
+ if (!live) return
277
+ view.current?.setImages(s, m, src.width / src.height)
278
+ setReady(true)
279
+ })
280
+ return () => {
281
+ live = false
282
+ }
283
+ }, [p.url, st.source, st.autoLevels])
284
+
285
+ useEffect(() => {
286
+ if (ready) view.current?.draw(params)
287
+ })
288
+ useEffect(() => {
289
+ const onResize = (): void => view.current?.draw(params)
290
+ window.addEventListener('resize', onResize)
291
+ return () => window.removeEventListener('resize', onResize)
292
+ })
293
+
294
+ const drag = useRef<{ x: number; y: number } | null>(null)
295
+ const onMove = (e: React.PointerEvent<HTMLCanvasElement>): void => {
296
+ const d = drag.current
297
+ if (d == null) return
298
+ setParams({
299
+ ...params,
300
+ yaw: params.yaw + (e.clientX - d.x) * 0.008,
301
+ pitch: Math.min(1.4, Math.max(-1.4, params.pitch + (e.clientY - d.y) * 0.008)),
302
+ })
303
+ drag.current = { x: e.clientX, y: e.clientY }
304
+ }
305
+
306
+ if (error != null) return <div className="err">{error}</div>
307
+ return (
308
+ <div className="glWrap">
309
+ <canvas
310
+ ref={ref}
311
+ className="gl"
312
+ onPointerDown={(e) => {
313
+ drag.current = { x: e.clientX, y: e.clientY }
314
+ e.currentTarget.setPointerCapture(e.pointerId)
315
+ }}
316
+ onPointerUp={() => (drag.current = null)}
317
+ onPointerMove={onMove}
318
+ onWheel={(e) =>
319
+ setParams({ ...params, zoom: Math.min(3, Math.max(0.3, params.zoom * (e.deltaY > 0 ? 1.08 : 0.93))) })
320
+ }
321
+ />
322
+ <div className="glControls">
323
+ <label>
324
+ depth
325
+ <input
326
+ type="range"
327
+ min={0}
328
+ max={1}
329
+ step={0.01}
330
+ value={params.depthScale}
331
+ onChange={(e) => setParams({ ...params, depthScale: Number(e.target.value) })}
332
+ />
333
+ </label>
334
+ <label>
335
+ shading
336
+ <input
337
+ type="range"
338
+ min={0}
339
+ max={1}
340
+ step={0.01}
341
+ value={params.shade}
342
+ onChange={(e) => setParams({ ...params, shade: Number(e.target.value) })}
343
+ />
344
+ </label>
345
+ <span className="dim">drag to orbit · wheel to zoom</span>
346
+ </div>
347
+ </div>
348
+ )
349
+ })
350
+
351
+ /** the panel's relight widget, fed with the focus and the best finished maps of the grid */
352
+ const RelightPanel = observer(function RelightPanel(p: { st: AppSt }) {
353
+ const maps = p.st.relightMaps
354
+ const roles: RelightRoles = { image: 'source' }
355
+ for (const m of maps) if (m.tag !== 'source') Object.assign(roles, { [m.tag]: m.tag })
356
+ if (roles.depth == null && roles.normal == null)
357
+ return <div className="err">run a depth or a normal model first</div>
358
+ const images = maps.map((m) => ({ filename: m.tag, url: m.url, absPath: null, tags: [m.tag] }))
359
+ return (
360
+ <div className="relightWrap">
361
+ <RelightWidgetView key={maps.map((m) => m.url).join('|')} widget={widget.relight(roles)} images={images} />
362
+ <div className="dim small">
363
+ maps: {maps.map((m) => m.tag).join(' · ')}. Run more models in the grid to add a map (albedo, roughness and
364
+ metalness come from the materials section).
365
+ </div>
366
+ </div>
367
+ )
368
+ })
369
+
370
+ const Focus = observer(function Focus(p: { st: AppSt }) {
371
+ const { st } = p
372
+ const model = st.focus != null ? st.model(st.focus) : undefined
373
+ const r = model != null ? st.result(model.id) : undefined
374
+ useEffect(() => {
375
+ const onKey = (e: KeyboardEvent): void => {
376
+ if (e.key === 'Escape') st.closeFocus()
377
+ }
378
+ window.addEventListener('keydown', onKey)
379
+ return () => window.removeEventListener('keydown', onKey)
380
+ }, [st])
381
+ if (model == null || r?.url == null) return null
382
+ const others = st.doneModels.filter((m) => m.id !== model.id)
383
+ return (
384
+ <div className="focus" onClick={(e) => e.target === e.currentTarget && st.closeFocus()}>
385
+ <div className="focusBox">
386
+ <div className="focusBar">
387
+ <b>
388
+ {model.label} <span className="fam">{model.family}</span>
389
+ </b>
390
+ <Seg
391
+ value={st.focusView}
392
+ options={
393
+ model.kind === 'depth'
394
+ ? [
395
+ ['wipe', 'compare'],
396
+ ['3d', '3D relief'],
397
+ ['light', 'relight'],
398
+ ]
399
+ : model.kind === 'normal'
400
+ ? [
401
+ ['wipe', 'compare'],
402
+ ['light', 'relight'],
403
+ ]
404
+ : [['wipe', 'compare']]
405
+ }
406
+ onChange={(v) => st.set('focusView', v)}
407
+ />
408
+ {st.focusView === 'wipe' && (
409
+ <select value={st.wipeAgainst} onChange={(e) => st.set('wipeAgainst', e.target.value)}>
410
+ <option value="source">against the source</option>
411
+ {others.map((m) => (
412
+ <option key={m.id} value={m.id}>
413
+ against {m.label} {m.family}
414
+ </option>
415
+ ))}
416
+ </select>
417
+ )}
418
+ <a className="ghost" href={r.url} download={`${st.source?.name ?? 'image'}.${model.id}.png`}>
419
+ download
420
+ </a>
421
+ <button className="ghost" onClick={() => st.closeFocus()}>
422
+ close
423
+ </button>
424
+ </div>
425
+ {st.focusView === 'wipe' ? (
426
+ <Wipe st={st} model={model} url={r.url} />
427
+ ) : st.focusView === '3d' ? (
428
+ <ReliefPanel key={model.id} st={st} url={r.url} />
429
+ ) : (
430
+ <RelightPanel st={st} />
431
+ )}
432
+ </div>
433
+ </div>
434
+ )
435
+ })
436
+
437
+ export const App = observer(function App(p: { st: AppSt }) {
438
+ const { st } = p
439
+ return (
440
+ <div className="app">
441
+ <header>
442
+ <h1>depth explorer</h1>
443
+ <span className="dim">every depth, normal and material estimator on {st.host || '…'}, one image</span>
444
+ </header>
445
+ {st.loadError != null && <div className="err">server: {st.loadError}</div>}
446
+ <div className="body">
447
+ <Sidebar st={st} />
448
+ <main>
449
+ <Section st={st} title="depth" models={st.depthModels} />
450
+ <Section st={st} title="normals" models={st.normalModels} />
451
+ <Section st={st} title="materials" models={st.materialModels} />
452
+ </main>
453
+ </div>
454
+ <Focus st={st} />
455
+ </div>
456
+ )
457
+ })