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,202 @@
1
+ // raw WebGL2 relief: a 256² grid displaced by the depth map, textured with the source, drag to
2
+ // orbit. No 3D library: one mesh, one program, a few matrix helpers. Relighting is the panel's
3
+ // relight widget (src/cli/serve/web/widgets/), shared with the explorer.
4
+
5
+ const RELIEF_VS = `#version 300 es
6
+ in vec2 a_uv;
7
+ uniform sampler2D u_depth;
8
+ uniform mat4 u_mvp;
9
+ uniform float u_scale;
10
+ uniform float u_aspect;
11
+ out vec2 v_uv;
12
+ out vec3 v_pos;
13
+ void main() {
14
+ float d = texture(u_depth, a_uv).r;
15
+ v_uv = a_uv;
16
+ v_pos = vec3((a_uv.x - 0.5) * u_aspect, 0.5 - a_uv.y, d * u_scale);
17
+ gl_Position = u_mvp * vec4(v_pos, 1.0);
18
+ }`
19
+
20
+ const RELIEF_FS = `#version 300 es
21
+ precision highp float;
22
+ in vec2 v_uv;
23
+ in vec3 v_pos;
24
+ uniform sampler2D u_src;
25
+ uniform float u_shade;
26
+ out vec4 o;
27
+ void main() {
28
+ vec3 n = normalize(cross(dFdx(v_pos), dFdy(v_pos)));
29
+ float lam = clamp(dot(n, normalize(vec3(-0.4, 0.5, 0.8))), 0.0, 1.0);
30
+ vec3 c = texture(u_src, v_uv).rgb;
31
+ o = vec4(mix(c, c * (0.35 + 0.8 * lam), u_shade), 1.0);
32
+ }`
33
+
34
+ type Mat4 = Float32Array
35
+
36
+ function mul(a: Mat4, b: Mat4): Mat4 {
37
+ const o = new Float32Array(16)
38
+ for (let c = 0; c < 4; c++)
39
+ for (let r = 0; r < 4; r++) {
40
+ let s = 0
41
+ for (let k = 0; k < 4; k++) s += (a[k * 4 + r] ?? 0) * (b[c * 4 + k] ?? 0)
42
+ o[c * 4 + r] = s
43
+ }
44
+ return o
45
+ }
46
+ function perspective(fovy: number, aspect: number, near: number, far: number): Mat4 {
47
+ const f = 1 / Math.tan(fovy / 2)
48
+ const nf = 1 / (near - far)
49
+ return new Float32Array([f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) * nf, -1, 0, 0, 2 * far * near * nf, 0])
50
+ }
51
+ function rotX(a: number): Mat4 {
52
+ const c = Math.cos(a)
53
+ const s = Math.sin(a)
54
+ return new Float32Array([1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1])
55
+ }
56
+ function rotY(a: number): Mat4 {
57
+ const c = Math.cos(a)
58
+ const s = Math.sin(a)
59
+ return new Float32Array([c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1])
60
+ }
61
+ function translate(x: number, y: number, z: number): Mat4 {
62
+ return new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1])
63
+ }
64
+
65
+ function compile(gl: WebGL2RenderingContext, vs: string, fs: string): WebGLProgram {
66
+ const prog = gl.createProgram()
67
+ for (const [type, src] of [
68
+ [gl.VERTEX_SHADER, vs],
69
+ [gl.FRAGMENT_SHADER, fs],
70
+ ] as const) {
71
+ const sh = gl.createShader(type)
72
+ if (sh == null) throw new Error('createShader failed')
73
+ gl.shaderSource(sh, src)
74
+ gl.compileShader(sh)
75
+ if (!gl.getShaderParameter(sh, gl.COMPILE_STATUS)) throw new Error(`shader: ${gl.getShaderInfoLog(sh)}`)
76
+ gl.attachShader(prog, sh)
77
+ }
78
+ gl.bindAttribLocation(prog, 0, 'a_uv')
79
+ gl.linkProgram(prog)
80
+ if (!gl.getProgramParameter(prog, gl.LINK_STATUS)) throw new Error(`link: ${gl.getProgramInfoLog(prog)}`)
81
+ return prog
82
+ }
83
+
84
+ const GRID = 256
85
+
86
+ export type GlParams = {
87
+ yaw: number
88
+ pitch: number
89
+ zoom: number
90
+ depthScale: number
91
+ shade: number
92
+ }
93
+
94
+ export class GlView {
95
+ private gl: WebGL2RenderingContext
96
+ private relief: WebGLProgram
97
+ private gridVao: WebGLVertexArrayObject
98
+ private gridCount: number
99
+ private texSrc: WebGLTexture
100
+ private texMap: WebGLTexture
101
+ private aspect = 1
102
+
103
+ constructor(private canvas: HTMLCanvasElement) {
104
+ const gl = canvas.getContext('webgl2', { antialias: true })
105
+ if (gl == null) throw new Error('WebGL2 is not available in this browser')
106
+ this.gl = gl
107
+ this.relief = compile(gl, RELIEF_VS, RELIEF_FS)
108
+
109
+ const uv = new Float32Array((GRID + 1) * (GRID + 1) * 2)
110
+ for (let y = 0; y <= GRID; y++)
111
+ for (let x = 0; x <= GRID; x++) {
112
+ uv[(y * (GRID + 1) + x) * 2] = x / GRID
113
+ uv[(y * (GRID + 1) + x) * 2 + 1] = y / GRID
114
+ }
115
+ const idx = new Uint32Array(GRID * GRID * 6)
116
+ let i = 0
117
+ for (let y = 0; y < GRID; y++)
118
+ for (let x = 0; x < GRID; x++) {
119
+ const a = y * (GRID + 1) + x
120
+ const b = a + 1
121
+ const c = a + GRID + 1
122
+ const d = c + 1
123
+ idx.set([a, c, b, b, c, d], i)
124
+ i += 6
125
+ }
126
+ this.gridCount = idx.length
127
+ this.gridVao = this.vao(uv, idx)
128
+ this.texSrc = this.tex()
129
+ this.texMap = this.tex()
130
+ }
131
+
132
+ private vao(uv: Float32Array, idx: Uint32Array): WebGLVertexArrayObject {
133
+ const gl = this.gl
134
+ const vao = gl.createVertexArray()
135
+ gl.bindVertexArray(vao)
136
+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer())
137
+ gl.bufferData(gl.ARRAY_BUFFER, uv, gl.STATIC_DRAW)
138
+ gl.enableVertexAttribArray(0)
139
+ gl.vertexAttribPointer(0, 2, gl.FLOAT, false, 0, 0)
140
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gl.createBuffer())
141
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, idx, gl.STATIC_DRAW)
142
+ gl.bindVertexArray(null)
143
+ return vao
144
+ }
145
+
146
+ private tex(): WebGLTexture {
147
+ const gl = this.gl
148
+ const t = gl.createTexture()
149
+ gl.bindTexture(gl.TEXTURE_2D, t)
150
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
151
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
152
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
153
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
154
+ return t
155
+ }
156
+
157
+ /** the source image and the map (grey depth or normal), any sizes: both are sampled by uv */
158
+ setImages(src: TexImageSource, map: TexImageSource, aspect: number): void {
159
+ const gl = this.gl
160
+ this.aspect = aspect
161
+ for (const [t, img] of [
162
+ [this.texSrc, src],
163
+ [this.texMap, map],
164
+ ] as const) {
165
+ gl.bindTexture(gl.TEXTURE_2D, t)
166
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img)
167
+ }
168
+ }
169
+
170
+ draw(p: GlParams): void {
171
+ const gl = this.gl
172
+ const dpr = window.devicePixelRatio || 1
173
+ const w = Math.round(this.canvas.clientWidth * dpr)
174
+ const h = Math.round(this.canvas.clientHeight * dpr)
175
+ if (this.canvas.width !== w || this.canvas.height !== h) {
176
+ this.canvas.width = w
177
+ this.canvas.height = h
178
+ }
179
+ gl.viewport(0, 0, w, h)
180
+ gl.clearColor(0.07, 0.075, 0.085, 1)
181
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT)
182
+ gl.activeTexture(gl.TEXTURE0)
183
+ gl.bindTexture(gl.TEXTURE_2D, this.texSrc)
184
+ gl.activeTexture(gl.TEXTURE1)
185
+ gl.bindTexture(gl.TEXTURE_2D, this.texMap)
186
+ const view = w / Math.max(1, h)
187
+
188
+ gl.enable(gl.DEPTH_TEST)
189
+ gl.useProgram(this.relief)
190
+ const fit = Math.max(this.aspect, 1)
191
+ const model = mul(rotX(p.pitch), mul(rotY(p.yaw), translate(0, 0, -p.depthScale / 2)))
192
+ const mvp = mul(perspective(0.7, view, 0.05, 20), mul(translate(0, 0, -1.9 * fit * p.zoom), model))
193
+ gl.uniformMatrix4fv(gl.getUniformLocation(this.relief, 'u_mvp'), false, mvp)
194
+ gl.uniform1f(gl.getUniformLocation(this.relief, 'u_scale'), p.depthScale)
195
+ gl.uniform1f(gl.getUniformLocation(this.relief, 'u_aspect'), this.aspect)
196
+ gl.uniform1f(gl.getUniformLocation(this.relief, 'u_shade'), p.shade)
197
+ gl.uniform1i(gl.getUniformLocation(this.relief, 'u_src'), 0)
198
+ gl.uniform1i(gl.getUniformLocation(this.relief, 'u_depth'), 1)
199
+ gl.bindVertexArray(this.gridVao)
200
+ gl.drawElements(gl.TRIANGLES, this.gridCount, gl.UNSIGNED_INT, 0)
201
+ }
202
+ }
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>depth explorer</title>
7
+ <meta name="shot-ready" content="wait" />
8
+ <link rel="stylesheet" href="./styles.css" />
9
+ </head>
10
+ <body>
11
+ <div id="root"></div>
12
+ <script type="module" src="./main.tsx"></script>
13
+ </body>
14
+ </html>
@@ -0,0 +1,19 @@
1
+ import { createRoot } from 'react-dom/client'
2
+ import { WIDGET_STYLES } from '../../../src/cli/serve/web/widgets/widgetStyles.ts'
3
+ import { App } from './App.tsx'
4
+ import { AppSt } from './state.ts'
5
+
6
+ // the panel's output widget rules (the relight view is the panel's widget)
7
+ const styleEl = document.createElement('style')
8
+ styleEl.textContent = WIDGET_STYLES
9
+ document.head.appendChild(styleEl)
10
+
11
+ const st = new AppSt()
12
+ // console debugging path (app-state-tree: expose the root)
13
+ ;(globalThis as { st?: AppSt }).st = st
14
+ Object.assign(window, { tour: (t: number) => st.tour(t) })
15
+ void st.boot()
16
+
17
+ const rootEl = document.getElementById('root')
18
+ if (rootEl == null) throw new Error('#root missing from index.html')
19
+ createRoot(rootEl).render(<App st={st} />)
@@ -0,0 +1,86 @@
1
+ // depth map display: grey or turbo, optional min/max stretch. Each model outputs its own range,
2
+ // the stretch makes them comparable at a glance.
3
+ import type { Colormap } from './state.ts'
4
+
5
+ /** Google's turbo colormap, polynomial fit (Mikhailov 2019) */
6
+ function turbo(x: number): [number, number, number] {
7
+ const r =
8
+ 0.13572138 + x * (4.6153926 + x * (-42.66032258 + x * (132.13108234 + x * (-152.94239396 + x * 59.28637943))))
9
+ const g = 0.09140261 + x * (2.19418839 + x * (4.84296658 + x * (-14.18503333 + x * (4.27729857 + x * 2.82956604))))
10
+ const b =
11
+ 0.1066733 + x * (12.64194608 + x * (-60.58204836 + x * (110.36276771 + x * (-89.90310912 + x * 27.34824973))))
12
+ const c = (v: number): number => Math.round(Math.min(1, Math.max(0, v)) * 255)
13
+ return [c(r), c(g), c(b)]
14
+ }
15
+ const TURBO: [number, number, number][] = Array.from({ length: 256 }, (_, i) => turbo(i / 255))
16
+
17
+ export async function loadImage(url: string): Promise<HTMLImageElement> {
18
+ const img = new Image()
19
+ img.src = url
20
+ await img.decode()
21
+ return img
22
+ }
23
+
24
+ /** the depth map as a grey canvas, stretched to 0..255 when `stretch` (2nd and 98th percentiles) */
25
+ export function greyDepth(img: HTMLImageElement, stretch: boolean): HTMLCanvasElement {
26
+ const c = document.createElement('canvas')
27
+ c.width = img.naturalWidth
28
+ c.height = img.naturalHeight
29
+ const ctx = c.getContext('2d', { willReadFrequently: true })
30
+ if (ctx == null) throw new Error('no 2d context')
31
+ ctx.drawImage(img, 0, 0)
32
+ const data = ctx.getImageData(0, 0, c.width, c.height)
33
+ const px = data.data
34
+ let lo = 0
35
+ let hi = 255
36
+ if (stretch) {
37
+ const hist = new Uint32Array(256)
38
+ for (let i = 0; i < px.length; i += 4) {
39
+ const v = px[i] ?? 0
40
+ hist[v] = (hist[v] ?? 0) + 1
41
+ }
42
+ const n = px.length / 4
43
+ let acc = 0
44
+ lo = -1
45
+ for (let v = 0; v < 256; v++) {
46
+ acc += hist[v] ?? 0
47
+ if (lo < 0 && acc >= n * 0.02) lo = v
48
+ if (acc >= n * 0.98) {
49
+ hi = v
50
+ break
51
+ }
52
+ }
53
+ if (hi <= lo) hi = lo + 1
54
+ }
55
+ const k = 255 / (hi - lo)
56
+ for (let i = 0; i < px.length; i += 4) {
57
+ const v = Math.min(255, Math.max(0, ((px[i] ?? 0) - lo) * k))
58
+ px[i] = v
59
+ px[i + 1] = v
60
+ px[i + 2] = v
61
+ }
62
+ ctx.putImageData(data, 0, 0)
63
+ return c
64
+ }
65
+
66
+ /** grey depth → the picked colormap, drawn into `out` */
67
+ export function paintDepth(grey: HTMLCanvasElement, map: Colormap, out: HTMLCanvasElement): void {
68
+ out.width = grey.width
69
+ out.height = grey.height
70
+ const ctx = out.getContext('2d')
71
+ const src = grey.getContext('2d')
72
+ if (ctx == null || src == null) throw new Error('no 2d context')
73
+ if (map === 'gray') {
74
+ ctx.drawImage(grey, 0, 0)
75
+ return
76
+ }
77
+ const data = src.getImageData(0, 0, grey.width, grey.height)
78
+ const px = data.data
79
+ for (let i = 0; i < px.length; i += 4) {
80
+ const t = TURBO[px[i] ?? 0] ?? [0, 0, 0]
81
+ px[i] = t[0]
82
+ px[i + 1] = t[1]
83
+ px[i + 2] = t[2]
84
+ }
85
+ ctx.putImageData(data, 0, 0)
86
+ }
@@ -0,0 +1,329 @@
1
+ // the one state tree of the page: the catalog from the server, the source image, one result per
2
+ // (image, detail, model), the view settings. A sequential run queue: one prompt at a time on the GPU.
3
+ import { makeAutoObservable, runInAction } from 'mobx'
4
+
5
+ export type WeightFile = { node: string; input: string; file: string; folder: string; url: string }
6
+ export type ModelInfo = {
7
+ id: string
8
+ label: string
9
+ family: string
10
+ year: number
11
+ kind: 'depth' | 'normal' | 'material'
12
+ tier: 'modern' | 'classic'
13
+ blurb: string
14
+ autoDownload: boolean
15
+ ok: boolean
16
+ missingNodes: string[]
17
+ missingFiles: WeightFile[]
18
+ }
19
+ export type Source = { key: string; url: string; name: string; width: number; height: number }
20
+ export type Colormap = 'gray' | 'turbo'
21
+ export type FocusView = 'wipe' | '3d' | 'light'
22
+
23
+ export class ResultSt {
24
+ status: 'queued' | 'running' | 'done' | 'error' = 'queued'
25
+ url: string | null = null
26
+ ms: number | null = null
27
+ error: string | null = null
28
+ startedAt = 0
29
+ constructor() {
30
+ makeAutoObservable(this)
31
+ }
32
+ }
33
+
34
+ export class AppSt {
35
+ host = ''
36
+ models: ModelInfo[] = []
37
+ samples: string[] = []
38
+ loadError: string | null = null
39
+ source: Source | null = null
40
+ detail = 768
41
+ showClassic = false
42
+ showMissing = true
43
+ colormap: Colormap = 'turbo'
44
+ autoLevels = true
45
+ focus: string | null = null
46
+ focusView: FocusView = 'wipe'
47
+ /** the left side of the wipe: 'source' or a model id */
48
+ wipeAgainst = 'source'
49
+ /** the wipe handle, 0..100 % of the width */
50
+ wipeX = 50
51
+ /** the 3D relief camera and surface */
52
+ relief = { yaw: 0.35, pitch: 0.2, zoom: 1, depthScale: 0.3, shade: 0.6 }
53
+ results = new Map<string, ResultSt>()
54
+ private queue: { key: string; model: string; image: string; detail: number }[] = []
55
+ private draining = false
56
+ /** ticks every 200 ms while something runs, for the elapsed timers */
57
+ now = Date.now()
58
+
59
+ constructor() {
60
+ makeAutoObservable(this, { results: true })
61
+ setInterval(() => runInAction(() => (this.now = Date.now())), 200)
62
+ }
63
+
64
+ async boot(): Promise<void> {
65
+ try {
66
+ const [m, s] = await Promise.all([fetch('/api/models'), fetch('/api/samples')])
67
+ const mj = (await m.json()) as { host: string; models: ModelInfo[] }
68
+ const sj = (await s.json()) as string[]
69
+ runInAction(() => {
70
+ this.host = mj.host
71
+ this.models = mj.models
72
+ this.samples = sj
73
+ })
74
+ // deep link: ?image=<sample>&run=all|<id,id>&focus=<id>&view=wipe|3d|light
75
+ const q = new URLSearchParams(location.search)
76
+ const pick = q.get('image')
77
+ const first =
78
+ (pick != null && sj.includes(pick) ? pick : null) ?? sj.find((x) => x.startsWith('lioness')) ?? sj[0]
79
+ if (first != null) await this.loadSample(first)
80
+ const run = q.get('run')
81
+ if (run === 'all') this.runAll()
82
+ else if (run != null) for (const id of run.split(',')) if (this.model(id)?.ok === true) this.enqueue(id)
83
+ const focus = q.get('focus')
84
+ const view = q.get('view')
85
+ await this.settled()
86
+ if (focus != null) {
87
+ this.openFocus(focus)
88
+ if (view === 'wipe' || view === '3d' || view === 'light') this.set('focusView', view)
89
+ }
90
+ } catch (e) {
91
+ runInAction(() => (this.loadError = e instanceof Error ? e.message : String(e)))
92
+ }
93
+ // the shot service waits for this mark (sk shot): every queued run has ended
94
+ document.querySelector('meta[name="shot-ready"]')?.setAttribute('content', 'ready')
95
+ }
96
+
97
+ /** the scripted tour a demo video steps through (`sk shot --step tour`), over finished results:
98
+ * the grid, a wipe against the source then against another model, the 3D relief, a material
99
+ * map, then the relight widget's own tour */
100
+ async tour(t: number): Promise<void> {
101
+ const main = document.querySelector('main')
102
+ const wave = (a: number, b: number): number => Math.min(1, Math.max(0, (t - a) / (b - a)))
103
+ if (t < 3) {
104
+ this.closeFocus()
105
+ if (main != null) main.scrollTop = wave(0.5, 3) * (main.scrollHeight - main.clientHeight)
106
+ return
107
+ }
108
+ if (t < 10) {
109
+ this.openFocus(this.firstDoneId('depth') ?? 'da3-mono-large')
110
+ this.set('focusView', 'wipe')
111
+ this.set('wipeAgainst', t < 6.5 ? 'source' : (this.firstDoneId('depth', 1) ?? 'source'))
112
+ const k = t < 6.5 ? wave(3, 6.5) : wave(6.5, 10)
113
+ this.set('wipeX', 50 + 42 * Math.sin(k * Math.PI * 2))
114
+ return
115
+ }
116
+ if (t < 14) {
117
+ this.openFocus(this.firstDoneId('depth') ?? 'da3-mono-large')
118
+ this.set('focusView', '3d')
119
+ this.set('relief', {
120
+ ...this.relief,
121
+ yaw: -0.75 + 1.5 * wave(10, 14),
122
+ pitch: 0.45,
123
+ depthScale: 0.5,
124
+ zoom: 0.62,
125
+ })
126
+ return
127
+ }
128
+ if (t < 16.5) {
129
+ this.openFocus('iid-albedo')
130
+ this.set('focusView', 'wipe')
131
+ this.set('wipeAgainst', 'source')
132
+ this.set('wipeX', 85 - 70 * wave(14, 16.5))
133
+ return
134
+ }
135
+ this.openFocus(this.firstDoneId('normal') ?? 'moge2-normal')
136
+ this.set('focusView', 'light')
137
+ // the widget mounts on this render, and registers its hook when it does
138
+ for (let i = 0; i < 200 && typeof Reflect.get(window, 'relightTour') !== 'function'; i++)
139
+ await new Promise((ok) => setTimeout(ok, 16))
140
+ const f: unknown = Reflect.get(window, 'relightTour')
141
+ if (typeof f === 'function') await f(t - 16.5)
142
+ }
143
+
144
+ /** the id of the `nth` finished modern result of a kind, in catalog order */
145
+ firstDoneId(kind: ModelInfo['kind'], nth = 0): string | null {
146
+ const done = this.models.filter(
147
+ (m) => m.kind === kind && m.tier === 'modern' && this.result(m.id)?.status === 'done',
148
+ )
149
+ return done[nth]?.id ?? null
150
+ }
151
+
152
+ get visibleModels(): ModelInfo[] {
153
+ return this.models.filter((m) => (this.showClassic || m.tier === 'modern') && (this.showMissing || m.ok))
154
+ }
155
+ get depthModels(): ModelInfo[] {
156
+ return this.visibleModels.filter((m) => m.kind === 'depth')
157
+ }
158
+ get normalModels(): ModelInfo[] {
159
+ return this.visibleModels.filter((m) => m.kind === 'normal')
160
+ }
161
+ get materialModels(): ModelInfo[] {
162
+ return this.visibleModels.filter((m) => m.kind === 'material')
163
+ }
164
+
165
+ /** the url of the first finished result among `ids`, in that order of preference */
166
+ firstDone(ids: string[]): string | null {
167
+ for (const id of ids) {
168
+ const url = this.result(id)?.url
169
+ if (this.result(id)?.status === 'done' && url != null) return url
170
+ }
171
+ return null
172
+ }
173
+
174
+ /** every map the relight view can use for the focused model: the focus itself, the best
175
+ * finished depth and normal of the grid, and the finished material maps */
176
+ get relightMaps(): { tag: string; url: string }[] {
177
+ const focus = this.focus != null ? this.model(this.focus) : undefined
178
+ const src = this.source
179
+ if (focus == null || src == null) return []
180
+ const byKind = (kind: ModelInfo['kind']): string[] => [
181
+ ...(focus.kind === kind ? [focus.id] : []),
182
+ ...this.models.filter((m) => m.kind === kind && m.tier === 'modern').map((m) => m.id),
183
+ ]
184
+ const out: { tag: string; url: string }[] = [{ tag: 'source', url: src.url }]
185
+ const add = (tag: string, url: string | null): void => {
186
+ if (url != null) out.push({ tag, url })
187
+ }
188
+ add('depth', this.firstDone(byKind('depth')))
189
+ add('normal', this.firstDone(byKind('normal')))
190
+ add('albedo', this.firstDone(['iid-albedo', 'marigold2-albedo']))
191
+ add('roughness', this.firstDone(['iid-roughness']))
192
+ add('metalness', this.firstDone(['iid-metalness']))
193
+ add('specular', this.firstDone(['iid-specular']))
194
+ return out
195
+ }
196
+ get runnable(): ModelInfo[] {
197
+ return this.visibleModels.filter((m) => m.ok)
198
+ }
199
+ get busy(): boolean {
200
+ return this.queue.length > 0 || this.draining
201
+ }
202
+
203
+ model(id: string): ModelInfo | undefined {
204
+ return this.models.find((m) => m.id === id)
205
+ }
206
+ resultKey(model: string): string {
207
+ return `${this.source?.key ?? '-'}:${this.detail}:${model}`
208
+ }
209
+ result(model: string): ResultSt | undefined {
210
+ return this.results.get(this.resultKey(model))
211
+ }
212
+ get doneModels(): ModelInfo[] {
213
+ return this.models.filter((m) => this.result(m.id)?.status === 'done')
214
+ }
215
+
216
+ async loadSample(name: string): Promise<void> {
217
+ const blob = await (await fetch(`/api/samples/${encodeURIComponent(name)}`)).blob()
218
+ await this.setSource(blob, name)
219
+ }
220
+
221
+ async setSource(blob: Blob, name: string): Promise<void> {
222
+ const url = URL.createObjectURL(blob)
223
+ const img = new Image()
224
+ img.src = url
225
+ await img.decode()
226
+ const res = await fetch('/api/image', { method: 'POST', body: blob })
227
+ const j = (await res.json()) as { key?: string; error?: string }
228
+ if (j.key == null) throw new Error(j.error ?? 'upload failed')
229
+ const key = j.key
230
+ runInAction(() => {
231
+ this.source = { key, url, name, width: img.naturalWidth, height: img.naturalHeight }
232
+ this.focus = null
233
+ })
234
+ }
235
+
236
+ enqueue(model: string): void {
237
+ const src = this.source
238
+ if (src == null) return
239
+ const key = this.resultKey(model)
240
+ const prev = this.results.get(key)
241
+ if (prev != null && (prev.status === 'queued' || prev.status === 'running')) return
242
+ this.results.set(key, new ResultSt())
243
+ this.queue.push({ key, model, image: src.key, detail: this.detail })
244
+ void this.drain()
245
+ }
246
+
247
+ runAll(): void {
248
+ for (const m of this.runnable) if (this.result(m.id)?.status !== 'done') this.enqueue(m.id)
249
+ }
250
+
251
+ /** resolves once the run queue is empty */
252
+ settled(): Promise<void> {
253
+ return new Promise((resolve) => {
254
+ const tick = (): void => {
255
+ if (this.busy) setTimeout(tick, 100)
256
+ else resolve()
257
+ }
258
+ tick()
259
+ })
260
+ }
261
+
262
+ private async drain(): Promise<void> {
263
+ if (this.draining) return
264
+ this.draining = true
265
+ try {
266
+ for (;;) {
267
+ const job = this.queue.shift()
268
+ if (job == null) break
269
+ const r = this.results.get(job.key)
270
+ if (r == null) continue
271
+ runInAction(() => {
272
+ r.status = 'running'
273
+ r.startedAt = Date.now()
274
+ })
275
+ try {
276
+ const res = await fetch('/api/run', {
277
+ method: 'POST',
278
+ headers: { 'content-type': 'application/json' },
279
+ body: JSON.stringify({ image: job.image, model: job.model, detail: job.detail }),
280
+ })
281
+ if (!res.ok) {
282
+ const j = (await res.json()) as { error?: string }
283
+ throw new Error(j.error ?? `http ${res.status}`)
284
+ }
285
+ const url = URL.createObjectURL(await res.blob())
286
+ const ms = Number(res.headers.get('x-ms'))
287
+ runInAction(() => {
288
+ r.url = url
289
+ r.ms = ms
290
+ r.status = 'done'
291
+ })
292
+ } catch (e) {
293
+ runInAction(() => {
294
+ r.error = e instanceof Error ? e.message : String(e)
295
+ r.status = 'error'
296
+ })
297
+ }
298
+ }
299
+ } finally {
300
+ runInAction(() => (this.draining = false))
301
+ }
302
+ }
303
+
304
+ openFocus(model: string): void {
305
+ const m = this.model(model)
306
+ this.focus = model
307
+ if (m?.kind === 'normal' && this.focusView === '3d') this.focusView = 'light'
308
+ if (m?.kind === 'material') this.focusView = 'wipe'
309
+ }
310
+
311
+ set<
312
+ K extends
313
+ | 'detail'
314
+ | 'showClassic'
315
+ | 'showMissing'
316
+ | 'colormap'
317
+ | 'autoLevels'
318
+ | 'focusView'
319
+ | 'wipeAgainst'
320
+ | 'wipeX'
321
+ | 'relief',
322
+ >(k: K, v: this[K]): void {
323
+ this[k] = v
324
+ }
325
+
326
+ closeFocus(): void {
327
+ this.focus = null
328
+ }
329
+ }