-
Notifications
You must be signed in to change notification settings - Fork 7
/
Story.java
2882 lines (2327 loc) · 111 KB
/
Story.java
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
package com.bladecoder.ink.runtime;
import com.bladecoder.ink.runtime.Error.ErrorType;
import com.bladecoder.ink.runtime.SimpleJson.InnerWriter;
import com.bladecoder.ink.runtime.SimpleJson.Writer;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Stack;
/**
* A Story is the core class that represents a complete Ink narrative, and
* manages the evaluation and state of it.
*/
public class Story implements VariablesState.VariableChanged {
/**
* General purpose delegate definition for bound EXTERNAL function definitions
* from ink. Note that this version isn't necessary if you have a function with
* three arguments or less.
*
* @param <R> the result type
* @see ExternalFunction0
* @see ExternalFunction1
* @see ExternalFunction2
* @see ExternalFunction3
*/
public interface ExternalFunction<R> {
R call(Object... args) throws Exception;
}
/**
* EXTERNAL function delegate with zero arguments.
*
* @param <R> the result type
*/
public abstract static class ExternalFunction0<R> implements ExternalFunction<R> {
@Override
public final R call(Object... args) throws Exception {
if (args.length != 0) {
throw new IllegalArgumentException("Expecting 0 arguments.");
}
return call();
}
protected abstract R call() throws Exception;
}
/**
* EXTERNAL function delegate with one argument.
*
* @param <T> the argument type
* @param <R> the result type
*/
public abstract static class ExternalFunction1<T, R> implements ExternalFunction<R> {
@Override
public final R call(Object... args) throws Exception {
if (args.length != 1) {
throw new IllegalArgumentException("Expecting 1 argument.");
}
return call(coerceArg(args[0]));
}
protected abstract R call(T t) throws Exception;
@SuppressWarnings("unchecked")
protected T coerceArg(Object arg) throws Exception {
return (T) arg;
}
}
/**
* EXTERNAL function delegate with two arguments.
*
* @param <T1> the first argument type
* @param <T2> the second argument type
* @param <R> the result type
*/
public abstract static class ExternalFunction2<T1, T2, R> implements ExternalFunction<R> {
@Override
public final R call(Object... args) throws Exception {
if (args.length != 2) {
throw new IllegalArgumentException("Expecting 2 arguments.");
}
return call(coerceArg0(args[0]), coerceArg1(args[1]));
}
protected abstract R call(T1 t1, T2 t2) throws Exception;
@SuppressWarnings("unchecked")
protected T1 coerceArg0(Object arg) throws Exception {
return (T1) arg;
}
@SuppressWarnings("unchecked")
protected T2 coerceArg1(Object arg) throws Exception {
return (T2) arg;
}
}
/**
* EXTERNAL function delegate with three arguments.
*
* @param <T1> the first argument type
* @param <T2> the second argument type
* @param <T3> the third argument type
* @param <R> the result type
*/
public abstract static class ExternalFunction3<T1, T2, T3, R> implements ExternalFunction<R> {
@Override
public final R call(Object... args) throws Exception {
if (args.length != 3) {
throw new IllegalArgumentException("Expecting 3 arguments.");
}
return call(coerceArg0(args[0]), coerceArg1(args[1]), coerceArg2(args[2]));
}
protected abstract R call(T1 t1, T2 t2, T3 t3) throws Exception;
@SuppressWarnings("unchecked")
protected T1 coerceArg0(Object arg) throws Exception {
return (T1) arg;
}
@SuppressWarnings("unchecked")
protected T2 coerceArg1(Object arg) throws Exception {
return (T2) arg;
}
@SuppressWarnings("unchecked")
protected T3 coerceArg2(Object arg) throws Exception {
return (T3) arg;
}
}
static class ExternalFunctionDef {
public ExternalFunction<?> function;
public boolean lookaheadSafe;
}
// Version numbers are for engine itself and story file, rather
// than the story state save format
// -- old engine, new format: always fail
// -- new engine, old format: possibly cope, based on this number
// When incrementing the version number above, the question you
// should ask yourself is:
// -- Will the engine be able to load an old story file from
// before I made these changes to the engine?
// If possible, you should support it, though it's not as
// critical as loading old save games, since it's an
// in-development problem only.
/**
* Delegate definition for variable observation - see ObserveVariable.
*/
public interface VariableObserver {
void call(String variableName, Object newValue);
}
/**
* The current version of the ink story file format.
*/
public static final int inkVersionCurrent = 21;
/**
* The minimum legacy version of ink that can be loaded by the current version
* of the code.
*/
public static final int inkVersionMinimumCompatible = 18;
private Container mainContentContainer;
private ListDefinitionsOrigin listDefinitions;
/**
* An ink file can provide a fallback functions for when when an EXTERNAL has
* been left unbound by the client, and the fallback function will be called
* instead. Useful when testing a story in playmode, when it's not possible to
* write a client-side C# external function, but you don't want it to fail to
* run.
*/
private boolean allowExternalFunctionFallbacks;
private final HashMap<String, ExternalFunctionDef> externals;
private boolean hasValidatedExternals;
private StoryState state;
private Container temporaryEvaluationContainer;
private HashMap<String, List<VariableObserver>> variableObservers;
private final List<Container> prevContainers = new ArrayList<>();
private Profiler profiler;
private boolean asyncContinueActive;
private StoryState stateSnapshotAtLastNewline = null;
private int recursiveContinueCount = 0;
private boolean asyncSaving;
private boolean sawLookaheadUnsafeFunctionAfterNewline = false;
public Error.ErrorHandler onError = null;
// Warning: When creating a Story using this constructor, you need to
// call ResetState on it before use. Intended for compiler use only.
// For normal use, use the constructor that takes a json string.
public Story(Container contentContainer, List<ListDefinition> lists) {
mainContentContainer = contentContainer;
if (lists != null) {
listDefinitions = new ListDefinitionsOrigin(lists);
}
externals = new HashMap<>();
}
public Story(Container contentContainer) {
this(contentContainer, null);
}
/**
* Construct a Story Object using a JSON String compiled through inklecate.
*/
public Story(String jsonString) throws Exception {
this((Container) null);
HashMap<String, Object> rootObject = SimpleJson.textToDictionary(jsonString);
Object versionObj = rootObject.get("inkVersion");
if (versionObj == null)
throw new Exception("ink version number not found. Are you sure it's a valid .ink.json file?");
int formatFromFile = versionObj instanceof String ? Integer.parseInt((String) versionObj) : (int) versionObj;
if (formatFromFile > inkVersionCurrent) {
throw new Exception("Version of ink used to build story was newer than the current version of the engine");
} else if (formatFromFile < inkVersionMinimumCompatible) {
throw new Exception(
"Version of ink used to build story is too old to be loaded by this version of the engine");
} else if (formatFromFile != inkVersionCurrent) {
System.out.println("WARNING: Version of ink used to build story doesn't match current version of engine. "
+ "Non-critical, but recommend synchronising.");
}
Object rootToken = rootObject.get("root");
if (rootToken == null)
throw new Exception("Root node for ink not found. Are you sure it's a valid .ink.json file?");
Object listDefsObj = rootObject.get("listDefs");
if (listDefsObj != null) {
listDefinitions = Json.jTokenToListDefinitions(listDefsObj);
}
RTObject runtimeObject = Json.jTokenToRuntimeObject(rootToken);
mainContentContainer = runtimeObject instanceof Container ? (Container) runtimeObject : null;
resetState();
}
void addError(String message) throws Exception {
addError(message, false, false);
}
void warning(String message) throws Exception {
addError(message, true, false);
}
void addError(String message, boolean isWarning, boolean useEndLineNumber) throws Exception {
DebugMetadata dm = currentDebugMetadata();
String errorTypeStr = isWarning ? "WARNING" : "ERROR";
if (dm != null) {
int lineNum = useEndLineNumber ? dm.endLineNumber : dm.startLineNumber;
message = String.format("RUNTIME %s: '%s' line %d: %s", errorTypeStr, dm.fileName, lineNum, message);
} else if (!state.getCurrentPointer().isNull()) {
message = String.format(
"RUNTIME %s: (%s): %s",
errorTypeStr, state.getCurrentPointer().getPath().toString(), message);
} else {
message = "RUNTIME " + errorTypeStr + ": " + message;
}
state.addError(message, isWarning);
// In a broken state don't need to know about any other errors.
if (!isWarning) state.forceEnd();
}
/**
* Start recording ink profiling information during calls to Continue on Story.
* Return a Profiler instance that you can request a report from when you're
* finished.
*
* @throws Exception
*/
public Profiler startProfiling() throws Exception {
ifAsyncWeCant("start profiling");
profiler = new Profiler();
return profiler;
}
/**
* Stop recording ink profiling information during calls to Continue on Story.
* To generate a report from the profiler, call
*/
public void endProfiling() {
profiler = null;
}
void Assert(boolean condition, Object... formatParams) throws Exception {
Assert(condition, null, formatParams);
}
void Assert(boolean condition, String message, Object... formatParams) throws Exception {
if (!condition) {
if (message == null) {
message = "Story assert";
}
if (formatParams != null && formatParams.length > 0) {
message = String.format(message, formatParams);
}
throw new Exception(message + " " + currentDebugMetadata());
}
}
/**
* Binds a Java function to an ink EXTERNAL function.
*
* @param funcName EXTERNAL ink function name to bind to.
* @param func The Java function to bind.
* @param lookaheadSafe The ink engine often evaluates further than you might
* expect beyond the current line just in case it sees glue
* that will cause the two lines to become one. In this
* case it's possible that a function can appear to be
* called twice instead of just once, and earlier than you
* expect. If it's safe for your function to be called in
* this way (since the result and side effect of the
* function will not change), then you can pass 'true'.
* Usually, you want to pass 'false', especially if you
* want some action to be performed in game code when this
* function is called.
*/
public void bindExternalFunction(String funcName, ExternalFunction<?> func, boolean lookaheadSafe)
throws Exception {
ifAsyncWeCant("bind an external function");
Assert(!externals.containsKey(funcName), "Function '" + funcName + "' has already been bound.");
ExternalFunctionDef externalFunctionDef = new ExternalFunctionDef();
externalFunctionDef.function = func;
externalFunctionDef.lookaheadSafe = lookaheadSafe;
externals.put(funcName, externalFunctionDef);
}
public void bindExternalFunction(String funcName, ExternalFunction<?> func) throws Exception {
bindExternalFunction(funcName, func, true);
}
@SuppressWarnings("unchecked")
public <T> T tryCoerce(Object value, Class<T> type) throws Exception {
if (value == null) return null;
if (type.isAssignableFrom(value.getClass())) return (T) value;
if (value instanceof Float && type == Integer.class) {
Integer intVal = (int) Math.round((Float) value);
return (T) intVal;
}
if (value instanceof Integer && type == Float.class) {
Float floatVal = Float.valueOf((Integer) value);
return (T) floatVal;
}
if (value instanceof Integer && type == Boolean.class) {
int intVal = (Integer) value;
return (T) (intVal == 0 ? Boolean.FALSE : Boolean.TRUE);
}
if (value instanceof Boolean && type == Integer.class) {
boolean val = (Boolean) value;
return (T) (val ? (Integer) 1 : (Integer) 0);
}
if (type == String.class) {
return (T) value.toString();
}
Assert(false, "Failed to cast " + value.getClass().getCanonicalName() + " to " + type.getCanonicalName());
return null;
}
/**
* Get any global tags associated with the story. These are defined as hash tags
* defined at the very top of the story.
*
* @throws Exception
*/
public List<String> getGlobalTags() throws Exception {
return tagsAtStartOfFlowContainerWithPathString("");
}
/**
* Gets any tags associated with a particular knot or knot.stitch. These are
* defined as hash tags defined at the very top of a knot or stitch.
*
* @param path The path of the knot or stitch, in the form "knot" or
* "knot.stitch".
* @throws Exception
*/
public List<String> tagsForContentAtPath(String path) throws Exception {
return tagsAtStartOfFlowContainerWithPathString(path);
}
List<String> tagsAtStartOfFlowContainerWithPathString(String pathString) throws Exception {
Path path = new Path(pathString);
// Expected to be global story, knot or stitch
Container flowContainer = contentAtPath(path).getContainer();
while (true) {
RTObject firstContent = flowContainer.getContent().get(0);
if (firstContent instanceof Container) flowContainer = (Container) firstContent;
else break;
}
// Any initial tag objects count as the "main tags" associated with that
// story/knot/stitch
boolean inTag = false;
List<String> tags = null;
for (RTObject c : flowContainer.getContent()) {
if (c instanceof ControlCommand) {
ControlCommand command = (ControlCommand) c;
if (command.getCommandType() == ControlCommand.CommandType.BeginTag) {
inTag = true;
} else if (command.getCommandType() == ControlCommand.CommandType.EndTag) {
inTag = false;
}
} else if (inTag) {
if (c instanceof StringValue) {
StringValue str = (StringValue) c;
if (tags == null) tags = new ArrayList<>();
tags.add(str.value);
} else {
error("Tag contained non-text content. Only plain text is allowed when using globalTags or "
+ "TagsAtContentPath. If you want to evaluate dynamic content, you need to use story"
+ ".Continue().");
}
}
// Any other content - we're done
// We only recognise initial text-only tags
else {
break;
}
}
return tags;
}
/**
* Useful when debugging a (very short) story, to visualise the state of the
* story. Add this call as a watch and open the extended text. A left-arrow mark
* will denote the current point of the story. It's only recommended that this
* is used on very short debug stories, since it can end up generate a large
* quantity of text otherwise.
*/
public String buildStringOfHierarchy() {
StringBuilder sb = new StringBuilder();
getMainContentContainer()
.buildStringOfHierarchy(sb, 0, state.getCurrentPointer().resolve());
return sb.toString();
}
public ExternalFunction<?> getExternalFunction(String functionName) {
ExternalFunctionDef externalFunctionDef = externals.get(functionName);
if (externalFunctionDef != null) {
return externalFunctionDef.function;
}
return null;
}
void callExternalFunction(String funcName, int numberOfArguments) throws Exception {
ExternalFunctionDef funcDef;
Container fallbackFunctionContainer = null;
funcDef = externals.get(funcName);
// Should this function break glue? Abort run if we've already seen a newline.
// Set a bool to tell it to restore the snapshot at the end of this instruction.
if (funcDef != null && !funcDef.lookaheadSafe && stateSnapshotAtLastNewline != null) {
sawLookaheadUnsafeFunctionAfterNewline = true;
return;
}
// Try to use fallback function?
if (funcDef == null) {
if (allowExternalFunctionFallbacks) {
fallbackFunctionContainer = knotContainerWithName(funcName);
Assert(
fallbackFunctionContainer != null,
"Trying to call EXTERNAL function '" + funcName
+ "' which has not been bound, and fallback ink function could not be found.");
// Divert direct into fallback function and we're done
state.getCallStack()
.push(PushPopType.Function, 0, state.getOutputStream().size());
state.setDivertedPointer(Pointer.startOf(fallbackFunctionContainer));
return;
} else {
Assert(
false,
"Trying to call EXTERNAL function '" + funcName
+ "' which has not been bound (and ink fallbacks disabled).");
}
}
// Pop arguments
ArrayList<Object> arguments = new ArrayList<>();
for (int i = 0; i < numberOfArguments; ++i) {
Value<?> poppedObj = (Value<?>) state.popEvaluationStack();
Object valueObj = poppedObj.getValueObject();
arguments.add(valueObj);
}
// Reverse arguments from the order they were popped,
// so they're the right way round again.
Collections.reverse(arguments);
// Run the function!
Object funcResult = funcDef.function.call(arguments.toArray());
// Convert return value (if any) to the a type that the ink engine can use
RTObject returnObj;
if (funcResult != null) {
returnObj = AbstractValue.create(funcResult);
Assert(
returnObj != null,
"Could not create ink value from returned Object of type "
+ funcResult.getClass().getCanonicalName());
} else {
returnObj = new Void();
}
state.pushEvaluationStack(returnObj);
}
/**
* Check whether more content is available if you were to call Continue() - i.e.
* are we mid story rather than at a choice point or at the end.
*
* @return true if it's possible to call Continue()
*/
public boolean canContinue() {
return state.canContinue();
}
/**
* Chooses the Choice from the currentChoices list with the given index.
* Internally, this sets the current content path to that pointed to by the
* Choice, ready to continue story evaluation.
*/
public void chooseChoiceIndex(int choiceIdx) throws Exception {
List<Choice> choices = getCurrentChoices();
Assert(choiceIdx >= 0 && choiceIdx < choices.size(), "choice out of range");
// Replace callstack with the one from the thread at the choosing point,
// so that we can jump into the right place in the flow.
// This is important in case the flow was forked by a new thread, which
// can create multiple leading edges for the story, each of
// which has its own context.
Choice choiceToChoose = choices.get(choiceIdx);
state.getCallStack().setCurrentThread(choiceToChoose.getThreadAtGeneration());
choosePath(choiceToChoose.targetPath);
}
void choosePath(Path p) throws Exception {
choosePath(p, true);
}
void choosePath(Path p, boolean incrementingTurnIndex) throws Exception {
state.setChosenPath(p, incrementingTurnIndex);
// Take a note of newly visited containers for read counts etc
visitChangedContainersDueToDivert();
}
/**
* Change the current position of the story to the given path. From here you can
* call Continue() to evaluate the next line.
* <p>
* The path String is a dot-separated path as used ly by the engine. These
* examples should work:
* <p>
* myKnot myKnot.myStitch
* <p>
* Note however that this won't necessarily work:
* <p>
* myKnot.myStitch.myLabelledChoice
* <p>
* ...because of the way that content is nested within a weave structure.
* <p>
* By default this will reset the callstack beforehand, which means that any
* tunnels, threads or functions you were in at the time of calling will be
* discarded. This is different from the behaviour of ChooseChoiceIndex, which
* will always keep the callstack, since the choices are known to come from the
* correct state, and known their source thread.
* <p>
* You have the option of passing false to the resetCallstack parameter if you
* don't want this behaviour, and will leave any active threads, tunnels or
* function calls in-tact.
* <p>
* This is potentially dangerous! If you're in the middle of a tunnel, it'll
* redirect only the inner-most tunnel, meaning that when you tunnel-return
* using '->->->', it'll return to where you were before. This may be
* what you want though. However, if you're in the middle of a function,
* ChoosePathString will throw an exception.
*
* @param path A dot-separted path string, as specified above.
* @param resetCallstack Whether to reset the callstack first (see summary
* description).
* @param arguments Optional set of arguments to pass, if path is to a knot
* that takes them.
*/
public void choosePathString(String path, boolean resetCallstack, Object[] arguments) throws Exception {
ifAsyncWeCant("call ChoosePathString right now");
if (resetCallstack) {
resetCallstack();
} else {
// ChoosePathString is potentially dangerous since you can call it when the
// stack is
// pretty much in any state. Let's catch one of the worst offenders.
if (state.getCallStack().getCurrentElement().type == PushPopType.Function) {
String funcDetail = "";
Container container = state.getCallStack().getCurrentElement().currentPointer.container;
if (container != null) {
funcDetail = "(" + container.getPath().toString() + ") ";
}
throw new Exception("Story was running a function " + funcDetail + "when you called ChoosePathString("
+ path + ") - this is almost certainly not not what you want! Full stack trace: \n"
+ state.getCallStack().getCallStackTrace());
}
}
state.passArgumentsToEvaluationStack(arguments);
choosePath(new Path(path));
}
public void choosePathString(String path) throws Exception {
choosePathString(path, true, null);
}
public void choosePathString(String path, boolean resetCallstack) throws Exception {
choosePathString(path, resetCallstack, null);
}
void ifAsyncWeCant(String activityStr) throws Exception {
if (asyncContinueActive)
throw new Exception("Can't " + activityStr
+ ". Story is in the middle of a ContinueAsync(). Make more ContinueAsync() calls or a single "
+ "Continue() call beforehand.");
}
SearchResult contentAtPath(Path path) throws Exception {
return getMainContentContainer().contentAtPath(path);
}
Container knotContainerWithName(String name) {
INamedContent namedContainer = mainContentContainer.getNamedContent().get(name);
if (namedContainer != null) return namedContainer instanceof Container ? (Container) namedContainer : null;
else return null;
}
/**
* The current flow name if using multi-flow functionality - see SwitchFlow
*/
public String getCurrentFlowName() {
return state.getCurrentFlowName();
}
/**
* Is the default flow currently active? By definition, will also return true if not using multi-flow
* functionality - see SwitchFlow
*/
public boolean currentFlowIsDefaultFlow() {
return state.currentFlowIsDefaultFlow();
}
/**
* Names of currently alive flows (not including the default flow)
*/
public List<String> aliveFlowNames() {
return state.aliveFlowNames();
}
public void switchFlow(String flowName) throws Exception {
ifAsyncWeCant("switch flow");
if (asyncSaving)
throw new Exception("Story is already in background saving mode, can't switch flow to " + flowName);
state.switchFlowInternal(flowName);
}
public void removeFlow(String flowName) throws Exception {
state.removeFlowInternal(flowName);
}
public void switchToDefaultFlow() throws Exception {
state.switchToDefaultFlowInternal();
}
/**
* Continue the story for one line of content, if possible. If you're not sure
* if there's more content available, for example if you want to check whether
* you're at a choice point or at the end of the story, you should call
* canContinue before calling this function.
*
* @return The line of text content.
*/
public String Continue() throws StoryException, Exception {
continueAsync(0);
return getCurrentText();
}
/**
* If ContinueAsync was called (with milliseconds limit > 0) then this
* property will return false if the ink evaluation isn't yet finished, and you
* need to call it again in order for the Continue to fully complete.
*/
public boolean asyncContinueComplete() {
return !asyncContinueActive;
}
/**
* An "asnychronous" version of Continue that only partially evaluates the ink,
* with a budget of a certain time limit. It will exit ink evaluation early if
* the evaluation isn't complete within the time limit, with the
* asyncContinueComplete property being false. This is useful if ink evaluation
* takes a long time, and you want to distribute it over multiple game frames
* for smoother animation. If you pass a limit of zero, then it will fully
* evaluate the ink in the same way as calling Continue (and in fact, this
* exactly what Continue does internally).
*/
public void continueAsync(float millisecsLimitAsync) throws Exception {
if (!hasValidatedExternals) validateExternalBindings();
continueInternal(millisecsLimitAsync);
}
void continueInternal() throws Exception {
continueInternal(0);
}
void continueInternal(float millisecsLimitAsync) throws Exception {
if (profiler != null) profiler.preContinue();
boolean isAsyncTimeLimited = millisecsLimitAsync > 0;
recursiveContinueCount++;
// Doing either:
// - full run through non-async (so not active and don't want to be)
// - Starting async run-through
if (!asyncContinueActive) {
asyncContinueActive = isAsyncTimeLimited;
if (!canContinue()) {
throw new Exception("Can't continue - should check canContinue before calling Continue");
}
state.setDidSafeExit(false);
state.resetOutput();
// It's possible for ink to call game to call ink to call game etc
// In this case, we only want to batch observe variable changes
// for the outermost call.
if (recursiveContinueCount == 1) state.getVariablesState().setbatchObservingVariableChanges(true);
}
// Start timing
Stopwatch durationStopwatch = new Stopwatch();
durationStopwatch.start();
boolean outputStreamEndsInNewline = false;
sawLookaheadUnsafeFunctionAfterNewline = false;
do {
try {
outputStreamEndsInNewline = continueSingleStep();
} catch (StoryException e) {
addError(e.getMessage(), false, e.useEndLineNumber);
break;
}
if (outputStreamEndsInNewline) break;
// Run out of async time?
if (asyncContinueActive && durationStopwatch.getElapsedMilliseconds() > millisecsLimitAsync) {
break;
}
} while (canContinue());
durationStopwatch.stop();
// 4 outcomes:
// - got newline (so finished this line of text)
// - can't continue (e.g. choices or ending)
// - ran out of time during evaluation
// - error
//
// Successfully finished evaluation in time (or in error)
if (outputStreamEndsInNewline || !canContinue()) {
// Need to rewind, due to evaluating further than we should?
if (stateSnapshotAtLastNewline != null) {
restoreStateSnapshot();
}
// Finished a section of content / reached a choice point?
if (!canContinue()) {
if (state.getCallStack().canPopThread())
addError("Thread available to pop, threads should always be flat by the end of evaluation?");
if (state.getGeneratedChoices().size() == 0
&& !state.isDidSafeExit()
&& temporaryEvaluationContainer == null) {
if (state.getCallStack().canPop(PushPopType.Tunnel))
addError("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?");
else if (state.getCallStack().canPop(PushPopType.Function))
addError("unexpectedly reached end of content. Do you need a '~ return'?");
else if (!state.getCallStack().canPop())
addError("ran out of content. Do you need a '-> DONE' or '-> END'?");
else addError("unexpectedly reached end of content for unknown reason. Please debug compiler!");
}
}
state.setDidSafeExit(false);
sawLookaheadUnsafeFunctionAfterNewline = false;
if (recursiveContinueCount == 1) state.getVariablesState().setbatchObservingVariableChanges(false);
asyncContinueActive = false;
}
recursiveContinueCount--;
if (profiler != null) profiler.postContinue();
// Report any errors that occured during evaluation.
// This may either have been StoryExceptions that were thrown
// and caught during evaluation, or directly added with AddError.
if (state.hasError() || state.hasWarning()) {
if (onError != null) {
if (state.hasError()) {
for (String err : state.getCurrentErrors()) {
onError.error(err, ErrorType.Error);
}
}
if (state.hasWarning()) {
for (String err : state.getCurrentWarnings()) {
onError.error(err, ErrorType.Warning);
}
}
resetErrors();
}
// Throw an exception since there's no error handler
else {
StringBuilder sb = new StringBuilder();
sb.append("Ink had ");
if (state.hasError()) {
sb.append(state.getCurrentErrors().size());
sb.append(state.getCurrentErrors().size() == 1 ? " error" : " errors");
if (state.hasWarning()) sb.append(" and ");
}
if (state.hasWarning()) {
sb.append(state.getCurrentWarnings().size());
sb.append(state.getCurrentWarnings().size() == 1 ? " warning" : " warnings");
}
sb.append(". It is strongly suggested that you assign an error handler to story.onError. The first "
+ "issue was: ");
sb.append(
state.hasError()
? state.getCurrentErrors().get(0)
: state.getCurrentWarnings().get(0));
// If you get this exception, please assign an error handler to your story.
// If you're using Unity, you can do something like this when you create
// your story:
//
// var story = new Ink.Runtime.Story(jsonTxt);
// story.onError = (errorMessage, errorType) => {
// if( errorType == ErrorType.Warning )
// Debug.LogWarning(errorMessage);
// else
// Debug.LogError(errorMessage);
// };
//
//
throw new StoryException(sb.toString());
}
}
}
boolean continueSingleStep() throws Exception {
if (profiler != null) profiler.preStep();
// Run main step function (walks through content)
step();
if (profiler != null) profiler.postStep();
// Run out of content and we have a default invisible choice that we can follow?
if (!canContinue() && !state.getCallStack().elementIsEvaluateFromGame()) {
tryFollowDefaultInvisibleChoice();
}
if (profiler != null) profiler.preSnapshot();
// Don't save/rewind during string evaluation, which is e.g. used for choices
if (!state.inStringEvaluation()) {
// We previously found a newline, but were we just double checking that
// it wouldn't immediately be removed by glue?
if (stateSnapshotAtLastNewline != null) {
// Has proper text or a tag been added? Then we know that the newline
// that was previously added is definitely the end of the line.
OutputStateChange change = calculateNewlineOutputStateChange(
stateSnapshotAtLastNewline.getCurrentText(), state.getCurrentText(),
stateSnapshotAtLastNewline.getCurrentTags().size(),
state.getCurrentTags().size());
// The last time we saw a newline, it was definitely the end of the line, so we
// want to rewind to that point.
if (change == OutputStateChange.ExtendedBeyondNewline || sawLookaheadUnsafeFunctionAfterNewline) {
restoreStateSnapshot();
// Hit a newline for sure, we're done
return true;
}
// Newline that previously existed is no longer valid - e.g.
// glue was encounted that caused it to be removed.
else if (change == OutputStateChange.NewlineRemoved) {
stateSnapshotAtLastNewline = null;
discardSnapshot();
}
}
// Current content ends in a newline - approaching end of our evaluation
if (state.outputStreamEndsInNewline()) {
// If we can continue evaluation for a bit:
// Create a snapshot in case we need to rewind.
// We're going to continue stepping in case we see glue or some
// non-text content such as choices.
if (canContinue()) {
// Don't bother to record the state beyond the current newline.
// e.g.:
// Hello world\n // record state at the end of here
// ~ complexCalculation() // don't actually need this unless it generates text
if (stateSnapshotAtLastNewline == null) stateSnapshot();
}
// Can't continue, so we're about to exit - make sure we
// don't have an old state hanging around.
else {
discardSnapshot();
}
}
}