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,143 @@
1
+ """Terminal output for the CLI.
2
+
3
+ Design goals, in priority order:
4
+
5
+ 1. The verdict is unmistakable and comes LAST, so the last thing on screen is
6
+ the answer rather than a warning.
7
+ 2. A failure can never be mistaken for progress. Failure glyph, the word
8
+ "failed", and the exit code all agree.
9
+ 3. Default output is scannable. Long explanations are demoted to stderr and
10
+ to -v; nothing is deleted, only folded.
11
+ 4. "Could not run" is never reported as "failed". A missing dependency is a
12
+ tooling problem, not a shader problem, and conflating them sends people
13
+ looking in the wrong place.
14
+
15
+ Unicode: emoji are auto-detected. Several render double-width and would break
16
+ the indentation, so an ASCII set is used when the stream cannot encode them.
17
+ Set VS2_ASCII=1 to force ASCII.
18
+ """
19
+ import os
20
+ import sys
21
+
22
+ # --- glyph sets ------------------------------------------------------------
23
+
24
+ _UNICODE = {'ok': '\u2705', 'warn': '\u26a0\ufe0f', 'fail': '\u274c'}
25
+ _ASCII = {'ok': '[ok]', 'warn': '[!]', 'fail': '[X]'}
26
+
27
+ # Indent for body lines, matched to the glyph actually used. The warning
28
+ # emoji renders two cells wide; the ASCII tokens are three characters.
29
+ _PAD_UNICODE = 2
30
+ _PAD_ASCII = 4
31
+
32
+ DIM, BOLD, RESET = '\033[2m', '\033[1m', '\033[0m'
33
+
34
+
35
+ def supports_unicode(stream=None) -> bool:
36
+ """Can this stream encode the glyphs? Falls back to ASCII if not."""
37
+ if os.environ.get('VS2_ASCII'):
38
+ return False
39
+ stream = stream or sys.stdout
40
+ enc = (getattr(stream, 'encoding', None) or '').lower()
41
+ if 'utf' in enc:
42
+ return True
43
+ try:
44
+ # probe by encoding, never by writing: the old probe wrote the three
45
+ # glyphs into the caller's stream, polluting any writable stream
46
+ # whose `encoding` is missing. test_cli.UnicodeProbeTests.
47
+ (_UNICODE['ok'] + _UNICODE['warn'] + _UNICODE['fail']).encode(
48
+ enc or 'utf-8')
49
+ return True
50
+ except (LookupError, UnicodeEncodeError):
51
+ return False
52
+
53
+
54
+ class Reporter:
55
+ """Renders the run. Verdict last; detail on stderr and behind -v."""
56
+
57
+ def __init__(self, verbose=False, stream=None, errstream=None):
58
+ self.verbose = verbose
59
+ self.out = stream or sys.stdout
60
+ self.err = errstream or sys.stderr
61
+ self.glyphs = _UNICODE if supports_unicode(self.out) else _ASCII
62
+ self._color = self.out.isatty() and not os.environ.get('NO_COLOR')
63
+ self._collecting = False
64
+ self._notes = []
65
+ self._unverified = []
66
+
67
+ # -- primitives -------------------------------------------------------
68
+ def _w(self, text=''):
69
+ self.out.write(text + '\n')
70
+
71
+ def _paint(self, text, code):
72
+ return (code + text + RESET) if self._color else text
73
+
74
+ def _glyph(self, kind):
75
+ return self.glyphs[kind]
76
+
77
+ # -- progress ---------------------------------------------------------
78
+ def step(self, text):
79
+ """Progress chatter. Only with -v; the default output is the verdict."""
80
+ if self.verbose:
81
+ self._w(' %s' % self._paint(text, DIM))
82
+
83
+ def note(self, text):
84
+ """Collected and shown under the verdict."""
85
+ self._notes.append(text)
86
+
87
+ def unverified(self, headline, detail):
88
+ """An assumption the tool could not check. Always shown: it changes
89
+ how much the result can be trusted."""
90
+ self._unverified.append((headline, detail))
91
+
92
+ def detail(self, text):
93
+ """Long explanation. stderr, and only with -v."""
94
+ if self.verbose:
95
+ self.err.write(text + '\n')
96
+
97
+ # -- verdict ----------------------------------------------------------
98
+ def _line(self, kind, headline, body=None, action=None, footer=None,
99
+ wrote=None):
100
+ pad = ' ' * (_PAD_UNICODE if self.glyphs is _UNICODE
101
+ else _PAD_ASCII)
102
+ self._w()
103
+ head = '%s %s' % (self._glyph(kind), headline)
104
+ self._w(self._paint(head, BOLD))
105
+ if body:
106
+ for ln in body if isinstance(body, (list, tuple)) else [body]:
107
+ self._w('%s%s' % (pad, ln))
108
+ if action:
109
+ self._w('%s-> %s' % (pad, self._paint(action, DIM)))
110
+ if footer:
111
+ self._w('%s%s' % (pad, self._paint(footer, DIM)))
112
+
113
+ def success(self, name, wrote=None, stats=None):
114
+ if isinstance(stats, (list, tuple)):
115
+ stats = ' \u00b7 '.join(str(x) for x in stats)
116
+ self._line('ok', '%s -> %s' % (name, wrote) if wrote else name,
117
+ body=[stats] if stats else None)
118
+ for headline, detail in self._unverified:
119
+ self._line('warn', 'unverified: %s' % headline, body=detail)
120
+ if self._notes:
121
+ self._w()
122
+ import textwrap
123
+ for n in self._notes:
124
+ for i, ln in enumerate(textwrap.wrap(str(n), 66)):
125
+ self._w(' %s' % self._paint(('note: ' if i == 0 else ' ') + ln, DIM))
126
+ if self.verbose:
127
+ self._w()
128
+
129
+ def failure(self, name, headline, body=None, action=None, exit_code=1,
130
+ wrote=False):
131
+ self._line('fail', '%s - %s' % (name, headline), body=body,
132
+ action=action,
133
+ footer='exit %d . %s' % (exit_code,
134
+ 'wrote %s' % wrote if wrote
135
+ else 'nothing written'))
136
+ for headline, detail in self._unverified:
137
+ self._line('warn', 'unverified: %s' % headline, body=detail)
138
+
139
+ def skipped(self, name, headline, body=None, action=None, exit_code=2):
140
+ """Not a failure: something the run needed did not happen."""
141
+ self._line('warn', '%s - %s' % (name, headline), body=body,
142
+ action=action,
143
+ footer='exit %d' % exit_code)
@@ -0,0 +1,149 @@
1
+ """Optional Shadertoy pass/channel metadata, supplied alongside the code.
2
+
3
+ WHY THIS EXISTS
4
+ ---------------
5
+ A Shadertoy ".txt" paste is the shader BODY only. Everything that makes a
6
+ Shadertoy shader what it is - how many passes, which pass writes the screen,
7
+ and crucially what each iChannel is bound to - lives in the web UI, not in
8
+ the file. Shadertoy's own guidance is to inspect the pass configuration
9
+ before assuming what a channel holds, because a channel may be a texture, a
10
+ feedback buffer, a cubemap, video, keyboard or audio.
11
+
12
+ The site being unavailable makes that inspection harder, not the problem
13
+ easier. So rather than guess, the converter accepts a small JSON sidecar
14
+ that states what the body needs, and downgrades its confidence when it is
15
+ absent.
16
+
17
+ HOW TO SUPPLY IT
18
+ ----------------
19
+ Any of these, all equivalent:
20
+
21
+ 1. A sidecar file next to the body: `my-shader.stmeta.json` beside
22
+ `my-shader.shadertoy`, or any single `*.stmeta.json` in the directory.
23
+ 2. A JSON block pasted at the TOP of the .txt, in a comment:
24
+
25
+ /*{
26
+ "passes": 1,
27
+ "final_pass": 0,
28
+ "channels": {"iChannel0": {"sampler": "texture",
29
+ "source": "a user-supplied image"}}
30
+ }*/
31
+ ... body follows ...
32
+
33
+ 3. `--meta path/to/file.json` on the command line.
34
+
35
+ WHAT IT RESOLVES
36
+ ----------------
37
+ channels : replaces the UNVERIFIED warning with a CONFIRMED one when the
38
+ sampler is an ordinary user image, or refuses when the channel
39
+ is a buffer/cubemap/keyboard, or audio (VS-2 has an audio
40
+ sampler, fftTex, but no mapping is implemented).
41
+ passes : tells the converter which pass writes the screen, instead of
42
+ assuming the last one.
43
+ uniforms : supplies the iChannelResolution-style dimensions if needed.
44
+
45
+ Only `channels` changes the safety verdict. Everything else is refinement:
46
+ absent it, the conversion still happens, just marked unverified.
47
+ """
48
+
49
+ import json
50
+ import os
51
+ import re
52
+
53
+ # Sampler kinds VS-2 can bind. VS-2 binds one image to `imageTex`.
54
+ REPRESENTABLE_SAMPLERS = {'texture', 'image', 'video', '2d'}
55
+ # Refused: VS-2 has no input for these, and audio has no mapping yet
56
+ # (it would need `fftTex`, and "audio" does not say waveform or FFT).
57
+ UNREPRESENTABLE_SAMPLERS = {'buffer', 'cube', 'cubemap', 'audio', 'keyboard'}
58
+
59
+ _META_BLOCK_RE = re.compile(r'/\*(.*?)\*/', re.DOTALL)
60
+
61
+
62
+ def find_meta_file(body_path):
63
+ """Sidecar next to the body: <stem>.stmeta.json, else a lone one nearby.
64
+
65
+ `None` means there is no file (stdin); only --meta and the inline block
66
+ can supply metadata then.
67
+ """
68
+ if not body_path:
69
+ return None
70
+ stem, _ = os.path.splitext(body_path)
71
+ for cand in (stem + '.stmeta.json', body_path + '.stmeta.json'):
72
+ if os.path.exists(cand):
73
+ return cand
74
+ d = os.path.dirname(os.path.abspath(body_path)) or '.'
75
+ try:
76
+ found = [f for f in os.listdir(d) if f.endswith('.stmeta.json')]
77
+ except OSError:
78
+ return None
79
+ return os.path.join(d, found[0]) if len(found) == 1 else None
80
+
81
+
82
+ def meta_from_source(source):
83
+ """A JSON block at the very top of the .txt, inside a comment."""
84
+ m = _META_BLOCK_RE.search(source)
85
+ if not m:
86
+ return None
87
+ try:
88
+ data = json.loads(m.group(1).strip())
89
+ except (json.JSONDecodeError, ValueError):
90
+ return None
91
+ return data if isinstance(data, dict) else None
92
+
93
+
94
+ def load_meta(body_path, source, explicit=None):
95
+ """Resolve metadata from, in order: --meta, sidecar, inline block.
96
+
97
+ Returns (meta_dict_or_None, where_it_came_from).
98
+ """
99
+ if explicit:
100
+ if not os.path.exists(explicit):
101
+ raise ValueError('meta file not found: %s' % explicit)
102
+ with open(explicit) as f:
103
+ return json.load(f), explicit
104
+ path = find_meta_file(body_path)
105
+ if path:
106
+ with open(path) as f:
107
+ return json.load(f), path
108
+ inline = meta_from_source(source)
109
+ if inline is not None:
110
+ return inline, 'inline block'
111
+ return None, None
112
+
113
+
114
+ def resolve_channels(meta, channels_found):
115
+ """Decide the safety verdict for each iChannel the body reads.
116
+
117
+ Returns (status, notes) where status is:
118
+ 'confirmed' - metadata says it is an ordinary image; safe
119
+ 'unverified' - no metadata; we are guessing
120
+ 'unrepresentable' - metadata says buffer/cubemap/audio; refuse
121
+ """
122
+ if not meta or 'channels' not in meta:
123
+ return 'unverified', []
124
+ declared = meta.get('channels') or {}
125
+ notes = []
126
+ worst = 'confirmed'
127
+ for ch in channels_found:
128
+ entry = declared.get('iChannel%s' % ch) or declared.get(ch) or {}
129
+ sampler = str(entry.get('sampler', '')).strip().lower()
130
+ if not sampler:
131
+ notes.append('iChannel%s: declared but no sampler given' % ch)
132
+ worst = 'unverified' if worst == 'confirmed' else worst
133
+ elif sampler in UNREPRESENTABLE_SAMPLERS:
134
+ if sampler == 'audio':
135
+ notes.append(
136
+ 'iChannel%s is audio: VS-2 has an audio sampler '
137
+ '(fftTex), but no mapping is implemented and "audio" '
138
+ 'does not say whether the channel is a waveform or an '
139
+ 'FFT' % ch)
140
+ else:
141
+ notes.append('iChannel%s is a %s, which VS-2 has no input '
142
+ 'for' % (ch, sampler))
143
+ worst = 'unrepresentable'
144
+ elif sampler in REPRESENTABLE_SAMPLERS:
145
+ src = entry.get('source', '')
146
+ notes.append('iChannel%s confirmed: %s%s'
147
+ % (ch, sampler,
148
+ ' (%s)' % src if src else ''))
149
+ return worst, notes
@@ -0,0 +1,80 @@
1
+ """Shared text helpers for the conversion core.
2
+
3
+ Kept separate from detector and generator because BOTH must apply the same
4
+ comment-stripping before scanning for API names. When only the detector did
5
+ it, `convert()` still scanned raw text and refused a valid shader whose
6
+ comment merely mentioned `lerp()` - the same false positive, fixed in one
7
+ place and reintroduced in the other.
8
+ """
9
+ import re
10
+
11
+
12
+ # The names VS 2 supplies itself. A declaration of one is a redeclaration,
13
+ # never a parameter - so the detector's budget and the validator's
14
+ # redeclaration check must read the same list, or a name added to one drifts
15
+ # from the other.
16
+ ENGINE_VARS = ('resolution', 'time', 'texCoord', 'color', 'alpha',
17
+ 'imageTex', 'imageResolution', 'fftTex')
18
+ ENGINE_VAR_RE = re.compile(
19
+ r'^(float|vec2|vec3|vec4|int|mat2|mat3|sampler2D)\s+('
20
+ + '|'.join(ENGINE_VARS) + r')\b')
21
+
22
+ # A `uniform` declaration that names a candidate parameter. Numeric types only:
23
+ # a sampler is an image binding, not a knob, and VS 2 supplies imageTex.
24
+ UNIFORM_NAME_RE = re.compile(
25
+ r'uniform\s+(?:float|vec2|vec3|vec4|int|mat2|mat3)\s+(\w+)')
26
+
27
+
28
+ def code_only(source: str) -> str:
29
+ """Source with comments and string-literal contents blanked, preserving
30
+ line structure.
31
+
32
+ API and HLSL checks must not fire on a mention inside a comment. A
33
+ converted shader legitimately carries comments like
34
+ "// original: lerp(a, b, c)" documenting where the math came from, and
35
+ scanning raw text reads that as unconverted HLSL.
36
+
37
+ String literals are masked because generator._enclosing_block counts
38
+ braces on this output: a `}` in a string used to shift the depth count
39
+ and return a span one character past the real closing brace
40
+ (test_scope_helpers.EnclosingBlockTests.test_braces_in_strings_and_comments_are_ignored).
41
+
42
+ Newlines are preserved so per-line checks (engine-var redeclaration) keep
43
+ their reported line numbers.
44
+ """
45
+ def _blank(m):
46
+ return re.sub(r'[^\n]', ' ', m.group(0))
47
+ out = re.sub(r'/\*.*?\*/', _blank, source, flags=re.DOTALL)
48
+ out = re.sub(r'//[^\n]*', _blank, out)
49
+ return _blank_string_literals(out)
50
+
51
+
52
+ def _blank_string_literals(src: str) -> str:
53
+ """Blank the contents of "..." and '...' literals; the quotes stay put.
54
+
55
+ Same-length output, escape-aware. Carried over from the deleted
56
+ generator._mask_comments_and_strings; newlines inside a literal are kept
57
+ (code_only's line-structure contract, and brace counting treats ' ' and
58
+ '\\n' alike). test_scope_helpers.EnclosingBlockTests.
59
+ """
60
+ out = list(src)
61
+ i, n = 0, len(src)
62
+ while i < n:
63
+ c = src[i]
64
+ if c in '"\'':
65
+ quote = c
66
+ j = i + 1
67
+ while j < n:
68
+ if src[j] == '\\' and j + 1 < n:
69
+ j += 2
70
+ continue
71
+ if src[j] == quote:
72
+ break
73
+ j += 1
74
+ for k in range(i + 1, min(j, n - 1)):
75
+ if out[k] != '\n':
76
+ out[k] = ' '
77
+ i = j + 1
78
+ else:
79
+ i += 1
80
+ return ''.join(out)
@@ -0,0 +1,5 @@
1
+ """
2
+ Optional renderer for VS-2 shader verification.
3
+
4
+ Requires: moderngl + numpy + Pillow
5
+ """