forked from Warzone2100/warzone2100
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqtscriptfuncs.cpp
2790 lines (2642 loc) · 115 KB
/
qtscriptfuncs.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
/*
This file is part of Warzone 2100.
Copyright (C) 2011 Warzone 2100 Project
Warzone 2100 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 2 of the License, or
(at your option) any later version.
Warzone 2100 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 Warzone 2100; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file qtscriptfuncs.cpp
*
* New scripting system -- script functions
*/
#include "lib/framework/wzapp.h"
#include "lib/framework/wzconfig.h"
#include "lib/sound/audio.h"
#include "lib/netplay/netplay.h"
#include "qtscriptfuncs.h"
#include <QtScript/QScriptValue>
#include <QtCore/QStringList>
#include "action.h"
#include "console.h"
#include "design.h"
#include "map.h"
#include "mission.h"
#include "group.h"
#include "transporter.h"
#include "message.h"
#include "display3d.h"
#include "intelmap.h"
#include "hci.h"
#include "wrappers.h"
#include "challenge.h"
#include "research.h"
#include "multilimit.h"
#include "multigifts.h"
#include "template.h"
#include "lighting.h"
#include "radar.h"
#include "frontend.h"
#include "loop.h"
#include "scriptextern.h"
#include "gateway.h"
#include "mapgrid.h"
#define FAKE_REF_LASSAT 999
#define ALL_PLAYERS -1
#define ALLIES -2
#define ENEMIES -3
// hack, this is used from scriptfuncs.cpp -- and we don't want to include any stinkin' wzscript headers here!
// TODO, move this stuff into a script common subsystem
extern bool structDoubleCheck(BASE_STATS *psStat,UDWORD xx,UDWORD yy, SDWORD maxBlockingTiles);
extern Vector2i positions[MAX_PLAYERS];
extern std::vector<Vector2i> derricks;
#define SCRIPT_ASSERT_PLAYER(_context, _player) \
SCRIPT_ASSERT(_context, _player >= 0 && _player < MAX_PLAYERS, "Invalid player index %d", _player);
// ----------------------------------------------------------------------------------------
// Utility functions -- not called directly from scripts
//;; \subsection{Research}
//;; Describes a research item. The following properties are defined:
//;; \begin{description}
//;; \item[power] Number of power points needed for starting the research.
//;; \item[points] Number of resarch points needed to complete the research.
//;; \item[started] A boolean saying whether or not this research has been started by current player or any of its allies.
//;; \item[done] A boolean saying whether or not this research has been completed.
//;; \item[name] A string containing the canonical name of the research.
//;; \end{description}
QScriptValue convResearch(RESEARCH *psResearch, QScriptEngine *engine, int player)
{
QScriptValue value = engine->newObject();
value.setProperty("power", (int)psResearch->researchPower);
value.setProperty("points", (int)psResearch->researchPoints);
bool started = false;
for (int i = 0; i < game.maxPlayers; i++)
{
if (aiCheckAlliances(player, i) || player == i)
{
int bits = asPlayerResList[i][psResearch->index].ResearchStatus;
started = started || (bits & STARTED_RESEARCH) || (bits & STARTED_RESEARCH_PENDING) || (bits & RESBITS_PENDING_ONLY);
}
}
value.setProperty("started", started); // including whether an ally has started it
value.setProperty("done", IsResearchCompleted(&asPlayerResList[player][psResearch->index]));
value.setProperty("name", psResearch->pName);
return value;
}
//;; \subsection{Structure\label{objects:structure}}
//;; Describes a structure (building). It inherits all the properties of the base object (see below).
//;; In addition, the following properties are defined:
//;; \begin{description}
//;; \item[status] The completeness status of the structure. It will be one of BEING_BUILT and BUILT.
//;; \item[type] The type will always be STRUCTURE.
//;; \item[cost] What it would cost to build this structure. (3.2+ only)
//;; \item[stattype] The stattype defines the type of structure. It will be one of HQ, FACTORY, POWER_GEN, RESOURCE_EXTRACTOR,
//;; LASSAT, DEFENSE, WALL, RESEARCH_LAB, REPAIR_FACILITY, CYBORG_FACTORY, VTOL_FACTORY, REARM_PAD, SAT_UPLINK, GATE
//;; and COMMAND_CONTROL.
//;; \item[modules] If the stattype is set to one of the factories, POWER_GEN or RESEARCH_LAB, then this property is set to the
//;; number of module upgrades it has.
//;; \item[canHitAir] True if the structure has anti-air capabilities. (3.2+ only)
//;; \item[canHitGround] True if the structure has anti-ground capabilities. (3.2+ only)
//;; \item[isSensor] True if the structure has sensor ability. (3.2+ only)
//;; \item[isCB] True if the structure has counter-battery ability. (3.2+ only)
//;; \item[isRadarDetector] True if the structure has radar detector ability. (3.2+ only)
//;; \item[range] Maximum range of its weapons. (3.2+ only)
//;; \item[hasIndirect] One or more of the structure's weapons are indirect. (3.2+ only)
//;; \end{description}
QScriptValue convStructure(STRUCTURE *psStruct, QScriptEngine *engine)
{
bool aa = false;
bool ga = false;
bool indirect = false;
int range = -1;
for (int i = 0; i < psStruct->numWeaps; i++)
{
if (psStruct->asWeaps[i].nStat)
{
WEAPON_STATS *psWeap = &asWeaponStats[psStruct->asWeaps[i].nStat];
aa = aa || psWeap->surfaceToAir & SHOOT_IN_AIR;
ga = ga || psWeap->surfaceToAir & SHOOT_ON_GROUND;
indirect = indirect || psWeap->movementModel == MM_INDIRECT || psWeap->movementModel == MM_HOMINGINDIRECT;
range = MAX((int)psWeap->longRange, range);
}
}
QScriptValue value = convObj(psStruct, engine);
value.setProperty("isCB", structCBSensor(psStruct), QScriptValue::ReadOnly);
value.setProperty("isSensor", structStandardSensor(psStruct), QScriptValue::ReadOnly);
value.setProperty("canHitAir", aa, QScriptValue::ReadOnly);
value.setProperty("canHitGround", ga, QScriptValue::ReadOnly);
value.setProperty("hasIndirect", indirect, QScriptValue::ReadOnly);
value.setProperty("isRadarDetector", objRadarDetector(psStruct), QScriptValue::ReadOnly);
value.setProperty("range", range, QScriptValue::ReadOnly);
value.setProperty("status", (int)psStruct->status, QScriptValue::ReadOnly);
value.setProperty("health", 100 * structureBody(psStruct) / MAX(1, psStruct->body), QScriptValue::ReadOnly);
value.setProperty("cost", psStruct->pStructureType->powerToBuild, QScriptValue::ReadOnly);
switch (psStruct->pStructureType->type) // don't bleed our source insanities into the scripting world
{
case REF_WALL:
case REF_WALLCORNER:
case REF_GATE:
value.setProperty("stattype", (int)REF_WALL, QScriptValue::ReadOnly);
break;
case REF_BLASTDOOR:
case REF_DEFENSE:
if (isLasSat(psStruct->pStructureType))
{
value.setProperty("stattype", (int)FAKE_REF_LASSAT, QScriptValue::ReadOnly);
break;
}
value.setProperty("stattype", (int)REF_DEFENSE, QScriptValue::ReadOnly);
break;
default:
value.setProperty("stattype", (int)psStruct->pStructureType->type, QScriptValue::ReadOnly);
break;
}
if (psStruct->pStructureType->type == REF_FACTORY || psStruct->pStructureType->type == REF_CYBORG_FACTORY
|| psStruct->pStructureType->type == REF_VTOL_FACTORY)
{
FACTORY *psFactory = (FACTORY *)psStruct->pFunctionality;
value.setProperty("modules", psFactory->capacity, QScriptValue::ReadOnly);
}
else if (psStruct->pStructureType->type == REF_RESEARCH)
{
value.setProperty("modules", ((RESEARCH_FACILITY *)psStruct->pFunctionality)->capacity, QScriptValue::ReadOnly);
}
else if (psStruct->pStructureType->type == REF_POWER_GEN)
{
value.setProperty("modules", ((POWER_GEN *)psStruct->pFunctionality)->capacity);
}
else
{
value.setProperty("modules", QScriptValue::NullValue);
}
return value;
}
//;; \subsection{Feature}
//;; Describes a feature (a \emph{game object} not owned by any player). It inherits all the properties of the base object (see below).
//;; In addition, the following properties are defined:
//;; \begin{description}
//;; \item[type] It will always be FEATURE.
//;; \item[damageable] Can this feature be damaged?
//;; \end{description}
QScriptValue convFeature(FEATURE *psFeature, QScriptEngine *engine)
{
QScriptValue value = convObj(psFeature, engine);
value.setProperty("health", 100 * psFeature->psStats->body / MAX(1, psFeature->body), QScriptValue::ReadOnly);
value.setProperty("damageable", psFeature->psStats->damageable, QScriptValue::ReadOnly);
return value;
}
//;; \subsection{Droid}
//;; Describes a droid. It inherits all the properties of the base object (see below).
//;; In addition, the following properties are defined:
//;; \begin{description}
//;; \item[type] It will always be DROID.
//;; \item[order] The current order of the droid. This is its plan. The following orders are defined:
//;; \begin{description}
//;; \item[DORDER_ATTACK] Order a droid to attack something.
//;; \item[DORDER_MOVE] Order a droid to move somewhere.
//;; \item[DORDER_SCOUT] Order a droid to move somewhere and stop to attack anything on the way.
//;; \item[DORDER_BUILD] Order a droid to build something.
//;; \item[DORDER_HELPBUILD] Order a droid to help build something.
//;; \item[DORDER_LINEBUILD] Order a droid to build something repeatedly in a line.
//;; \item[DORDER_REPAIR] Order a droid to repair something.
//;; \item[DORDER_RETREAT] Order a droid to retreat back to HQ.
//;; \item[DORDER_PATROL] Order a droid to patrol.
//;; \item[DORDER_DEMOLISH] Order a droid to demolish something.
//;; \item[DORDER_EMBARK] Order a droid to embark on a transport.
//;; \item[DORDER_DISEMBARK] Order a transport to disembark its units at the given position.
//;; \item[DORDER_FIRESUPPORT] Order a droid to fire at whatever the target sensor is targeting. (3.2+ only)
//;; \item[DORDER_STOP] Order a droid to stop whatever it is doing. (3.2+ only)
//;; \item[DORDER_RTR] Order a droid to return for repairs. (3.2+ only)
//;; \item[DORDER_RTB] Order a droid to return to base. (3.2+ only)
//;; \item[DORDER_HOLD] Order a droid to hold its position. (3.2+ only)
//;; \item[DORDER_REARM] Order a VTOL droid to rearm. If given a target, will go to specified rearm pad. If not, will go to nearest rearm pad. (3.2+ only)
//;; \item[DORDER_OBSERVE] Order a droid to keep a target in sensor view. (3.2+ only)
//;; \item[DORDER_RECOVER] Order a droid to pick up something. (3.2+ only)
//;; \end{description}
//;; \item[action] The current action of the droid. This is how it intends to carry out its plan. The
//;; C++ code may change the action frequently as it tries to carry out its order. You never want to set
//;; the action directly, but it may be interesting to look at what it currently is.
//;; \item[droidType] The droid's type. The following types are defined:
//;; \begin{description}
//;; \item[DROID_CONSTRUCT] Trucks and cyborg constructors.
//;; \item[DROID_WEAPON] Droids with weapon turrets, except cyborgs.
//;; \item[DROID_PERSON] Non-cyborg two-legged units, like scavengers.
//;; \item[DROID_REPAIR] Units with repair turret, including repair cyborgs.
//;; \item[DROID_SENSOR] Units with sensor turret.
//;; \item[DROID_ECM] Unit with ECM jammer turret.
//;; \item[DROID_CYBORG] Cyborgs with weapons.
//;; \item[DROID_TRANSPORTER] Cyborg transporter.
//;; \item[DROID_SUPERTRANSPORTER] Droid transporter.
//;; \item[DROID_COMMAND] Commanders.
//;; \end{description}
//;; \item[group] The group this droid is member of. This is a numerical ID. If not a member of any group, will be set to \emph{null}.
//;; \item[armed] The percentage of weapon capability that is fully armed. Will be \emph{null} for droids other than VTOLs.
//;; \item[experience] Amount of experience this droid has, based on damage it has dealt to enemies.
//;; \item[cost] What it would cost to build the droid. (3.2+ only)
//;; \item[isVTOL] True if the droid is VTOL. (3.2+ only)
//;; \item[canHitAir] True if the droid has anti-air capabilities. (3.2+ only)
//;; \item[canHitGround] True if the droid has anti-ground capabilities. (3.2+ only)
//;; \item[isSensor] True if the droid has sensor ability. (3.2+ only)
//;; \item[isCB] True if the droid has counter-battery ability. (3.2+ only)
//;; \item[isRadarDetector] True if the droid has radar detector ability. (3.2+ only)
//;; \item[hasIndirect] One or more of the droid's weapons are indirect. (3.2+ only)
//;; \item[range] Maximum range of its weapons. (3.2+ only)
//;; \item[body] The body component of the droid. (3.2+ only)
//;; \item[propulsion] The propulsion component of the droid. (3.2+ only)
//;; \end{description}
QScriptValue convDroid(DROID *psDroid, QScriptEngine *engine)
{
bool aa = false;
bool ga = false;
bool indirect = false;
int range = -1;
for (int i = 0; i < psDroid->numWeaps; i++)
{
if (psDroid->asWeaps[i].nStat)
{
WEAPON_STATS *psWeap = &asWeaponStats[psDroid->asWeaps[i].nStat];
aa = aa || psWeap->surfaceToAir & SHOOT_IN_AIR;
ga = ga || psWeap->surfaceToAir & SHOOT_ON_GROUND;
indirect = indirect || psWeap->movementModel == MM_INDIRECT || psWeap->movementModel == MM_HOMINGINDIRECT;
range = MAX((int)psWeap->longRange, range);
}
}
DROID_TYPE type = psDroid->droidType;
QScriptValue value = convObj(psDroid, engine);
value.setProperty("action", (int)psDroid->action, QScriptValue::ReadOnly);
if (range >= 0)
{
value.setProperty("range", range, QScriptValue::ReadOnly);
}
else
{
value.setProperty("range", QScriptValue::NullValue);
}
value.setProperty("order", (int)psDroid->order.type, QScriptValue::ReadOnly);
value.setProperty("cost", calcDroidPower(psDroid), QScriptValue::ReadOnly);
value.setProperty("hasIndirect", indirect, QScriptValue::ReadOnly);
switch (psDroid->droidType) // hide some engine craziness
{
case DROID_CYBORG_CONSTRUCT:
type = DROID_CONSTRUCT; break;
case DROID_DEFAULT:
case DROID_CYBORG_SUPER:
type = DROID_WEAPON; break;
case DROID_CYBORG_REPAIR:
type = DROID_REPAIR; break;
default:
break;
}
value.setProperty("isRadarDetector", objRadarDetector(psDroid), QScriptValue::ReadOnly);
value.setProperty("isCB", cbSensorDroid(psDroid), QScriptValue::ReadOnly);
value.setProperty("isSensor", standardSensorDroid(psDroid), QScriptValue::ReadOnly);
value.setProperty("canHitAir", aa, QScriptValue::ReadOnly);
value.setProperty("canHitGround", ga, QScriptValue::ReadOnly);
value.setProperty("isVTOL", isVtolDroid(psDroid), QScriptValue::ReadOnly);
value.setProperty("droidType", (int)type, QScriptValue::ReadOnly);
value.setProperty("experience", (double)psDroid->experience / 65536.0, QScriptValue::ReadOnly);
value.setProperty("health", 100.0 / (double)psDroid->originalBody * (double)psDroid->body, QScriptValue::ReadOnly);
value.setProperty("body", asBodyStats[psDroid->asBits[COMP_BODY].nStat].pName);
value.setProperty("propulsion", asBodyStats[psDroid->asBits[COMP_PROPULSION].nStat].pName);
if (isVtolDroid(psDroid))
{
value.setProperty("armed", 100.0 / (double)MAX(asWeaponStats[psDroid->asWeaps[0].nStat].numRounds, 1)
* (double)psDroid->asWeaps[0].ammo);
if (psDroid->asWeaps[0].ammo > asWeaponStats[psDroid->asWeaps[0].nStat].numRounds)
debug(LOG_ERROR, "%s has %d and %d", objInfo(psDroid), psDroid->asWeaps[0].ammo, asWeaponStats[psDroid->asWeaps[0].nStat].numRounds);
}
else
{
value.setProperty("armed", QScriptValue::NullValue);
}
if (psDroid->psGroup)
{
value.setProperty("group", (int)psDroid->psGroup->id, QScriptValue::ReadOnly);
}
else
{
value.setProperty("group", QScriptValue::NullValue);
}
return value;
}
//;; \subsection{Base Object}
//;; Describes a basic object. It will always be a droid, structure or feature, but sometimes
//;; the difference does not matter, and you can treat any of them simply as a basic object.
//;; The following properties are defined:
//;; \begin{description}
//;; \item[type] It will be one of DROID, STRUCTURE or FEATURE.
//;; \item[id] The unique ID of this object.
//;; \item[x] X position of the object in tiles.
//;; \item[y] Y position of the object in tiles.
//;; \item[z] Z (height) position of the object in tiles.
//;; \item[player] The player owning this object.
//;; \item[selected] A boolean saying whether 'selectedPlayer' has selected this object.
//;; \item[name] A user-friendly name for this object.
//;; \item[health] Percentage that this object is damaged (where 100% means not damaged at all).
//;; \item[armour] Amount of armour points that protect against kinetic weapons.
//;; \item[thermal] Amount of thermal protection that protect against heat based weapons.
//;; \item[born] The game time at which this object was produced or came into the world. (3.2+ only)
//;; \end{description}
QScriptValue convObj(BASE_OBJECT *psObj, QScriptEngine *engine)
{
QScriptValue value = engine->newObject();
ASSERT_OR_RETURN(value, psObj, "No object for conversion");
value.setProperty("id", psObj->id, QScriptValue::ReadOnly);
value.setProperty("x", map_coord(psObj->pos.x), QScriptValue::ReadOnly);
value.setProperty("y", map_coord(psObj->pos.y), QScriptValue::ReadOnly);
value.setProperty("z", map_coord(psObj->pos.z), QScriptValue::ReadOnly);
value.setProperty("player", psObj->player, QScriptValue::ReadOnly);
value.setProperty("armour", psObj->armour[WC_KINETIC], QScriptValue::ReadOnly);
value.setProperty("thermal", psObj->armour[WC_HEAT], QScriptValue::ReadOnly);
value.setProperty("type", psObj->type, QScriptValue::ReadOnly);
value.setProperty("selected", psObj->selected, QScriptValue::ReadOnly);
value.setProperty("name", objInfo(psObj), QScriptValue::ReadOnly);
value.setProperty("born", psObj->born, QScriptValue::ReadOnly);
return value;
}
QScriptValue convMax(BASE_OBJECT *psObj, QScriptEngine *engine)
{
switch (psObj->type)
{
case OBJ_DROID: return convDroid((DROID *)psObj, engine);
case OBJ_STRUCTURE: return convStructure((STRUCTURE *)psObj, engine);
case OBJ_FEATURE: return convFeature((FEATURE *)psObj, engine);
default: ASSERT(false, "No such supported object type"); return convObj(psObj, engine);
}
}
// ----------------------------------------------------------------------------------------
// Label system (function defined in qtscript.h header)
//
struct labeltype { Vector2i p1, p2; int id; int type; int player; };
static QHash<QString, labeltype> labels;
// Load labels
bool loadLabels(const char *filename)
{
if (!PHYSFS_exists(filename))
{
debug(LOG_SAVE, "No %s found -- not adding any labels", filename);
return false;
}
WzConfig ini(filename);
if (ini.status() != QSettings::NoError)
{
debug(LOG_ERROR, "No label file %s", filename);
return false;
}
labels.clear();
QStringList list = ini.childGroups();
debug(LOG_SAVE, "Loading %d labels...", list.size());
for (int i = 0; i < list.size(); ++i)
{
ini.beginGroup(list[i]);
labeltype p;
QString label(ini.value("label").toString());
if (labels.contains(label))
{
debug(LOG_ERROR, "Duplicate label found");
}
else if (list[i].startsWith("position"))
{
p.p1 = ini.vector2i("pos");
p.p2 = p.p1;
p.type = SCRIPT_POSITION;
p.player = -1;
p.id = -1;
labels.insert(label, p);
}
else if (list[i].startsWith("area"))
{
p.p1 = ini.vector2i("pos1");
p.p2 = ini.vector2i("pos2");
p.type = SCRIPT_AREA;
p.player = -1;
p.id = -1;
labels.insert(label, p);
}
else if (list[i].startsWith("object"))
{
p.id = ini.value("id").toInt();
p.type = ini.value("type").toInt();
p.player = ini.value("player").toInt();
labels.insert(label, p);
}
else
{
debug(LOG_ERROR, "Misnamed group in %s", filename);
}
ini.endGroup();
}
return true;
}
bool writeLabels(const char *filename)
{
int c[3];
memset(c, 0, sizeof(c));
WzConfig ini(filename);
if (ini.status() != QSettings::NoError)
{
debug(LOG_ERROR, "Could not open %s", filename);
return false;
}
for (QHash<QString, labeltype>::const_iterator i = labels.constBegin(); i != labels.constEnd(); i++)
{
QString key = i.key();
labeltype l = i.value();
if (l.type == SCRIPT_POSITION)
{
ini.beginGroup("position_" + QString::number(c[0]++));
ini.setVector2i("pos", l.p1);
ini.setValue("label", key);
ini.endGroup();
}
else if (l.type == SCRIPT_AREA)
{
ini.beginGroup("area_" + QString::number(c[1]++));
ini.setVector2i("pos1", l.p1);
ini.setVector2i("pos2", l.p2);
ini.setValue("label", key);
ini.endGroup();
}
else
{
ini.beginGroup("object_" + QString::number(c[2]++));
ini.setValue("id", l.id);
ini.setValue("player", l.player);
ini.setValue("type", l.type);
ini.setValue("label", key);
ini.endGroup();
}
}
return true;
}
// ----------------------------------------------------------------------------------------
// Script functions
//
// All script functions should be prefixed with "js_" then followed by same name as in script.
//-- \subsection{enumLabels()}
//-- Returns a string list of labels that exist for this map. (3.2+ only)
static QScriptValue js_enumLabels(QScriptContext *, QScriptEngine *engine)
{
QStringList matches = labels.keys();
QScriptValue result = engine->newArray(matches.size());
for (int i = 0; i < matches.size(); i++)
{
result.setProperty(i, QScriptValue(matches[i]), QScriptValue::ReadOnly);
}
return result;
}
//-- \subsection{label(key)}
//-- Fetch something denoted by a label. A label refers to an area, a position or a \emph{game object} on
//-- the map defined using the map editor and stored together with the map. The only argument
//-- is a text label. The function returns an object that has a type variable defining what it
//-- is (in case this is unclear). This type will be one of DROID, STRUCTURE, FEATURE, AREA
//-- and POSITION. The AREA has defined 'x', 'y', 'x2', and 'y2', while POSITION has only
//-- defined 'x' and 'y'.
static QScriptValue js_label(QScriptContext *context, QScriptEngine *engine)
{
QString label = context->argument(0).toString();
QScriptValue ret = engine->newObject();
if (labels.contains(label))
{
labeltype p = labels.value(label);
if (p.type == SCRIPT_AREA || p.type == SCRIPT_POSITION)
{
ret.setProperty("x", map_coord(p.p1.x), QScriptValue::ReadOnly);
ret.setProperty("y", map_coord(p.p1.y), QScriptValue::ReadOnly);
ret.setProperty("type", p.type, QScriptValue::ReadOnly);
}
if (p.type == SCRIPT_AREA)
{
ret.setProperty("x2", map_coord(p.p2.x), QScriptValue::ReadOnly);
ret.setProperty("xy", map_coord(p.p2.y), QScriptValue::ReadOnly);
}
else if (p.type == OBJ_DROID)
{
DROID *psDroid = IdToDroid(p.id, p.player);
if (psDroid) ret = convDroid(psDroid, engine);
}
else if (p.type == OBJ_STRUCTURE)
{
STRUCTURE *psStruct = IdToStruct(p.id, p.player);
if (psStruct) ret = convStructure(psStruct, engine);
}
else if (p.type == OBJ_FEATURE)
{
FEATURE *psFeature = IdToFeature(p.id, p.player);
if (psFeature) ret = convFeature(psFeature, engine);
}
}
else debug(LOG_ERROR, "label %s not found!", label.toUtf8().constData());
return ret;
}
//-- \subsection{enumBlips(player)}
//-- Return an array containing all the non-transient radar blips that the given player
//-- can see. This includes sensors revealed by radar detectors, as well as ECM jammers.
//-- It does not include units going out of view.
static QScriptValue js_enumBlips(QScriptContext *context, QScriptEngine *engine)
{
QList<Position> matches;
int player = context->argument(0).toInt32();
SCRIPT_ASSERT_PLAYER(context, player);
for (BASE_OBJECT *psSensor = apsSensorList[0]; psSensor; psSensor = psSensor->psNextFunc)
{
if (psSensor->visible[player] > 0 && psSensor->visible[player] < UBYTE_MAX)
{
matches.push_back(psSensor->pos);
}
}
QScriptValue result = engine->newArray(matches.size());
for (int i = 0; i < matches.size(); i++)
{
Position p = matches.at(i);
QScriptValue v = engine->newObject();
v.setProperty("x", map_coord(p.x), QScriptValue::ReadOnly);
v.setProperty("y", map_coord(p.y), QScriptValue::ReadOnly);
result.setProperty(i, v);
}
return result;
}
//-- \subsection{enumGateways()}
//-- Return an array containing all the gateways on the current map. The array contains object with the properties
//-- x1, y1, x2 and y2.
static QScriptValue js_enumGateways(QScriptContext *, QScriptEngine *engine)
{
QScriptValue result = engine->newArray(gwNumGateways());
int i = 0;
for (GATEWAY *psGateway = gwGetGateways(); psGateway; psGateway = psGateway->psNext)
{
QScriptValue v = engine->newObject();
v.setProperty("x1", psGateway->x1, QScriptValue::ReadOnly);
v.setProperty("y1", psGateway->y1, QScriptValue::ReadOnly);
v.setProperty("x2", psGateway->x2, QScriptValue::ReadOnly);
v.setProperty("y2", psGateway->y2, QScriptValue::ReadOnly);
result.setProperty(i++, v);
}
return result;
}
//-- \subsection{enumGroup(group)}
//-- Return an array containing all the droid members of a given group.
static QScriptValue js_enumGroup(QScriptContext *context, QScriptEngine *engine)
{
int groupId = context->argument(0).toInt32();
QList<DROID *> matches;
DROID_GROUP *psGroup = grpFind(groupId);
DROID *psCurr;
SCRIPT_ASSERT(context, psGroup, "Invalid group index %d", groupId);
for (psCurr = psGroup->psList; psCurr != NULL; psCurr = psCurr->psGrpNext)
{
matches.push_back(psCurr);
}
QScriptValue result = engine->newArray(matches.size());
for (int i = 0; i < matches.size(); i++)
{
DROID *psDroid = matches.at(i);
result.setProperty(i, convDroid(psDroid, engine));
}
return result;
}
//-- \subsection{newGroup()}
//-- Allocate a new group. Returns its numerical ID.
static QScriptValue js_newGroup(QScriptContext *, QScriptEngine *)
{
DROID_GROUP *newGrp = grpCreate();
return QScriptValue(newGrp->id);
}
//-- \subsection{activateStructure(structure, [target[, ability]])}
//-- Activate a special ability on a structure. Currently only works on the lassat.
//-- The lassat needs a target.
static QScriptValue js_activateStructure(QScriptContext *context, QScriptEngine *)
{
QScriptValue structVal = context->argument(0);
int id = structVal.property("id").toInt32();
int player = structVal.property("player").toInt32();
STRUCTURE *psStruct = IdToStruct(id, player);
SCRIPT_ASSERT(context, psStruct, "No such structure id %d belonging to player %d", id, player);
// ... and then do nothing with psStruct yet
QScriptValue objVal = context->argument(1);
int oid = objVal.property("id").toInt32();
int oplayer = objVal.property("player").toInt32();
BASE_OBJECT *psObj = IdToPointer(oid, oplayer);
SCRIPT_ASSERT(context, psObj, "No such object id %d belonging to player %d", oid, oplayer);
orderStructureObj(player, psObj);
return QScriptValue(true);
}
//-- \subsection{findResearch(research)}
//-- Return list of research items remaining to research for the given research item. (3.2+ only)
static QScriptValue js_findResearch(QScriptContext *context, QScriptEngine *engine)
{
QList<RESEARCH *> list;
QString resName = context->argument(0).toString();
int player = engine->globalObject().property("me").toInt32();
RESEARCH *psTarget = getResearch(resName.toUtf8().constData());
SCRIPT_ASSERT(context, psTarget, "No such research: %s", resName.toUtf8().constData());
PLAYER_RESEARCH *plrRes = &asPlayerResList[player][psTarget->index];
if (IsResearchStartedPending(plrRes) || IsResearchCompleted(plrRes))
{
return engine->newArray(0); // return empty array
}
// Go down the requirements list for the desired tech
QList<RESEARCH *> reslist;
RESEARCH *cur = psTarget;
while (cur)
{
if (!(asPlayerResList[player][cur->index].ResearchStatus & RESEARCHED))
{
debug(LOG_SCRIPT, "Added research in %d's %s for %s", player, cur->pName, psTarget->pName);
list.append(cur);
}
RESEARCH *prev = cur;
cur = NULL;
if (prev->pPRList.size())
{
cur = &asResearch[prev->pPRList[0]]; // get first pre-req
}
for (int i = 1; i < prev->pPRList.size(); i++)
{
// push any other pre-reqs on the stack
reslist += &asResearch[prev->pPRList[i]];
}
if (!cur && reslist.size())
{
cur = reslist.takeFirst(); // retrieve options from the stack
}
}
QScriptValue retval = engine->newArray(list.size());
for (int i = 0; i < list.size(); i++)
{
retval.setProperty(i, convResearch(list[i], engine, i));
}
return retval;
}
//-- \subsection{pursueResearch(lab, research)}
//-- Start researching the first available technology on the way to the given technology.
//-- First parameter is the structure to research in, which must be a research lab. The
//-- second parameter is the technology to pursue, as a text string as defined in "research.txt".
//-- The second parameter may also be an array of such strings. The first technology that has
//-- not yet been researched in that list will be pursued.
static QScriptValue js_pursueResearch(QScriptContext *context, QScriptEngine *engine)
{
QScriptValue structVal = context->argument(0);
int id = structVal.property("id").toInt32();
int player = structVal.property("player").toInt32();
STRUCTURE *psStruct = IdToStruct(id, player);
SCRIPT_ASSERT(context, psStruct, "No such structure id %d belonging to player %d", id, player);
QScriptValue list = context->argument(1);
RESEARCH *psResearch = NULL; // Dummy initialisation.
if (list.isArray())
{
int length = list.property("length").toInt32();
int k;
for (k = 0; k < length; k++)
{
QString resName = list.property(k).toString();
psResearch = getResearch(resName.toUtf8().constData());
SCRIPT_ASSERT(context, psResearch, "No such research: %s", resName.toUtf8().constData());
PLAYER_RESEARCH *plrRes = &asPlayerResList[player][psResearch->index];
if (!IsResearchStartedPending(plrRes) && !IsResearchCompleted(plrRes))
{
break; // use this one
}
}
if (k == length)
{
debug(LOG_SCRIPT, "Exhausted research list -- doing nothing");
return QScriptValue(false);
}
}
else
{
QString resName = list.toString();
psResearch = getResearch(resName.toUtf8().constData());
SCRIPT_ASSERT(context, psResearch, "No such research: %s", resName.toUtf8().constData());
PLAYER_RESEARCH *plrRes = &asPlayerResList[player][psResearch->index];
if (IsResearchStartedPending(plrRes) || IsResearchCompleted(plrRes))
{
debug(LOG_SCRIPT, "%s has already been researched!", resName.toUtf8().constData());
return QScriptValue(false);
}
}
SCRIPT_ASSERT(context, psStruct->pStructureType->type == REF_RESEARCH, "Not a research lab: %s", objInfo(psStruct));
RESEARCH_FACILITY *psResLab = (RESEARCH_FACILITY *)psStruct->pFunctionality;
SCRIPT_ASSERT(context, psResLab->psSubject == NULL, "Research lab not ready");
// Go down the requirements list for the desired tech
QList<RESEARCH *> reslist;
RESEARCH *cur = psResearch;
int iterations = 0; // Only used to assert we're not stuck in the loop.
while (cur)
{
if (researchAvailable(cur->index, player))
{
bool started = false;
for (int i = 0; i < game.maxPlayers; i++)
{
if (aiCheckAlliances(player, i) || i == player)
{
int bits = asPlayerResList[i][cur->index].ResearchStatus;
started = started || (bits & STARTED_RESEARCH) || (bits & STARTED_RESEARCH_PENDING)
|| (bits & RESBITS_PENDING_ONLY) || (bits & RESEARCHED);
}
}
if (!started) // found relevant item on the path?
{
sendResearchStatus(psStruct, cur->index, player, true);
#if defined (DEBUG)
char sTemp[128];
sprintf(sTemp, "player:%d starts topic from script: %s", player, cur->pName);
NETlogEntry(sTemp, SYNC_FLAG, 0);
#endif
debug(LOG_SCRIPT, "Started research in %d's %s(%d) of %s", player,
objInfo(psStruct), psStruct->id, cur->pName);
return QScriptValue(true);
}
}
RESEARCH *prev = cur;
cur = NULL;
if (prev->pPRList.size())
{
cur = &asResearch[prev->pPRList[0]]; // get first pre-req
}
for (int i = 1; i < prev->pPRList.size(); i++)
{
// push any other pre-reqs on the stack
reslist += &asResearch[prev->pPRList[i]];
}
if (!cur && reslist.size())
{
cur = reslist.takeFirst(); // retrieve options from the stack
}
ASSERT_OR_RETURN(QScriptValue(false), ++iterations < asResearch.size()*100 || !cur, "Possible cyclic dependencies in prerequisites, possibly of research \"%s\".", cur->pName);
}
debug(LOG_SCRIPT, "No research topic found for %s(%d)", objInfo(psStruct), psStruct->id);
return QScriptValue(false); // none found
}
//-- \subsection{getResearch(research)}
//-- Fetch information about a given technology item, given by a string that matches
//-- its definition in "research.txt". If not found, returns null.
static QScriptValue js_getResearch(QScriptContext *context, QScriptEngine *engine)
{
int player = engine->globalObject().property("me").toInt32();
QString resName = context->argument(0).toString();
RESEARCH *psResearch = getResearch(resName.toUtf8().constData());
if (!psResearch)
{
return QScriptValue::NullValue;
}
return convResearch(psResearch, engine, player);
}
//-- \subsection{enumResearch()}
//-- Returns an array of all research objects that are currently and immediately available for research.
static QScriptValue js_enumResearch(QScriptContext *context, QScriptEngine *engine)
{
QList<RESEARCH *> reslist;
int player = engine->globalObject().property("me").toInt32();
for (int i = 0; i < asResearch.size(); i++)
{
RESEARCH *psResearch = &asResearch[i];
if (!IsResearchCompleted(&asPlayerResList[player][i]) && researchAvailable(i, player))
{
reslist += psResearch;
}
}
QScriptValue result = engine->newArray(reslist.size());
for (int i = 0; i < reslist.size(); i++)
{
result.setProperty(i, convResearch(reslist[i], engine, player));
}
return result;
}
//-- \subsection{componentAvailable(component type, component name)}
//-- Checks whether a given component is available to the current player.
static QScriptValue js_componentAvailable(QScriptContext *context, QScriptEngine *engine)
{
int player = engine->globalObject().property("me").toInt32();
COMPONENT_TYPE comp = (COMPONENT_TYPE)context->argument(0).toInt32();
QString compName = context->argument(1).toString();
int result = getCompFromName(comp, compName.toUtf8().constData());
SCRIPT_ASSERT(context, result >= 0, "No such component: %s", compName.toUtf8().constData());
bool avail = apCompLists[player][comp][result] == AVAILABLE;
return QScriptValue(avail);
}
//-- \subsection{addFeature(x, y, name)}
//-- Create and place a feature at the given x, y position. Will cause a desync in multiplayer.
//-- Returns the created game object on success, null otherwise. (3.2+ only)
static QScriptValue js_addFeature(QScriptContext *context, QScriptEngine *engine)
{
int x = context->argument(0).toInt32();
int y = context->argument(1).toInt32();
QString featName = context->argument(2).toString();
int feature = getFeatureStatFromName(featName.toUtf8().constData());
FEATURE_STATS *psStats = &asFeatureStats[feature];
for (FEATURE *psFeat = apsFeatureLists[0]; psFeat; psFeat = psFeat->psNext)
{
SCRIPT_ASSERT(context, map_coord(psFeat->pos.x) != x || map_coord(psFeat->pos.y) != y,
"Building feature on tile already occupied");
return QScriptValue::NullValue;
}
return convFeature(buildFeature(psStats, world_coord(x), world_coord(y), false), engine);
}
//-- \subsection{addDroid(player, x, y, name, body, propulsion, reserved, droid type, turrets...)}
//-- Create and place a droid at the given x, y position as belonging to the given player, built with
//-- the given components. Currently does not support placing droids in multiplayer, doing so will
//-- cause a desync. Returns a boolean that is true on success.
static QScriptValue js_addDroid(QScriptContext *context, QScriptEngine *engine)
{
int player = context->argument(0).toInt32();
SCRIPT_ASSERT_PLAYER(context, player);
int x = context->argument(1).toInt32();
int y = context->argument(2).toInt32();
QString templName = context->argument(3).toString();
DROID_TEMPLATE sTemplate, *psTemplate = &sTemplate;
DROID_TYPE droidType = (DROID_TYPE)context->argument(7).toInt32();
int numTurrets = context->argumentCount() - 8; // anything beyond first eight parameters, are turrets
COMPONENT_TYPE compType = COMP_NUMCOMPONENTS;
memset(psTemplate->asParts, 0, sizeof(psTemplate->asParts)); // reset to defaults
memset(psTemplate->asWeaps, 0, sizeof(psTemplate->asWeaps));
int body = getCompFromName(COMP_BODY, context->argument(4).toString().toUtf8().constData());
int propulsion = getCompFromName(COMP_PROPULSION, context->argument(5).toString().toUtf8().constData());
if (body < 0)
{
debug(LOG_ERROR, "Wanted to build %s, but body type unavailable", templName.toUtf8().constData());
return QScriptValue(false); // no component available
}
if (propulsion < 0)
{
debug(LOG_ERROR, "Wanted to build %s, but propulsion type unavailable", templName.toUtf8().constData());
return QScriptValue(false); // no component available
}
psTemplate->asParts[COMP_BODY] = body;
psTemplate->asParts[COMP_PROPULSION] = propulsion;
psTemplate->numWeaps = 0;
for (int i = 0; i < numTurrets; i++)
{
context->argument(8 + i).toString();
int j;
switch (droidType)
{
case DROID_PERSON:
case DROID_WEAPON:
case DROID_CYBORG:
case DROID_TRANSPORTER:
case DROID_SUPERTRANSPORTER:
case DROID_DEFAULT:
case DROID_CYBORG_SUPER:
j = getCompFromName(COMP_WEAPON, context->argument(8 + i).toString().toUtf8().constData());
if (j < 0)
{
debug(LOG_SCRIPT, "Wanted to build %s at (%d, %d), but no weapon unavailable",
templName.toUtf8().constData(), x, y);
return QScriptValue(false);
}
psTemplate->asWeaps[i] = j;
psTemplate->numWeaps++;
continue;
case DROID_CYBORG_CONSTRUCT:
case DROID_CONSTRUCT:
compType = COMP_CONSTRUCT;
break;
case DROID_COMMAND:
compType = COMP_BRAIN;
psTemplate->numWeaps = 1; // hack, necessary to pass intValidTemplate
break;
case DROID_REPAIR:
case DROID_CYBORG_REPAIR:
compType = COMP_REPAIRUNIT;
break;
case DROID_ECM:
compType = COMP_ECM;
break;
case DROID_SENSOR:
compType = COMP_SENSOR;
break;
case DROID_ANY:
break; // wtf
}
j = getCompFromName(compType, context->argument(8 + i).toString().toUtf8().constData());
if (j < 0)
{
debug(LOG_SCRIPT, "Wanted to build %s, but turret unavailable", templName.toUtf8().constData());
return QScriptValue(false);
}
psTemplate->asParts[compType] = j;
}
psTemplate->droidType = droidType; // may be overwritten by the call below
bool valid = intValidTemplate(psTemplate, templName.toUtf8().constData(), true);
if (valid)
{
bool oldMulti = bMultiMessages;
bMultiMessages = false; // ugh, fixme
DROID *psDroid = buildDroid(psTemplate, world_coord(x), world_coord(y), player, false, NULL);
if (psDroid)
{
addDroid(psDroid, apsDroidLists);
debug(LOG_LIFE, "Created droid %s by script for player %d: %u", objInfo(psDroid), player, psDroid->id);
}
else
{
debug(LOG_ERROR, "Invalid droid %s", templName.toUtf8().constData());
}
bMultiMessages = oldMulti; // ugh
}
else
{
debug(LOG_ERROR, "Invalid template %s", templName.toUtf8().constData());
}
return QScriptValue(valid);
}
static int get_first_available_component(STRUCTURE *psFactory, const QScriptValue &list, COMPONENT_TYPE type)
{
const int player = psFactory->player;
const int capacity = psFactory->pFunctionality->factory.capacity; // check body size
if (list.isArray())
{
int length = list.property("length").toInt32();
int k;