vs2convert 0.2.0__py3-none-any.whl

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.
@@ -0,0 +1,1363 @@
1
+ """
2
+ VS-2 conversion engine - transforms source shaders into complete VS-2 .frag files.
3
+
4
+ Pipeline: consume source metadata -> format-specific body transforms (scope-aware
5
+ parameter remapping, builtin renames) -> output-pattern rewrite -> precision block
6
+ -> manifest header.
7
+
8
+ Hard gates (ConversionError): MilkDrop/HLSL, bundled textures, feedback buffers /
9
+ ISF TARGET inputs, and Shadertoy shaders reading more than one distinct
10
+ iChannel (VS-2 binds one imageTex plus the engine audio sampler fftTex).
11
+
12
+ Image inputs are NOT gated. A single iChannel0 read, or an ISF
13
+ `TYPE: image` input, renames to `imageTex` per formal-spec.md, which VS-2
14
+ binds from the layer's configured image. The image is implicit: no manifest
15
+ parameter is created for it.
16
+
17
+ Manifest knobs are injected by the VS-2 engine as uniforms; body references to
18
+ knob names are valid as-is.
19
+ """
20
+ import re
21
+ import json
22
+ import uuid as _uuid
23
+
24
+ from .gates import NON_FORCEABLE
25
+ from .textutil import code_only, ENGINE_VARS, UNIFORM_NAME_RE
26
+
27
+ MAX_PARAMS = 7
28
+ SPEED_KEYWORDS = ('speed', 'rate', 'frequency', 'freq')
29
+
30
+ # Longest UNVERIFIED marker body written into a .frag, before the trailing
31
+ # "...". The terminal keeps the full paragraph; the file gets the fact and
32
+ # the subject.
33
+ _UNVERIFIED_MARKER_MAX = 100
34
+
35
+ GLSL_TYPES = ('float', 'vec2', 'vec3', 'vec4', 'int', 'bool',
36
+ 'mat2', 'mat3', 'mat4')
37
+
38
+ MANIFEST_BLOCK_RE = re.compile(r'/\*(.*?)\*/', re.DOTALL)
39
+ UNIFORM_DECL_RE = re.compile(
40
+ r'^[ \t]*uniform\b[^;]*;', re.MULTILINE | re.DOTALL)
41
+ PRECISION_RE = re.compile(r'#ifdef\s+GL_ES')
42
+
43
+
44
+ class ConversionError(Exception):
45
+ """Fatal: source cannot be converted automatically.
46
+
47
+ `gate` is a stable id from core.gates.GATES (or None for a bare format
48
+ complaint). The public API turns it into a structured Rejection; it is
49
+ set at the raise site so no message-to-id table has to be maintained.
50
+ """
51
+
52
+ def __init__(self, message: str, gate: str = None):
53
+ super().__init__(message)
54
+ self.gate = gate
55
+
56
+
57
+ def _fmt_num(v) -> str:
58
+ """GLSL-safe float literal."""
59
+ f = float(v)
60
+ s = f"{f:.6g}"
61
+ if '.' not in s and 'e' not in s and 'E' not in s:
62
+ s += '.0'
63
+ return s
64
+
65
+
66
+ def _snake(name: str) -> str:
67
+ s = re.sub(r'[^a-zA-Z0-9_]', '_', name)
68
+ s = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', s)
69
+ s = s.lower()
70
+ s = re.sub(r'_+', '_', s).strip('_')
71
+ if not s:
72
+ s = 'param'
73
+ if s[0].isdigit():
74
+ s = '_' + s
75
+ return s
76
+
77
+
78
+ def _referenced(name: str, code: str) -> bool:
79
+ r"""True when `name` is an identifier in `code`, which must already have
80
+ comments and string literals stripped (`code_only`). A declared knob the
81
+ body never reads is a dead slider; the external validator rejects it, so
82
+ the knob is dropped with a warning.
83
+
84
+ The `(?<!\w.)` guard is the one the mouse-axis and rename passes use: a
85
+ knob named `x` must not be "referenced" by `uv.x`."""
86
+ return bool(re.search(r'(?<![\w.])' + re.escape(name) + r'\b', code))
87
+
88
+
89
+ def _find_manifest_params(source: str) -> dict:
90
+ """Extract {name: {default, min, max}} from a /* {json} */ manifest block."""
91
+ for block in MANIFEST_BLOCK_RE.findall(source):
92
+ try:
93
+ data = json.loads(block.strip())
94
+ except (json.JSONDecodeError, ValueError):
95
+ continue
96
+ if isinstance(data, dict) and 'parameters' in data:
97
+ out = {}
98
+ for p in data.get('parameters', []):
99
+ if isinstance(p, dict) and p.get('name'):
100
+ out[p['name']] = {
101
+ 'default': p.get('default', 0.5),
102
+ 'min': p.get('min', 0.0),
103
+ 'max': p.get('max', 1.0),
104
+ }
105
+ return out
106
+ return {}
107
+
108
+
109
+ def _strip_uniforms(source: str) -> str:
110
+ """Remove uniform declarations (engine/manifest inject these)."""
111
+ return UNIFORM_DECL_RE.sub('', source)
112
+
113
+
114
+ def _strip_consumed_manifests(source: str) -> str:
115
+ """Remove comment blocks that parsed as JSON metadata (manifest/ISF INPUTS)."""
116
+ def _keep(m):
117
+ try:
118
+ data = json.loads(m.group(1).strip())
119
+ except (json.JSONDecodeError, ValueError):
120
+ return m.group(0)
121
+ if isinstance(data, dict) and ('parameters' in data or 'INPUTS' in data):
122
+ return ''
123
+ return m.group(0)
124
+ return MANIFEST_BLOCK_RE.sub(_keep, source)
125
+
126
+
127
+ def _ensure_precision(source: str) -> str:
128
+ if PRECISION_RE.search(source):
129
+ return source
130
+ return ("#ifdef GL_ES\nprecision highp float;\n#endif\n\n" + source)
131
+
132
+
133
+ def _enclosing_block(src: str, pos: int):
134
+ """Innermost {...} block containing pos. Returns (start, end) or None.
135
+ When the block is a function body, the range is extended back over the
136
+ signature so parameter declarations fall inside it.
137
+
138
+ Braces inside comments and string literals are ignored: a `}` in a
139
+ comment used to inflate the backward depth count and return a span one
140
+ character past the real closing brace.
141
+ """
142
+ src = code_only(src)
143
+ depth = 0
144
+ open_pos = None
145
+ for i in range(pos, -1, -1):
146
+ c = src[i]
147
+ if c == '}':
148
+ depth += 1
149
+ elif c == '{':
150
+ if depth == 0:
151
+ open_pos = i
152
+ break
153
+ depth -= 1
154
+ if open_pos is None:
155
+ return None
156
+ depth = 0
157
+ close_pos = None
158
+ for j in range(open_pos, len(src)):
159
+ if src[j] == '{':
160
+ depth += 1
161
+ elif src[j] == '}':
162
+ depth -= 1
163
+ if depth == 0:
164
+ close_pos = j + 1
165
+ break
166
+ if close_pos is None:
167
+ return None
168
+ k = open_pos - 1
169
+ while k >= 0 and src[k] in ' \t\n\r':
170
+ k -= 1
171
+ if k >= 0 and src[k] == ')':
172
+ pdepth = 0
173
+ for i in range(k, -1, -1):
174
+ if src[i] == ')':
175
+ pdepth += 1
176
+ elif src[i] == '(':
177
+ pdepth -= 1
178
+ if pdepth == 0:
179
+ m = i
180
+ while m >= 0 and (src[m].isalnum() or src[m] in '_'):
181
+ m -= 1
182
+ return (m + 1, close_pos)
183
+ return (open_pos, close_pos)
184
+
185
+
186
+ def _replace_scoped(src: str, name: str, plain: str, wrapped: str) -> str:
187
+ """Replace `name` refs: plain inside blocks that declare it (local scope,
188
+ e.g. function parameters), wrapped everywhere else (global/knob reference)."""
189
+ decl_re = re.compile(
190
+ r'\b(?:' + '|'.join(GLSL_TYPES) + r')\s+' + re.escape(name) + r'\b')
191
+ decls = list(decl_re.finditer(src))
192
+ if not decls:
193
+ return re.sub(r'\b' + re.escape(name) + r'\b', wrapped, src)
194
+
195
+ plain_ranges = []
196
+ for d in decls:
197
+ blk = _enclosing_block(src, d.start())
198
+ if blk:
199
+ plain_ranges.append(blk)
200
+ else:
201
+ # global-scope declaration: entire file is plain for this name
202
+ return re.sub(r'\b' + re.escape(name) + r'\b', plain, src)
203
+ plain_ranges.sort()
204
+
205
+ out = []
206
+ idx = 0
207
+ for m in re.finditer(r'\b' + re.escape(name) + r'\b', src):
208
+ if m.start() < idx:
209
+ continue
210
+ in_plain = any(s <= m.start() < e for s, e in plain_ranges)
211
+ out.append(src[idx:m.start()])
212
+ out.append(plain if in_plain else wrapped)
213
+ idx = m.end()
214
+ out.append(src[idx:])
215
+ return ''.join(out)
216
+
217
+
218
+ def _rewrite_output(source: str) -> str:
219
+ """Replace the final fragColor/gl_FragColor = vec4(...) assignment with the
220
+ VS-2 coloredPixels pattern. Paren-depth aware (handles nested commas)."""
221
+ pat = re.compile(r'\b(fragColor|gl_FragColor)\s*=\s*vec4\s*\(')
222
+ matches = list(pat.finditer(source))
223
+ if not matches:
224
+ return source
225
+ # KNOWN LIMITATION (2026-09-25, deliberately left unfixed - see PRD 14).
226
+ # Only the LAST fragColor assignment is rewritten. A shader that sets its
227
+ # output inside an if/else chain therefore gets the VS-2 transparency
228
+ # convention on one branch and not the others, so the screen shows a seam
229
+ # where alpha behaviour changes mid-frame. Raw `fragColor = vec4(...)` is
230
+ # still valid GLSL, so this is cosmetic, NOT a compile failure.
231
+ #
232
+ # Evidence: 0 of the 79 shipped shaders branch on output, and all 15
233
+ # VS-2-native shaders (12 factory + 3 image-input) have exactly ONE
234
+ # assignment - so nothing currently exercises it.
235
+ #
236
+ # The fix is NOT to rewrite each branch independently (that is what
237
+ # produces the seam). It is to hoist the branch outputs into temporaries
238
+ # and emit ONE final assignment, matching the native convention:
239
+ # vec3 vs2Final; float vs2Alpha;
240
+ # if (...) { vs2Final = ...; vs2Alpha = ...; } else { ... }
241
+ # { ...one output pattern, applied uniformly... }
242
+ # That is a real GLSL transform, not a regex, and it needs a branched
243
+ # shader checked in VS-2 before it can be trusted.
244
+ m = matches[-1]
245
+ open_idx = m.end() - 1
246
+ depth = 0
247
+ close_idx = None
248
+ for i in range(open_idx, len(source)):
249
+ if source[i] == '(':
250
+ depth += 1
251
+ elif source[i] == ')':
252
+ depth -= 1
253
+ if depth == 0:
254
+ close_idx = i
255
+ break
256
+ if close_idx is None:
257
+ return source
258
+ inner = source[open_idx + 1:close_idx]
259
+ args, cur, d = [], '', 0
260
+ for ch in inner:
261
+ if ch == '(':
262
+ d += 1
263
+ elif ch == ')':
264
+ d -= 1
265
+ if ch == ',' and d == 0:
266
+ args.append(cur)
267
+ cur = ''
268
+ else:
269
+ cur += ch
270
+ args.append(cur)
271
+ args = [a.strip() for a in args]
272
+ # The match regex only ever matches a `vec4(` call. Every valid shape:
273
+ # vec4(r,g,b,a) 4 args
274
+ # vec4(vec2,g,b) 3 args
275
+ # vec4(rgb, a) 2 args
276
+ # vec4(v) 1 arg
277
+ # A three-arg vec4 whose first argument is a vec2 needs vec3(v2, g),
278
+ # not vec3(v2, g, b) - the old code emitted four components and produced
279
+ # GLSL that did not compile (found 2026-10-20: fragColor = vec4(uv, .5, 1)).
280
+ vec2_names = set(re.findall(r'\bvec2\s+([A-Za-z_]\w*)', source))
281
+
282
+ def is_vec2(text):
283
+ return (text.startswith('vec2(') or text in vec2_names
284
+ or bool(re.search(r'\.(?:xy|rg|st)$', text)))
285
+
286
+ if len(args) == 4:
287
+ expr = f"vec3({args[0]}, {args[1]}, {args[2]})"
288
+ elif len(args) == 3 and is_vec2(args[0]):
289
+ expr = f"vec3({args[0]}, {args[1]})"
290
+ elif len(args) == 2 and not is_vec2(args[0]):
291
+ expr = args[0]
292
+ elif len(args) == 1:
293
+ expr = f"({args[0]}).rgb"
294
+ else:
295
+ return source # ambiguous shape; leave it rather than corrupt it
296
+ end = close_idx + 1
297
+ while end < len(source) and source[end] in ' \t':
298
+ end += 1
299
+ if end < len(source) and source[end] == ';':
300
+ end += 1
301
+ # Two different transparency conventions, and picking the wrong one is
302
+ # invisible to every structural check.
303
+ #
304
+ # PROCEDURAL (no image sampling): alpha = how BRIGHT the pixel is.
305
+ # float coloredPixels = dot(clamp(vs2Final,0,1), vec3(1.0));
306
+ # fragColor = vec4(vs2Final * color.rgb, alpha * coloredPixels);
307
+ #
308
+ # IMAGE-INPUT (samples imageTex): alpha = the IMAGE'S OWN alpha.
309
+ # fragColor = vec4(vs2Final * color.rgb, srcAlpha * alpha);
310
+ # Confirmed against all three authoritative references in
311
+ # factory-references/VS2-image-input/ (texture-glitch:162,
312
+ # texture-kaleidoscope:95, texture-ripple:85) - all use col.a, never
313
+ # coloredPixels.
314
+ #
315
+ # Using the procedural pattern on an image shader makes alpha ~1.0
316
+ # wherever the sampled image is bright, so the shader renders as a solid
317
+ # full-bleed rectangle and ignores the image's own transparency. A real
318
+ # Shadertoy glitch does `texture(iChannel0, uv * 0.5)`, averaging the same
319
+ # half-image 20 times, so it is bright almost everywhere.
320
+ if _samples_image(source):
321
+ # Recover the source's own alpha, which is the whole point of the
322
+ # image pattern. `vec4(rgb, a)` arrives as 2 args and `vec4(r,g,b,a)`
323
+ # as 4; `vec3(rgb)` has none. Picking wrong silently drops the alpha,
324
+ # which is how a first attempt produced `1.0 * alpha` for a shader
325
+ # whose alpha came from `sum.a`.
326
+ if len(args) == 4:
327
+ alpha_expr = args[3]
328
+ elif len(args) == 3:
329
+ alpha_expr = args[2]
330
+ elif len(args) == 2:
331
+ alpha_expr = args[1]
332
+ elif len(args) == 1:
333
+ alpha_expr = "(%s).a" % args[0]
334
+ else:
335
+ return source # ambiguous shape; leave it rather than guess
336
+ replacement = ("{\n"
337
+ " vec3 vs2Final = " + expr + ";\n"
338
+ " fragColor = vec4(vs2Final * color.rgb, "
339
+ + alpha_expr + " * alpha);\n"
340
+ "}")
341
+ else:
342
+ replacement = (
343
+ "{\n"
344
+ " vec3 vs2Final = " + expr + ";\n"
345
+ " float coloredPixels = dot(clamp(vs2Final, 0.0, 1.0), vec3(1.0));\n"
346
+ " fragColor = vec4(vs2Final * color.rgb, alpha * coloredPixels);\n"
347
+ "}")
348
+ return source[:m.start()] + replacement + source[end:]
349
+
350
+
351
+ def _samples_image(body: str) -> bool:
352
+ """True if the body reads VS-2's image sampler.
353
+
354
+ Matches `texture(imageTex, ...)`, `textureLod`, and the ISF accessors
355
+ after they have been rewritten. Comments are ignored: a shader whose
356
+ comment says "samples imageTex" is still procedural.
357
+ """
358
+ code = code_only(body)
359
+ return bool(re.search(r'\btexture\w*\s*\(\s*imageTex\b', code)
360
+ or re.search(r'\bimageTex\s*[,)]', code))
361
+
362
+
363
+ def _rename_shadowed_engine_vars(source: str) -> str:
364
+ """Rename local declarations that shadow an engine uniform, keeping the
365
+ initializer's reference to the engine value intact.
366
+
367
+ Every engine uniform is in scope, not just `color`/`alpha`.
368
+
369
+ A real case: Shadertoy
370
+ float time = mod(iTime*100.0, 32.0)/110.0;
371
+ becomes, after the iTime->time rename,
372
+ float time = mod(time*100.0, 32.0)/110.0;
373
+ which initialises `time` from itself. The shader still compiles and
374
+ renders - it simply stops animating. Structural validation cannot see
375
+ that; the render gate's motion check is what catches it.
376
+
377
+ The fix renames the LOCAL to `srcTime` and leaves the engine `time` on
378
+ the right-hand side, so the source's own arithmetic is preserved and the
379
+ engine uniform stays reachable.
380
+ """
381
+ lines = source.split('\n')
382
+ # Byte offset of each line start, so a declaration can be located in the
383
+ # whole source and its enclosing block resolved.
384
+ starts = [0]
385
+ for line in lines[:-1]:
386
+ starts.append(starts[-1] + len(line) + 1)
387
+ type_alt = '|'.join(GLSL_TYPES)
388
+ for var in sorted(ENGINE_VARS):
389
+ decl = re.compile(
390
+ r'^(\s*)(' + type_alt + r')\s+' + var + r'\s*=\s*(.*)$')
391
+ # Rename ONLY when a real shadowing declaration exists. Renaming
392
+ # unconditionally would rewrite every legitimate engine reference,
393
+ # including the `imageTex` the iChannel rename just produced.
394
+ decl_lines = [i for i, l in enumerate(lines) if decl.match(l)]
395
+ if not decl_lines:
396
+ continue
397
+ renamed = 'src' + var[0].upper() + var[1:]
398
+ # A shadowing declaration only shadows INSIDE its own block. Renaming
399
+ # file-wide rewrote the engine uniform inside functions that never
400
+ # declared the name: Jazz_Universe's `volumetricFog` reads the engine
401
+ # `time`, received `srcTime`, and the GLSL did not compile. A
402
+ # top-level declaration (no enclosing block) shadows everywhere.
403
+ scopes = [_enclosing_block(source, starts[i]) or (0, len(source))
404
+ for i in decl_lines]
405
+ for i, line in enumerate(lines):
406
+ m = decl.match(line)
407
+ if m:
408
+ # Declaration: rename the declared name, keep the init as-is.
409
+ lines[i] = '%s%s %s = %s' % (m.group(1), m.group(2),
410
+ renamed, m.group(3))
411
+ elif any(s <= starts[i] < e for s, e in scopes):
412
+ lines[i] = re.sub(r'\b' + var + r'\b', renamed, line)
413
+ return '\n'.join(lines)
414
+
415
+
416
+ def _coalesce_frag_color_writes(body: str) -> str:
417
+ """Fold `fragColor.a = X; fragColor.rgb = Y;` into one `fragColor = ...`.
418
+
419
+ Some sources - a real Shadertoy glitch among them - write the output in
420
+ two component assignments. That is equivalent GLSL, but the external
421
+ validator requires a single `fragColor =` (validate_shader.py:156) and
422
+ every golden VS-2 shader uses one. Left split, a correct conversion
423
+ reports as a hard error.
424
+ """
425
+ if re.search(r'\bfragColor\s*=', body) and not re.search(
426
+ r'\bfragColor\s*\.\s*[argb]\w*\s*=', body):
427
+ return body
428
+ lines = body.split('\n')
429
+ out, i = [], 0
430
+ while i < len(lines):
431
+ m = re.match(r'^(\s*)fragColor\.(\w+)\s*=\s*(.+?);\s*$', lines[i])
432
+ if not m:
433
+ out.append(lines[i])
434
+ i += 1
435
+ continue
436
+ indent, comp, expr = m.group(1), m.group(2), m.group(3)
437
+ comps = {}
438
+ # Gather consecutive component writes in any order.
439
+ j = i
440
+ while j < len(lines):
441
+ m2 = re.match(r'^(\s*)fragColor\.(\w+)\s*=\s*(.+?);\s*$',
442
+ lines[j])
443
+ if not m2 or m2.group(1) != indent:
444
+ break
445
+ comps[m2.group(2)] = m2.group(3)
446
+ j += 1
447
+ if set(comps) <= {'rgb', 'a'} and 'rgb' in comps:
448
+ alpha = comps.get('a', '1.0')
449
+ out.append('%sfragColor = vec4(%s, %s);' % (indent, comps['rgb'],
450
+ alpha))
451
+ i = j
452
+ else:
453
+ out.append(lines[i])
454
+ i += 1
455
+ return '\n'.join(out)
456
+
457
+
458
+ def _flip_image_sample_v(body: str) -> str:
459
+ """`texture(iChannel0, uv)` -> `texture(imageTex, vec2(uv.x, 1.0 - uv.y))`.
460
+
461
+ Single left-to-right pass, depth-aware, so nested calls and extra
462
+ arguments (Shadertoy allows a bias third arg) survive intact.
463
+ """
464
+ out = []
465
+ i = 0
466
+ n = len(body)
467
+ while i < n:
468
+ m = re.compile(r'\btexture\s*\(\s*iChannel[0-3]\b').search(body, i)
469
+ if not m:
470
+ out.append(body[i:])
471
+ break
472
+ out.append(body[i:m.start()])
473
+ open_idx = body.index('(', m.start())
474
+ depth, close_idx = 0, None
475
+ for j in range(open_idx, n):
476
+ if body[j] == '(':
477
+ depth += 1
478
+ elif body[j] == ')':
479
+ depth -= 1
480
+ if depth == 0:
481
+ close_idx = j
482
+ break
483
+ if close_idx is None:
484
+ out.append(body[m.start():])
485
+ break
486
+ inner = body[open_idx + 1:close_idx]
487
+ args, cur, d = [], '', 0
488
+ for ch in inner:
489
+ if ch == '(':
490
+ d += 1
491
+ elif ch == ')':
492
+ d -= 1
493
+ if ch == ',' and d == 0:
494
+ args.append(cur)
495
+ cur = ''
496
+ else:
497
+ cur += ch
498
+ args.append(cur)
499
+ # args[0] is the SAMPLER (iChannel0); the uv is args[1]. Taking
500
+ # args[0] produced texture(imageTex, vec2((imageTex).x, ...)).
501
+ uv = args[1].strip() if len(args) > 1 and args[1].strip() else 'texCoord'
502
+ rest = ', '.join(a.strip() for a in args[2:])
503
+ new_inner = 'imageTex, vec2((%s).x, 1.0 - (%s).y)' % (uv, uv)
504
+ if rest:
505
+ new_inner += ', ' + rest
506
+ out.append('texture(' + new_inner + ')')
507
+ i = close_idx + 1
508
+ return ''.join(out)
509
+
510
+
511
+ def _build_manifest(params: list, shader_name: str) -> tuple:
512
+ """params: [{'name': ..., 'default': ...}] already sanitized and clamped.
513
+
514
+ Returns (header, manifest): the serialised comment written to the .frag
515
+ and the same data as a dict, so callers need not re-parse it.
516
+ """
517
+ manifest = {
518
+ "author": "VS-2 Convert",
519
+ "color": "#ffffff",
520
+ "movement": True,
521
+ "parameters": [
522
+ {"default": round(float(p['default']), 4), "name": p['name']}
523
+ for p in params[:MAX_PARAMS]
524
+ ],
525
+ "url": "",
526
+ "uuid": str(_uuid.uuid4()),
527
+ }
528
+ return "/*\n" + json.dumps(manifest, indent=4) + "\n*/\n\n", manifest
529
+
530
+
531
+
532
+ # ---------------------------------------------------------------------------
533
+ # format-specific body transforms
534
+ # ---------------------------------------------------------------------------
535
+
536
+ def _params_from(raw_params: dict, body: str, report: dict) -> tuple:
537
+ """Normalise candidate parameters into manifest entries.
538
+
539
+ Shared by the Shadertoy and GLSLSandbox paths: snake_case, engine-name
540
+ collisions, the 0..1 clamp, speed baking (rule 4), the dead-knob drop, and
541
+ the body renames the snake_case needs. The caller supplies the default:
542
+ a manifest states one, a GLSLSandbox uniform does not.
543
+ """
544
+ params = []
545
+ seen = set()
546
+ renames = {}
547
+ for name, info in raw_params.items():
548
+ clean = _snake(name)
549
+ # two source names can snake-case onto one (fooBar and foo_bar both
550
+ # become foo_bar) and the external validator rejects duplicate
551
+ # manifest names, so a collision gets an _amt suffix, as on the ISF
552
+ # path. test_engine.SnakeCaseCollisionTests.
553
+ while clean in seen or clean in ENGINE_VARS:
554
+ clean += '_amt'
555
+ seen.add(clean)
556
+ default = min(1.0, max(0.0, float(info['default'])))
557
+ if any(kw in clean for kw in SPEED_KEYWORDS):
558
+ body = re.sub(r'\b' + re.escape(name) + r'\b',
559
+ _fmt_num(info['default']), body)
560
+ report['baked'].append(
561
+ f"{name} -> {_fmt_num(info['default'])} (speed baked per rule 4)")
562
+ continue
563
+ if not _referenced(name, code_only(body)):
564
+ report['warnings'].append(
565
+ f"param '{name}' dropped: not referenced in the shader body "
566
+ "(dead knob)")
567
+ continue
568
+ if default != float(info['default']):
569
+ report['warnings'].append(
570
+ f"param '{clean}': default {info['default']} clamped to "
571
+ f"{default} (knob range 0..1)")
572
+ if clean != name:
573
+ renames[name] = clean
574
+ params.append({'name': clean, 'default': default})
575
+ if renames:
576
+ # one pass over every rename: per-name subs in sequence let a later
577
+ # rename re-rename an earlier one's references (fooBar -> foo_bar,
578
+ # then foo_bar -> foo_bar_amt, would clobber the first knob's uses).
579
+ # test_engine.SnakeCaseCollisionTests.
580
+ body = re.sub(r'\b(?:%s)\b' % '|'.join(re.escape(n) for n in renames),
581
+ lambda m: renames[m.group(0)], body)
582
+ return body, params
583
+
584
+
585
+ def _convert_shadertoy(source: str, report: dict, meta: dict = None) -> tuple:
586
+ """Returns (body, manifest_params)."""
587
+ raw_params = _find_manifest_params(source)
588
+ # iMouse axes become manifest params; collected here and merged below,
589
+ # because the Shadertoy path builds `params` after the body rewrite.
590
+ mouse_axes = []
591
+ if not raw_params:
592
+ for m in re.finditer(
593
+ r'uniform\s+(float|vec2|vec3|vec4)\s+(\w+)\s*;', source):
594
+ raw_params[m.group(2)] = {'default': 0.5, 'min': 0.0, 'max': 1.0}
595
+
596
+ body = _strip_uniforms(source)
597
+ body = _strip_consumed_manifests(body)
598
+
599
+ # formal-spec.md: `iChannel0..3` maps to `imageTex`. VS-2 binds the
600
+ # layer's configured image there, and ignores a configured image for
601
+ # shaders that do not sample it. So a single-channel read is an ordinary
602
+ # image-input shader, not something to refuse.
603
+ _channels = sorted(set(re.findall(r'\biChannel([0-3])\b', body)))
604
+ _chan_meta = sorted(set(re.findall(r'\biChannel(?:Resolution|Time)\b', body)))
605
+ if len(_channels) > 1:
606
+ raise ConversionError(
607
+ "reads %d distinct iChannels (iChannel%s): VS-2 binds one "
608
+ "imageTex and one fixed audio sampler (fftTex), so the channels "
609
+ "cannot be preserved. Convert by hand"
610
+ % (len(_channels), ''.join(_channels)), gate='shadertoy-multi-channel')
611
+ if _channels:
612
+ # SAFETY: a Shadertoy iChannel is a binding SLOT, not a known image.
613
+ # Per Shadertoy's own model it may hold a texture, a feedback buffer,
614
+ # a cubemap, a video source, keyboard data, or an audio input, and
615
+ # "iChannel0 does not always mean the main texture" - it means whatever
616
+ # the pass configuration attached to slot 0. The pass configuration
617
+ # lives on the Shadertoy page, not in the .txt, so from source alone
618
+ # we cannot know. Mapping an unknown slot onto imageTex is therefore
619
+ # a GUESS, and a wrong guess produces a shader that
620
+ # renders but is not the original.
621
+ #
622
+ # So: the conversion is allowed to proceed, because refusing every
623
+ # channel shader would block the common and legitimate case of a
624
+ # single user-supplied image, but the uncertainty is stated loudly and
625
+ # the output is marked so it cannot be mistaken for a verified
626
+ # conversion. See gates.py:shadertoy-channel-uncertainty.
627
+ _slot = _channels[0]
628
+ # If the user supplied pass metadata, we no longer have to guess.
629
+ from .shadertoy_meta import resolve_channels
630
+ _status, _notes = resolve_channels(meta, _channels)
631
+ if _status == 'confirmed':
632
+ for _n in _notes:
633
+ report['warnings'].append('confirmed: ' + _n)
634
+ report['warnings'].append(
635
+ "iChannel%s verified from the supplied pass metadata as an "
636
+ "ordinary image; mapped to VS-2's imageTex." % _slot)
637
+ elif _status == 'unrepresentable':
638
+ raise ConversionError(
639
+ "cannot be mapped to VS-2: %s. Convert it by hand"
640
+ % ('; '.join(_notes) or 'unrepresentable sampler'),
641
+ gate='shadertoy-unrepresentable-channel')
642
+ else:
643
+ report['warnings'].append(
644
+ "UNVERIFIED: iChannel%s is a Shadertoy binding slot, not a "
645
+ "guaranteed image - it may be a feedback buffer, cubemap, "
646
+ "video, or audio (which would need fftTex, not emitted "
647
+ "here). Mapped to VS-2's imageTex, which binds the "
648
+ "image set on the layer. Supply pass metadata to confirm (see "
649
+ "core/shadertoy_meta.py), or check the Shadertoy page's pass "
650
+ "settings by hand." % _slot)
651
+ for _n in _notes:
652
+ report['warnings'].append('meta: ' + _n)
653
+ if _chan_meta:
654
+ report['warnings'].append(
655
+ "iChannelResolution/iChannelTime referenced: these describe "
656
+ "the bound slot and have no VS-2 equivalent. Any scaling or "
657
+ "sync built on them is not preserved.")
658
+ # Y ORIENTATION. Shadertoy and VS-2 disagree about which way image V
659
+ # runs, so a Shadertoy image shader converted verbatim renders its
660
+ # image upside down in VS-2. Established empirically by the author
661
+ # running a real Shadertoy glitch in VS-2 (2026-09-25) - NOT by a spec
662
+ # line: the skill docs document no flip rule, and
663
+ # factory-references/VS2-image-input/ are VS-2-native so they carry no
664
+ # flip either. Do not add a second flip if this ever looks wrong.
665
+ #
666
+ # Flipped at the sample site, not at the uv assignment: a converted
667
+ # shader typically reuses one uv for procedural work too, and
668
+ # flipping it at the declaration would invert that as well.
669
+ body = _flip_image_sample_v(body)
670
+ body = re.sub(r'\biChannel[0-3]\b', 'imageTex', body)
671
+ body = re.sub(r'\biChannelResolution\b', 'imageResolution', body)
672
+ body = re.sub(r'\biChannelTime\b', 'time', body)
673
+ body = re.sub(r'\biResolution\b', 'resolution', body)
674
+ body = re.sub(r'\biTime\b', 'time', body)
675
+ # iMouse -> x / y manifest parameters, per formal-spec.md:25 and
676
+ # conversion-guide.md:130 ("iMouse (point2D) -> x, y (two float params)").
677
+ # Substituting a constant vec4(0.0) instead silently froze every
678
+ # mouse-driven term: a real Shadertoy glitch shader used
679
+ # `GLITCH = 0.1 + iMouse.x / iResolution.x`, which became a constant 0.1
680
+ # and lost its interaction entirely while still validating clean.
681
+ if re.search(r'\biMouse\b', body):
682
+ # UNITS. Shadertoy's iMouse.xy is in PIXELS, not normalized - confirmed
683
+ # in the Shadertoy/Natron porting docs ("Mouse position, in pixels") and
684
+ # in Shadertoy's own idiom `vec2 mouse = iMouse.xy / iResolution.xy`.
685
+ # A VS-2 knob is 0..1, so substituting one directly under a
686
+ # `/ iResolution.x` divisor changes the term by ~1000x: a real glitch
687
+ # shader used `0.1 + iMouse.x / iResolution.x`, and the naive mapping
688
+ # produced `0.1 + x / resolution.x` = 0.1 + 0.5/1920 instead of 0.6.
689
+ #
690
+ # So: emit iMouse in PIXELS (`x * resolution.x`), which preserves the
691
+ # source's arithmetic exactly. The source's own division then yields
692
+ # the normalized value it always did.
693
+ body = re.sub(r'\biMouse\.x\b', '(x * resolution.x)', body)
694
+ body = re.sub(r'\biMouse\.y\b', '(y * resolution.y)', body)
695
+ body = re.sub(r'\biMouse\b',
696
+ 'vec4(x * resolution.x, y * resolution.y, 0.0, 0.0)',
697
+ body)
698
+ # Bare identifier only, in CODE only. `\by\b` also matches member
699
+ # access (`uv.y`, which nearly every shader has) and, on the real
700
+ # glitch shader, the comment `//note: /\ t=[0;0.5;1], y=[0;1;0]`.
701
+ # Both produced a spurious `y` knob. Strip comments first, then
702
+ # exclude member access.
703
+ _code = code_only(body)
704
+ for _ax in ('x', 'y'):
705
+ if re.search(r'(?<![\w.])' + _ax + r'\b', _code):
706
+ mouse_axes.append(_ax)
707
+ report['warnings'].append(
708
+ "iMouse -> x / y manifest parameters (formal-spec.md:25), "
709
+ "expressed in PIXELS to match Shadertoy's units, so the source's "
710
+ "own / iResolution arithmetic is preserved. Wire these up in VS-2.")
711
+ body = re.sub(r'\biDate\b', 'vec4(0.0)', body)
712
+
713
+ body = _rename_shadowed_engine_vars(body)
714
+
715
+ if re.search(r'\bmainImage\s*\(', body) and \
716
+ not re.search(r'\bvoid\s+main\s*\(', body):
717
+ # INLINE the Shadertoy entry point into main(), rather than wrapping:
718
+ # void mainImage(out vec4 fragColor, in vec2 fragCoord) { ... }
719
+ # mainImage(fragColor, gl_FragCoord.xy)
720
+ # The wrapper form assigns fragColor only inside mainImage, and both
721
+ # the external validator and a human reading the file miss that. VS-2
722
+ # shaders put the assignment directly in main() - see every golden
723
+ # example - so rename the signature and rewrite the two Shadertoy
724
+ # out/in params to the engine names.
725
+ # Capture the Shadertoy parameter NAMES, which may be anything
726
+ # (commonly `fragColor`/`fragCoord`, but not required), strip the
727
+ # signature, and rewrite every reference to the engine equivalents.
728
+ # Rewriting only the declaration left bodies using `f`/`c` referring
729
+ # to identifiers that no longer existed.
730
+ sig = re.compile(
731
+ r'void\s+mainImage\s*\(\s*out\s+vec4\s+(\w+)\s*,'
732
+ r'\s*in\s+vec2\s+(\w+)\s*\)\s*(\{)', re.DOTALL)
733
+ msig = sig.search(body)
734
+ if msig:
735
+ out_name, in_name, brace = msig.group(1), msig.group(2), msig.group(3)
736
+ body = sig.sub('void main(void)' + brace, body, count=1)
737
+ # The in-parameter is a vec2. Shadertoy passes fragCoord in PIXELS,
738
+ # so `fragCoord / iResolution.xy` normalises it. VS-2's texCoord is
739
+ # ALREADY a normalised 0..1 uv, so the two are not interchangeable:
740
+ # mapping the param to `gl_FragCoord` is wrong, and a shader that
741
+ # divides by resolution afterwards ends up with pixel coordinates
742
+ # again. Confirmed by the author: a raymarched ISF converted this way
743
+ # rendered a BLACK SCREEN in VS-2 and appeared the moment the line
744
+ # was changed to `texCoord` (PR feedback 2026-09-25).
745
+ for old_name, new_name in ((out_name, 'fragColor'),
746
+ (in_name, 'texCoord')):
747
+ if old_name == new_name:
748
+ continue
749
+ # Don't touch struct field access (`.name`) or declarations.
750
+ body = re.sub(r'(?<![\w.])' + re.escape(old_name)
751
+ + r'\b', new_name, body)
752
+ # `fragCoord` is now `texCoord`, which is ALREADY a 0..1 uv, but
753
+ # the Shadertoy body still multiplies by and divides by the render
754
+ # size to construct one. Cancel the shared factor:
755
+ # (texCoord * 2.0 - resolution.xy) / resolution.y == texCoord*2 - 1
756
+ # Author-verified 2026-09-25: the reduced form renders and
757
+ # animates; the unreduced one renders flat or black.
758
+ for _ in range(3):
759
+ body = re.sub(
760
+ r'\(\s*texCoord\s*\*\s*([\d.]+)\s*-\s*'
761
+ r'resolution\s*\.\s*xy\s*\)\s*/\s*resolution\s*\.\s*y',
762
+ r'(texCoord * \1 - 1.0)', body)
763
+ body = re.sub(
764
+ r'\(\s*texCoord\s*-\s*([\d.]+)\s*\*\s*'
765
+ r'resolution\s*\.\s*xy\s*\)\s*/\s*resolution\s*\.\s*y',
766
+ r'(texCoord - \1)', body)
767
+ # A Shadertoy body that divided by resolution to normalise now
768
+ # divides an already-normalised uv again. Cancel the division so the
769
+ # value matches what the source computed.
770
+ body = re.sub(
771
+ r'texCoord\s*/\s*resolution\.xy', 'texCoord', body)
772
+ body = re.sub(
773
+ r'texCoord\.xy\s*/\s*resolution\.xy', 'texCoord', body)
774
+ else:
775
+ body = body.replace('fragCoord', 'texCoord')
776
+ elif not re.search(r'\bvoid\s+main\s*\(', body):
777
+ raise ConversionError("no mainImage() or main() entry point found",
778
+ gate='missing-entry-point')
779
+
780
+ body = _coalesce_frag_color_writes(body)
781
+ body = _rewrite_output(body)
782
+ body = _ensure_precision(body)
783
+
784
+ body, params = _params_from(raw_params, body, report)
785
+
786
+ for _ax in mouse_axes:
787
+ if not any(p['name'] == _ax for p in params):
788
+ if len(params) >= MAX_PARAMS:
789
+ report['warnings'].append(
790
+ "iMouse axis '%s' dropped: over the 7-param budget" % _ax)
791
+ # dropping the axis must not eat member access: \bx\b also matches the x in
792
+ # resolution.x, and produced `resolution.0.5` (invalid GLSL). test_engine.
793
+ body = re.sub(r'(?<![\w.])' + _ax + r'\b', '0.5', body)
794
+ continue
795
+ params.append({'name': _ax, 'default': 0.5})
796
+ return body, params
797
+
798
+
799
+
800
+
801
+ def _convert_glslsandbox(source: str, report: dict, meta: dict = None) -> tuple:
802
+ """uniform time/resolution/mouse style source."""
803
+ body = _strip_uniforms(source)
804
+ # The declarations are stripped, so a non-engine uniform the body still
805
+ # reads must reach the manifest or the output names an undeclared
806
+ # identifier. There is no declared default or range, so each starts at
807
+ # 0.5 - the same value the mouse-axis knobs use. `mouse` is not a knob:
808
+ # the pass below rewrites it to the x/y pan, the same as on Shadertoy.
809
+ # _params_from applies the snake_case, clamp and dead-knob rules.
810
+ _raw = {_n: {'default': 0.5}
811
+ for _n in UNIFORM_NAME_RE.findall(source)
812
+ if _n not in ENGINE_VARS and _n != 'mouse'}
813
+ if re.search(r'\bsurfacePosition\b', body):
814
+ body = re.sub(
815
+ r'\bsurfacePosition\b',
816
+ 'vec2(texCoord.x, texCoord.y * resolution.y / resolution.x)',
817
+ body)
818
+ wants_mouse = bool(re.search(r'\bmouse\b', body, re.IGNORECASE))
819
+ if wants_mouse:
820
+ body = re.sub(r'\bmouse\b', 'vec2(x, y)', body)
821
+ report['warnings'].append("mouse -> vec2(x, y) pan parameters")
822
+ body = _rename_shadowed_engine_vars(body)
823
+ body = re.sub(r'\bgl_FragColor\b', 'fragColor', body)
824
+ body = _rewrite_output(body)
825
+ body = _ensure_precision(body)
826
+ if not re.search(r'\bvoid\s+main\s*\(', body):
827
+ raise ConversionError("no main() entry point found",
828
+ gate='missing-entry-point')
829
+ body, knobs = _params_from(_raw, body, report)
830
+ # A pan axis never overwrites a real knob of the same name.
831
+ pan_params = [{'name': _ax, 'default': 0.5}
832
+ for _ax in ('x', 'y')
833
+ if wants_mouse and not any(p['name'] == _ax for p in knobs)]
834
+ return body, knobs + pan_params
835
+
836
+
837
+
838
+ def _convert_isf(source: str, report: dict, meta: dict = None) -> tuple:
839
+ """Returns (body, manifest_params). Parses the ISF INPUTS block."""
840
+ inputs = None
841
+ m = MANIFEST_BLOCK_RE.search(source)
842
+ if m:
843
+ try:
844
+ header = json.loads(m.group(1).strip())
845
+ inputs = header.get('INPUTS', [])
846
+ except (json.JSONDecodeError, ValueError):
847
+ inputs = None
848
+ if not inputs:
849
+ raise ConversionError("ISF INPUTS block not found or not parseable",
850
+ gate='isf-parse-failure')
851
+
852
+ # --- hard gates before any transformation ---
853
+ header_all = {}
854
+ if m:
855
+ try:
856
+ header_all = json.loads(m.group(1).strip())
857
+ except (json.JSONDecodeError, ValueError):
858
+ header_all = {}
859
+ if any(inp.get('TARGET') for inp in inputs) or \
860
+ any(p.get('TARGET') for p in header_all.get('PASSES', [])):
861
+ raise ConversionError(
862
+ "feedback buffer (ISF TARGET input/pass): VS-2 is single-pass "
863
+ "with no feedback; convert it by hand", gate='isf-feedback-buffer')
864
+ # BUNDLED image resources: a top-level "IMPORTED" dict naming files the
865
+ # composition ships with, e.g. {"blendImage": {"PATH": "Hexagon.tiff"}}.
866
+ # Per docs.isf.video/ref_json and the canonical Test-ImportedImage.fs.
867
+ # These are pixel data travelling with the .fs; VS-2 has no equivalent,
868
+ # so refuse rather than silently drop the blend.
869
+ #
870
+ # USAGE, NOT DECLARATION. Only refuse when the body actually SAMPLES an
871
+ # imported resource. Declaring one is not the same as using one:
872
+ # `phreax twisted carbon.fs` declares TEXTURE_0 in IMPORTED but its only
873
+ # reference is inside a `//` comment, so it converts fine without one.
874
+ # The first version of this gate keyed on the manifest alone and declined
875
+ # a perfectly good shader - caught by running the 41-source ISF corpus,
876
+ # not by any test. Same error class as the earlier blanket image-input
877
+ # decline: refusing on a structural fact instead of actual usage.
878
+ _imported = header_all.get('IMPORTED') if isinstance(header_all, dict) else None
879
+ if _imported:
880
+ _body = code_only(source)
881
+ _used = [n for n in sorted(_imported)
882
+ if re.search(r'\b' + re.escape(str(n)) + r'\b', _body)]
883
+ if _used:
884
+ raise ConversionError(
885
+ f"bundled image resources in IMPORTED ({', '.join(_used[:4])}): "
886
+ f"the body samples them, and they are image files shipped with "
887
+ f"the .fs, so VS-2 has nowhere to put them. Supply the image in "
888
+ f"VS-2 instead, or convert it by hand",
889
+ gate='isf-imported-resources')
890
+ report['warnings'].append(
891
+ "IMPORTED declares %d image resource(s) that the body never "
892
+ "samples, so they were dropped. Harmless, but check the source if "
893
+ "that is not expected." % len(_imported))
894
+
895
+ # Non-ISF GLSL texture calls. Genuinely unrepresentable: these imply a
896
+ # multi-pass merge, which VS-2 does not have.
897
+ if re.search(r'\btexture2D\s*\(|\btex2D\s*\(', code_only(source)):
898
+ raise ConversionError(
899
+ "bundled texture input (texture2D/tex2D): hard gate; convert by "
900
+ "hand", gate='glsl-texture2d')
901
+
902
+ body = source[m.end():] if m else source
903
+ body = _strip_uniforms(body)
904
+
905
+ # --- classify inputs: knob vs baked-to-default constant ---
906
+ manifest = []
907
+ baked = {}
908
+ used_names = set()
909
+ seen_image = False
910
+ _image_inputs = []
911
+ for inp in inputs:
912
+ name = inp.get('NAME', '')
913
+ itype = inp.get('TYPE', 'float')
914
+ default = inp.get('DEFAULT', 0.0)
915
+ if itype == 'image':
916
+ # An ISF `TYPE: image` input is not an image the converter has to
917
+ # supply. It is the shader declaring that it REQUIRES an image -
918
+ # the same role as a Shadertoy iChannel0 read. VS-2 satisfies it
919
+ # from the layer's configured image via `imageTex`, and ignores a
920
+ # configured image for shaders that do not sample one.
921
+ #
922
+ # So: do not turn it into a manifest parameter (formal-spec.md:
923
+ # "No image parameter is declared in the manifest. The image is
924
+ # implicit."), and do not reject it. The body samples whatever
925
+ # sampler the source used; rename to imageTex so it resolves
926
+ # against the engine's binding.
927
+ report['warnings'].append(
928
+ f"input '{name}' is an image: the converted shader samples "
929
+ f"imageTex, which VS-2 binds from the image configured on the "
930
+ f"layer. It needs an image set in VS-2 to show anything.")
931
+ seen_image = True
932
+ _image_inputs.append(str(name))
933
+ continue
934
+ clean = _snake(name)
935
+ while clean in used_names or clean in ENGINE_VARS:
936
+ clean += '_amt'
937
+ if itype != 'float':
938
+ if isinstance(default, (list, tuple)) and len(default) == 4:
939
+ literal = ("vec4(" + ", ".join(_fmt_num(v) for v in default)
940
+ + ")")
941
+ elif isinstance(default, (list, tuple)) and len(default) == 2:
942
+ literal = f"vec2({default[0]}, {default[1]})"
943
+ elif default is True or default is False:
944
+ literal = 'true' if default else 'false'
945
+ elif itype == 'long':
946
+ values = inp.get('VALUES', [])
947
+ literal = (str(values.index(default)) if default in values
948
+ else '0')
949
+ elif isinstance(default, str):
950
+ literal = '0'
951
+ report['warnings'].append(
952
+ f"input '{name}' (type {itype}, default '{default}') "
953
+ f"baked to 0 - not expressible in GLSL")
954
+ else:
955
+ literal = _fmt_num(default)
956
+ baked[name] = literal
957
+ report['warnings'].append(
958
+ f"input '{name}' (type {itype}) baked to {literal}")
959
+ continue
960
+ if any(kw in clean for kw in SPEED_KEYWORDS):
961
+ baked[name] = _fmt_num(default)
962
+ report['baked'].append(
963
+ f"{name} -> {_fmt_num(default)} (speed baked per rule 4)")
964
+ continue
965
+ if len(manifest) >= MAX_PARAMS:
966
+ baked[name] = _fmt_num(default)
967
+ report['baked'].append(
968
+ f"{name} -> {_fmt_num(default)} (over 7-param budget)")
969
+ continue
970
+ lo = float(inp.get('MIN', 0.0))
971
+ hi = float(inp.get('MAX', 1.0))
972
+ dflt = float(default)
973
+ if hi <= lo:
974
+ lo, hi = 0.0, 1.0
975
+ knob = min(1.0, max(0.0, (dflt - lo) / (hi - lo)))
976
+ manifest.append({'name': clean, 'default': knob,
977
+ '_lo': lo, '_hi': hi, '_orig': name})
978
+ used_names.add(clean)
979
+ baked[name] = None # marker: kept as knob
980
+
981
+ # An ISF that declares an image input almost certainly samples a sampler.
982
+ # ISF spells the sampler as `sampler_main`/`sampler_image`/`sampler`, or
983
+ # uses an image uniform directly; all of them become the engine's
984
+ # imageTex, which VS-2 binds from the layer's configured image.
985
+ # MULTIPLE distinct image inputs cannot be represented. VS-2 binds ONE
986
+ # image to imageTex, so N image inputs would all collapse onto the same
987
+ # sampler - and the shader passes them to different places, so the result
988
+ # is not merely imprecise, it references samplers that were never declared
989
+ # and will not compile. Real case: GLSLOP developer-k0rz1pe2.fs declares
990
+ # six (src0..src5) and passed each to a different call.
991
+ #
992
+ # This is the ISF counterpart of the Shadertoy multi-channel gate, and it
993
+ # rests on the same evidence: formal-spec.md:26 and :274 map every image
994
+ # input to a SINGLE sampler, imageTex.
995
+ if len(_image_inputs) > 1:
996
+ raise ConversionError(
997
+ "declares %d distinct image inputs (%s): VS-2 binds a single "
998
+ "image to imageTex, so they cannot all be preserved. Convert by "
999
+ "hand"
1000
+ % (len(_image_inputs), ', '.join(_image_inputs[:4])),
1001
+ gate='isf-multiple-image-inputs')
1002
+
1003
+ if seen_image:
1004
+ # ISF image accessors (docs.isf.video/ref_json): IMG_NORM_PIXEL(name, uv)
1005
+ # and IMG_THIS_PIXEL(name) read the image named in INPUTS. VS-2 exposes a
1006
+ # single sampler, imageTex, so every one of these becomes a texture()
1007
+ # call against it. Leaving them in would emit a shader that cannot
1008
+ # compile - these are ISF host functions, not GLSL.
1009
+ body = re.sub(r'\bIMG_NORM_PIXEL\s*\(\s*\w+\s*,', 'texture(imageTex,', body)
1010
+ body = re.sub(r'\bIMG_THIS_PIXEL\s*\(\s*\w+\s*\)', 'texture(imageTex, texCoord)', body)
1011
+ body = re.sub(r'\bIMG_PIXEL\s*\(\s*\w+\s*,', 'texture(imageTex,', body)
1012
+ body = re.sub(r'\btexture2D\s*\(\s*\w+\s*,', 'texture(imageTex,', body)
1013
+ body = re.sub(r'\btexture\s*\(\s*\w+\s*,', 'texture(imageTex,', body)
1014
+
1015
+ # --- ISF builtins ---
1016
+ if re.search(r'\bPASSINDEX\b', body):
1017
+ if re.search(r'\bbuffer[A-D]\b|\bBuffer[A-D]\b|\bfeedback\b', body):
1018
+ raise ConversionError(
1019
+ "multi-pass feedback (buffer/feedback refs): VS-2 is "
1020
+ "single-pass; convert it by hand", gate='body-feedback-refs')
1021
+ # project onto the FINAL pass (the composite that writes fragColor);
1022
+ # count comes from the header PASSES array, default 2. The
1023
+ # `passes = 1` that used to sit here was dead - the next line
1024
+ # reassigns it unconditionally; test_gates.py body-feedback-refs
1025
+ # covers this path.
1026
+ passes = max(1, len(header_all.get('PASSES', [])) or 1)
1027
+ final_pass = str(passes - 1)
1028
+ body = re.sub(r'\bPASSINDEX\b', final_pass, body)
1029
+ report['warnings'].append(
1030
+ f"PASSINDEX -> {final_pass} (single-pass projection onto the "
1031
+ f"final pass of {passes})")
1032
+ if re.search(r'\bMOUSE\b', body):
1033
+ mouse_is_vec4 = bool(re.search(
1034
+ r'uniform\s+vec4\s+MOUSE\b', source))
1035
+ mouse_expr = ('vec4(x, y, 0.0, 0.0)' if mouse_is_vec4
1036
+ else 'vec2(x, y)')
1037
+ if len(manifest) + 2 <= MAX_PARAMS and 'x' not in used_names \
1038
+ and 'y' not in used_names:
1039
+ body = re.sub(r'\bMOUSE\b', mouse_expr, body)
1040
+ manifest.append({'name': 'x', 'default': 0.5})
1041
+ manifest.append({'name': 'y', 'default': 0.5})
1042
+ used_names.update({'x', 'y'})
1043
+ report['warnings'].append(
1044
+ f"MOUSE -> {mouse_expr} pan parameters")
1045
+ else:
1046
+ body = re.sub(r'\bMOUSE\b',
1047
+ 'vec4(0.5, 0.5, 0.0, 0.0)' if mouse_is_vec4
1048
+ else 'vec2(0.5)', body)
1049
+ report['warnings'].append("MOUSE -> static centre")
1050
+ # Shadertoy helper functions take the fragment coordinate as a vec2 uv
1051
+ # parameter - `float raymarch(vec3 from, vec3 dir, vec2 fragCoord, ...)`.
1052
+ # The mainImage in-param is renamed above; these are ordinary helpers and
1053
+ # were missed, so they kept calling an identifier VS-2 no longer defines.
1054
+ # Same reasoning: the parameter IS a 0..1 uv, so texCoord is the right
1055
+ # name, and `fragCoord / resolution.xy` inside them becomes texCoord.
1056
+ body = re.sub(
1057
+ r'\bin\s+vec2\s+fragCoord\b', 'in vec2 texCoord', body)
1058
+ body = re.sub(r'(?<![\w.])fragCoord(?![\w])', 'texCoord', body)
1059
+
1060
+ # Prose mentions, e.g. "// Replaced fragCoord and iResolution with
1061
+ # gl_FragCoord and RENDERSIZE". Not code, but leaving it makes a
1062
+ # completeness check for gl_FragCoord impossible to run over the corpus.
1063
+ body = re.sub(r'(//[^\n]*?)\bgl_FragCoord\b',
1064
+ r'\1the fragment coordinate', body)
1065
+
1066
+ # RENDERSIZE is the render target size in pixels. The normal way an ISF
1067
+ # source turns the fragment coordinate into a 0..1 uv is
1068
+ # `gl_FragCoord.xy / RENDERSIZE.xy`. VS-2's `texCoord` IS that 0..1 uv
1069
+ # already, so the whole expression becomes `texCoord`.
1070
+ #
1071
+ # Leaving it as gl_FragCoord/resolution is NOT equivalent: it depends on
1072
+ # gl_FragCoord behaving as it does on the desktop GL the source assumed.
1073
+ # A raymarched ISF converted this way rendered a BLACK SCREEN in VS-2 and
1074
+ # appeared the instant the line used `texCoord` (author-verified,
1075
+ # 2026-09-25). Do this substitution BEFORE RENDERSIZE -> resolution, so
1076
+ # the composed pattern is still recognisable.
1077
+ body = re.sub(
1078
+ r'gl_FragCoord\s*\.\s*xy\s*/\s*RENDERSIZE\s*\.\s*xy', 'texCoord', body)
1079
+ # Dividing by RENDERSIZE.y (not RENDERSIZE.xy) is a per-axis squash the
1080
+ # source wrote deliberately, e.g.
1081
+ # (gl_FragCoord.xy / RENDERSIZE.y - RENDERSIZE.xy / RENDERSIZE.y)
1082
+ # The `.xy` MUST be preserved: collapsing it to a bare `texCoord` yields
1083
+ # `texCoord.y - RENDERSIZE.xy / RENDERSIZE.y`, a FLOAT minus a vec2 -
1084
+ # ill-typed GLSL. On the author's VS-2 that rendered as horizontal lines
1085
+ # with no circular shapes at all. Keep the pair so the identity above can
1086
+ # reduce it to a well-typed vec2.
1087
+ body = re.sub(
1088
+ r'gl_FragCoord\s*\.\s*xy\s*/\s*RENDERSIZE\b',
1089
+ 'texCoord * RENDERSIZE.xy / RENDERSIZE', body)
1090
+ body = re.sub(
1091
+ r'gl_FragCoord\s*/\s*RENDERSIZE\s*\.\s*xy', 'texCoord', body)
1092
+ body = re.sub(
1093
+ r'gl_FragCoord\s*/\s*RENDERSIZE\b', 'texCoord', body)
1094
+ body = re.sub(r'\bRENDERSIZE\b', 'resolution', body)
1095
+
1096
+ # A source that normalised as `gl_FragCoord.xy / RENDERSIZE.xy` is fully
1097
+ # reduced to texCoord above. But `fragCoord / resolution.xy` inside a
1098
+ # helper, or a `texCoord / RENDERSIZE.xy` the source wrote directly, is
1099
+ # still a divide by the size applied to an already-normalised uv. Cancel it.
1100
+ for _ in range(3):
1101
+ body = re.sub(
1102
+ r'texCoord\s*/\s*resolution\.xy', 'texCoord', body)
1103
+ # gl_FragCoord is not usable in VS-2. Author-verified 2026-09-25: three
1104
+ # julia variants differing only in the uv derivation - the texCoord one
1105
+ # rendered and animated, both gl_FragCoord ones failed.
1106
+ #
1107
+ # Identity FIRST: the fragment coordinate in pixels IS the normalised
1108
+ # texCoord times the render size,
1109
+ # gl_FragCoord.xy == texCoord * RENDERSIZE.xy
1110
+ # so every algebraic shape reduces correctly:
1111
+ # (gl_FragCoord.xy*2 - RENDERSIZE.xy)/RENDERSIZE.y
1112
+ # -> (texCoord*RENDERSIZE.xy*2 - RENDERSIZE.xy)/RENDERSIZE.y
1113
+ # -> texCoord*2 - 1
1114
+ # which is the form the author verified renders. Without the identity the
1115
+ # four `*2 - RENDERSIZE.xy)/RENDERSIZE.y` shaders emit
1116
+ # `texCoord*2 - resolution.xy`, a vec2 minus a differently-scaled vec2,
1117
+ # and render flat.
1118
+ #
1119
+ # This MUST precede the scalar rules: a rule matching `gl_FragCoord\.x`
1120
+ # matches the leading x of `.xy` and mangles the pair.
1121
+ body = re.sub(r'gl_FragCoord\s*\.\s*xy',
1122
+ 'texCoord * RENDERSIZE.xy', body)
1123
+ body = re.sub(
1124
+ r'texCoord\s*\*\s*RENDERSIZE\s*\.\s*xy\s*/\s*RENDERSIZE\s*\.\s*xy',
1125
+ 'texCoord', body)
1126
+ body = re.sub(
1127
+ r'texCoord\s*\*\s*RENDERSIZE\s*\.\s*xy\s*/\s*RENDERSIZE\b',
1128
+ 'texCoord', body)
1129
+ # a scalar swizzle of the identity: (texCoord * RENDERSIZE.xy).x
1130
+ body = re.sub(
1131
+ r'\(\s*texCoord\s*\*\s*RENDERSIZE\s*\.\s*xy\s*\)\s*\.\s*xy',
1132
+ 'texCoord', body)
1133
+ body = re.sub(r'\bRENDERSIZE\b', 'resolution', body)
1134
+
1135
+ # The identity leaves `(texCoord * resolution.xy * 2.0 - resolution.xy)`.
1136
+ # Factor the shared resolution.xy out of the pair and cancel the divisor:
1137
+ # (T*S*2 - S) / S == T*2 - 1
1138
+ # Applied to the whole parenthesised group, not just a bare divide, so
1139
+ # the emitted uv reads like the hand-written factory shaders.
1140
+ for _ in range(3):
1141
+ body = re.sub(
1142
+ r'\(\s*texCoord\s*\*\s*resolution\s*\.\s*xy\s*\*\s*'
1143
+ r'([\d.]+)\s*-\s*resolution\s*\.\s*xy\s*\)\s*'
1144
+ r'/\s*resolution\s*\.\s*y',
1145
+ r'(texCoord * \1 - 1.0)', body)
1146
+ body = re.sub(
1147
+ r'\(\s*texCoord\s*\*\s*resolution\s*\.\s*xy\s*\*\s*'
1148
+ r'([\d.]+)\s*-\s*resolution\s*\.\s*xy\s*\)\s*'
1149
+ r'/\s*resolution\s*\.\s*xy',
1150
+ r'(texCoord * \1 - 1.0)', body)
1151
+ body = re.sub(
1152
+ r'\(\s*texCoord\s*\*\s*resolution\s*\.\s*xy\s*-\s*'
1153
+ r'([\d.]+)\s*\*\s*resolution\s*\.\s*xy\s*\)\s*'
1154
+ r'/\s*resolution\s*\.\s*y',
1155
+ r'(texCoord - \1)', body)
1156
+ # Same fold, operands in the other order: the source may write
1157
+ # `RENDERSIZE.xy * 0.5` rather than `0.5 * RENDERSIZE.xy`, which
1158
+ # leaves (texCoord * resolution.xy - resolution.xy * K) after the
1159
+ # identity - a different string from the case above.
1160
+ body = re.sub(
1161
+ r'\(\s*texCoord\s*\*\s*resolution\s*\.\s*xy\s*-\s*'
1162
+ r'resolution\s*\.\s*xy\s*\*\s*([\d.]+)\s*\)\s*'
1163
+ r'/\s*resolution\s*\.\s*y',
1164
+ r'(texCoord - \1)', body)
1165
+
1166
+ # Engine aspect factor, matching the expert reference conversions.
1167
+ # texCoord is NOT pre-corrected by VS-2 (author
1168
+ # verified 2026-09-26: an uncorrected circle renders wider than tall) and
1169
+ # the golden form scales Y: `* vec2(1.0, div)` with
1170
+ # div = resolution.y / resolution.x (author verified: renders round).
1171
+ #
1172
+ # A deliberate DEPARTURE from source fidelity. 17 of the 18 expert
1173
+ # conversions carry the factor even where the ISF source has no aspect
1174
+ # correction at all; the expert comment reads "engine convention
1175
+ # (div = y/x); matches source framing on square canvases". The ISF
1176
+ # sources divide by RENDERSIZE.y, which is square-canvas framing, so on a
1177
+ # landscape canvas the source IS stretched and the engine form is right.
1178
+ # Staying faithful to the source contradicted the reference set 17/18.
1179
+ _DIV = ' float div = resolution.y / resolution.x;\n'
1180
+ for _pat, _rep in (
1181
+ (r'\(\s*texCoord\s*\*\s*([\d.]+)\s*-\s*1\.0\s*\)',
1182
+ r'(texCoord * \1 - 1.0) * vec2(1.0, div)'),
1183
+ (r'\(\s*texCoord\s*-\s*([\d.]+)\s*\)',
1184
+ r'(texCoord - \1) * vec2(1.0, div)')):
1185
+ _new, _n = re.subn(_pat, _rep, body)
1186
+ if _n:
1187
+ body = _new
1188
+ break
1189
+ if 'vec2(1.0, div)' in body and _DIV not in body:
1190
+ body = body.replace('void main() {\n', 'void main() {\n' + _DIV, 1)
1191
+
1192
+ # Scalar swizzles, applied AFTER the .xy normalisation above: a
1193
+ # `gl_FragCoord.x` must not be eaten by an .xy rule, and the .xy
1194
+ # form must be reduced before these run. These feed pixel-scale
1195
+ # hashes (fract(sin(gl_FragCoord.x * 12.9898 + ...))), so they are
1196
+ # the pixel coordinate per component, not a normalised uv.
1197
+ # Load-bearing: no normalisation pattern covers a bare swizzle.
1198
+ body = re.sub(r'gl_FragCoord\s*\.\s*x',
1199
+ '(texCoord * resolution.xy).x', body)
1200
+ body = re.sub(r'gl_FragCoord\s*\.\s*y',
1201
+ '(texCoord * resolution.xy).y', body)
1202
+ body = re.sub(r'gl_FragCoord\s*\.\s*z',
1203
+ '(texCoord * resolution.xy).z', body)
1204
+
1205
+
1206
+
1207
+ # (texCoord * resolution.xy / resolution.xy) is just texCoord. The
1208
+ # identity substitution above introduces the cancel wherever a source
1209
+ # already normalised by RENDERSIZE.xy; fold it so the emitted uv reads
1210
+ # like the hand-written factory shaders rather than carrying a no-op.
1211
+ for _ in range(3):
1212
+ # Cancel the divide first: this only matches a genuine division, so
1213
+ # it cannot damage a swizzle of the identity. Doing it in the other
1214
+ # order rewrites `(texCoord * resolution.xy).xy / resolution.xy`
1215
+ # into `texCoord / resolution.xy`, which is a different shader.
1216
+ body = re.sub(
1217
+ r'texCoord\s*\*\s*resolution\.xy\s*/\s*resolution\.xy',
1218
+ 'texCoord', body)
1219
+ # Then the swizzle of the identity is just texCoord.
1220
+ body = re.sub(
1221
+ r'\(\s*texCoord\s*\*\s*resolution\.xy\s*\)\s*\.\s*xy',
1222
+ 'texCoord', body)
1223
+
1224
+ body = re.sub(r'\bisf_FragNormCoord\b', 'texCoord', body)
1225
+ body = re.sub(r'\bgl_FragColor\b', 'fragColor', body)
1226
+
1227
+ # --- input substitution: baked -> literal everywhere; knobs -> scoped wrap
1228
+ # NOTE: runs BEFORE the uppercase builtin TIME rename so an ISF input
1229
+ # literally named `time` cannot collide with the engine clock.
1230
+ for orig, literal in baked.items():
1231
+ if literal is not None:
1232
+ body = _replace_scoped(body, orig, literal, literal)
1233
+ for p in manifest:
1234
+ orig = p.get('_orig')
1235
+ if orig is None: # synthetic knob (x/y from MOUSE)
1236
+ continue
1237
+ wrap = (f"({p['_lo']:.6g} + {p['name']} * "
1238
+ f"({p['_hi']:.6g} - {p['_lo']:.6g}))")
1239
+ body = _replace_scoped(body, orig, p['name'], wrap)
1240
+
1241
+ body = re.sub(r'\bTIME\b', 'time', body)
1242
+
1243
+ body = _rename_shadowed_engine_vars(body)
1244
+ body = _rewrite_output(body)
1245
+ body = _ensure_precision(body)
1246
+ if not re.search(r'\bvoid\s+main\s*\(', body):
1247
+ raise ConversionError("no main() entry point found",
1248
+ gate='missing-entry-point')
1249
+ # A knob can lose its only use during the rewrites above (e.g. an alpha
1250
+ # argument the coloredPixels output rewrite replaces). Drop it now and warn
1251
+ # so the validator never sees a dead slider. Synthetic pan knobs (_orig
1252
+ # absent) are used by construction; an image input never reaches here.
1253
+ _code = code_only(body)
1254
+ _kept = []
1255
+ for p in manifest:
1256
+ if p.get('_orig') is not None and not _referenced(p['name'], _code):
1257
+ report['warnings'].append(
1258
+ f"param '{p['_orig']}' dropped: not referenced in the shader "
1259
+ "body (dead knob)")
1260
+ continue
1261
+ _kept.append(p)
1262
+ manifest = _kept
1263
+ for p in manifest:
1264
+ p.pop('_lo', None)
1265
+ p.pop('_hi', None)
1266
+ p.pop('_orig', None)
1267
+ return body, manifest
1268
+
1269
+
1270
+
1271
+ # ---------------------------------------------------------------------------
1272
+ # public API
1273
+ # ---------------------------------------------------------------------------
1274
+
1275
+ def _unverified_marker(warnings: list) -> str:
1276
+ """One-line `// UNVERIFIED:` comment for the .frag, or ''.
1277
+
1278
+ The terminal prints the whole paragraph. The file gets the fact and the
1279
+ subject - the reader who closes the terminal and opens the .frag in VS 2
1280
+ otherwise has no trace of the doubt. Capped on a word boundary.
1281
+ """
1282
+ for w in warnings:
1283
+ if w.startswith('UNVERIFIED'):
1284
+ text = re.sub(r'^UNVERIFIED:\s*', '', w.split('. ')[0].rstrip('.'))
1285
+ if len(text) > _UNVERIFIED_MARKER_MAX:
1286
+ text = text[:_UNVERIFIED_MARKER_MAX].rsplit(' ', 1)[0] + '...'
1287
+ return '// UNVERIFIED: %s\n\n' % text
1288
+ return ''
1289
+
1290
+
1291
+ def _forced_fallback(source: str, report: dict) -> tuple:
1292
+ """Best-effort body when --force overrides a hard gate.
1293
+
1294
+ Deliberately minimal and honest: strip uniforms, do the mechanical
1295
+ builtin renames, and hand the result over marked as forced. It does NOT
1296
+ try to be clever, because a forced conversion is a starting point for a
1297
+ human, not a working shader.
1298
+ """
1299
+ body = _strip_uniforms(source)
1300
+ body = re.sub(r'\biResolution\b', 'resolution', body)
1301
+ body = re.sub(r'\biTime\b', 'time', body)
1302
+ body = re.sub(r'\biChannel[0-3]\b', 'imageTex', body)
1303
+ body = re.sub(r'\bgl_FragColor\b', 'fragColor', body)
1304
+ body = re.sub(r'\btexture2D\s*\(', 'texture(', body)
1305
+ return body, []
1306
+
1307
+
1308
+ def convert(source: str, fmt: str, shader_name: str,
1309
+ force: bool = False, meta: dict = None) -> dict:
1310
+ """Convert source shader to a complete VS-2 .frag string.
1311
+
1312
+ Returns {'frag': str, 'manifest': dict, 'warnings': [..], 'baked': [..],
1313
+ 'params': [..]} - `params` are the ones actually emitted, so at most
1314
+ MAX_PARAMS entries.
1315
+ Raises ConversionError for sources that cannot be converted safely.
1316
+ """
1317
+ report = {'warnings': [], 'baked': [], 'params': [], 'meta': meta or {}}
1318
+
1319
+ # Scan code with comments blanked: a comment naming frac()/lerp() is
1320
+ # documentation of the original, not unconverted HLSL.
1321
+ # ISF takes texture2D through _convert_isf, which labels it glsl-texture2d.
1322
+ _hlsl_texture = r'|tex2D|texture2D' if fmt != 'ISF' else ''
1323
+ if re.search(r'\b(frac|lerp%s)\s*\(' % _hlsl_texture, code_only(source)):
1324
+ raise ConversionError(
1325
+ "HLSL/bundled-texture source (MilkDrop): multi-pass merge is not "
1326
+ "automated; convert it by hand", gate='hlsl-milkdrop')
1327
+
1328
+ fmt_map = {
1329
+ 'Shadertoy': _convert_shadertoy,
1330
+ 'ISF': _convert_isf,
1331
+ 'GLSLSandbox': _convert_glslsandbox,
1332
+ 'PlainGLSL': _convert_shadertoy,
1333
+ }
1334
+ if fmt not in fmt_map:
1335
+ raise ConversionError(f"unsupported format: {fmt}",
1336
+ gate='unsupported-format')
1337
+
1338
+ try:
1339
+ body, params = fmt_map[fmt](source, report, meta=meta)
1340
+ except ConversionError as exc:
1341
+ # --force means "convert anyway", so a capability gate that the user
1342
+ # has explicitly overridden must not abort the run. Gates in
1343
+ # NON_FORCEABLE are different: no fallback can express them, so the
1344
+ # decline stands.
1345
+ if not force or exc.gate in NON_FORCEABLE:
1346
+ raise
1347
+ report['warnings'].append(
1348
+ "FORCED past a hard conversion gate: the output is very likely "
1349
+ "broken. Treat it as a starting point for a manual conversion, "
1350
+ "not as a working shader.")
1351
+ body, params = _forced_fallback(source, report)
1352
+ # The fallback renames; it cannot invent an entry point. Without this,
1353
+ # a forceable gate is a back door around missing-entry-point: the
1354
+ # output draws nothing and the run reports ok.
1355
+ if not re.search(r'\b(?:mainImage|main)\s*\(', code_only(body)):
1356
+ raise ConversionError(
1357
+ "no mainImage() or main() entry point found",
1358
+ gate='missing-entry-point')
1359
+ header, manifest = _build_manifest(params, shader_name)
1360
+ report['params'] = params[:MAX_PARAMS]
1361
+ report['manifest'] = manifest
1362
+ report['frag'] = header + _unverified_marker(report['warnings']) + body
1363
+ return report