diff options
| author | Narek Shaghoyan <narekshagoyan7@gmail.com> | 2026-11-22 17:13:37 +0000 |
|---|---|---|
| committer | Narek Shaghoyan <narekshagoyan7@gmail.com> | 2026-11-22 17:13:37 +0000 |
| commit | e2c9ba7661d03e06f6cfd23c20ed78ce4c60f33e (patch) | |
| tree | fecb3abb59d84672a62b8a79bbb219797ce876fc /tools/first_light.py | |
| parent | 49475796c226c8511b9470bf97a4daf57b8af323 (diff) | |
first_light: support negative OBJ indices, comments, continuations, and bounds checks in read_obj
tools/first_light.py read_obj() computed vi = int(parts[0]) - 1, which shifted negative relative OBJ indices off by one, turned invalid index 0 silently into positions[-1], crashed on inline # comments or line continuations, and failed with raw IndexError/ValueError on short or out-of-range lines. Resolve negative indices relative to current list length, strip # comments, join trailing-backslash continuations, validate vertex indices cleanly with SystemExit, and add synthetic ReadObjTests.
Diffstat (limited to 'tools/first_light.py')
| -rw-r--r-- | tools/first_light.py | 57 |
1 files changed, 52 insertions, 5 deletions
diff --git a/tools/first_light.py b/tools/first_light.py index 6fe7899ce..a8fd8d320 100644 --- a/tools/first_light.py +++ b/tools/first_light.py | |||
| @@ -131,26 +131,71 @@ def translate(work: str, picked: list[dict]) -> dict: | |||
| 131 | return result | 131 | return result |
| 132 | 132 | ||
| 133 | 133 | ||
| 134 | def _obj_lines(handle): | ||
| 135 | """Yield logical OBJ lines with trailing-backslash continuations joined and # comments stripped.""" | ||
| 136 | pending = "" | ||
| 137 | for raw_line in handle: | ||
| 138 | stripped = raw_line.rstrip("\r\n") | ||
| 139 | if stripped.endswith("\\"): | ||
| 140 | pending += stripped[:-1] | ||
| 141 | continue | ||
| 142 | yield (pending + stripped).split("#", 1)[0] | ||
| 143 | pending = "" | ||
| 144 | if pending: | ||
| 145 | yield pending.split("#", 1)[0] | ||
| 146 | |||
| 147 | |||
| 148 | def _parse_obj_int(token: str, path: str, kind: str) -> int: | ||
| 149 | try: | ||
| 150 | return int(token) | ||
| 151 | except ValueError: | ||
| 152 | raise SystemExit(f"{path}: invalid {kind} index {token!r}") from None | ||
| 153 | |||
| 154 | |||
| 134 | def read_obj( | 155 | def read_obj( |
| 135 | path: str, | 156 | path: str, |
| 136 | ) -> tuple[list[tuple[float, float, float, float, float]], list[int]]: | 157 | ) -> tuple[list[tuple[float, float, float, float, float]], list[int]]: |
| 137 | """Positions, UVs and triangles as (x, y, z, u, v) vertices plus a u32 index list.""" | 158 | """Positions, UVs and triangles as (x, y, z, u, v) vertices plus a u32 index list.""" |
| 138 | positions, uvs, faces = [], [], [] | 159 | positions, uvs, faces = [], [], [] |
| 139 | with open(path, encoding="utf-8", errors="replace") as f: | 160 | with open(path, encoding="utf-8", errors="replace") as f: |
| 140 | for line in f: | 161 | for line in _obj_lines(f): |
| 141 | p = line.split() | 162 | p = line.split() |
| 142 | if not p: | 163 | if not p: |
| 143 | continue | 164 | continue |
| 144 | if p[0] == "v": | 165 | if p[0] == "v": |
| 145 | positions.append(tuple(float(x) for x in p[1:4])) | 166 | if len(p) < 4: |
| 167 | raise SystemExit(f"{path}: short vertex line: {line.strip()!r}") | ||
| 168 | try: | ||
| 169 | positions.append(tuple(float(x) for x in p[1:4])) | ||
| 170 | except ValueError: | ||
| 171 | raise SystemExit(f"{path}: invalid vertex coordinates: {line.strip()!r}") from None | ||
| 146 | elif p[0] == "vt": | 172 | elif p[0] == "vt": |
| 147 | uvs.append(tuple(float(x) for x in p[1:3])) | 173 | if len(p) < 3: |
| 174 | raise SystemExit(f"{path}: short texture-coordinate line: {line.strip()!r}") | ||
| 175 | try: | ||
| 176 | uvs.append(tuple(float(x) for x in p[1:3])) | ||
| 177 | except ValueError: | ||
| 178 | raise SystemExit(f"{path}: invalid texture coordinates: {line.strip()!r}") from None | ||
| 148 | elif p[0] == "f": | 179 | elif p[0] == "f": |
| 149 | face = [] | 180 | face = [] |
| 150 | for word in p[1:]: | 181 | for word in p[1:]: |
| 151 | parts = word.split("/") | 182 | parts = word.split("/") |
| 152 | vi = int(parts[0]) - 1 | 183 | raw_vi = _parse_obj_int(parts[0], path, "vertex") |
| 153 | ti = int(parts[1]) - 1 if len(parts) > 1 and parts[1] else -1 | 184 | if raw_vi == 0: |
| 185 | raise SystemExit(f"{path}: vertex index 0 is out of range (OBJ indices are 1-based)") | ||
| 186 | vi = len(positions) + raw_vi if raw_vi < 0 else raw_vi - 1 | ||
| 187 | if raw_vi < 0 and vi < 0: | ||
| 188 | raise SystemExit(f"{path}: vertex index {raw_vi} is out of range for {len(positions)} vertex(es)") | ||
| 189 | if len(parts) > 1 and parts[1]: | ||
| 190 | raw_ti = _parse_obj_int(parts[1], path, "texture-coordinate") | ||
| 191 | if raw_ti == 0: | ||
| 192 | ti = -1 | ||
| 193 | else: | ||
| 194 | ti = len(uvs) + raw_ti if raw_ti < 0 else raw_ti - 1 | ||
| 195 | if raw_ti < 0 and ti < 0: | ||
| 196 | ti = -1 | ||
| 197 | else: | ||
| 198 | ti = -1 | ||
| 154 | face.append((vi, ti)) | 199 | face.append((vi, ti)) |
| 155 | for k in range(1, len(face) - 1): | 200 | for k in range(1, len(face) - 1): |
| 156 | faces.extend((face[0], face[k], face[k + 1])) | 201 | faces.extend((face[0], face[k], face[k + 1])) |
| @@ -158,6 +203,8 @@ def read_obj( | |||
| 158 | raise SystemExit(f"no vertices or faces in {path}") | 203 | raise SystemExit(f"no vertices or faces in {path}") |
| 159 | unique, vertices, indices = {}, [], [] | 204 | unique, vertices, indices = {}, [], [] |
| 160 | for vi, ti in faces: | 205 | for vi, ti in faces: |
| 206 | if not 0 <= vi < len(positions): | ||
| 207 | raise SystemExit(f"{path}: vertex index {vi + 1} is out of range for {len(positions)} vertex(es)") | ||
| 161 | key = (vi, ti) | 208 | key = (vi, ti) |
| 162 | if key not in unique: | 209 | if key not in unique: |
| 163 | unique[key] = len(vertices) | 210 | unique[key] = len(vertices) |