-
Notifications
You must be signed in to change notification settings - Fork 121
/
ncsfile.cpp
1650 lines (1294 loc) · 42.9 KB
/
ncsfile.cpp
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
/* xoreos - A reimplementation of BioWare's Aurora engine
*
* xoreos is the legal property of its developers, whose names
* can be found in the AUTHORS file distributed with this source
* distribution.
*
* xoreos 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.
*
* xoreos 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 xoreos. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file
* Handling BioWare's NWN Compiled Scripts.
*/
/* Based on the NCS specs by Torlack.
*
* Torlack's own site is down, but our docs repository hosts a
* a mirror (<https://github.com/xoreos/xoreos-docs>).
*/
#include <cassert>
#include <boost/make_shared.hpp>
#include "src/common/util.h"
#include "src/common/error.h"
#include "src/common/maths.h"
#include "src/common/ustring.h"
#include "src/common/readstream.h"
#include "src/common/encoding.h"
#include "src/common/debug.h"
#include "src/aurora/resman.h"
#include "src/aurora/nwscript/ncsfile.h"
#include "src/aurora/nwscript/object.h"
#include "src/aurora/nwscript/functionman.h"
using Common::kDebugScripts;
static const uint32_t kNCSTag = MKTAG('N', 'C', 'S', ' ');
static const uint32_t kVersion10 = MKTAG('V', '1', '.', '0');
static const uint32_t kScriptObjectSelf = 0x00000000;
static const uint32_t kScriptObjectInvalid = 0x00000001;
static const uint32_t kScriptObjectInvalid2 = 0xFFFFFFFF;
static const uint32_t kScriptObjectTypeInvalid = 0x7F000000;
namespace Aurora {
namespace NWScript {
NCSStack::NCSStack() {
reset();
}
NCSStack::~NCSStack() {
}
void NCSStack::reset() {
clear();
_stackPtr = -1;
_basePtr = -1;
}
bool NCSStack::empty() const {
return _stackPtr < 0;
}
Variable &NCSStack::top() {
if (_stackPtr == -1)
throw Common::Exception("NCSStack: Stack underflow");
return at(_stackPtr);
}
Variable NCSStack::pop() {
if (_stackPtr == -1)
throw Common::Exception("NCSStack: Stack underflow");
return at(_stackPtr--);
}
void NCSStack::push(const Variable &obj) {
if (_stackPtr == 0x7FFFFFFF) // Like this will ever happen :P
throw Common::Exception("NCSStack: Stack overflow");
if (_stackPtr == (int32_t)size() - 1)
push_back(obj);
else
at(_stackPtr + 1) = obj;
_stackPtr++;
}
Variable &NCSStack::getRelSP(int32_t pos) {
if ((pos > -4) || ((pos % 4) != 0))
throw Common::Exception("NCSStack::get(): Illegal position %d", pos);
int32_t stackPos = _stackPtr - ((pos / -4) - 1);
if (stackPos < 0)
throw Common::Exception("NCSStack::get(): Position %d below the bottom", pos);
return at(stackPos);
}
void NCSStack::setRelSP(int32_t pos, const Variable &obj) {
if ((pos > -4) || ((pos % 4) != 0))
throw Common::Exception("NCSStack::set(): Illegal position %d", pos);
int32_t stackPos = _stackPtr - ((pos / -4) - 1);
if (stackPos < 0)
throw Common::Exception("NCSStack::set(): Position %d below the bottom", pos);
at(stackPos) = obj;
}
Variable &NCSStack::getRelBP(int32_t pos) {
if ((pos > -4) || ((pos % 4) != 0))
throw Common::Exception("NCSStack::get(): Illegal position %d", pos);
int32_t stackPos = _basePtr - ((pos / -4) - 1);
if (stackPos < 0)
throw Common::Exception("NCSStack::get(): Position %d below the bottom", pos);
return at(stackPos);
}
void NCSStack::setRelBP(int32_t pos, const Variable &obj) {
if ((pos > -4) || ((pos % 4) != 0))
throw Common::Exception("NCSStack::set(): Illegal position %d", pos);
int32_t stackPos = _basePtr - ((pos / -4) - 1);
if (stackPos < 0)
throw Common::Exception("NCSStack::set(): Position %d below the bottom", pos);
at(stackPos) = obj;
}
int32_t NCSStack::getStackPtr() {
return (_stackPtr + 1) * -4;
}
void NCSStack::setStackPtr(int32_t pos) {
if ((pos > 0) || ((pos % 4) != 0))
throw Common::Exception("NCSStack::setStackPtr(): Illegal position %d", pos);
_stackPtr = (pos / -4) - 1;
if ((int32_t)size() < (_stackPtr + 1))
resize(_stackPtr + 1);
}
int32_t NCSStack::getBasePtr() {
return (_basePtr + 1) * -4;
}
void NCSStack::setBasePtr(int32_t pos) {
if ((pos > 0) || ((pos % 4) != 0))
throw Common::Exception("NCSStack::setBasePtr(): Illegal position %d", pos);
_basePtr = (pos / -4) - 1;
}
void NCSStack::print() const {
if (!DebugMan.isEnabled(kDebugScripts, 3))
return;
debugC(kDebugScripts, 3, ".--- %d ---.", _stackPtr);
for (int32_t i = _stackPtr; i >= 0; i--) {
const Variable &var = at(i);
Common::UString str;
formatVariable(str, var);
debugC(kDebugScripts, 3, "| %04d: %02d - %s", i, var.getType(), str.c_str());
}
debugC(kDebugScripts, 3, "'--- ---'");
}
#define OPCODE(x) { &NCSFile::x, #x }
#define OPCODE0() { 0, "" }
void NCSFile::setupOpcodes() {
static const Opcode opcodes[] = {
// 0x00
OPCODE(o_nop), // Doesn't exist
OPCODE(o_cpdownsp),
OPCODE(o_rsadd),
OPCODE(o_cptopsp),
// 0x04
OPCODE(o_const),
OPCODE(o_action),
OPCODE(o_logand),
OPCODE(o_logor),
// 0x08
OPCODE(o_incor),
OPCODE(o_excor),
OPCODE(o_booland),
OPCODE(o_eq),
// 0x0C
OPCODE(o_neq),
OPCODE(o_geq),
OPCODE(o_gt),
OPCODE(o_lt),
// 0x10
OPCODE(o_leq),
OPCODE(o_shleft),
OPCODE(o_shright),
OPCODE(o_ushright),
// 0x14
OPCODE(o_add),
OPCODE(o_sub),
OPCODE(o_mul),
OPCODE(o_div),
// 0x18
OPCODE(o_mod),
OPCODE(o_neg),
OPCODE(o_comp),
OPCODE(o_movsp),
// 0x1C
OPCODE(o_storestateall),
OPCODE(o_jmp),
OPCODE(o_jsr),
OPCODE(o_jz),
// 0x20
OPCODE(o_retn),
OPCODE(o_destruct),
OPCODE(o_not),
OPCODE(o_decsp),
// 0x24
OPCODE(o_incsp),
OPCODE(o_jnz),
OPCODE(o_cpdownbp),
OPCODE(o_cptopbp),
// 0x28
OPCODE(o_decbp),
OPCODE(o_incbp),
OPCODE(o_savebp),
OPCODE(o_restorebp),
// 0x2C
OPCODE(o_storestate),
OPCODE(o_nop),
OPCODE0(),
OPCODE0(),
// 0x30
OPCODE(o_writearray),
OPCODE0(),
OPCODE(o_readarray),
OPCODE0(),
// 0x34
OPCODE0(),
OPCODE0(),
OPCODE0(),
OPCODE(o_getref),
// 0x38
OPCODE0(),
OPCODE(o_getrefarray)
};
_opcodes = opcodes;
_opcodeListSize = ARRAYSIZE(opcodes);
}
#undef OPCODE
NCSFile::NCSFile(Common::SeekableReadStream *ncs) : _script(ncs) {
assert(_script);
load();
}
NCSFile::NCSFile(const Common::UString &ncs) : _name(ncs) {
_script.reset(ResMan.getResource(ncs, kFileTypeNCS));
if (!_script)
throw Common::Exception("No such NCS \"%s\"", ncs.c_str());
load();
}
NCSFile::~NCSFile() {
}
const Common::UString &NCSFile::getName() const {
return _name;
}
VariableContainer &NCSFile::getEnvironment() {
return _env;
}
void NCSFile::setEnvironment(const VariableContainer &env) {
_env = env;
}
void NCSFile::setParameters(std::vector<int> parameters) {
_parameters = parameters;
}
int NCSFile::getParameter(size_t index) const {
if (_parameters.size() >= index)
return 0;
return _parameters[index];
}
void NCSFile::setParameterString(const Common::UString ¶meterString) {
_parameterString = parameterString;
}
const Common::UString &NCSFile::getParameterString() const {
return _parameterString;
}
ScriptState NCSFile::getEmptyState() {
ScriptState state;
state.offset = 13; // 8 byte header + 5 byte program size dummy op
return state;
}
void NCSFile::load() {
readHeader(*_script);
if (_id != kNCSTag)
throw Common::Exception("Try to load non-NCS file");
if (_version != kVersion10)
throw Common::Exception("Unsupported NCS file version %08X", _version);
byte lengthOpcode = _script->readByte();
if (lengthOpcode != 0x42)
throw Common::Exception("Script size opcode != 0x42 (0x%02X)", lengthOpcode);
uint32_t length = _script->readUint32BE();
if (length > ((uint32_t) _script->size()))
throw Common::Exception("Script size %u > stream size %u", length, (uint)_script->size());
if (length < ((uint32_t) _script->size()))
warning("TODO: NCSFile::load(): Script size %u < stream size %u", length, (uint)_script->size());
setupOpcodes();
reset();
}
void NCSFile::reset() {
_stack.reset();
while (!_returnOffsets.empty())
_returnOffsets.pop();
_storedState.setType(kTypeVoid);
_return.setType(kTypeVoid);
_script->seek(13); // 8 byte header + 5 byte program size dummy op
}
const Variable &NCSFile::run(Object *owner, Object *triggerer) {
return run(getEmptyState(), ObjectReference(owner), ObjectReference(triggerer));
}
const Variable &NCSFile::run(const ObjectReference owner, const ObjectReference triggerer) {
return run(getEmptyState(), ObjectReference(owner), ObjectReference(triggerer));
}
const Variable &NCSFile::run(const ScriptState &state, Object *owner, Object *triggerer) {
return run(state, ObjectReference(owner), ObjectReference(triggerer));
}
const Variable &NCSFile::run(const ScriptState &state, const ObjectReference owner, const ObjectReference triggerer) {
debugC(kDebugScripts, 1, "=== Running script \"%s\" (%d) ===",
_name.c_str(), state.offset);
reset();
_script->seek(state.offset);
// Push global variables
std::vector<class Variable>::const_reverse_iterator var;
for (var = state.globals.rbegin(); var != state.globals.rend(); ++var)
_stack.push(*var);
_stack.setBasePtr(_stack.getStackPtr());
// Push local variables
for (var = state.locals.rbegin(); var != state.locals.rend(); ++var)
_stack.push(*var);
return execute(owner, triggerer);
}
const Variable &NCSFile::execute(const ObjectReference owner, const ObjectReference triggerer) {
_owner = owner;
_triggerer = triggerer;
while (executeStep())
;
if (!_stack.empty())
_return = _stack.top();
if (!_stack.empty() && (_stack.top().getType() == kTypeInt))
debugC(kDebugScripts, 1, "=> Script\"%s\" returns: %d",
_name.c_str(), _stack.top().getInt());
_owner = 0;
_triggerer = 0;
return _return;
}
bool NCSFile::executeStep() {
byte opcode, type;
try {
opcode = _script->readByte();
type = _script->readByte();
} catch (...) {
return false;
}
if ((opcode >= _opcodeListSize) || (!_opcodes[opcode].proc))
throw Common::Exception("NCSFile::executeStep(): Illegal instruction 0x%02x", opcode);
debugC(kDebugScripts, 1, "NWScript opcode %s [0x%02X]", _opcodes[opcode].desc, opcode);
(this->*(_opcodes[opcode].proc))((InstructionType)type);
_stack.print();
debugC(kDebugScripts, 2, "[RETURN: %d]",
_returnOffsets.empty() ? -1 : _returnOffsets.top());
return true;
}
void NCSFile::decompile() {
uint32_t oldScriptPos = _script->pos();
_script->seek(13); // 8 byte header + 5 byte program size dummy op
// TODO
_script->seek(oldScriptPos);
}
// OPCODES!
/** RSADD: push an empty variable onto the stack. */
void NCSFile::o_rsadd(InstructionType type) {
switch (type) {
case kInstTypeInt:
_stack.push(kTypeInt);
break;
case kInstTypeFloat:
_stack.push(kTypeFloat);
break;
case kInstTypeString:
case kInstTypeResource:
_stack.push(kTypeString);
break;
case kInstTypeObject:
_stack.push(kTypeObject);
break;
case kInstTypeEngineType0:
case kInstTypeEngineType1:
case kInstTypeEngineType2:
case kInstTypeEngineType3:
case kInstTypeEngineType4:
case kInstTypeEngineType5:
_stack.push(kTypeEngineType);
break;
case kInstTypeIntArray:
case kInstTypeFloatArray:
case kInstTypeStringArray:
case kInstTypeObjectArray:
case kInstTypeResourceArray:
case kInstTypeEngineType0Array:
case kInstTypeEngineType1Array:
case kInstTypeEngineType2Array:
case kInstTypeEngineType3Array:
case kInstTypeEngineType4Array:
case kInstTypeEngineType5Array:
_stack.push(kTypeArray);
break;
default:
throw Common::Exception("NCSFile::o_rsadd(): Illegal type %d", type);
}
}
/** CONST: push a constant (predetermined value) variable onto the stack. */
void NCSFile::o_const(InstructionType type) {
switch (type) {
case kInstTypeInt:
_stack.push(_script->readSint32BE());
break;
case kInstTypeFloat:
_stack.push(_script->readIEEEFloatBE());
break;
case kInstTypeString:
case kInstTypeResource: {
_stack.push(Common::readStringFixed(*_script, Common::kEncodingASCII, _script->readUint16BE()));
break;
}
case kInstTypeObject: {
/* The scripts only know of two constant objects:
* - OBJECT_SELF, the owner object of the script
* - OBJECT_INVALID, an invalid object
*
* In the bytecode, the latter can be initialized by a few different
* magic values. They *should* all have the same effect, though.
*/
uint32_t objectID = _script->readUint32BE();
if (objectID == kScriptObjectSelf)
_stack.push(_owner);
else if (objectID == kScriptObjectInvalid)
_stack.push((Object *) 0);
else if (objectID == kScriptObjectInvalid2)
_stack.push((Object *) 0);
else if (objectID == kScriptObjectTypeInvalid)
_stack.push((Object *) 0);
else
throw Common::Exception("NCSFile::o_const(): Illegal object ID %d", objectID);
break;
}
default:
throw Common::Exception("NCSFile::o_const(): Illegal type %d", type);
}
}
/** Helper function for o_action(), doing the actual engine function calling. */
void NCSFile::callEngine(Aurora::NWScript::FunctionContext &ctx,
uint32_t function, uint8_t argCount) {
if ((argCount < ctx.getParamMin()) || (argCount > ctx.getParamMax()))
throw Common::Exception("NCSFile::callEngine(): Argument count mismatch (%u vs %u - %u)",
argCount, (uint)ctx.getParamMin(), (uint)ctx.getParamMax());
ctx.setCurrentScript(this);
ctx.setCaller(_owner);
ctx.setTriggerer(_triggerer);
// Pop parameters
ctx.setParamsSpecified(argCount);
for (uint8_t i = 0; i < argCount; i++) {
Variable ¶m = ctx.getParams()[i];
Type type = param.getType();
if (type == kTypeAny)
type = _stack.top().getType();
switch (type) {
case kTypeInt:
case kTypeFloat:
case kTypeString:
case kTypeObject:
case kTypeEngineType:
case kTypeReference:
case kTypeArray:
param = _stack.pop();
break;
case kTypeVector: {
// A vector is held as three floats on the stack
float z = _stack.pop().getFloat();
float y = _stack.pop().getFloat();
float x = _stack.pop().getFloat();
param.setVector(x, y, z);
break;
}
case kTypeScriptState:
// The script state, "action" type, isn't stored on the stack at all
param.getScriptState() = _storedState.getScriptState();
_storedState.setType(kTypeVoid);
break;
default:
throw Common::Exception("NCSFile::callEngine(): Invalid argument type %d",
param.getType());
break;
}
}
// Call the engine function
debugC(kDebugScripts, 1, "NWScript engine function %s (%d)", ctx.getName().c_str(), function);
FunctionMan.call(function, ctx);
// Push return values
Variable &retVal = ctx.getReturn();
switch (retVal.getType()) {
case kTypeVoid:
break;
case kTypeInt:
case kTypeFloat:
case kTypeString:
case kTypeObject:
case kTypeEngineType:
case kTypeArray:
_stack.push(retVal);
break;
case kTypeVector: {
// A vector is held as three floats on the stack
float x, y, z;
retVal.getVector(x, y, z);
_stack.push(x);
_stack.push(y);
_stack.push(z);
break;
}
default:
throw Common::Exception("NCSFile::callEngine(): Invalid return type %d",
retVal.getType());
break;
}
}
/** ACTION: call a game-specific engine function. */
void NCSFile::o_action(InstructionType type) {
if (type != kInstTypeNone)
throw Common::Exception("NCSFile::o_action(): Illegal type %d", type);
uint16_t routineNumber = _script->readUint16BE();
uint8_t argCount = _script->readByte();
Aurora::NWScript::FunctionContext ctx = FunctionMan.createContext(routineNumber);
try {
callEngine(ctx, routineNumber, argCount);
} catch (Common::Exception &e) {
e.add("Failed running engine function \"%s\" (%d)",
ctx.getName().c_str(), routineNumber);
throw;
}
}
/** LOGAND: perform a logical boolean AND (&&). */
void NCSFile::o_logand(InstructionType type) {
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_logand(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg1 && arg2);
}
/** LOGOR: perform a logical boolean OR (||). */
void NCSFile::o_logor(InstructionType type) {
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_logor(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg1 || arg2);
}
/** INCOR: perform a bit-wise inclusive OR (|). */
void NCSFile::o_incor(InstructionType type) {
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_incor(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg1 | arg2);
}
/** EXCOR: perform a bit-wise exclusive OR (^). */
void NCSFile::o_excor(InstructionType type) {
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_excor(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg1 ^ arg2);
}
/** BOOLAND: perform a bit-wise AND (&). */
void NCSFile::o_booland(InstructionType type) {
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_booland(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg1 & arg2);
}
/** EQ: compare the top-most stack elements for equality (==). */
void NCSFile::o_eq(InstructionType type) {
size_t n = 1;
if (type == kInstTypeStructStruct) {
// Comparisons between two structs (or two vectors) come with the size of the type
const size_t size = _script->readUint16BE();
if ((size % 4) != 0)
throw Common::Exception("NCSFile::o_eq(): size %% 4 != 0");
n = size / 4;
}
std::vector<Variable> args1, args2;
args1.reserve(n);
args2.reserve(n);
for (size_t i = 0; i < n; i++)
args1.push_back(_stack.pop());
for (size_t i = 0; i < n; i++)
args2.push_back(_stack.pop());
_stack.push(args1 == args2);
}
/** NEQ: compare the top-most stack elements for inequality (!=). */
void NCSFile::o_neq(InstructionType type) {
size_t n = 1;
if (type == kInstTypeStructStruct) {
// Comparisons between two structs (or two vectors) come with the size of the type
const size_t size = _script->readUint16BE();
if ((size % 4) != 0)
throw Common::Exception("NCSFile::o_neq(): size %% 4 != 0");
n = size / 4;
}
std::vector<Variable> args1, args2;
args1.reserve(n);
args2.reserve(n);
for (size_t i = 0; i < n; i++)
args1.push_back(_stack.pop());
for (size_t i = 0; i < n; i++)
args2.push_back(_stack.pop());
_stack.push(args1 != args2);
}
/** GEQ: compare the top-most stack elements, greater-or-equal (>=). */
void NCSFile::o_geq(InstructionType type) {
switch (type) {
case kInstTypeIntInt:
{
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg2 >= arg1);
}
break;
case kInstTypeFloatFloat:
{
float arg1 = _stack.pop().getFloat();
float arg2 = _stack.pop().getFloat();
_stack.push(arg2 >= arg1);
}
break;
default:
throw Common::Exception("NCSFile::o_geq(): Illegal type %d", type);
}
}
/** GT: compare the top-most stack elements, greater (>). */
void NCSFile::o_gt(InstructionType type) {
switch (type) {
case kInstTypeIntInt:
{
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg2 > arg1);
}
break;
case kInstTypeFloatFloat:
{
float arg1 = _stack.pop().getFloat();
float arg2 = _stack.pop().getFloat();
_stack.push(arg2 > arg1);
}
break;
default:
throw Common::Exception("NCSFile::o_gt(): Illegal type %d", type);
}
}
/** LT: compare the top-most stack elements, less (<). */
void NCSFile::o_lt(InstructionType type) {
switch (type) {
case kInstTypeIntInt:
{
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg2 < arg1);
}
break;
case kInstTypeFloatFloat:
{
float arg1 = _stack.pop().getFloat();
float arg2 = _stack.pop().getFloat();
_stack.push(arg2 < arg1);
}
break;
default:
throw Common::Exception("NCSFile::o_lt(): Illegal type %d", type);
}
}
/** LEQ: compare the top-most stack elements, less-or-equal (<=). */
void NCSFile::o_leq(InstructionType type) {
switch (type) {
case kInstTypeIntInt:
{
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg2 <= arg1);
}
break;
case kInstTypeFloatFloat:
{
float arg1 = _stack.pop().getFloat();
float arg2 = _stack.pop().getFloat();
_stack.push(arg2 <= arg1);
}
break;
default:
throw Common::Exception("NCSFile::o_leq(): Illegal type %d", type);
}
}
/** SHLEFT: shift the top-most stack element to the left (<<). */
void NCSFile::o_shleft(InstructionType type) {
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_shleft(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg2 << arg1);
}
/** SHRIGHT: signed-shift the top-most stack element to the right (>>>). */
void NCSFile::o_shright(InstructionType type) {
/* According to Skywing's NWNScriptLib
* (<https://github.com/SkywingvL/nwn2dev-public/blob/master/NWNScriptLib/NWScriptVM.cpp#L2233>):
* "The operation implemented here is actually a complex sequence that, if
* the amount to be shifted is negative, involves both a front-loaded and
* end-loaded negate built on top of a signed shift." */
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_shright(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
if (arg2 < 0) {
arg2 = -arg2;
_stack.push(-(arg2 >> arg1));
} else
_stack.push(arg2 >> arg1);
}
/** USHRIGHT: shift the top-most stack element to the right (>>). */
void NCSFile::o_ushright(InstructionType type) {
/* According to Skywing's NWNScriptLib
* (<https://github.com/SkywingvL/nwn2dev-public/blob/master/NWNScriptLib/NWScriptVM.cpp#L2272>):
* "While this operator may have originally been intended to implement
* an unsigned shift, it actually performs an arithmetic (signed) shift." */
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_ushright(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
_stack.push(arg2 >> arg1);
}
/** MOD: calculate the remainder (modulo) of an integer division (%). */
void NCSFile::o_mod(InstructionType type) {
if (type != kInstTypeIntInt)
throw Common::Exception("NCSFile::o_mod(): Illegal type %d", type);
int32_t arg1 = _stack.pop().getInt();
int32_t arg2 = _stack.pop().getInt();
if (arg1 == 0)
throw Common::Exception("NCSFile::o_mod(): Modulus by zero");
else if (arg1 < 0 || arg2 < 0)
throw Common::Exception("NCSFile::o_mod(): Modulus by negative number (%d %% %d)", arg2, arg1);
_stack.push(arg2 % arg1);
}
/** NEQ: negate the top-most stack element (unary -). */
void NCSFile::o_neg(InstructionType type) {
switch (type) {
case kInstTypeInt:
_stack.push(-_stack.pop().getInt());
break;
case kInstTypeFloat:
_stack.push(-_stack.pop().getFloat());
break;
default:
throw Common::Exception("NCSFile::o_neg(): Illegal type %d", type);
}
}
/** COMP: calculate the 1-complement of the top-most stack element (~). */
void NCSFile::o_comp(InstructionType type) {
if (type != kInstTypeInt)
throw Common::Exception("NCSFile::o_comp(): Illegal type %d", type);
_stack.push(~_stack.pop().getInt());
}
/** MOVSP: pop elements off the stack. */
void NCSFile::o_movsp(InstructionType type) {
if (type != kInstTypeNone)
throw Common::Exception("NCSFile::o_movsp(): Illegal type %d", type);
_stack.setStackPtr(_stack.getStackPtr() - _script->readSint32BE());
}
/** JMP: jump directly to a different script offset. */
void NCSFile::o_jmp(InstructionType type) {
if (type != kInstTypeNone)
throw Common::Exception("NCSFile::o_jmp(): Illegal type %d", type);
int32_t offset = _script->readSint32BE();
_script->skip(offset - 6);
}
/** JZ: jump conditionally if the top-most stack element is 0. */
void NCSFile::o_jz(InstructionType type) {
if (type != kInstTypeNone)
throw Common::Exception("NCSFile::o_jz(): Illegal type %d", type);
int32_t offset = _script->readSint32BE();
if (!_stack.pop().getInt())
_script->skip(offset - 6);
}
/** NOT: boolean-negate the top-most stack element (!). */
void NCSFile::o_not(InstructionType type) {
if (type != kInstTypeInt)
throw Common::Exception("NCSFile::o_not(): Illegal type %d", type);
_stack.push(!_stack.pop().getInt());
}
/** DECSP: decrement the value of a stack element (--). */
void NCSFile::o_decsp(InstructionType type) {
if (type != kInstTypeInt)
throw Common::Exception("NCSFile::o_decsp(): Illegal type %d", type);
int32_t offset = _script->readSint32BE();
_stack.setRelSP(offset, _stack.getRelSP(offset).getInt() - 1);
}
/** INCSP: increment the value of a stack element (++). */