-
Notifications
You must be signed in to change notification settings - Fork 0
/
ink.py
executable file
·367 lines (328 loc) · 12.4 KB
/
ink.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
import json
story = None
class Story:
def __init__(self, jdata):
self.version = jdata.get('inkVersion')
self.root = Container(jdata.get('root', {}))
self.list_defs = jdata.get('listDefs')
class Container:
def __init__(self, data, parent=None, name=None): # TODO: Track stack and use to make contents more useful
self.raw = data
self.contents = [Container(element, self) if type(element) == list else parse_object(element, self) for element in self.raw[:-1]]
self.parent = parent
self.sub_elements = {}
if data[-1]:
self.name = name or data[-1].get('#n')
self.flags = data[-1].get('#f', 0)
for name, container in data[-1].items():
if name in ['#n', '#f']: # Don't try to create containers for the special keys #n and #f
continue
self.sub_elements[name] = Container(container, self, name)
else:
self.name = name
self.flags = 0
self.count_visits = bool(self.flags & 1)
self.track_turn_index = bool(self.flags & 2)
self.count_start_only = bool(self.flags & 4)
def __repr__(self):
ret = f'Container: {self.name or "(unnamed)"}'
if self.sub_elements:
ret += f' ({len(self.sub_elements)} sub-element(s))'
return ret
def __getattr__(self, attr):
if attr not in self.__dict__:
try:
value = self.__dict__['sub_elements'][attr]
self.__dict__[attr] = value
except KeyError:
raise AttributeError
return self.__dict__[attr]
class Path:
def __init__(self, path):
self.path = path
self.components = path.split('.')
if self.is_relative():
self.components = self.components[1:]
def is_relative(self):
return self.path.startswith('.')
def pop(self):
if len(self.components) == 1:
return self.components[0], None
else:
new_path = '.' + '.'.join(self.components[1:])
return self.components[0], Path(new_path)
def __repr__(self):
return f'{"Relative" if self.is_relative() else "Absolute"} Path: {self.path}'
class Divert:
def __init__(self, data: dict, container: Container):
self.raw = data
self.parent = container
if '->' in data:
self.path = data["->"]
if 'var' in data:
self.type = "Variable divert"
else:
self.path = Path(self.path)
self.type = "Standard divert"
elif "f()" in data:
self.path = Path(data["f()"])
self.type = "Function call"
elif "->t->" in data:
self.path = Path(data["->t->"])
self.type = "Tunnel"
elif "x()" in data:
self.path = data["x()"]
self.type = "External function"
else:
self.type = "Unknown"
self.path = ""
self.conditional = data.get('c')
def __repr__(self):
return f'{self.type}: {self.path}{" (conditional)" if self.conditional else ""}'
def __getattr__(self, attr):
if attr not in self.__dict__:
if attr == 'target':
if type(self.path) == Path:
value = Divert.resolve_path(self.path, self)
self.__dict__['target'] = value
else:
self.__dict__['target'] = self.path
return self.__dict__[attr]
# takes a path, root container, and starting position and returns the element referenced.
@staticmethod
def resolve_path(path: Path, start: Container):
if path is None:
return start
selector, new_path = path.pop()
anchor = None
if path.is_relative():
anchor = start
else:
anchor = story.root
if selector == '^':
return Divert.resolve_path(new_path, anchor.parent)
try:
index = int(selector)
return Divert.resolve_path(new_path, anchor.contents[index-1])
except ValueError:
try:
return Divert.resolve_path(new_path, anchor.sub_elements[selector])
except KeyError:
print(f'Failed to resolve path {path} for container {start.raw}')
class Command:
control_commands = {
"ev" : "Begin logical evaluation mode.",
"/ev" : "End logical evaluation mode.",
"out" : "The topmost object on the evaluation stack is popped and appended to the output stream (main story output).",
"pop" : "Pops a value from the evaluation stack, without appending to the output stream.",
"->->" : "Pop the callstack.",
"~ret" : "Pop the callstack.",
"du" : "Duplicate the topmost object on the evaluation stack.",
"str" : "Begin string evaluation mode.",
"/str" : "End string evaluation mode.",
"nop" : "No-operation.",
"choiceCnt": "Pushes an integer with the current number of choices to the evaluation stack.",
"turns" : "Pops from the evaluation stack, expecting to see a divert target for a knot, stitch, gather or choice. Pushes an integer with the number of turns since that target was last visited by the story engine.",
"turn" : "Turns",
"readC" : "ReadCount",
"srnd" : "Seeds the RNG",
"visit" : "Pushes an integer with the number of visits to the current container by the story engine.",
"seq" : "Pops an integer, expected to be the number of elements in a sequence that's being entered. In return, it pushes an integer with the next sequence shuffle index to the evaluation stack. This shuffle index is derived from the number of elements in the sequence, the number of elements in it, and the story's random seed from when it was first begun.",
"thread" : "Clones/starts a new thread, as used with the <- knot syntax in ink. This essentially clones the entire callstack, branching it.",
"done" : "Tries to close/pop the active thread, otherwise marks the story flow safe to exit without a loose end warning.",
"end" : "Ends the story flow immediately, closes all active threads, unwinds the callstack, and removes any choices that were previously created.",
"void" : "Places an object on the evaluation stack when a function returns without a value.",
"listInt" : "ListFromInt",
"range" : "ListRange",
"lrnd" : "ListRandom",
}
def __init__(self, command):
self.command = command
self.description = Command.control_commands.get(command)
def __repr__(self):
return f'Command: {self.command}'
def __str__(self):
return f'{self.command} - {self.description}'
class Variable:
def __init__(self, operation):
assert type(operation) == dict
self.reassignment = operation.get('re', False)
try:
self.target = operation['VAR=']
self.operation = 'Set'
except KeyError:
try:
self.target = operation['temp=']
self.operation = 'Set'
except KeyError:
try:
self.target = operation['VAR?']
self.operation = 'Get'
except KeyError:
try:
self.target = operation['^var']
self.operation = 'Pointer'
except KeyError:
raise ValueError(f'Unknown operation for given dict {operation}')
def __repr__(self):
s = f'{self.operation} {self.target}'
if self.operation == 'Set':
s += f' ({"reassignment" if self.reassignment else "new"})'
return s
def __str__(self):
s = f'{self.operation} {self.target} from stack'
if self.operation == 'Set':
s += f' ({"reassignment" if self.reassignment else "new"})'
return s
class NativeFunctionCall:
native_functions = {
('+', 'x.Union(y)'),
('-', 'x - y'),
('CEILING', '(float)Math.Ceiling((double)x)'),
('>=', 'x >= y'),
('/', 'x / y'),
('+', 'x + y'),
('<', 'x < y'),
('LIST_INVERT', 'x.inverse'),
('>', 'x > y'),
('||', 'x != 0f || y != 0f'),
('==', 'x.Equals(y)'),
('||', 'x.Count > 0 || y.Count > 0'),
('FLOOR', '(float)Math.Floor((double)x)'),
('!=', '!x.Equals(y)'),
('&&', 'x != 0 && y != 0'),
('LIST_COUNT', 'x.Count'),
('?', 'x.Contains(y)'),
('!', 'x == 0'),
('&&', 'x != 0f && y != 0f'),
('INT', '(int)x'),
('%', 'x % y'),
('MIN', 'Math.Min(x, y)'),
('!', 'x == 0f'),
('<', 'x.LessThan(y)'),
('*', 'x * y'),
('_', '-x'),
('&&', 'x.Count > 0 && y.Count > 0'),
('<=', 'x.LessThanOrEquals(y)'),
('LIST_ALL', 'x.all'),
('>=', 'x.GreaterThanOrEquals(y)'),
('||', 'x != 0 || y != 0'),
('>', 'x.GreaterThan(y)'),
('==', 'x == y'),
('LIST_MIN', 'x.MinAsList()'),
('LIST_MAX', 'x.MaxAsList()'),
('!=', 'x != y'),
('LIST_VALUE', 'x.maxItem.Value'),
('!?', '!x.Contains(y)'),
('!', '(x.Count == 0) ? 1 : 0'),
('POW', '(float)Math.Pow((double)x, (double)y)'),
('-', 'x.Without(y)'),
('MAX', 'Math.Max(x, y)'),
('<=', 'x <= y'),
('^', 'x.Intersect(y)'),
('FLOAT', '(float)x')
}
native_functions = [
'+',
'-',
'*',
'/',
'>',
'<',
'>=',
'<=',
'==',
'!=',
'?', # Contains
'!',
'%',
'_', # Negation
'^', # Intersection
'||',
'&&',
'!?', # Does not contain
'CEILING',
'FLOOR',
'INT',
'FLOAT',
'POW',
'MIN',
'MAX',
'LIST_INVERT', # Ink list inverse
'LIST_ALL',
'LIST_VALUE',
'LIST_MIN',
'LIST_MAX',
'LIST_COUNT'
]
def __init__(self, operation):
self.operation = operation
def __repr__(self):
return self.operation
class Choice:
def __init__(self, choice):
pass
class ReadCount:
def __init__(self, data):
self.path = data['CNT?']
def __repr__(self):
return f'Read count: {self.path}'
class InkList:
def __init__(self, data):
self.origins = data.get('origins')
self.data = data.get('list')
def __repr__(self): # TODO more useful repr
return repr(self.data)
class Glue:
def __init__(self, data):
pass
def __repr__(self):
return 'Glue'
def parse_object(object, container):
try:
obj_type = get_type(object)
except ValueError as e:
print(e)
try:
if obj_type == Divert:
return Divert(object, container)
return obj_type(object)
except:
print(f'error parsing object {object}')
# takes any object and returns the most likely type
def get_type(object):
if type(object) in (int, float, bool):
return type(object)
elif type(object) == str:
if object == '\n' or object.startswith('^'):
return str
elif object == '<>':
return Glue
elif object == 'L^':
return Command
elif object in Command.control_commands:
return Command
elif object in NativeFunctionCall.native_functions:
return NativeFunctionCall
if type(object) == list:
return Container
elif type(object) == dict:
if any([key in object for key in ['^var', 'VAR=', 'temp=', 'VAR?']]):
return Variable
elif 'CNT?' in object:
return ReadCount
elif any([key in object for key in ['^->', '->', 'f()', '->t->', 'x()']]):
return Divert
elif '*' in object and 'flg' in object:
return Choice
elif 'list' in object:
return InkList
else:
print(f'unknown dict {object}')
raise ValueError(f'unknown dict {object}')
else:
print(f'unknown object type - {object}')
return ValueError(f'unknown object type - {object}')
with open('data.json', encoding='utf-8-sig') as f:
data = json.load(f)
story = Story(data)