rpgsync 0.1.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.
rpgsync/dynparams.py ADDED
@@ -0,0 +1,357 @@
1
+ """DynParams plugin: which parameter of which command a comment overwrites.
2
+
3
+ DynParams (DynPlugins/DynParams.dll) rewrites the parameters of the next
4
+ command from comment commands::
5
+
6
+ @dynparams_add_param 2, V152 parameter 2 (1-based) := variable 152
7
+ @dynparams_overwrite_next apply to the next command
8
+
9
+ The decompiler names what they overwrite in a hint:
10
+ ``dyn.dynparams_add_param(2, variables.id) # → ConditionalBranch: switch``.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from pydantic import BaseModel
16
+
17
+ from . import commands as K
18
+ from . import named
19
+ from .commands import Ctx
20
+ from .lcf import Command
21
+
22
+ # Lines the plugin never overwrites: the overwrite waits for the next command
23
+ SKIPPED = {0, K.END, *K.GROUPS}
24
+
25
+ TARGETS = {"pictures": "picture", "actors": "actor", "enemies": "enemy", "char": "event", "vehicle": "vehicle"}
26
+
27
+ # Parameters of the commands written by hand in pyexpr (not described in named.SPECS),
28
+ # from the DynParams readme. The last name repeats for the remaining parameters.
29
+ TABLE: dict[int, list[str]] = {
30
+ 10120: ["transparent", "position", "auto position", "continue events"],
31
+ 10130: ["face index", "right side", "flip"],
32
+ 10140: ["cancel"],
33
+ 10150: ["digits", "variable"],
34
+ 10210: ["target type", "first switch", "last switch", "operation"],
35
+ 10220: ["target type", "first variable", "last variable", "operation", "operand type", "operand", "operand 2"],
36
+ 10230: ["operation", "time type", "time", "visible", "in battle", "timer"],
37
+ 10310: ["operation", "amount type", "amount"],
38
+ 10320: ["operation", "item type", "item", "amount type", "amount"],
39
+ 10330: ["operation", "actor type", "actor"],
40
+ 10410: ["actor type", "actor", "operation", "amount type", "amount", "level-up message"],
41
+ 10420: ["actor type", "actor", "operation", "amount type", "amount", "level-up message"],
42
+ 10490: ["actor type", "actor"],
43
+ 10810: ["map", "x", "y", "direction"],
44
+ 10860: ["event", "position type", "x", "y", "direction"],
45
+ 10910: ["position type", "x", "y", "variable"],
46
+ 10920: ["position type", "x", "y", "variable"],
47
+ 11210: ["animation", "target", "wait", "whole map"],
48
+ 11330: ["event", "frequency", "repeat", "skippable", "route step"],
49
+ 11410: ["duration", "wait for key"],
50
+ 11510: ["fade in", "volume", "tempo", "balance"],
51
+ 11550: ["volume", "tempo", "balance"],
52
+ 11610: [
53
+ "variable",
54
+ "wait",
55
+ "unused",
56
+ "decision",
57
+ "cancel",
58
+ "numbers",
59
+ "operators",
60
+ "time variable",
61
+ "store time",
62
+ "shift",
63
+ "down",
64
+ "left",
65
+ "right",
66
+ "up",
67
+ ],
68
+ }
69
+ CONDITION = ["condition type", "first reference", "second type", "second reference", "third reference", "else branch"]
70
+ BY_TYPE: dict[tuple[int, int], list[str]] = {
71
+ (12010, 0): ["condition type", "switch", "on/off", "unused", "unused", "else branch"],
72
+ (12010, 1): ["condition type", "variable", "operand type", "operand", "comparison", "else branch"],
73
+ (12330, 0): ["call type", "common event", "unused"],
74
+ (12330, 1): ["call type", "event", "page"],
75
+ (12330, 2): ["call type", "event variable", "page variable"],
76
+ }
77
+
78
+
79
+ def _field_slots(f: named.Field) -> list[str]:
80
+ name = f.name.lstrip("_")
81
+ if f.kind == "bits":
82
+ return []
83
+ if f.kind == "const":
84
+ return ["mode"]
85
+ if f.kind == "xy":
86
+ return ["position type", "x", "y"]
87
+ if f.kind == "mxy":
88
+ return ["position type", "map", "x", "y"]
89
+ if f.kind in ("actor", "value", "amount3"):
90
+ return [name + " type", name]
91
+ if f.kind in ("optid", "optvar"):
92
+ return ["use " + name, name]
93
+ return [name]
94
+
95
+
96
+ def slots(c: Command, ctx: Ctx) -> list[str]:
97
+ """Name of each parameter of a command (its last name repeats for the parameters after)."""
98
+ p = c.params
99
+ if p and (c.code, p[0]) in BY_TYPE:
100
+ return BY_TYPE[(c.code, p[0])]
101
+ if c.code in (12010, 13310):
102
+ return CONDITION
103
+ if c.code in TABLE:
104
+ return TABLE[c.code]
105
+ specs = named.BY_CODE.get(c.code, [])
106
+ spec = next((s for s in specs if s.decode(c, ctx) is not None), specs[0] if specs else None)
107
+ if spec is None:
108
+ return []
109
+ names = [TARGETS.get(spec.target, spec.target)] if spec.target else []
110
+ for f in spec.fields:
111
+ names += _field_slots(f)
112
+ return names
113
+
114
+
115
+ def slot_hint(c: Command, index: int, ctx: Ctx) -> str:
116
+ """``ConditionalBranch: switch`` for parameter 2 (1-based) of an if."""
117
+ what = K.CODE_NAMES.get(c.code, str(c.code))
118
+ if not 1 <= index <= len(c.params):
119
+ return "%s has no parameter %d (it has %d)" % (what, index, len(c.params))
120
+ names = slots(c, ctx)
121
+ if not names:
122
+ return "%s: parameter %d" % (what, index)
123
+ return "%s: %s" % (what, names[min(index, len(names)) - 1])
124
+
125
+
126
+ def _call(cmds: list[Command], i: int) -> tuple[str, list[str]] | None:
127
+ """(function, arguments) of a DynParams comment command, else None."""
128
+ if cmds[i].code != 12410 or not cmds[i].string[:11].lower() == b"@dynparams_":
129
+ return None
130
+ text = cmds[i].string
131
+ for c in cmds[i + 1 :]: # DynRPG reads the following comment lines too
132
+ if c.code != 22410:
133
+ break
134
+ text += c.string
135
+ head, _, rest = text.decode("latin-1").partition(" ")
136
+ args = [a.strip() for a in rest.split(",")] if rest.strip() else []
137
+ return head[1:].lower(), args
138
+
139
+
140
+ class Overwrite(BaseModel):
141
+ """What the comments build until @dynparams_overwrite_next, and the command it rewrites
142
+ (positions in the command list)."""
143
+
144
+ at: int | None = None # the @dynparams_overwrite_next comment, None if not reached
145
+ target: int | None = None # the rewritten command, None when not among the commands
146
+ params: list[tuple[int, int]] = [] # (comment, 1-based parameter index)
147
+ lines: list[tuple[int, int]] = [] # (comment, message line)
148
+ choices: list[tuple[int, int]] = [] # (comment, choice)
149
+
150
+
151
+ def _int(arg: str) -> int | None:
152
+ return int(arg) if arg.lstrip("-").isdigit() else None
153
+
154
+
155
+ def play(cmds: list[Command]) -> list[Overwrite]:
156
+ """Plays the plugin on sibling commands (one block, in order): one Overwrite per
157
+ @dynparams_overwrite_next, plus the last one when it is not applied among them."""
158
+ out: list[Overwrite] = []
159
+ cur = Overwrite()
160
+ index: int | None = 5 # @dynparams_add_param with one value: parameter 5, then 6, ...
161
+ for i, c in enumerate(cmds):
162
+ if cur.at is not None and c.code not in SKIPPED and c.code != 22410:
163
+ cur.target = i
164
+ out.append(cur)
165
+ cur, index = Overwrite(), 5
166
+ continue # its text may be rewritten: don't read it as a command
167
+ call = _call(cmds, i)
168
+ if call is None:
169
+ continue
170
+ func, args = call
171
+ n = _int(args[0]) if args else None
172
+ if func == "dynparams_add_param":
173
+ if len(args) == 1:
174
+ if index is not None:
175
+ cur.params.append((i, index))
176
+ index += 1
177
+ elif n is not None:
178
+ cur.params.append((i, n))
179
+ elif func == "dynparams_set_index":
180
+ index = n # None: set from a variable, unknown
181
+ elif func in ("dynparams_message_line_append_string", "dynparams_message_line_append_number"):
182
+ if n is not None:
183
+ cur.lines.append((i, n))
184
+ elif func in ("dynparams_choice_case_append_string", "dynparams_choice_case_append_number"):
185
+ if n is not None:
186
+ cur.choices.append((i, n))
187
+ elif func == "dynparams_clear_params":
188
+ cur, index = Overwrite(), 5
189
+ elif func == "dynparams_overwrite_next":
190
+ cur.at = i
191
+ if cur.at is not None:
192
+ out.append(cur)
193
+ return out
194
+
195
+
196
+ def hints(cmds: list[Command], ctx: Ctx) -> dict[int, str]:
197
+ """Hints for the DynParams comments among sibling commands: the parameter each
198
+ @dynparams_add_param overwrites, the command @dynparams_overwrite_next rewrites.
199
+ A target outside these commands (after the end of the block) gets no hint."""
200
+ out: dict[int, str] = {}
201
+ for o in play(cmds):
202
+ if o.target is None:
203
+ continue
204
+ target = cmds[o.target]
205
+ for i, index in o.params:
206
+ out[i] = "→ " + slot_hint(target, index, ctx)
207
+ out[o.at] = "→ " + K.CODE_NAMES.get(target.code, str(target.code))
208
+ return out
209
+
210
+
211
+ # --------------------------------------------------------------------------
212
+ # Checks: errors break the game in RPG_RT, warnings do not
213
+ # --------------------------------------------------------------------------
214
+
215
+ FUNCTIONS = {
216
+ "dynparams_add_param",
217
+ "dynparams_set_index",
218
+ "dynparams_append_string",
219
+ "dynparams_append_number",
220
+ "dynparams_message_line_append_string",
221
+ "dynparams_message_line_append_number",
222
+ "dynparams_choice_case_append_string",
223
+ "dynparams_choice_case_append_number",
224
+ "dynparams_overwrite_next",
225
+ "dynparams_clear_params",
226
+ "dynparams_list_params",
227
+ "dynparams_start_record",
228
+ "dynparams_stop_record",
229
+ }
230
+ BUILDERS = FUNCTIONS - {
231
+ "dynparams_overwrite_next",
232
+ "dynparams_clear_params",
233
+ "dynparams_list_params",
234
+ "dynparams_start_record",
235
+ "dynparams_stop_record",
236
+ }
237
+ MESSAGE_LINES = 4
238
+
239
+
240
+ class Problem(BaseModel):
241
+ error: bool # breaks the game in RPG_RT (crash, error box); else a warning
242
+ message: str
243
+
244
+
245
+ def _blocks(cmds: list[Command]) -> list[list[int]]:
246
+ """Positions of the sibling commands of each block (same indent, same parent)."""
247
+ blocks: list[list[int]] = []
248
+ stack: list[tuple[int, list[int]]] = []
249
+ for i, c in enumerate(cmds):
250
+ while stack and stack[-1][0] > c.indent:
251
+ stack.pop()
252
+ if not stack or stack[-1][0] < c.indent:
253
+ stack.append((c.indent, []))
254
+ blocks.append(stack[-1][1])
255
+ stack[-1][1].append(i)
256
+ return blocks
257
+
258
+
259
+ def _loop_of(cmds: list[Command], i: int) -> int | None:
260
+ """The loop command around command i, else None."""
261
+ indent = cmds[i].indent
262
+ for j in range(i - 1, -1, -1):
263
+ if cmds[j].indent < indent:
264
+ if cmds[j].code == 12210:
265
+ return j
266
+ indent = cmds[j].indent
267
+ return None
268
+
269
+
270
+ def _name(c: Command) -> str:
271
+ return K.CODE_NAMES.get(c.code, str(c.code))
272
+
273
+
274
+ def problems(cmds: list[Command]) -> list[Problem]:
275
+ """DynParams mistakes in an event's command list."""
276
+ if not any(c.code == 12410 and c.string[:11].lower() == b"@dynparams_" for c in cmds):
277
+ return [] # no DynParams comment (most lists): nothing to play
278
+ out: dict[str, Problem] = {}
279
+
280
+ def add(error: bool, i: int, what: str) -> None:
281
+ text = cmds[i].string.decode("latin-1")
282
+ message = "%s: %s" % (text, what)
283
+ out.setdefault(message, Problem(error=error, message=message))
284
+
285
+ # each comment on its own
286
+ unapplied = None
287
+ for i in range(len(cmds)):
288
+ call = _call(cmds, i)
289
+ if call is None:
290
+ continue
291
+ func, args = call
292
+ n = _int(args[0]) if args else None
293
+ if func not in FUNCTIONS:
294
+ add(False, i, "unknown DynParams command, RPG_RT ignores it")
295
+ elif func == "dynparams_add_param" and len(args) > 1 and n is not None and n < 1:
296
+ add(True, i, "parameters start at 1: DynParams writes outside the command (RPG_RT may crash)")
297
+ elif func.startswith("dynparams_message_line_") and n is not None and not 1 <= n <= MESSAGE_LINES:
298
+ add(True, i, "message lines are 1 to %d: DynParams shows an error box" % MESSAGE_LINES)
299
+ elif func.startswith("dynparams_choice_case_") and n is not None and n < 1:
300
+ add(True, i, "choices start at 1: DynParams shows an error box")
301
+ if func in BUILDERS and unapplied is None:
302
+ # applied later, or at the next turn of the loop around it
303
+ loop = _loop_of(cmds, i)
304
+ start = i + 1 if loop is None else loop + 1
305
+ others = (_call(cmds, j) for j in range(start, len(cmds)) if j != i)
306
+ if not any(c and c[0] in ("dynparams_overwrite_next", "dynparams_clear_params") for c in others):
307
+ unapplied = i
308
+ if unapplied is not None:
309
+ add(False, unapplied, "never applied: no @dynparams_overwrite_next after it")
310
+
311
+ # what each overwrite does to its command
312
+ for block in _blocks(cmds):
313
+ siblings = [cmds[i] for i in block]
314
+ for o in play(siblings):
315
+ if o.target is None:
316
+ add(False, block[o.at], "no command after it in its block: it rewrites whatever runs next")
317
+ continue
318
+ target = siblings[o.target]
319
+ for i, index in o.params:
320
+ if not 1 <= index <= len(target.params):
321
+ add(
322
+ True,
323
+ block[i],
324
+ "%s has no parameter %d (it has %d): DynParams writes outside the command "
325
+ "(RPG_RT may crash)" % (_name(target), index, len(target.params)),
326
+ )
327
+ j = o.target + 1
328
+ while j < len(siblings) and siblings[j].code == 20110: # the message's other lines
329
+ j += 1
330
+ if o.lines:
331
+ if target.code != 10110:
332
+ add(False, block[o.lines[0][0]], "message lines only change a message, not %s" % _name(target))
333
+ else:
334
+ shown = j - o.target
335
+ for i, line in o.lines:
336
+ if line > shown:
337
+ add(False, block[i], "the message has %d line(s): line %d is not shown" % (shown, line))
338
+ if o.choices:
339
+ k = o.target if target.code == 10140 else j if target.code == 10110 else None
340
+ if k is None or k >= len(siblings) or siblings[k].code != 10140:
341
+ add(
342
+ False,
343
+ block[o.choices[0][0]],
344
+ "choices only change a Show Choices (or one right after the message), not %s" % _name(target),
345
+ )
346
+ continue
347
+ count = 0
348
+ for c in siblings[k + 1 :]:
349
+ if c.code == 20141:
350
+ break
351
+ count += c.code == 20140
352
+ for i, choice in o.choices:
353
+ if choice > count:
354
+ add(
355
+ False, block[i], "Show Choices has %d choice(s): choice %d is not changed" % (count, choice)
356
+ )
357
+ return list(out.values())