exopython 1.0.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.
exopy/decompile.py ADDED
@@ -0,0 +1,528 @@
1
+ import base64, hashlib, marshal, zlib
2
+ import re
3
+ import gzip
4
+ import os
5
+ import struct
6
+ import sys
7
+ from . import _state
8
+ from .constants import TILE_IDS, OBJECT_PROPERTIES
9
+
10
+ _ID_TO_TILE = {v: k for k, v in TILE_IDS.items()}
11
+ _ID_TO_PROP = {pid: (name, ptype) for name, (pid, ptype) in OBJECT_PROPERTIES.items()}
12
+
13
+
14
+
15
+
16
+ KEYS_FILE = os.path.expanduser("~/.exopy_keys.txt")
17
+
18
+
19
+ def _check_owner_key(level_uuid: str, expected_hash_hex: str) -> bool:
20
+ if not expected_hash_hex or not os.path.exists(KEYS_FILE):
21
+ return False
22
+ with open(KEYS_FILE, "r", encoding="utf-8") as f:
23
+ for line in f:
24
+ if "=" in line:
25
+ k, v = line.strip().split("=", 1)
26
+ if k.strip() == level_uuid:
27
+ h = hashlib.sha256(v.strip().encode("utf-8")).digest()[:8].hex()
28
+ if h == expected_hash_hex:
29
+ return True
30
+ return False
31
+
32
+
33
+ def _pack_obfuscated_py(code: str, seed: str) -> str:
34
+ # Compile to Python bytecode before compressing & scrambling
35
+ bc = marshal.dumps(compile(code, "<exopy>", "exec"))
36
+ key = hashlib.sha256(seed.encode("utf-8")).digest()[:16]
37
+ raw = zlib.compress(bc, 9)
38
+ xored = bytes(b ^ key[i % len(key)] for i, b in enumerate(raw))
39
+ blob = base64.b85encode(xored).decode("ascii")
40
+ k_hex = key.hex()
41
+ return (
42
+ "# ExoPy Protected Bytecode\n"
43
+ "import base64 as _b, marshal as _m, zlib as _z\n"
44
+ f"_k=bytes.fromhex('{k_hex}')\n"
45
+ f"_d=_b.b85decode(b'{blob}')\n"
46
+ "exec(_m.loads(_z.decompress(bytes(x^_k[i%len(_k)] for i,x in enumerate(_d)))))\n"
47
+ )
48
+
49
+ def read_exopy_meta(data: bytes):
50
+ """Read hidden ExoPy trailing footer (EXPY...YPXE) if present."""
51
+ if len(data) >= 12 and data.endswith(b"YPXE"):
52
+ body_len = struct.unpack("<H", data[-6:-4])[0]
53
+ start = len(data) - 6 - body_len
54
+ if start >= 0 and data[start : start + 4] == b"EXPY":
55
+ flags = data[start + 4]
56
+ wm_len = data[start + 5]
57
+ wm = data[start + 6 : start + 6 + wm_len].decode("utf-8", errors="replace")
58
+ kh = ""
59
+ if flags & 0x08:
60
+ kh_start = start + 6 + wm_len
61
+ kh = data[kh_start : kh_start + 8].hex()
62
+ return {
63
+ "source": "footer",
64
+ "compiled_by_exopy": bool(flags & 0x01),
65
+ "decompiled_by_exopy": bool(flags & 0x02),
66
+ "obfuscated": bool(flags & 0x04),
67
+ "watermark": wm,
68
+ "key_hash": kh,
69
+ }, data[:start]
70
+ return None, data
71
+
72
+ class BinaryReader:
73
+ def __init__(self, b: bytes):
74
+ self.b, self.i = b, 0
75
+
76
+ def raw(self, n: int) -> bytes:
77
+ if self.i + n > len(self.b):
78
+ raise EOFError("Unexpected end of file")
79
+ s = self.b[self.i : self.i + n]
80
+ self.i += n
81
+ return s
82
+
83
+ def u8(self) -> int: return self.raw(1)[0]
84
+ def bool(self) -> bool: return self.u8() != 0
85
+ def i32(self) -> int: return struct.unpack("<i", self.raw(4))[0]
86
+ def i64(self) -> int: return struct.unpack("<q", self.raw(8))[0]
87
+ def f32(self) -> float: return round(struct.unpack("<f", self.raw(4))[0], 4)
88
+ def vec2(self): return (self.f32(), self.f32())
89
+ def color(self): return tuple(struct.unpack("<f", self.raw(4))[0] for _ in range(4))
90
+
91
+ def varint(self) -> int:
92
+ v = shift = 0
93
+ while True:
94
+ b = self.u8()
95
+ v |= (b & 0x7F) << shift
96
+ if not (b & 0x80):
97
+ return v
98
+ shift += 7
99
+
100
+ def string(self) -> str:
101
+ return self.raw(self.varint()).decode("utf-8", errors="replace")
102
+
103
+ def vec(self, fn):
104
+ return [fn() for _ in range(self.i32())]
105
+
106
+ def option(self, fn):
107
+ return fn() if self.bool() else None
108
+
109
+
110
+
111
+ def _safe_ident(name: str, fallback: str) -> str:
112
+ s = re.sub(r"[^a-zA-Z0-9_]", "_", name.strip()).strip("_").lower()
113
+ if not s or s[0].isdigit():
114
+ return fallback
115
+ return s
116
+
117
+ def _try_box(corners):
118
+ if len(corners) != 1 or len(corners[0]) != 4:
119
+ return None
120
+ xs = sorted(set(round(p[0], 3) for p in corners[0]))
121
+ ys = sorted(set(round(p[1], 3) for p in corners[0]))
122
+ if len(xs) == 2 and len(ys) == 2 and abs(xs[0] + xs[1]) < 1e-2 and abs(ys[0] + ys[1]) < 1e-2:
123
+ return (round(xs[1] - xs[0], 3), round(ys[1] - ys[0], 3))
124
+ return None
125
+
126
+ def _rgba_to_hex(rgba) -> str:
127
+ r, g, b, a = [max(0, min(255, int(round(c * 255)))) for c in rgba]
128
+ return f"#{r:02X}{g:02X}{b:02X}" if a == 255 else f"#{r:02X}{g:02X}{b:02X}{a:02X}"
129
+
130
+
131
+ def _read_prop(r: BinaryReader):
132
+ pid = r.i32()
133
+ name, ptype = _ID_TO_PROP[pid]
134
+ if ptype == "color": return name, _rgba_to_hex(r.color())
135
+ if ptype == "i32": return name, r.i32()
136
+ if ptype == "f32": return name, r.f32()
137
+ if ptype == "bool": return name, r.bool()
138
+ if ptype == "vec2": return name, r.vec2()
139
+ if ptype == "str": return name, r.string()
140
+ if ptype == "vi32": return name, r.vec(r.i32)
141
+ if ptype == "tcorners": return name, r.vec(lambda: r.vec(r.vec2))
142
+ raise KeyError(f"Unhandled property type: {ptype}")
143
+
144
+
145
+ def _read_nova(r: BinaryReader, ver: int = 18) -> dict:
146
+ dt = r.i32()
147
+ b = r.bool()
148
+ i = r.i32()
149
+ f = r.f32()
150
+ s = r.option(r.string)
151
+ c = r.color()
152
+ v = r.vec2()
153
+ if ver >= 19:
154
+ r.u8() # v19+ extra byte before int_list
155
+ il = r.option(lambda: r.vec(r.i32))
156
+ sub = r.option(lambda: r.vec(lambda: _read_nova(r, ver)))
157
+ if ver >= 19:
158
+ r.raw(4) # v19+ extra 4 bytes after sub_values
159
+ return {"dt": dt, "b": b, "i": i, "f": f, "s": s, "c": c, "v": v, "il": il, "sub": sub}
160
+
161
+
162
+ def _fmt_nova(nv: dict) -> str:
163
+ dt = nv["dt"]
164
+ if dt == 0: return repr(nv["b"])
165
+ if dt == 38: return repr(nv["i"])
166
+ if dt == 56: return repr(nv["f"])
167
+ if dt == 94: return repr(nv["s"] or "")
168
+ if dt == 99: return repr(_rgba_to_hex(nv["c"]))
169
+ if dt == 103: return repr(nv["v"])
170
+ if dt == 134: return f"exovar.object_set({nv['il'] or []!r})"
171
+
172
+ kw = []
173
+ if nv["b"]: kw.append(f"bool_value={nv['b']!r}")
174
+ if nv["i"]: kw.append(f"int_value={nv['i']!r}")
175
+ if nv["f"]: kw.append(f"float_value={nv['f']!r}")
176
+ if nv["s"] is not None: kw.append(f"string_value={nv['s']!r}")
177
+ if any(abs(x) > 1e-6 for x in nv["c"]): kw.append(f"color_value={_rgba_to_hex(nv['c'])!r}")
178
+ if nv["v"] != (0.0, 0.0): kw.append(f"vector_value={nv['v']!r}")
179
+ if nv["il"] is not None: kw.append(f"int_list_value={nv['il']!r}")
180
+ if nv["sub"] is not None:
181
+ subs = ", ".join(_fmt_nova(s) for s in nv["sub"])
182
+ kw.append(f"sub_values=[{subs}]")
183
+ args = f"{dt}, " + ", ".join(kw) if kw else str(dt)
184
+ return f"exovar.value({args})"
185
+
186
+
187
+ def _read_action(r: BinaryReader, ver: int = 18) -> dict:
188
+ aid = r.i32()
189
+ closed = r.bool()
190
+ wait = r.bool()
191
+ rn = lambda: _read_nova(r, ver)
192
+ ra = lambda: r.vec(lambda: _read_action(r, ver))
193
+
194
+ if aid == 0: d = {"actions": ra(), "count": rn()}
195
+ elif aid == 1: d = {"actions": ra(), "condition": rn()}
196
+ elif aid == 2: d = {"if_actions": ra(), "else_actions": ra(), "condition": rn()}
197
+ elif aid == 3: d = {"fields": [rn()]}
198
+ elif aid == 4: d = {"fields": [rn()]}
199
+ elif aid in (5, 12, 13, 32): d = {"fields": [rn() for _ in range(5)]}
200
+ elif aid in (6, 14, 15, 16, 17, 44, 45): d = {"fields": [rn() for _ in range(4)]}
201
+ elif aid in (7, 8): d = {"fields": [rn() for _ in range(6)]}
202
+ elif aid == 9: d = {"var_id": r.i32(), "value": r.option(rn)}
203
+ elif aid == 10: d = {"var_id": r.i32()}
204
+ elif aid in (11, 21, 22, 24, 38, 39, 40, 43, 51): d = {"fields": [rn()]}
205
+ elif aid in (18, 19, 20, 23, 29, 31, 35, 36, 37, 41, 50, 52): d = {"fields": [rn(), rn()]}
206
+ elif aid in (25, 27): d = {"fields": []}
207
+ elif aid in (26, 28, 30, 33, 34, 42, 46): d = {"fields": [rn(), rn(), rn()]}
208
+ elif aid == 47: d = {"fn_id": r.i32(), "params": r.vec(lambda: (r.i32(), rn()))}
209
+ elif aid == 48: d = {"var_id": r.i32(), "value": r.option(rn), "duration": rn(), "easing": rn()}
210
+ elif aid == 49: d = {"target": rn(), "actions": ra()}
211
+ else: raise KeyError(f"Unknown ActionID: {aid}")
212
+
213
+ d.update({"aid": aid, "closed": closed, "wait": wait})
214
+ return d
215
+
216
+
217
+ def _emit_actions(acts, target_var: str, indent: str = "") -> list:
218
+ lines = []
219
+ for a in acts:
220
+ aid, wait = a["aid"], a["wait"]
221
+ if aid == 0:
222
+ lines.append(f"{indent}_rep = exoscript.block()")
223
+ lines.extend(_emit_actions(a["actions"], "_rep", indent))
224
+ lines.append(f"{indent}{target_var}.repeat({_fmt_nova(a['count'])}, _rep, wait={wait!r})")
225
+ elif aid == 1:
226
+ lines.append(f"{indent}_whl = exoscript.block()")
227
+ lines.extend(_emit_actions(a["actions"], "_whl", indent))
228
+ lines.append(f"{indent}{target_var}.repeat_while({_fmt_nova(a['condition'])}, _whl, wait={wait!r})")
229
+ elif aid == 2:
230
+ lines.append(f"{indent}_if = exoscript.block()")
231
+ lines.extend(_emit_actions(a["if_actions"], "_if", indent))
232
+ lines.append(f"{indent}_el = exoscript.block()")
233
+ lines.extend(_emit_actions(a["else_actions"], "_el", indent))
234
+ lines.append(f"{indent}{target_var}.if_else({_fmt_nova(a['condition'])}, _if, _el, wait={wait!r})")
235
+ elif aid == 3:
236
+ lines.append(f"{indent}{target_var}.wait({_fmt_nova(a['fields'][0])})")
237
+ elif aid == 4:
238
+ lines.append(f"{indent}{target_var}.wait_frames({_fmt_nova(a['fields'][0])})")
239
+ elif aid == 5:
240
+ f = [_fmt_nova(x) for x in a["fields"]]
241
+ lines.append(f"{indent}{target_var}.move({f[0]}, {f[1]}, is_global={f[2]}, duration={f[3]}, wait={wait!r})")
242
+ elif aid == 9:
243
+ val_s = _fmt_nova(a["value"]) if a["value"] is not None else "None"
244
+ lines.append(f"{indent}{target_var}.set_var({a['var_id']}, {val_s})")
245
+ elif aid == 10:
246
+ lines.append(f"{indent}{target_var}.reset_var({a['var_id']})")
247
+ elif aid == 6:
248
+ f = [_fmt_nova(x) for x in a["fields"]]
249
+ lines.append(f"{indent}{target_var}.scale({f[0]}, {f[1]}, duration={f[2]}, wait={wait!r})")
250
+ elif aid == 7:
251
+ f = [_fmt_nova(x) for x in a["fields"]]
252
+ lines.append(f"{indent}{target_var}.rotate({f[0]}, {f[1]}, duration={f[4]}, wait={wait!r})")
253
+ elif aid == 12:
254
+ f = [_fmt_nova(x) for x in a["fields"]]
255
+ lines.append(f"{indent}{target_var}.set_color({f[0]}, {f[1]}, duration={f[3]}, wait={wait!r})")
256
+ elif aid == 19:
257
+ lines.append(f"{indent}{target_var}.set_text({_fmt_nova(a['fields'][0])}, {_fmt_nova(a['fields'][1])})")
258
+ elif aid == 20:
259
+ lines.append(f"{indent}{target_var}.set_enabled({_fmt_nova(a['fields'][0])}, {_fmt_nova(a['fields'][1])})")
260
+ elif aid == 21:
261
+ lines.append(f"{indent}{target_var}.activate({_fmt_nova(a['fields'][0])})")
262
+ elif aid == 22:
263
+ lines.append(f"{indent}{target_var}.deactivate({_fmt_nova(a['fields'][0])})")
264
+ elif aid == 24:
265
+ lines.append(f"{indent}{target_var}.kill({_fmt_nova(a['fields'][0])})")
266
+ elif aid == 25:
267
+ lines.append(f"{indent}{target_var}.game_finish()")
268
+ elif aid == 41:
269
+ lines.append(f"{indent}{target_var}.game_text({_fmt_nova(a['fields'][0])}, {_fmt_nova(a['fields'][1])}, wait={wait!r})")
270
+ elif aid == 47:
271
+ p_str = ", ".join(f"({pid}, {_fmt_nova(v)})" for pid, v in a["params"])
272
+ lines.append(f"{indent}{target_var}.call_id({a['fn_id']}, [{p_str}], wait={wait!r})")
273
+ elif "fields" in a:
274
+ f = ", ".join(_fmt_nova(x) for x in a["fields"])
275
+ lines.append(f"{indent}{target_var}.raw_action({aid}{', ' + f if f else ''}, wait={wait!r})")
276
+ return lines
277
+
278
+
279
+ def _read_var(r: BinaryReader, ver: int = 18) -> dict:
280
+ return {"id": r.i32(), "name": r.string(), "stype": r.i32(), "init": _read_nova(r, ver)}
281
+
282
+
283
+ def _read_script(r: BinaryReader, ver: int = 18) -> dict:
284
+ sid = r.i32()
285
+ name = r.string()
286
+ is_fn = r.bool()
287
+ act_cnt = r.i32()
288
+ cond = _read_nova(r, ver)
289
+ activators = r.vec(lambda: (r.i32(), r.vec(lambda: _read_nova(r, ver))))
290
+ params = r.vec(lambda: _read_var(r, ver))
291
+ local_vars = r.vec(lambda: _read_var(r, ver))
292
+ actions = r.vec(lambda: _read_action(r, ver))
293
+ return {
294
+ "id": sid, "name": name, "is_fn": is_fn, "act_cnt": act_cnt,
295
+ "cond": cond, "activators": activators, "params": params,
296
+ "vars": local_vars, "actions": actions,
297
+ }
298
+
299
+
300
+ def decompile(filepath: str, out_py: str = None, generator_mode: bool = None, include_meta: bool = False):
301
+ """Read a .exolvl file and convert objects, layers, settings, variables, and scripts into exopy code."""
302
+ with open(filepath, "rb") as f:
303
+ raw = f.read()
304
+
305
+ data = gzip.decompress(raw) if raw[:2] == b"\x1f\x8b" else raw
306
+ exopy_meta, data = read_exopy_meta(data)
307
+ gen = _state.generator_mode if generator_mode is None else bool(generator_mode)
308
+ is_obf = bool(exopy_meta and exopy_meta.get('obfuscated'))
309
+ r = BinaryReader(data)
310
+ if r.raw(4) != b"NYA^":
311
+ raise ValueError("Not a valid .exolvl file (missing NYA^ magic)")
312
+
313
+ # --- 1. LocalLevel ---
314
+ ver = r.i32()
315
+ uid = r.string()
316
+ _lver = r.i32()
317
+ name = r.string()
318
+ _thumb = r.string()
319
+ r.i64(); r.i64(); author_ms = r.i64()
320
+ r.vec(r.i64)
321
+ silver_ms = r.i64(); gold_ms = r.i64()
322
+ laps = max(1, min(10, r.i32()))
323
+ private = r.bool()
324
+ _nova = r.bool()
325
+
326
+ # --- 2. LevelData: Objects & Layers ---
327
+ r.string(); r.i32(); r.bool()
328
+ for _ in range(6):
329
+ r.vec(r.i32)
330
+
331
+ objects = []
332
+ for _ in range(r.i32()):
333
+ eid, tid = r.i32(), r.i32()
334
+ r.i32(); r.i32()
335
+ pos, scale, rot, tag = r.vec2(), r.vec2(), r.f32(), r.string()
336
+ props = dict(r.vec(lambda: _read_prop(r)))
337
+ layer = r.i32()
338
+ r.i32(); r.vec(r.i32)
339
+ if tag == "__EXOPY_META__" and "Text" in props and props["Text"].startswith("EXOPY|"):
340
+ parts = dict(p.split("=", 1) for p in props["Text"].split("|")[1:] if "=" in p)
341
+ exopy_meta = {
342
+ "source": "object",
343
+ "compiled_by_exopy": True,
344
+ "decompiled_by_exopy": parts.get("dec") == "1",
345
+ "obfuscated": parts.get("obf") == "1",
346
+ "watermark": parts.get("wm", ""),
347
+ "key_hash": parts.get("kh", ""),
348
+ }
349
+ if exopy_meta['obfuscated']: is_obf = True
350
+ continue
351
+ objects.append((eid, tid, pos, scale, rot, tag, props, layer))
352
+
353
+ layers = []
354
+ for _ in range(r.i32()):
355
+ lid, lname = r.i32(), r.string()
356
+ r.bool(); r.bool(); r.bool()
357
+ fg, plx = r.i32(), r.vec2()
358
+ r.bool(); r.vec(r.i32)
359
+ layers.append((lid, lname, fg, plx))
360
+
361
+ # --- 3. LevelData: Scripts, Variables & Settings ---
362
+ nova_scripts, global_vars = [], []
363
+ theme, gravity = "Mountains", (0.0, -75.0)
364
+ lvl_settings = {"uuid": uid, "Private": private, "_ExopyDecompiled": True}
365
+ if author_ms: lvl_settings["AuthorTime"] = round(author_ms / 1000.0, 3)
366
+ if silver_ms: lvl_settings["Silver"] = round(silver_ms / 1000.0, 3)
367
+ if gold_ms: lvl_settings["Gold"] = round(gold_ms / 1000.0, 3)
368
+ tail_note = None
369
+
370
+ try:
371
+ n_prefabs = r.i32()
372
+ n_brushes = r.i32()
373
+ n_patterns = r.i32()
374
+ if n_prefabs or n_brushes or n_patterns:
375
+ raise NotImplementedError(f"non-empty prefabs({n_prefabs})/brushes({n_brushes})/patterns({n_patterns})")
376
+ if ver >= 17:
377
+ r.vec(r.color) # color_palette
378
+
379
+ r.i64(); r.vec(r.i64); r.i64(); r.i64(); r.i32()
380
+ lvl_settings["CenterCamera"] = r.bool()
381
+ r.vec(r.i32) # legacy scripts
382
+ if ver >= 19:
383
+ r.i32() # extra v19+ field before scripts
384
+ nova_scripts = r.vec(lambda: _read_script(r, ver))
385
+ global_vars = r.vec(lambda: _read_var(r, ver))
386
+
387
+ raw_theme = r.string().strip().lower()
388
+ theme = raw_theme.capitalize() if raw_theme in ("mountains", "halloween", "christmas", "custom") else "Mountains"
389
+ bg_col = _rgba_to_hex(r.color())
390
+ if theme == "Custom":
391
+ lvl_settings["CustomBackgroundColor"] = bg_col
392
+ r.raw(4)
393
+ r.i32(); r.vec2(); r.vec2(); r.color(); r.color(); r.i32()
394
+ r.color(); r.f32(); r.f32(); r.bool(); r.bool(); r.f32()
395
+
396
+ default_music = r.bool()
397
+ music_ids = r.vec(r.string)
398
+ if not default_music and music_ids:
399
+ lvl_settings["music"] = music_ids[0] if len(music_ids) == 1 else music_ids
400
+
401
+ lvl_settings["AllowDirectionChange"] = r.bool()
402
+ lvl_settings["DisableReplays"] = r.bool()
403
+ lvl_settings["DisableRevivePads"] = r.bool()
404
+ lvl_settings["DisableStartAnim"] = r.bool()
405
+ gravity = r.vec2()
406
+ except Exception as e:
407
+ tail_note = f"Partial tail parse ({e})"
408
+
409
+ # --- 4. Emit Runnable exopy Python Code ---
410
+ base_name = os.path.splitext(os.path.basename(filepath))[0]
411
+ lines = [
412
+ f"# Decompiled from {os.path.basename(filepath)} (format v{ver})",
413
+ "import exopy as exo",
414
+ "from exopy import scripts as exoscript",
415
+ "from exopy import variables as exovar",
416
+ "",
417
+ f"Settings = {lvl_settings!r}",
418
+ f"Level = exo.init({name!r}, {theme!r}, {laps}, {gravity!r}, Settings)",
419
+ "",
420
+ ]
421
+ if tail_note:
422
+ lines.append(f"# Note: {tail_note}")
423
+ lines.append("")
424
+
425
+ for lid, lname, fg, plx in layers:
426
+ if lid == 1:
427
+ continue
428
+ lines.append(f"layer_{lid} = exo.CreateLayer({lname!r}, foreground_type={fg}, parallax={plx})")
429
+ if len(layers) > 1:
430
+ lines.append("")
431
+
432
+ for eid, tid, pos, scale, rot, tag, props, layer in objects:
433
+ tile_arg = repr(_ID_TO_TILE[tid]) if tid in _ID_TO_TILE else str(tid)
434
+ cfg = {}
435
+ if scale != (1.0, 1.0): cfg["Scale"] = scale
436
+ if rot != 0.0: cfg["Rotation"] = rot
437
+ if tag: cfg["Tag"] = tag
438
+ if layer != 1: cfg["Layer"] = layer
439
+ for pk, pv in props.items():
440
+ if pk == "TerrainCorners":
441
+ box = _try_box(pv)
442
+ if box:
443
+ cfg["Box"] = box
444
+ continue
445
+ cfg[pk] = pv
446
+ if cfg:
447
+ lines.append(f"exo.CreateObj({tile_arg}, {pos}).settings({cfg!r}).pack()")
448
+ else:
449
+ lines.append(f"exo.CreateObj({tile_arg}, {pos}).pack()")
450
+
451
+ if global_vars:
452
+ lines.append("")
453
+ lines.append("# --- Global Variables ---")
454
+ for v in global_vars:
455
+ lines.append(f"var_{v['id']} = exovar.Variable({v['id']}, {v['name']!r}, {v['stype']}, {_fmt_nova(v['init'])})")
456
+ lines.append(f"Level.global_variables.append(var_{v['id']})")
457
+
458
+ if nova_scripts:
459
+ lines.append("")
460
+ lines.append("# --- ExoScripts & Functions ---")
461
+ used_names = set()
462
+ for idx, sc in enumerate(nova_scripts):
463
+ base = _safe_ident(sc["name"], f"script_{idx+1}")
464
+ sv = base if base not in used_names else f"{base}_{idx+1}"
465
+ used_names.add(sv)
466
+ c_args = [repr(sc["name"])]
467
+ if sc["is_fn"]: c_args.append("is_function=True")
468
+ if sc["act_cnt"] != 0: c_args.append(f"activation_count={sc['act_cnt']!r}")
469
+ cond_s = _fmt_nova(sc["cond"])
470
+ if cond_s != "True": c_args.append(f"condition={cond_s}")
471
+ lines.append(f"{sv} = exoscript.create({', '.join(c_args)})")
472
+ if sc["is_fn"]:
473
+ lines.append(f"{sv}.script_id = {sc['id']}")
474
+ for act_t, act_p in sc["activators"]:
475
+ p_args = ", ".join(_fmt_nova(p) for p in act_p)
476
+ lines.append(f"{sv}.on({act_t}{', ' + p_args if p_args else ''})")
477
+ for p in sc["params"]:
478
+ lines.append(f"{sv}.parameters.append(exovar.Parameter({p['id']}, {p['name']!r}, {p['stype']}, {_fmt_nova(p['init'])}))")
479
+ for lv in sc["vars"]:
480
+ lines.append(f"{sv}.variables.append(exovar.Variable({lv['id']}, {lv['name']!r}, {lv['stype']}, {_fmt_nova(lv['init'])}))")
481
+ lines.extend(_emit_actions(sc["actions"], sv))
482
+ lines.append(f"{sv}.pack()")
483
+ lines.append("")
484
+
485
+ key_hash = exopy_meta.get("key_hash", "") if exopy_meta else ""
486
+ owner_unlocked = is_obf and _check_owner_key(uid, key_hash)
487
+ obf_arg = ", obfuscate=True" if is_obf else ""
488
+ lines.append(f"Level.export('{base_name}_rebuilt.exolvl'{obf_arg})")
489
+ code = "\n".join(lines) + "\n"
490
+ if is_obf and not owner_unlocked:
491
+ code = _pack_obfuscated_py(code, uid)
492
+
493
+ if out_py is None:
494
+ out_py = f"{base_name}_exopy.py"
495
+ with open(out_py, "w") as f:
496
+ f.write(code)
497
+
498
+ gen = _state.generator_mode if generator_mode is None else bool(generator_mode)
499
+ fname = os.path.basename(out_py)
500
+ result = {
501
+ "ok": tail_note is None,
502
+ "path": out_py,
503
+ "name": name,
504
+ "uuid": uid,
505
+ "counts": {
506
+ "objects": len(objects),
507
+ "scripts": len(nova_scripts),
508
+ "variables": len(global_vars),
509
+ },
510
+ "code": code,
511
+ }
512
+ if include_meta:
513
+ result["obfuscated"] = is_obf
514
+ result["unlocked"] = owner_unlocked if is_obf else True
515
+ result["watermark"] = exopy_meta.get("watermark") if exopy_meta else None
516
+ if tail_note:
517
+ result["warning"] = tail_note
518
+ if gen:
519
+ return result
520
+ pass
521
+ return code
522
+
523
+
524
+ if __name__ == "__main__":
525
+ if len(sys.argv) < 2:
526
+ pass
527
+ sys.exit(1)
528
+ decompile(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else None)