-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathStory.ts
2423 lines (2000 loc) · 73.1 KB
/
Story.ts
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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Container } from "./Container";
import { InkObject } from "./Object";
import { JsonSerialisation } from "./JsonSerialisation";
import { StoryState } from "./StoryState";
import { ControlCommand } from "./ControlCommand";
import { PushPopType } from "./PushPop";
import { ChoicePoint } from "./ChoicePoint";
import { Choice } from "./Choice";
import { Divert } from "./Divert";
import {
Value,
StringValue,
IntValue,
DivertTargetValue,
VariablePointerValue,
ListValue,
} from "./Value";
import { Path } from "./Path";
import { Void } from "./Void";
import { Tag } from "./Tag";
import { VariableAssignment } from "./VariableAssignment";
import { VariableReference } from "./VariableReference";
import { NativeFunctionCall } from "./NativeFunctionCall";
import { StoryException } from "./StoryException";
import { PRNG } from "./PRNG";
import { StringBuilder } from "./StringBuilder";
import { ListDefinitionsOrigin } from "./ListDefinitionsOrigin";
import { ListDefinition } from "./ListDefinition";
import { Stopwatch } from "./StopWatch";
import { Pointer } from "./Pointer";
import { InkList, InkListItem, KeyValuePair } from "./InkList";
import { asOrNull, asOrThrows } from "./TypeAssertion";
import { DebugMetadata } from "./DebugMetadata";
import { throwNullException } from "./NullException";
import { SimpleJson } from "./SimpleJson";
import { ErrorHandler, ErrorType } from "./Error";
export { InkList } from "./InkList";
if (!Number.isInteger) {
Number.isInteger = function isInteger(nVal: any) {
return (
typeof nVal === "number" &&
isFinite(nVal) &&
nVal > -9007199254740992 &&
nVal < 9007199254740992 &&
Math.floor(nVal) === nVal
);
};
}
export class Story extends InkObject {
public static inkVersionCurrent = 20;
public inkVersionMinimumCompatible = 18;
get currentChoices() {
let choices: Choice[] = [];
if (this._state === null) {
return throwNullException("this._state");
}
for (let c of this._state.currentChoices) {
if (!c.isInvisibleDefault) {
c.index = choices.length;
choices.push(c);
}
}
return choices;
}
get currentText() {
this.IfAsyncWeCant("call currentText since it's a work in progress");
return this.state.currentText;
}
get currentTags() {
this.IfAsyncWeCant("call currentTags since it's a work in progress");
return this.state.currentTags;
}
get currentErrors() {
return this.state.currentErrors;
}
get currentWarnings() {
return this.state.currentWarnings;
}
get currentFlowName() {
return this.state.currentFlowName;
}
get hasError() {
return this.state.hasError;
}
get hasWarning() {
return this.state.hasWarning;
}
get variablesState() {
return this.state.variablesState;
}
get listDefinitions() {
return this._listDefinitions;
}
get state() {
return this._state;
}
public onError: ErrorHandler | null = null;
public onDidContinue: (() => void) | null = null;
public onMakeChoice: ((arg1: Choice) => void) | null = null;
public onEvaluateFunction:
| ((arg1: string, arg2: any[]) => void)
| null = null;
public onCompleteEvaluateFunction:
| ((arg1: string, arg2: any[], arg3: string, arg4: any) => void)
| null = null;
public onChoosePathString:
| ((arg1: string, arg2: any[]) => void)
| null = null;
// TODO: Implement Profiler
public StartProfiling() {
/* */
}
public EndProfiling() {
/* */
}
constructor(contentContainer: Container, lists: ListDefinition[] | null);
constructor(jsonString: string);
constructor(json: Record<string, any>);
constructor() {
super();
// Discrimination between constructors
let contentContainer: Container;
let lists: ListDefinition[] | null = null;
let json: Record<string, any> | null = null;
if (arguments[0] instanceof Container) {
contentContainer = arguments[0] as Container;
if (typeof arguments[1] !== "undefined") {
lists = arguments[1] as ListDefinition[];
}
// ------ Story (Container contentContainer, List<Runtime.ListDefinition> lists = null)
this._mainContentContainer = contentContainer;
// ------
} else {
if (typeof arguments[0] === "string") {
let jsonString = arguments[0] as string;
json = SimpleJson.TextToDictionary(jsonString);
} else {
json = arguments[0] as Record<string, any>;
}
}
// ------ Story (Container contentContainer, List<Runtime.ListDefinition> lists = null)
if (lists != null) this._listDefinitions = new ListDefinitionsOrigin(lists);
this._externals = new Map();
// ------
// ------ Story(string jsonString) : this((Container)null)
if (json !== null) {
let rootObject: Record<string, any> = json;
let versionObj = rootObject["inkVersion"];
if (versionObj == null)
throw new Error(
"ink version number not found. Are you sure it's a valid .ink.json file?"
);
let formatFromFile = parseInt(versionObj);
if (formatFromFile > Story.inkVersionCurrent) {
throw new Error(
"Version of ink used to build story was newer than the current version of the engine"
);
} else if (formatFromFile < this.inkVersionMinimumCompatible) {
throw new Error(
"Version of ink used to build story is too old to be loaded by this version of the engine"
);
} else if (formatFromFile != Story.inkVersionCurrent) {
console.warn(
"WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising."
);
}
let rootToken = rootObject["root"];
if (rootToken == null)
throw new Error(
"Root node for ink not found. Are you sure it's a valid .ink.json file?"
);
let listDefsObj;
if ((listDefsObj = rootObject["listDefs"])) {
this._listDefinitions = JsonSerialisation.JTokenToListDefinitions(
listDefsObj
);
}
this._mainContentContainer = asOrThrows(
JsonSerialisation.JTokenToRuntimeObject(rootToken),
Container
);
this.ResetState();
}
// ------
}
// Merge together `public string ToJson()` and `void ToJson(SimpleJson.Writer writer)`.
// Will only return a value if writer was not provided.
public ToJson(writer?: SimpleJson.Writer): string | void {
let shouldReturn = false;
if (!writer) {
shouldReturn = true;
writer = new SimpleJson.Writer();
}
writer.WriteObjectStart();
writer.WriteIntProperty("inkVersion", Story.inkVersionCurrent);
writer.WriteProperty("root", (w) =>
JsonSerialisation.WriteRuntimeContainer(w, this._mainContentContainer)
);
if (this._listDefinitions != null) {
writer.WritePropertyStart("listDefs");
writer.WriteObjectStart();
for (let def of this._listDefinitions.lists) {
writer.WritePropertyStart(def.name);
writer.WriteObjectStart();
for (let [key, value] of def.items) {
let item = InkListItem.fromSerializedKey(key);
let val = value;
writer.WriteIntProperty(item.itemName, val);
}
writer.WriteObjectEnd();
writer.WritePropertyEnd();
}
writer.WriteObjectEnd();
writer.WritePropertyEnd();
}
writer.WriteObjectEnd();
if (shouldReturn) return writer.toString();
}
public ResetState() {
this.IfAsyncWeCant("ResetState");
this._state = new StoryState(this);
this._state.variablesState.ObserveVariableChange(
this.VariableStateDidChangeEvent.bind(this)
);
this.ResetGlobals();
}
public ResetErrors() {
if (this._state === null) {
return throwNullException("this._state");
}
this._state.ResetErrors();
}
public ResetCallstack() {
this.IfAsyncWeCant("ResetCallstack");
if (this._state === null) {
return throwNullException("this._state");
}
this._state.ForceEnd();
}
public ResetGlobals() {
if (this._mainContentContainer.namedContent.get("global decl")) {
let originalPointer = this.state.currentPointer.copy();
this.ChoosePath(new Path("global decl"), false);
this.ContinueInternal();
this.state.currentPointer = originalPointer;
}
this.state.variablesState.SnapshotDefaultGlobals();
}
public SwitchFlow(flowName: string) {
this.IfAsyncWeCant("switch flow");
if (this._asyncSaving) {
throw new Error(
"Story is already in background saving mode, can't switch flow to " +
flowName
);
}
this.state.SwitchFlow_Internal(flowName);
}
public RemoveFlow(flowName: string) {
this.state.RemoveFlow_Internal(flowName);
}
public SwitchToDefaultFlow() {
this.state.SwitchToDefaultFlow_Internal();
}
public Continue() {
this.ContinueAsync(0);
return this.currentText;
}
get canContinue() {
return this.state.canContinue;
}
get asyncContinueComplete() {
return !this._asyncContinueActive;
}
public ContinueAsync(millisecsLimitAsync: number) {
if (!this._hasValidatedExternals) this.ValidateExternalBindings();
this.ContinueInternal(millisecsLimitAsync);
}
public ContinueInternal(millisecsLimitAsync = 0) {
if (this._profiler != null) this._profiler.PreContinue();
let isAsyncTimeLimited = millisecsLimitAsync > 0;
this._recursiveContinueCount++;
if (!this._asyncContinueActive) {
this._asyncContinueActive = isAsyncTimeLimited;
if (!this.canContinue) {
throw new Error(
"Can't continue - should check canContinue before calling Continue"
);
}
this._state.didSafeExit = false;
this._state.ResetOutput();
if (this._recursiveContinueCount == 1)
this._state.variablesState.batchObservingVariableChanges = true;
}
let durationStopwatch = new Stopwatch();
durationStopwatch.Start();
let outputStreamEndsInNewline = false;
this._sawLookaheadUnsafeFunctionAfterNewline = false;
do {
try {
outputStreamEndsInNewline = this.ContinueSingleStep();
} catch (e) {
if (!(e instanceof StoryException)) throw e;
this.AddError(e.message, undefined, e.useEndLineNumber);
break;
}
if (outputStreamEndsInNewline) break;
if (
this._asyncContinueActive &&
durationStopwatch.ElapsedMilliseconds > millisecsLimitAsync
) {
break;
}
} while (this.canContinue);
durationStopwatch.Stop();
if (outputStreamEndsInNewline || !this.canContinue) {
if (this._stateSnapshotAtLastNewline !== null) {
this.RestoreStateSnapshot();
}
if (!this.canContinue) {
if (this.state.callStack.canPopThread)
this.AddError(
"Thread available to pop, threads should always be flat by the end of evaluation?"
);
if (
this.state.generatedChoices.length == 0 &&
!this.state.didSafeExit &&
this._temporaryEvaluationContainer == null
) {
if (this.state.callStack.CanPop(PushPopType.Tunnel))
this.AddError(
"unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?"
);
else if (this.state.callStack.CanPop(PushPopType.Function))
this.AddError(
"unexpectedly reached end of content. Do you need a '~ return'?"
);
else if (!this.state.callStack.canPop)
this.AddError(
"ran out of content. Do you need a '-> DONE' or '-> END'?"
);
else
this.AddError(
"unexpectedly reached end of content for unknown reason. Please debug compiler!"
);
}
}
this.state.didSafeExit = false;
this._sawLookaheadUnsafeFunctionAfterNewline = false;
if (this._recursiveContinueCount == 1)
this._state.variablesState.batchObservingVariableChanges = false;
this._asyncContinueActive = false;
if (this.onDidContinue !== null) this.onDidContinue();
}
this._recursiveContinueCount--;
if (this._profiler != null) this._profiler.PostContinue();
// In the following code, we're masking a lot of non-null assertion,
// because testing for against `hasError` or `hasWarning` makes sure
// the arrays are present and contain at least one element.
if (this.state.hasError || this.state.hasWarning) {
if (this.onError !== null) {
if (this.state.hasError) {
for (let err of this.state.currentErrors!) {
this.onError(err, ErrorType.Error);
}
}
if (this.state.hasWarning) {
for (let err of this.state.currentWarnings!) {
this.onError(err, ErrorType.Warning);
}
}
this.ResetErrors();
} else {
let sb = new StringBuilder();
sb.Append("Ink had ");
if (this.state.hasError) {
sb.Append(`${this.state.currentErrors!.length}`);
sb.Append(
this.state.currentErrors!.length == 1 ? " error" : "errors"
);
if (this.state.hasWarning) sb.Append(" and ");
}
if (this.state.hasWarning) {
sb.Append(`${this.state.currentWarnings!.length}`);
sb.Append(
this.state.currentWarnings!.length == 1 ? " warning" : "warnings"
);
if (this.state.hasWarning) sb.Append(" and ");
}
sb.Append(
". It is strongly suggested that you assign an error handler to story.onError. The first issue was: "
);
sb.Append(
this.state.hasError
? this.state.currentErrors![0]
: this.state.currentWarnings![0]
);
throw new StoryException(sb.toString());
}
}
}
public ContinueSingleStep() {
if (this._profiler != null) this._profiler.PreStep();
this.Step();
if (this._profiler != null) this._profiler.PostStep();
if (!this.canContinue && !this.state.callStack.elementIsEvaluateFromGame) {
this.TryFollowDefaultInvisibleChoice();
}
if (this._profiler != null) this._profiler.PreSnapshot();
if (!this.state.inStringEvaluation) {
if (this._stateSnapshotAtLastNewline !== null) {
if (this._stateSnapshotAtLastNewline.currentTags === null) {
return throwNullException("this._stateAtLastNewline.currentTags");
}
if (this.state.currentTags === null) {
return throwNullException("this.state.currentTags");
}
let change = this.CalculateNewlineOutputStateChange(
this._stateSnapshotAtLastNewline.currentText,
this.state.currentText,
this._stateSnapshotAtLastNewline.currentTags.length,
this.state.currentTags.length
);
if (
change == Story.OutputStateChange.ExtendedBeyondNewline ||
this._sawLookaheadUnsafeFunctionAfterNewline
) {
this.RestoreStateSnapshot();
return true;
} else if (change == Story.OutputStateChange.NewlineRemoved) {
this.DiscardSnapshot();
}
}
if (this.state.outputStreamEndsInNewline) {
if (this.canContinue) {
if (this._stateSnapshotAtLastNewline == null) this.StateSnapshot();
} else {
this.DiscardSnapshot();
}
}
}
if (this._profiler != null) this._profiler.PostSnapshot();
return false;
}
public CalculateNewlineOutputStateChange(
prevText: string | null,
currText: string | null,
prevTagCount: number,
currTagCount: number
) {
if (prevText === null) {
return throwNullException("prevText");
}
if (currText === null) {
return throwNullException("currText");
}
let newlineStillExists =
currText.length >= prevText.length &&
currText.charAt(prevText.length - 1) == "\n";
if (
prevTagCount == currTagCount &&
prevText.length == currText.length &&
newlineStillExists
)
return Story.OutputStateChange.NoChange;
if (!newlineStillExists) {
return Story.OutputStateChange.NewlineRemoved;
}
if (currTagCount > prevTagCount)
return Story.OutputStateChange.ExtendedBeyondNewline;
for (let i = prevText.length; i < currText.length; i++) {
let c = currText.charAt(i);
if (c != " " && c != "\t") {
return Story.OutputStateChange.ExtendedBeyondNewline;
}
}
return Story.OutputStateChange.NoChange;
}
public ContinueMaximally() {
this.IfAsyncWeCant("ContinueMaximally");
let sb = new StringBuilder();
while (this.canContinue) {
sb.Append(this.Continue());
}
return sb.toString();
}
public ContentAtPath(path: Path) {
return this.mainContentContainer.ContentAtPath(path);
}
public KnotContainerWithName(name: string) {
let namedContainer = this.mainContentContainer.namedContent.get(name);
if (namedContainer instanceof Container) return namedContainer;
else return null;
}
public PointerAtPath(path: Path) {
if (path.length == 0) return Pointer.Null;
let p = new Pointer();
let pathLengthToUse = path.length;
let result = null;
if (path.lastComponent === null) {
return throwNullException("path.lastComponent");
}
if (path.lastComponent.isIndex) {
pathLengthToUse = path.length - 1;
result = this.mainContentContainer.ContentAtPath(
path,
undefined,
pathLengthToUse
);
p.container = result.container;
p.index = path.lastComponent.index;
} else {
result = this.mainContentContainer.ContentAtPath(path);
p.container = result.container;
p.index = -1;
}
if (
result.obj == null ||
(result.obj == this.mainContentContainer && pathLengthToUse > 0)
) {
this.Error(
"Failed to find content at path '" +
path +
"', and no approximation of it was possible."
);
} else if (result.approximate)
this.Warning(
"Failed to find content at path '" +
path +
"', so it was approximated to: '" +
result.obj.path +
"'."
);
return p;
}
public StateSnapshot() {
this._stateSnapshotAtLastNewline = this._state;
this._state = this._state.CopyAndStartPatching();
}
public RestoreStateSnapshot() {
if (this._stateSnapshotAtLastNewline === null) {
throwNullException("_stateSnapshotAtLastNewline");
}
this._stateSnapshotAtLastNewline.RestoreAfterPatch();
this._state = this._stateSnapshotAtLastNewline;
this._stateSnapshotAtLastNewline = null;
if (!this._asyncSaving) {
this._state.ApplyAnyPatch();
}
}
public DiscardSnapshot() {
if (!this._asyncSaving) this._state.ApplyAnyPatch();
this._stateSnapshotAtLastNewline = null;
}
public CopyStateForBackgroundThreadSave() {
this.IfAsyncWeCant("start saving on a background thread");
if (this._asyncSaving)
throw new Error(
"Story is already in background saving mode, can't call CopyStateForBackgroundThreadSave again!"
);
let stateToSave = this._state;
this._state = this._state.CopyAndStartPatching();
this._asyncSaving = true;
return stateToSave;
}
public BackgroundSaveComplete() {
if (this._stateSnapshotAtLastNewline === null) {
this._state.ApplyAnyPatch();
}
this._asyncSaving = false;
}
public Step() {
let shouldAddToStream = true;
let pointer = this.state.currentPointer.copy();
if (pointer.isNull) {
return;
}
// Container containerToEnter = pointer.Resolve () as Container;
let containerToEnter = asOrNull(pointer.Resolve(), Container);
while (containerToEnter) {
this.VisitContainer(containerToEnter, true);
// No content? the most we can do is step past it
if (containerToEnter.content.length == 0) {
break;
}
pointer = Pointer.StartOf(containerToEnter);
// containerToEnter = pointer.Resolve() as Container;
containerToEnter = asOrNull(pointer.Resolve(), Container);
}
this.state.currentPointer = pointer.copy();
if (this._profiler != null) this._profiler.Step(this.state.callStack);
// Is the current content object:
// - Normal content
// - Or a logic/flow statement - if so, do it
// Stop flow if we hit a stack pop when we're unable to pop (e.g. return/done statement in knot
// that was diverted to rather than called as a function)
let currentContentObj = pointer.Resolve();
let isLogicOrFlowControl = this.PerformLogicAndFlowControl(
currentContentObj
);
// Has flow been forced to end by flow control above?
if (this.state.currentPointer.isNull) {
return;
}
if (isLogicOrFlowControl) {
shouldAddToStream = false;
}
// Choice with condition?
// var choicePoint = currentContentObj as ChoicePoint;
let choicePoint = asOrNull(currentContentObj, ChoicePoint);
if (choicePoint) {
let choice = this.ProcessChoice(choicePoint);
if (choice) {
this.state.generatedChoices.push(choice);
}
currentContentObj = null;
shouldAddToStream = false;
}
// If the container has no content, then it will be
// the "content" itself, but we skip over it.
if (currentContentObj instanceof Container) {
shouldAddToStream = false;
}
// Content to add to evaluation stack or the output stream
if (shouldAddToStream) {
// If we're pushing a variable pointer onto the evaluation stack, ensure that it's specific
// to our current (possibly temporary) context index. And make a copy of the pointer
// so that we're not editing the original runtime object.
// var varPointer = currentContentObj as VariablePointerValue;
let varPointer = asOrNull(currentContentObj, VariablePointerValue);
if (varPointer && varPointer.contextIndex == -1) {
// Create new object so we're not overwriting the story's own data
let contextIdx = this.state.callStack.ContextForVariableNamed(
varPointer.variableName
);
currentContentObj = new VariablePointerValue(
varPointer.variableName,
contextIdx
);
}
// Expression evaluation content
if (this.state.inExpressionEvaluation) {
this.state.PushEvaluationStack(currentContentObj);
}
// Output stream content (i.e. not expression evaluation)
else {
this.state.PushToOutputStream(currentContentObj);
}
}
// Increment the content pointer, following diverts if necessary
this.NextContent();
// Starting a thread should be done after the increment to the content pointer,
// so that when returning from the thread, it returns to the content after this instruction.
// var controlCmd = currentContentObj as ;
let controlCmd = asOrNull(currentContentObj, ControlCommand);
if (
controlCmd &&
controlCmd.commandType == ControlCommand.CommandType.StartThread
) {
this.state.callStack.PushThread();
}
}
public VisitContainer(container: Container, atStart: boolean) {
if (!container.countingAtStartOnly || atStart) {
if (container.visitsShouldBeCounted)
this.state.IncrementVisitCountForContainer(container);
if (container.turnIndexShouldBeCounted)
this.state.RecordTurnIndexVisitToContainer(container);
}
}
private _prevContainers: Container[] = [];
public VisitChangedContainersDueToDivert() {
let previousPointer = this.state.previousPointer.copy();
let pointer = this.state.currentPointer.copy();
if (pointer.isNull || pointer.index == -1) return;
this._prevContainers.length = 0;
if (!previousPointer.isNull) {
// Container prevAncestor = previousPointer.Resolve() as Container ?? previousPointer.container as Container;
let resolvedPreviousAncestor = previousPointer.Resolve();
let prevAncestor =
asOrNull(resolvedPreviousAncestor, Container) ||
asOrNull(previousPointer.container, Container);
while (prevAncestor) {
this._prevContainers.push(prevAncestor);
// prevAncestor = prevAncestor.parent as Container;
prevAncestor = asOrNull(prevAncestor.parent, Container);
}
}
let currentChildOfContainer = pointer.Resolve();
if (currentChildOfContainer == null) return;
// Container currentContainerAncestor = currentChildOfContainer.parent as Container;
let currentContainerAncestor = asOrNull(
currentChildOfContainer.parent,
Container
);
let allChildrenEnteredAtStart = true;
while (
currentContainerAncestor &&
(this._prevContainers.indexOf(currentContainerAncestor) < 0 ||
currentContainerAncestor.countingAtStartOnly)
) {
// Check whether this ancestor container is being entered at the start,
// by checking whether the child object is the first.
let enteringAtStart =
currentContainerAncestor.content.length > 0 &&
currentChildOfContainer == currentContainerAncestor.content[0] &&
allChildrenEnteredAtStart;
if (!enteringAtStart) allChildrenEnteredAtStart = false;
// Mark a visit to this container
this.VisitContainer(currentContainerAncestor, enteringAtStart);
currentChildOfContainer = currentContainerAncestor;
// currentContainerAncestor = currentContainerAncestor.parent as Container;
currentContainerAncestor = asOrNull(
currentContainerAncestor.parent,
Container
);
}
}
public ProcessChoice(choicePoint: ChoicePoint) {
let showChoice = true;
// Don't create choice if choice point doesn't pass conditional
if (choicePoint.hasCondition) {
let conditionValue = this.state.PopEvaluationStack();
if (!this.IsTruthy(conditionValue)) {
showChoice = false;
}
}
let startText = "";
let choiceOnlyText = "";
if (choicePoint.hasChoiceOnlyContent) {
// var choiceOnlyStrVal = state.PopEvaluationStack () as StringValue;
let choiceOnlyStrVal = asOrThrows(
this.state.PopEvaluationStack(),
StringValue
);
choiceOnlyText = choiceOnlyStrVal.value || "";
}
if (choicePoint.hasStartContent) {
// var startStrVal = state.PopEvaluationStack () as StringValue;
let startStrVal = asOrThrows(
this.state.PopEvaluationStack(),
StringValue
);
startText = startStrVal.value || "";
}
// Don't create choice if player has already read this content
if (choicePoint.onceOnly) {
let visitCount = this.state.VisitCountForContainer(
choicePoint.choiceTarget
);
if (visitCount > 0) {
showChoice = false;
}
}
// We go through the full process of creating the choice above so
// that we consume the content for it, since otherwise it'll
// be shown on the output stream.
if (!showChoice) {
return null;
}
let choice = new Choice();
choice.targetPath = choicePoint.pathOnChoice;
choice.sourcePath = choicePoint.path.toString();
choice.isInvisibleDefault = choicePoint.isInvisibleDefault;
choice.threadAtGeneration = this.state.callStack.ForkThread();
choice.text = (startText + choiceOnlyText).replace(/^[ \t]+|[ \t]+$/g, "");
return choice;
}
public IsTruthy(obj: InkObject) {
let truthy = false;
if (obj instanceof Value) {
let val = obj;
if (val instanceof DivertTargetValue) {
let divTarget = val;
this.Error(
"Shouldn't use a divert target (to " +
divTarget.targetPath +
") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)"
);
return false;
}
return val.isTruthy;
}
return truthy;
}
public PerformLogicAndFlowControl(contentObj: InkObject | null) {
if (contentObj == null) {
return false;
}
// Divert
if (contentObj instanceof Divert) {
let currentDivert = contentObj;
if (currentDivert.isConditional) {
let conditionValue = this.state.PopEvaluationStack();
// False conditional? Cancel divert
if (!this.IsTruthy(conditionValue)) return true;
}
if (currentDivert.hasVariableTarget) {
let varName = currentDivert.variableDivertName;
let varContents = this.state.variablesState.GetVariableWithName(
varName
);
if (varContents == null) {
this.Error(
"Tried to divert using a target from a variable that could not be found (" +
varName +
")"
);
} else if (!(varContents instanceof DivertTargetValue)) {
// var intContent = varContents as IntValue;
let intContent = asOrNull(varContents, IntValue);
let errorMessage =
"Tried to divert to a target from a variable, but the variable (" +
varName +
") didn't contain a divert target, it ";
if (intContent instanceof IntValue && intContent.value == 0) {
errorMessage += "was empty/null (the value 0).";