File: command.cpp

package info (click to toggle)
scummvm 2.9.1%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 450,580 kB
  • sloc: cpp: 4,299,825; asm: 28,322; python: 12,901; sh: 11,302; java: 9,289; xml: 7,895; perl: 2,639; ansic: 2,465; yacc: 1,670; javascript: 1,020; makefile: 933; lex: 578; awk: 275; objc: 82; sed: 11; php: 1
file content (1360 lines) | stat: -rw-r--r-- 44,132 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "engines/stark/resources/command.h"

#include "engines/stark/debug.h"

#include "engines/stark/formats/xrc.h"

#include "engines/stark/movement/followpath.h"
#include "engines/stark/movement/followpathlight.h"
#include "engines/stark/movement/turn.h"
#include "engines/stark/movement/walk.h"

#include "engines/stark/resources/anim.h"
#include "engines/stark/resources/animhierarchy.h"
#include "engines/stark/resources/animscript.h"
#include "engines/stark/resources/bookmark.h"
#include "engines/stark/resources/bonesmesh.h"
#include "engines/stark/resources/camera.h"
#include "engines/stark/resources/dialog.h"
#include "engines/stark/resources/floor.h"
#include "engines/stark/resources/floorfield.h"
#include "engines/stark/resources/fmv.h"
#include "engines/stark/resources/item.h"
#include "engines/stark/resources/knowledge.h"
#include "engines/stark/resources/layer.h"
#include "engines/stark/resources/light.h"
#include "engines/stark/resources/location.h"
#include "engines/stark/resources/path.h"
#include "engines/stark/resources/pattable.h"
#include "engines/stark/resources/script.h"
#include "engines/stark/resources/scroll.h"
#include "engines/stark/resources/sound.h"
#include "engines/stark/resources/speech.h"
#include "engines/stark/resources/string.h"
#include "engines/stark/resources/textureset.h"

#include "engines/stark/services/services.h"
#include "engines/stark/services/dialogplayer.h"
#include "engines/stark/services/diary.h"
#include "engines/stark/services/global.h"
#include "engines/stark/services/resourceprovider.h"
#include "engines/stark/services/userinterface.h"
#include "engines/stark/services/settings.h"

#include "common/random.h"

namespace Stark {
namespace Resources {

Command::~Command() {
}

Command::Command(Object *parent, byte subType, uint16 index, const Common::String &name) :
		Object(parent, subType, index, name) {
	_type = TYPE;
}

Command *Command::execute(uint32 callMode, Script *script) {
	switch (_subType) {
	case kCommandBegin:
		return opScriptBegin();
	case kScriptCall:
		return opScriptCall(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kDialogCall:
		return opDialogCall(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kSetInteractiveMode:
		return opSetInteractiveMode(_arguments[1].intValue);
	case kLocationGoTo:
	case kLocationGoToNewCD:
		return opLocationGoTo(_arguments[0].stringValue, _arguments[1].stringValue, _arguments[2].referenceValue, _arguments[3].intValue);
	case kScriptPause:
		return opScriptPause(script, _arguments[1].referenceValue);
	case kScriptAbort:
		return opScriptAbort(_arguments[1].referenceValue, _arguments[2].intValue);
	case kWalkTo:
		return opWalkTo(script, _arguments[2].referenceValue, _arguments[3].intValue);
	case kGameLoop:
		return opScriptPauseGameLoop(script, _arguments[1].intValue);
	case kScriptPauseRandom:
		return opScriptPauseRandom(script, _arguments[1].referenceValue);
	case kScriptPauseSkippable:
		return opScriptPauseSkippable(script, _arguments[1].referenceValue);
	case kExit2DLocation:
		return opExit2DLocation();
	case kGoto2DLocation:
		return opGoto2DLocation(_arguments[0].stringValue, _arguments[1].stringValue);
	case kRumbleScene:
		return opRumbleScene(script, _arguments[1].intValue, _arguments[2].intValue);
	case kFadeScene:
		return opFadeScene(script, _arguments[1].intValue, _arguments[2].intValue, _arguments[3].intValue);
	case kSwayScene:
		return opSwayScene(_arguments[1].intValue, _arguments[2].intValue, _arguments[3].intValue, _arguments[4].intValue);
	case kGameEnd:
		return opGameEnd();
	case kInventoryOpen:
		return opInventoryOpen(_arguments[1].intValue);
	case kFloatScene:
		return opFloatScene(_arguments[1].intValue, _arguments[2].intValue, _arguments[3].intValue);
	case kBookOfSecretsOpen:
		return opBookOfSecretsOpen();
	case kDoNothing:
		return opDoNothing();
	case kItem3DPlaceOn:
		return opItem3DPlaceOn(_arguments[1].referenceValue, _arguments[2].referenceValue);
	case kItem3DWalkTo:
		return opItem3DWalkTo(script, _arguments[1].referenceValue, _arguments[2].referenceValue, _arguments[3].intValue);
	case kItem3DFollowPath:
	case kItem2DFollowPath:
		return opItemFollowPath(script, _arguments[1].referenceValue, _arguments[2].referenceValue, _arguments[3].intValue, _arguments[4].intValue);
	case kItemLookAt:
		return opItemLookAt(script, _arguments[1].referenceValue, _arguments[2].referenceValue, _arguments[3].intValue,	_arguments[4].intValue);
	case kItemEnable:
		return opItemEnable(_arguments[1].referenceValue, _arguments[2].intValue);
	case kItemSelectInInventory:
		return opItemSelectInInventory(_arguments[1].referenceValue);
	case kItemSetActivity:
		return opItemSetActivity(script, _arguments[1].referenceValue, _arguments[2].intValue, _arguments[3].intValue);
	case kUseAnimHierarchy:
		return opUseAnimHierachy(_arguments[1].referenceValue);
	case kPlayAnimation:
		return opPlayAnimation(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kShowPlay:
		return opShowPlay(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kScriptEnable:
		return opScriptEnable(_arguments[1].referenceValue, _arguments[2].intValue);
	case kKnowledgeSetBoolean:
		return opKnowledgeSetBoolean(_arguments[1].referenceValue, _arguments[2].intValue);
	case kKnowledgeSetInteger:
		return opKnowledgeSetInteger(_arguments[1].referenceValue, _arguments[2].intValue);
	case kKnowledgeAddInteger:
		return opKnowledgeAddInteger(_arguments[1].referenceValue, _arguments[2].intValue);
	case kKnowledgeSetIntRandom:
		return opKnowledgeSetIntRandom(_arguments[1].referenceValue, _arguments[2].intValue, _arguments[3].intValue);
	case kKnowledgeSubValue:
		return opKnowledgeSubValue(_arguments[1].referenceValue, _arguments[2].referenceValue);
	case kEnableFloorField:
		return opEnableFloorField(_arguments[1].referenceValue, _arguments[2].intValue);
	case kPlayAnimScriptItem:
		return opPlayAnimScriptItem(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kItemAnimFollowPath:
		return opItemAnimFollowPath(script, _arguments[1].referenceValue, _arguments[2].referenceValue, _arguments[3].intValue, _arguments[4].intValue);
	case kKnowledgeAssignBool:
		return opKnowledgeAssignBool(_arguments[1].referenceValue, _arguments[2].referenceValue);
	case kKnowledgeAssignNegatedBool:
		return opKnowledgeAssignNegatedBool(_arguments[1].referenceValue, _arguments[2].referenceValue);
	case kKnowledgeAssignInteger:
		return opKnowledgeAssignInteger(_arguments[1].referenceValue, _arguments[2].referenceValue);
	case kLocationScrollTo:
		return opLocationScrollTo(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kSoundPlay:
		return opSoundPlay(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kItemLookDirection:
		return opItemLookDirection(script, _arguments[1].referenceValue, _arguments[2].intValue, _arguments[3].intValue);
	case kStopPlayingSound:
		return opStopPlayingSound(_arguments[1].referenceValue);
	case kLayerGoTo:
		return opLayerGoTo(_arguments[1].referenceValue);
	case kLayerEnable:
		return opLayerEnable(_arguments[1].referenceValue, _arguments[2].intValue);
	case kLocationScrollSet:
		return opLocationScrollSet(_arguments[1].referenceValue);
	case kFullMotionVideoPlay:
		return opFullMotionVideoPlay(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kAnimSetFrame:
		return opAnimSetFrame(_arguments[1].referenceValue, _arguments[2].referenceValue);
	case kDiaryEnableEntry:
		return opDiaryEnableEntry(_arguments[1].referenceValue);
	case kPATChangeTooltip:
		return opPATChangeTooltip(_arguments[1].referenceValue, _arguments[2].referenceValue);
	case kSoundChange:
		return opSoundChange(script, _arguments[1].referenceValue, _arguments[2].intValue, _arguments[3].intValue, _arguments[4].intValue, _arguments[5].intValue);
	case kLightSetColor:
		return opLightSetColor(_arguments[1].referenceValue, _arguments[2].intValue, _arguments[3].intValue, _arguments[4].intValue);
	case kLightFollowPath:
		return opLightFollowPath(script, _arguments[1].referenceValue, _arguments[2].referenceValue, _arguments[3].referenceValue, _arguments[4].intValue, _arguments[5].intValue);
	case kItem3DRunTo:
		return opItem3DRunTo(script, _arguments[1].referenceValue, _arguments[2].referenceValue, _arguments[3].intValue);
	case kItemPlaceDirection:
		return opItemPlaceDirection(_arguments[1].referenceValue, _arguments[2].intValue);
	case kItemRotateDirection:
		return opItemRotateDirection(script, _arguments[1].referenceValue, _arguments[2].intValue, _arguments[3].intValue, _arguments[4].intValue);
	case kActivateTexture:
		return opActivateTexture(_arguments[1].referenceValue);
	case kActivateMesh:
		return opActivateMesh(_arguments[1].referenceValue);
	case kItem3DSetWalkTarget:
		return opItem3DSetWalkTarget(_arguments[1].referenceValue, _arguments[2].referenceValue);
	case kSpeakWithoutTalking:
		return opSpeakWithoutTalking(script, _arguments[1].referenceValue, _arguments[2].intValue);
	case kIsOnFloorField:
		return opIsOnFloorField(_arguments[2].referenceValue, _arguments[3].referenceValue);
	case kIsItemEnabled:
		return opIsItemEnabled(_arguments[2].referenceValue);
	case kIsScriptEnabled:
		return opIsScriptEnabled(_arguments[2].referenceValue);
	case kIsKnowledgeBooleanSet:
		return opIsKnowledgeBooleanSet(_arguments[2].referenceValue);
	case kIsKnowledgeIntegerInRange:
		return opIsKnowledgeIntegerInRange(_arguments[2].referenceValue, _arguments[3].intValue, _arguments[4].intValue);
	case kIsKnowledgeIntegerAbove:
		return opIsKnowledgeIntegerAbove(_arguments[2].referenceValue, _arguments[3].intValue);
	case kIsKnowledgeIntegerEqual:
		return opIsKnowledgeIntegerEqual(_arguments[2].referenceValue, _arguments[3].intValue);
	case kIsKnowledgeIntegerLower:
		return opIsKnowledgeIntegerLower(_arguments[2].referenceValue, _arguments[3].intValue);
	case kIsScriptActive:
		return opIsScriptActive(_arguments[2].referenceValue);
	case kIsRandom:
		return opIsRandom(_arguments[2].intValue);
	case kIsAnimScriptItemReached:
		return opIsAnimScriptItemReached(_arguments[2].referenceValue);
	case kIsItemOnPlace:
		return opIsItemOnPlace(_arguments[2].referenceValue, _arguments[3].referenceValue);
	case kIsItemNearPlace:
		return opIsItemNearPlace(_arguments[2].referenceValue, _arguments[3].referenceValue, _arguments[4].intValue);
	case kIsAnimPlaying:
		return opIsAnimPlaying(_arguments[2].referenceValue);
	case kIsItemActivity:
		return opIsItemActivity(_arguments[2].referenceValue, _arguments[3].intValue);
	case kIsAnimAtTime:
		return opIsAnimAtTime(_arguments[2].referenceValue, _arguments[3].intValue);
	case kIsLocation2D:
		return opIsLocation2D();
	case kIsInventoryOpen:
		return opIsInventoryOpen();
	default:
		warning("Unimplemented command %d - %s", _subType, _name.c_str());
		printData();
		break;
	}

	return nextCommand();
}

Command *Command::opScriptBegin() {
	return nextCommand();
}

Command *Command::opScriptCall(Script *script, const ResourceReference &scriptRef, int32 synchronous) {
	Script *calleeScript = scriptRef.resolve<Script>();

	if (synchronous) {
		// Store the current command for use when the callee's execution ends
		script->addReturnObject(this);

		// Run the callee with the current script's execution context
		return calleeScript->getBeginCommand();
	} else {
		// Kickstart the callee script by skipping its Begin command, overriding all checks
		// Both scripts will continue in parallel
		calleeScript->goToNextCommand();
		return nextCommand();
	}
}

Command *Command::opDialogCall(Script *script, const ResourceReference &dialogRef, int32 suspend) {
	Dialog *dialog = dialogRef.resolve<Dialog>();
	StarkDialogPlayer->run(dialog);

	if (suspend) {
		script->suspend(dialog);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opSetInteractiveMode(bool enabled) {
	StarkUserInterface->setInteractive(enabled);

	return nextCommand();
}

Command *Command::opLocationGoTo(const Common::String &level, const Common::String &location, const ResourceReference &bookmarkRef, int32 direction) {
	uint levelIndex = strtol(level.c_str(), nullptr, 16);
	uint locationIndex = strtol(location.c_str(), nullptr, 16);
	StarkResourceProvider->requestLocationChange(levelIndex, locationIndex);
	StarkResourceProvider->setNextLocationPosition(bookmarkRef, direction);

	return nullptr;
}


Command *Command::opScriptPause(Script *script, const ResourceReference &durationRef) {
	Knowledge *duration = durationRef.resolve<Knowledge>();
	script->pause(duration->getIntegerValue());

	return this; // Stay on this command while the script is suspended
}

Command *Command::opWalkTo(Script *script, const ResourceReference &objectRef, int32 suspend) {
	Resources::ModelItem *april = StarkGlobal->getCurrent()->getInteractive();

	Math::Vector3d destinationPosition = getObjectPosition(objectRef);
	Math::Vector3d currentPosition = april->getPosition3D();

	if (destinationPosition == currentPosition) {
		return nextCommand();
	}

	Walk *walk = new Walk(april);
	walk->setDestination(destinationPosition);
	walk->start();

	april->setMovement(walk);

	if (suspend) {
		script->suspend(april);
		april->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opScriptPauseGameLoop(Script *script, int32 count) {
	uint gameloopDuration = StarkGlobal->getMillisecondsPerGameloop();

	script->pause(gameloopDuration * count);

	return this; // Stay on this command while the script is suspended
}

Command *Command::opScriptPauseRandom(Script *script, const ResourceReference &ref) {
	float randomFactor = StarkRandomSource->getRandomNumber(10000) / 10000.0;

	Knowledge *duration = ref.resolve<Knowledge>();
	script->pause(randomFactor * duration->getIntegerValue());

	return this; // Stay on this command while the script is suspended
}

Command *Command::opScriptPauseSkippable(Script *script, const ResourceReference &durationRef) {
	StarkUserInterface->setInteractive(false);

	Knowledge *duration = durationRef.resolve<Knowledge>();
	script->pause(duration->getIntegerValue());

	return this; // Stay on this command while the script is suspended
}

Command *Command::opScriptAbort(ResourceReference scriptRef, bool disable) {
	Script *script = scriptRef.resolve<Script>();

	if (!script->isOnBegin()) {
		script->stop();
	}

	script->enable(!disable);

	return nextCommand();
}

Command *Command::opExit2DLocation() {
	StarkResourceProvider->returnToPushedLocation();

	return nullptr;
}

Command *Command::opGoto2DLocation(const Common::String &level, const Common::String &location) {
	uint levelIndex = strtol(level.c_str(), nullptr, 16);
	uint locationIndex = strtol(location.c_str(), nullptr, 16);
	StarkResourceProvider->pushAndChangeLocation(levelIndex, locationIndex);

	return nullptr;
}

Command *Command::opRumbleScene(Script *script, int32 rumbleDuration, int32 pause) {
	Current *current = StarkGlobal->getCurrent();
	Location *location = current->getLocation();
	location->startRumble(rumbleDuration);

	if (pause) {
		script->pause(rumbleDuration);
		return this; // Stay on this command while the script is suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opFadeScene(Script *script, bool fadeOut, int32 fadeDuration, bool pause) {
	Current *current = StarkGlobal->getCurrent();
	Location *location = current->getLocation();
	if (fadeOut) {
		location->fadeOutInit(fadeDuration);
	} else {
		location->fadeInInit(fadeDuration);
	}

	if (pause) {
		script->pause(fadeDuration);
		return this; // Stay on this command while the script is suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opSwayScene(int32 periodMs, int32 angleIn, int32 amplitudeIn, int32 offsetIn) {
	Math::Angle angle = ABS(angleIn) % 360;
	float amplitude = amplitudeIn / 100.0f;
	float offset = offsetIn / 100.0f;

	Location *location = StarkGlobal->getCurrent()->getLocation();
	location->swayScene(periodMs, angle, amplitude, offset);

	return nextCommand();
}

Math::Vector3d Command::getObjectPosition(const ResourceReference &targetRef, int32 *floorFace) {
	Object *target = targetRef.resolve<Object>();
	Floor *floor = StarkGlobal->getCurrent()->getFloor();

	Math::Vector3d position;
	switch (target->getType().get()) {
		case Type::kBookmark: {
			Bookmark *bookmark = Object::cast<Bookmark>(target);
			position = bookmark->getPosition();

			if (floorFace) {
				*floorFace = floor->findFaceContainingPoint(position);
			}

	        break;
		}
		case Type::kItem: {
			FloorPositionedItem *item = Object::cast<FloorPositionedItem>(target);
			position = item->getPosition3D();

			if (floorFace) {
				*floorFace = item->getFloorFaceIndex();
			}

			break;
		}
		case Type::kPath: {
			assert(target->getSubType() == Path::kPath3D);

			Path3D *path = Object::cast<Path3D>(target);
			position = path->getVertexPosition3D(0, floorFace);

			break;
		}
		default:
			warning("Unimplemented getObjectPosition target type %s", target->getType().getName());
	}

	return position;
}

Command *Command::opGameEnd() {
	StarkUserInterface->requestQuitToMainMenu();

	return nextCommand();
}

Command *Command::opInventoryOpen(bool open) {
	StarkUserInterface->inventoryOpen(open);

	return nextCommand();
}

Command *Command::opFloatScene(int32 periodMs, int32 amplitudeIn, int32 offsetIn) {
	float amplitude = amplitudeIn / 10.0f;
	float offset = offsetIn / 100.0f;

	Location *location = StarkGlobal->getCurrent()->getLocation();
	location->floatScene(periodMs, amplitude, offset);

	return nextCommand();
}

Command *Command::opBookOfSecretsOpen() {
	StarkSettings->enableBookOfSecrets();

	return nextCommand();
}

Command *Command::opDoNothing() {
	return nextCommand();
}

Command *Command::opItem3DPlaceOn(const ResourceReference &itemRef, const ResourceReference &targetRef) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();

	int32 targetFace = -1;
	Math::Vector3d targetPosition = getObjectPosition(targetRef, &targetFace);

	item->setPosition3D(targetPosition);
	item->setFloorFaceIndex(targetFace);

	return nextCommand();
}

Command *Command::opItem3DWalkTo(Script *script, const ResourceReference &itemRef, const ResourceReference &targetRef, bool suspend) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();
	Math::Vector3d targetPosition = getObjectPosition(targetRef);

	Walk *walk = new Walk(item);
	walk->setDestination(targetPosition);
	walk->start();

	item->setMovement(walk);

	if (suspend) {
		script->suspend(item);
		item->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opItemFollowPath(Script *script, ResourceReference itemRef, ResourceReference pathRef, uint32 speed, uint32 suspend) {
	ItemVisual *item = itemRef.resolve<ItemVisual>();
	Path *path = pathRef.resolve<Path>();

	FollowPath *follow = new FollowPath(item);
	follow->setPath(path);
	follow->setSpeed(speed / 100.0f);
	follow->start();

	item->setMovement(follow);

	if (suspend) {
		script->suspend(item);
		item->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opItemLookAt(Script *script, const ResourceReference &itemRef, const ResourceReference &objRef, bool suspend, int32 unknown) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();
	Math::Vector3d currentPosition = item->getPosition3D();

	Math::Vector3d targetPosition = getObjectPosition(objRef);
	Math::Vector3d targetDirection = targetPosition - currentPosition;

	if (targetDirection == Math::Vector3d()) {
		// Can't look at a target if we are sitting on top of it
		return nextCommand();
	}

	Turn *movement = new Turn(item);
	movement->setTargetDirection(targetDirection);
	movement->start();

	item->setMovement(movement);

	if (suspend) {
		script->suspend(item);
		item->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opItemEnable(const ResourceReference &itemRef, int32 enable) {
	Item *item = itemRef.resolve<Item>();

	bool previousState = item->isEnabled();

	switch (enable) {
	case 0:
		item->setEnabled(false);
		break;
	case 1:
		if (!previousState) {
			item->setEnabled(true);

			if (item->getSubType() == Item::kItemInventory) {
				StarkUserInterface->notifyInventoryItemEnabled(item->getIndex());
			}
		}
		break;
	case 2:
		item->setEnabled(!previousState);
		break;
	default:
		warning("Unhandled item enable command %d", enable);
		break;
	}

	return nextCommand();
}

Command *Command::opItemSetActivity(Script *script, const ResourceReference &itemRef, int32 animActivity, bool wait) {
	Item *item = itemRef.resolve<Item>();
	ItemVisual *sceneItem = item->getSceneInstance();
	Anim *actionAnim = sceneItem->getActionAnim();

	if (wait && actionAnim) {
		assert(actionAnim->getSubType() == Anim::kAnimSkeleton || actionAnim->getSubType() == Anim::kAnimVideo);
		script->suspend(actionAnim);
		return this;
	} else {
		resumeItemSetActivity();
		return nextCommand();
	}
}

void Command::resumeItemSetActivity() {
	assert(_subType == kItemSetActivity);

	Item *item = _arguments[1].referenceValue.resolve<Item>();
	int32 animActivity = _arguments[2].intValue;
	ItemVisual *sceneItem = item->getSceneInstance();
	sceneItem->setMovement(nullptr);
	sceneItem->setAnimActivity(animActivity);
}

Command *Command::opItemSelectInInventory(const ResourceReference &itemRef) {
	InventoryItem *item = itemRef.resolve<InventoryItem>();
	StarkUserInterface->selectInventoryItem(item->getIndex());

	return nextCommand();
}

Command *Command::opUseAnimHierachy(const ResourceReference &animHierRef) {
	AnimHierarchy *animHier = animHierRef.resolve<AnimHierarchy>();
	Item *item = animHier->findParent<Item>();

	item->setAnimHierarchy(animHier);

	// TODO: Only set the anim activity if the next opcode is not going to do it
	ItemVisual *sceneItem = item->getSceneInstance();
	sceneItem->setAnimActivity(Anim::kActorActivityIdle);

	return nextCommand();
}

Command *Command::opPlayAnimation(Script *script, const ResourceReference &animRef, bool suspend) {
	Anim *anim = animRef.resolve<Anim>();
	Item *item = anim->findParent<Item>();
	ItemVisual *sceneItem = item->getSceneInstance();

	sceneItem->setMovement(nullptr);
	sceneItem->playActionAnim(anim);

	if (suspend) {
		anim->shouldResetItem(false); // The script system will take care of that when resuming
		script->suspend(anim);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opScriptEnable(const ResourceReference &scriptRef, int32 enable) {
	Script *script = scriptRef.resolve<Script>();

	bool previousState = script->isEnabled();

	switch (enable) {
		case 0:
			script->enable(false);
	        break;
		case 1:
			script->enable(true);
	        break;
		case 2:
			script->enable(!previousState);
	        break;
		default:
			warning("Unhandled script enable command %d", enable);
	        break;
	}

	return nextCommand();
}

Command *Command::opShowPlay(Script *script, const ResourceReference &ref, int32 suspend) {
	Speech *speech = ref.resolve<Speech>();
	speech->setPlayTalkAnim(true);

	StarkDialogPlayer->playSingle(speech);

	// TODO: Only set the anim activity if the next opcode is not going to do it

	if (suspend) {
		script->suspend(speech);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opKnowledgeSetBoolean(const ResourceReference &knowledgeRef, int32 enable) {
	Knowledge *boolean = knowledgeRef.resolve<Knowledge>();

	bool previousState = boolean->getBooleanValue();

	switch (enable) {
		case 0:
			boolean->setBooleanValue(false);
	        break;
		case 1:
			boolean->setBooleanValue(true);
	        break;
		case 2:
			boolean->setBooleanValue(!previousState);
	        break;
		default:
			warning("Unhandled set boolean value command %d", enable);
	        break;
	}

	return nextCommand();
}

Command *Command::opKnowledgeSetInteger(const ResourceReference &knowledgeRef, int32 value) {
	Knowledge *knowledge = knowledgeRef.resolve<Knowledge>();

	knowledge->setIntegerValue(value);

	return nextCommand();
}

Command *Command::opKnowledgeSetIntRandom(const ResourceReference &knowledgeRef, uint32 min, uint32 max) {
	Knowledge *knowledge = knowledgeRef.resolve<Knowledge>();

	uint32 value = StarkRandomSource->getRandomNumberRng(min, max);
	knowledge->setIntegerValue(value);

	return nextCommand();
}

Command *Command::opKnowledgeAddInteger(const ResourceReference &knowledgeRef, int32 increment) {
	Knowledge *knowledge = knowledgeRef.resolve<Knowledge>();

	int32 oldValue = knowledge->getIntegerValue();
	knowledge->setIntegerValue(oldValue + increment);

	return nextCommand();
}

Command *Command::opKnowledgeSubValue(const ResourceReference &knowledgeRef, const ResourceReference &valueRef) {
	Knowledge *knowledge = knowledgeRef.resolve<Knowledge>();
	Knowledge *operand = valueRef.resolve<Knowledge>();

	int32 oldValue = knowledge->getIntegerValue();
	int32 decrement = operand->getIntegerValue();

	knowledge->setIntegerValue(oldValue - decrement);

	return nextCommand();
}

Command *Command::opEnableFloorField(const ResourceReference &floorFieldRef, bool enable) {
	FloorField *floorField = floorFieldRef.resolve<FloorField>();
	Layer *layer = floorField->findParent<Layer>();
	Floor *floor = layer->findChild<Floor>();

	floor->enableFloorField(floorField, enable);

	return nextCommand();
}

Command *Command::opPlayAnimScriptItem(Script *script, const ResourceReference &animScriptItemRef, int32 suspend) {
	AnimScriptItem *animScriptItem = animScriptItemRef.resolve<AnimScriptItem>();
	AnimScript *animScript = animScriptItem->findParent<AnimScript>();
	Anim *anim = animScriptItem->findParent<Anim>();
	Item *item = animScriptItem->findParent<Item>();
	ItemVisual *sceneItem = item->getSceneInstance();

	sceneItem->playActionAnim(anim);
	animScript->goToScriptItem(animScriptItem);

	if (suspend) {
		script->suspend(anim);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opItemAnimFollowPath(Script *script, const ResourceReference &animRef, const ResourceReference &pathRef, int32 speed, bool suspend) {
	Anim *anim = animRef.resolve<Anim>();
	ItemVisual *item = anim->findParent<ItemVisual>();
	Path *path = pathRef.resolve<Path>();

	FollowPath *follow = new FollowPath(item);
	follow->setAnim(anim);
	follow->setPath(path);
	follow->setSpeed(speed / 100.0f);
	follow->start();

	item->setMovement(follow);

	if (suspend) {
		script->suspend(item);
		item->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opKnowledgeAssignBool(const ResourceReference &knowledgeRef1, const ResourceReference &knowledgeRef2) {
	Knowledge *src = knowledgeRef1.resolve<Knowledge>();
	Knowledge *dst = knowledgeRef2.resolve<Knowledge>();

	dst->setBooleanValue(src->getBooleanValue());

	return nextCommand();
}

Command *Command::opKnowledgeAssignNegatedBool(const ResourceReference &knowledgeRef1, const ResourceReference &knowledgeRef2) {
	Knowledge *src = knowledgeRef1.resolve<Knowledge>();
	Knowledge *dst = knowledgeRef2.resolve<Knowledge>();

	dst->setBooleanValue(!src->getBooleanValue());

	return nextCommand();
}

Command *Command::opKnowledgeAssignInteger(const ResourceReference &knowledgeRef1, const ResourceReference &knowledgeRef2) {
	Knowledge *src = knowledgeRef1.resolve<Knowledge>();
	Knowledge *dst = knowledgeRef2.resolve<Knowledge>();

	dst->setIntegerValue(src->getIntegerValue());

	return nextCommand();
}

Command *Command::opLocationScrollTo(Script *script, const ResourceReference &scrollRef, bool suspend) {
	Scroll *scroll = scrollRef.resolve<Scroll>();
	Location *location = scroll->findParent<Location>();

	location->stopAllScrolls();
	scroll->start();

	if (suspend) {
		script->suspend(scroll);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opSoundPlay(Script *script, const ResourceReference &soundRef, int32 suspend) {
	Sound *sound = soundRef.resolve<Sound>();
	sound->play();

	if (suspend) {
		script->suspend(sound);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opItemLookDirection(Script *script, const ResourceReference &itemRef, int32 direction, bool suspend) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();

	Current *current = StarkGlobal->getCurrent();
	Camera *camera = current->getCamera();
	Math::Angle cameraAngle = camera->getHorizontalAngle();
	Math::Angle targetAngle = direction + cameraAngle;

	Math::Matrix3 rot;
	rot.buildAroundZ(-targetAngle);

	Math::Vector3d directionVector(1.0, 0.0, 0.0);
	rot.transformVector(&directionVector);

	Turn *movement = new Turn(item);
	movement->setTargetDirection(directionVector);
	movement->start();

	item->setMovement(movement);

	if (suspend) {
		script->suspend(item);
		item->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opStopPlayingSound(const ResourceReference &soundRef) {
	Sound *soundObj = soundRef.resolve<Sound>();

	soundObj->stop();

	return nextCommand();
}

Command *Command::opLayerGoTo(const ResourceReference &layerRef) {
	Layer *layer = layerRef.resolve<Layer>();
	Location *location = layer->findParent<Location>();

	location->goToLayer(layer);

	return nextCommand();
}

Command *Command::opLayerEnable(const ResourceReference &layerRef, int32 enable) {
	Layer *layer = layerRef.resolve<Layer>();

	bool previousState = layer->isEnabled();

	switch (enable) {
		case 0:
			layer->enable(false);
			break;
		case 1:
			if (!previousState) {
				layer->enable(true);
			}
			break;
		case 2:
			layer->enable(!previousState);
			break;
		default:
			warning("Unhandled layer enable command %d", enable);
			break;
	}

	return nextCommand();
}

Command *Command::opLocationScrollSet(const ResourceReference &scrollRef) {
	Scroll *scroll =  scrollRef.resolve<Scroll>();
	scroll->applyToLocationImmediate();

	Location *location = scroll->findParent<Location>();
	location->stopFollowingCharacter();

	return nextCommand();
}

Command *Command::opFullMotionVideoPlay(Script *script, const ResourceReference &movieRef, int32 unknown) {
	// Stop skipping frames
	StarkGlobal->setNormalSpeed();

	// Characters don't need to continue their previous action after the FMV ends
	Current *current = StarkGlobal->getCurrent();
	Location *location = current->getLocation();
	location->resetAnimationBlending();

	FMV *movie =  movieRef.resolve<FMV>();
	movie->requestPlayback();

	// Unconditional suspension
	script->suspend(movie);

	return this; // Stay on the same command while suspended
}

Command *Command::opAnimSetFrame(const ResourceReference &animRef, const ResourceReference &knowledgeRef) {
	Anim *anim = animRef.resolve<Anim>();
	Knowledge *knowledge = knowledgeRef.resolve<Knowledge>();

	anim->selectFrame(knowledge->getIntegerValue());

	return nextCommand();
}

Command *Command::opDiaryEnableEntry(const ResourceReference &knowledgeRef) {
	Knowledge *entry = knowledgeRef.resolve<Knowledge>();

	if (!entry->getBooleanValue()) {
		entry->setBooleanValue(true);

		StarkDiary->addDiaryEntry(entry->getName());
	}

	return nextCommand();
}

Command *Command::opPATChangeTooltip(const ResourceReference &patRef, const ResourceReference &stringRef) {
	PATTable *entry = patRef.resolve<PATTable>();
	String *string = stringRef.resolve<String>();

	entry->setTooltip(string);

	return nextCommand();
}

Command *Command::opSoundChange(Script *script, const ResourceReference &soundRef, int32 volume, int32 pan, int32 duration, bool pause) {
	Sound *sound = soundRef.resolve<Sound>();
	sound->changeVolumePan(volume, pan, duration);

	if (pause) {
		script->pause(duration);
		return this; // Stay on the same command while paused
	} else {
		return nextCommand();
	}
}

Command *Command::opLightSetColor(const ResourceReference &lightRef, int32 red, int32 green, int32 blue) {
	Light *light = lightRef.resolve<Light>();

	light->setColor(red, green, blue);

	return nextCommand();
}

Command *Command::opLightFollowPath(Script *script, const ResourceReference &itemRef, const ResourceReference &lightRef,
									const ResourceReference &pathRef, int32 speed, bool suspend) {
	ItemVisual *item = itemRef.resolve<ItemVisual>();
	Light *light = lightRef.resolve<Light>();
	Path *path = pathRef.resolve<Path>();

	FollowPathLight *follow = new FollowPathLight(item);
	follow->setLight(light);
	follow->setPath(path);
	follow->setSpeed(speed / 100.0f);
	follow->start();

	item->setMovement(follow);

	if (suspend) {
		script->suspend(item);
		item->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opItem3DRunTo(Script *script, const ResourceReference &itemRef, const ResourceReference &targetRef, int32 suspend) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();
	Math::Vector3d targetPosition = getObjectPosition(targetRef);

	Walk *walk = new Walk(item);
	walk->setDestination(targetPosition);
	walk->setRunning();
	walk->start();

	item->setMovement(walk);

	if (suspend) {
		script->suspend(item);
		item->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opItemPlaceDirection(const ResourceReference &itemRef, int32 direction) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();

	Current *current = StarkGlobal->getCurrent();
	Camera *camera = current->getCamera();
	Math::Angle cameraAngle = camera->getHorizontalAngle();

	item->setDirection(direction + cameraAngle);

	return nextCommand();
}

Command *Command::opItemRotateDirection(Script *script, const ResourceReference &itemRef, int32 direction, int32 speed, bool suspend) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();

	Current *current = StarkGlobal->getCurrent();
	Camera *camera = current->getCamera();
	Math::Angle cameraAngle = camera->getHorizontalAngle();
	Math::Angle targetAngle = direction + cameraAngle;

	Math::Matrix3 rot;
	rot.buildAroundZ(-targetAngle);

	Math::Vector3d directionVector(1.0, 0.0, 0.0);
	rot.transformVector(&directionVector);

	Turn *movement = new Turn(item);
	movement->setTargetDirection(directionVector);
	movement->setSpeed(speed / (1000.0f * 33.0f));
	movement->start();

	item->setMovement(movement);

	if (suspend) {
		script->suspend(item);
		item->setMovementSuspendedScript(script);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opActivateTexture(const ResourceReference &textureRef) {
	TextureSet *texture = textureRef.resolve<TextureSet>();
	Item *item = texture->findParent<Item>();

	if (!item || (item->getSubType() != Item::kItemGlobalTemplate && item->getSubType() != Item::kItemLevelTemplate && item->getSubType() != Item::kItemModel)) {
		return nextCommand();
	}

	if (item->getSubType() == Item::kItemModel) {
		ModelItem *modelItem = Object::cast<ModelItem>(item);
		modelItem->setTexture(texture->getIndex(), texture->getSubType());
	} else {
		ItemTemplate *templateItem = Object::cast<ItemTemplate>(item);
		templateItem->setTexture(texture->getIndex(), texture->getSubType());
	}

	return nextCommand();
}

Command *Command::opActivateMesh(const ResourceReference &meshRef) {
	BonesMesh *mesh = meshRef.resolve<BonesMesh>();
	Item *item = mesh->findParent<Item>();

	if (!item || (item->getSubType() != Item::kItemGlobalTemplate && item->getSubType() != Item::kItemLevelTemplate && item->getSubType() != Item::kItemModel)) {
		return nextCommand();
	}

	if (item->getSubType() == Item::kItemModel) {
		ModelItem *modelItem = Object::cast<ModelItem>(item);
		modelItem->setBonesMesh(mesh->getIndex());
	} else {
		ItemTemplate *templateItem = Object::cast<ItemTemplate>(item);
		templateItem->setBonesMesh(mesh->getIndex());
	}

	return nextCommand();
}

Command *Command::opItem3DSetWalkTarget(const ResourceReference &itemRef, const ResourceReference &targetRef) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();
	Math::Vector3d targetPosition = getObjectPosition(targetRef);

	Walk *walk = dynamic_cast<Walk *>(item->getMovement());
	if (walk) {
		walk->changeDestination(targetPosition);
	} else {
		walk = new Walk(item);
		walk->setDestination(targetPosition);
		walk->start();

		item->setMovement(walk);
	}

	return nextCommand();
}

Command *Command::opSpeakWithoutTalking(Script *script, const ResourceReference &speechRef, int32 suspend) {
	Speech *speech = speechRef.resolve<Speech>();
	speech->setPlayTalkAnim(false);

	StarkDialogPlayer->playSingle(speech);

	if (suspend) {
		script->suspend(speech);
		return this; // Stay on the same command while suspended
	} else {
		return nextCommand();
	}
}

Command *Command::opIsOnFloorField(const ResourceReference &itemRef, const ResourceReference &floorFieldRef) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();
	FloorField *floorField = floorFieldRef.resolve<FloorField>();

	int32 itemFaceIndex = item->getFloorFaceIndex();
	bool itemOnFloorField = floorField->hasFace(itemFaceIndex);

	return nextCommandIf(itemOnFloorField);
}

Command *Command::opIsItemEnabled(const ResourceReference &itemRef) {
	Item *itemObj = itemRef.resolve<Item>();

	return nextCommandIf(itemObj->isEnabled());
}

Command *Command::opIsScriptEnabled(const ResourceReference &scriptRef) {
	Script *script = scriptRef.resolve<Script>();

	return nextCommandIf(script->isEnabled());
}

Command *Command::opIsKnowledgeBooleanSet(const ResourceReference &knowledgeRef) {
	Knowledge *value = knowledgeRef.resolve<Knowledge>();

	return nextCommandIf(value->getBooleanValue());
}

Command *Command::opIsKnowledgeIntegerInRange(const ResourceReference &knowledgeRef, int32 min, int32 max) {
	Knowledge *knowledgeValue = knowledgeRef.resolve<Knowledge>();
	int value = knowledgeValue->getIntegerValue();

	return nextCommandIf(value >= min && value <= max);
}

Command *Command::opIsKnowledgeIntegerAbove(const ResourceReference &knowledgeRef, int32 value) {
	Knowledge *knowledgeValue = knowledgeRef.resolve<Knowledge>();

	return nextCommandIf(knowledgeValue->getIntegerValue() > value);
}

Command *Command::opIsKnowledgeIntegerEqual(const ResourceReference &knowledgeRef, int32 value) {
	Knowledge *knowledgeValue = knowledgeRef.resolve<Knowledge>();

	return nextCommandIf(knowledgeValue->getIntegerValue() == value);
}

Command *Command::opIsKnowledgeIntegerLower(const ResourceReference &knowledgeRef, int32 value) {
	Knowledge *knowledgeValue = knowledgeRef.resolve<Knowledge>();

	return nextCommandIf(knowledgeValue->getIntegerValue() < value);
}

Command *Command::opIsScriptActive(const ResourceReference &scriptRef) {
	Script *script = scriptRef.resolve<Script>();

	return nextCommandIf(!script->isOnBegin());
}

Command *Command::opIsRandom(int32 chance) {
	int32 value = StarkRandomSource->getRandomNumber(100);

	return nextCommandIf(value < chance);
}

Command *Command::opIsAnimScriptItemReached(const ResourceReference &animScriptItemRef) {
	AnimScriptItem *animScriptItem = animScriptItemRef.resolve<AnimScriptItem>();
	AnimScript *animScript = animScriptItem->findParent<AnimScript>();

	return nextCommandIf(animScript->hasReached(animScriptItem));
}

Command *Command::opIsItemOnPlace(const ResourceReference &itemRef, const ResourceReference &positionRef) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();

	Math::Vector3d itemPostion = item->getPosition3D();
	Math::Vector3d testPosition = getObjectPosition(positionRef);

	return nextCommandIf(itemPostion == testPosition);
}

Command *Command::opIsItemNearPlace(const ResourceReference &itemRef, const ResourceReference &positionRef, int32 testDistance) {
	FloorPositionedItem *item = itemRef.resolve<FloorPositionedItem>();

	Math::Vector3d itemPostion = item->getPosition3D();
	Math::Vector3d testPosition = getObjectPosition(positionRef);

	return nextCommandIf(itemPostion.getDistanceTo(testPosition) < testDistance);
}

Command *Command::opIsAnimPlaying(const ResourceReference &animRef) {
	Anim *anim = animRef.resolve<Anim>();

	return nextCommandIf(anim->isInUse());
}

Command *Command::opIsItemActivity(const ResourceReference &itemRef, int32 value) {
	Item *item = itemRef.resolve<Item>();
	ItemVisual *sceneItem = item->getSceneInstance();

	return nextCommandIf(sceneItem->getAnimActivity() == value);
}

Command *Command::opIsAnimAtTime(const ResourceReference &animRef, int32 time) {
	Anim *anim = animRef.resolve<Anim>();

	bool condition = !anim->isInUse() || anim->isAtTime(time);

	return nextCommandIf(condition);
}

Command *Command::opIsLocation2D() {
	Current *current = StarkGlobal->getCurrent();
	Location *location = current->getLocation();

	return nextCommandIf(!location->has3DLayer());
}

Command *Command::opIsInventoryOpen() {
	bool invOpen = StarkUserInterface->isInventoryOpen();

	return nextCommandIf(invOpen);
}

Command *Command::nextCommand() {
	assert(!_arguments.empty());
	assert(_arguments[0].type == Argument::kTypeInteger1);

	return resolveArgumentSiblingReference(_arguments[0]);
}

Command *Command::nextCommandIf(bool predicate) {
	assert(_arguments.size() >= 2);
	assert(_arguments[0].type == Argument::kTypeInteger1);
	assert(_arguments[1].type == Argument::kTypeInteger1);

	if (predicate) {
		return resolveArgumentSiblingReference(_arguments[1]);
	} else {
		return resolveArgumentSiblingReference(_arguments[0]);
	}
}

Command *Command::resolveArgumentSiblingReference(const Argument &argument) {
	return _parent->findChildWithIndex<Command>(argument.intValue);
}

void Command::readData(Formats::XRCReadStream *stream) {
	uint32 count = stream->readUint32LE();
	for (uint i = 0; i < count; i++) {
		Argument argument;
		argument.type = stream->readUint32LE();

		switch (argument.type) {
		case 0: // A shortcut for an int with value 0
			argument.type = Argument::kTypeInteger1;
			argument.intValue = 0;
			break;
		case Argument::kTypeInteger1:
		case Argument::kTypeInteger2:
			argument.intValue = stream->readUint32LE();
			break;
		case Argument::kTypeResourceReference:
			argument.referenceValue = stream->readResourceReference();
			break;
		case Argument::kTypeString:
			argument.stringValue = stream->readString();
			break;
		default:
			error("Unknown argument type %d", argument.type);
		}

		_arguments.push_back(argument);
	}
}

Common::Array<Command::Argument> Command::getArguments() const {
	return _arguments;
}

} // End of namespace Resources
} // End of namespace Stark