forked from DFHack/dfhack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
siege-engine.cpp
2061 lines (1664 loc) · 56.5 KB
/
siege-engine.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
#include "Core.h"
#include <Console.h>
#include <Export.h>
#include <Error.h>
#include <PluginManager.h>
#include <modules/Gui.h>
#include <modules/Screen.h>
#include <modules/Maps.h>
#include <modules/MapCache.h>
#include <modules/World.h>
#include <modules/Units.h>
#include <modules/Job.h>
#include <modules/Materials.h>
#include <modules/Random.h>
#include <LuaTools.h>
#include <TileTypes.h>
#include <vector>
#include <cstdio>
#include <stack>
#include <string>
#include <cmath>
#include <string.h>
#include <VTableInterpose.h>
#include "df/building_drawbuffer.h"
#include "df/building_siegeenginest.h"
#include "df/building_stockpilest.h"
#include "df/buildings_other_id.h"
#include "df/builtin_mats.h"
#include "df/caste_raw.h"
#include "df/caste_raw_flags.h"
#include "df/creature_raw.h"
#include "df/flow_info.h"
#include "df/flow_type.h"
#include "df/game_mode.h"
#include "df/graphic.h"
#include "df/identity.h"
#include "df/invasion_info.h"
#include "df/item_actual.h"
#include "df/items_other_id.h"
#include "df/job.h"
#include "df/job.h"
#include "df/job_item.h"
#include "df/material.h"
#include "df/physical_attribute_type.h"
#include "df/proj_itemst.h"
#include "df/report.h"
#include "df/stockpile_links.h"
#include "df/strain_type.h"
#include "df/ui.h"
#include "df/ui_build_selector.h"
#include "df/unit.h"
#include "df/unit_misc_trait.h"
#include "df/unit_relationship_type.h"
#include "df/unit_skill.h"
#include "df/unit_soul.h"
#include "df/viewscreen_dwarfmodest.h"
#include "df/workshop_profile.h"
#include "df/world.h"
#include "MiscUtils.h"
using std::vector;
using std::string;
using std::stack;
using namespace DFHack;
using namespace df::enums;
using Screen::Pen;
DFHACK_PLUGIN("siege-engine");
REQUIRE_GLOBAL(gamemode);
REQUIRE_GLOBAL(gps);
REQUIRE_GLOBAL(world);
REQUIRE_GLOBAL(ui);
REQUIRE_GLOBAL(ui_build_selector);
REQUIRE_GLOBAL(process_jobs);
/*
Aiming is simulated by using a normal distribution to perturb X and Y.
The chance a normal distribution is within n*sigma of median is
erf(n/sqrt(2)). For direct hit, it must be within 0.5 tiles of
center, so it is erf(0.5/sigma/sqrt(2)) = erf(1/sigma/sqrt(8)).
Since it must hit in both X and Y, it must be squared, so final
is erf(1/sigma/sqrt(8))^2 = erf(skill*coeff/(distance*sqrt(8)))^2.
The chance to hit a RxR area is erf(skill*coeff*R/(distance*sqrt(8)))^2.
Catapults can fire between 30 and 100, and the projectile is supposed
to travel in an arc, and is thus harder to aim; yet they require a direct
hit unless using the feature for firing bins.
The coefficient of 30 gives the following probabilities:
| | Direct Hit | 3x3 Area Hit |
| | 30 50 100 | 30 50 100 |
| Novice | 15% 5% <5% | 75% 40% 10% |
| Adequate | 45% 20% 5% | 100% 85% 40% |
| Competent | 75% 40% 10% | 100% 100% 70% |
| Proficient | 100% 75% 30% | 100% 100% 95% |
| Professional | 100% 100% 80% | 100% 100% 100% |
| Legendary | 100% 100% 95% | 100% 100% 100% |
Original data:
* http://www.wolframalpha.com/input/?i=erf%2830*x%2Fsqrt%288%29%2F30%29^2%2C+erf%2830*x%2Fsqrt%288%29%2F50%29^2%2C+erf%2830*x%2Fsqrt%288%29%2F100%29^2%2C+x+from+0+to+15
* http://www.wolframalpha.com/input/?i=erf%2830*x*3%2Fsqrt%288%29%2F30%29^2%2C+erf%2830*x*3%2Fsqrt%288%29%2F50%29^2%2C+erf%2830*x*3%2Fsqrt%288%29%2F100%29^2%2C+x+from+0+to+6
Ballista can fire up to 200 tiles away, and can't use the bin method
to compensate for inaccuracy. On the other hand, it shoots straight
and should be easier to aim. It also damages everything in its path,
so the hit probability may be estimated using an 1D projection.
The coefficient of 48 gives the following probabilities:
| | Direct Hit | 1D Hit |
| | 30 50 100 200 | 30 50 100 200 |
| Novice | 25% 10% 5% <5% | 55% 35% 20% 10% |
| Adequate | 80% 45% 15% 5% | 90% 65% 40% 20% |
| Competent | 95% 70% 30% 8% | 100% 85% 50% 30% |
| Proficient | 100% 95% 65% 20% | 100% 100% 75% 45% |
| Accomplished | 100% 100% 95% 60% | 100% 100% 100% 75% |
| Legendary | 100% 100% 100% 85% | 100% 100% 100% 90% |
Original data:
* http://www.wolframalpha.com/input/?i=erf%2848*x%2Fsqrt%288%29%2F30%29^2%2C+erf%2848*x%2Fsqrt%288%29%2F50%29^2%2C+erf%2848*x%2Fsqrt%288%29%2F100%29^2%2C+erf%2848*x%2Fsqrt%288%29%2F200%29^2%2C+x+from+0+to+15
* http://www.wolframalpha.com/input/?i=erf%2848*x%2Fsqrt%288%29%2F30%29%2C+erf%2848*x%2Fsqrt%288%29%2F50%29%2C+erf%2848*x%2Fsqrt%288%29%2F100%29%2C+erf%2848*x%2Fsqrt%288%29%2F200%29%2C+x+from+0+to+15
Quality can increase range of both engines by 25% max, so it
also boosts aiming by 1.06x every step, up to 33.8% gain.
*/
/*
* Misc. utils
*/
static bool debug_mode = false;
static void setDebug(bool on)
{
debug_mode = on;
}
static void set_arrow_color(df::coord pos, int color)
{
auto tile = Maps::getTileOccupancy(pos);
if (tile)
tile->bits.arrow_color = color;
}
typedef std::pair<df::coord, df::coord> coord_range;
static void set_range(coord_range *target, df::coord p1, df::coord p2)
{
if (!p1.isValid() || !p2.isValid())
{
*target = coord_range();
}
else
{
target->first.x = std::min(p1.x, p2.x);
target->first.y = std::min(p1.y, p2.y);
target->first.z = std::min(p1.z, p2.z);
target->second.x = std::max(p1.x, p2.x);
target->second.y = std::max(p1.y, p2.y);
target->second.z = std::max(p1.z, p2.z);
}
}
static bool is_range_valid(const coord_range &target)
{
return target.first.isValid() && target.second.isValid();
}
static bool is_in_range(const coord_range &target, df::coord pos)
{
return target.first.isValid() && target.second.isValid() &&
target.first.x <= pos.x && pos.x <= target.second.x &&
target.first.y <= pos.y && pos.y <= target.second.y &&
target.first.z <= pos.z && pos.z <= target.second.z;
}
static std::pair<int, int> get_engine_range(df::building_siegeenginest *bld, float quality)
{
if (bld->type == siegeengine_type::Ballista)
return std::make_pair(1, 200 + int(10 * quality));
else
return std::make_pair(30 - int(quality), 100 + int(5 * quality));
}
static void orient_engine(df::building_siegeenginest *bld, df::coord target)
{
int dx = target.x - bld->centerx;
int dy = target.y - bld->centery;
if (abs(dx) > abs(dy))
bld->facing = (dx > 0) ?
df::building_siegeenginest::Right :
df::building_siegeenginest::Left;
else
bld->facing = (dy > 0) ?
df::building_siegeenginest::Down :
df::building_siegeenginest::Up;
}
static bool is_build_complete(df::building *bld)
{
return bld->getBuildStage() >= bld->getMaxBuildStage();
}
static float average_quality(df::building_actual *bld)
{
float quality = 0;
int count = 0;
for (size_t i = 0; i < bld->contained_items.size(); i++)
{
if (bld->contained_items[i]->use_mode != 2)
continue;
count++;
quality += bld->contained_items[i]->item->getQuality();
}
return count > 0 ? quality/count : 0;
}
static int point_distance(df::coord speed)
{
return std::max(abs(speed.x), std::max(abs(speed.y), abs(speed.z)));
}
inline void normalize(float &x, float &y, float &z)
{
float dist = sqrtf(x*x + y*y + z*z);
if (dist == 0.0f) return;
x /= dist; y /= dist; z /= dist;
}
static Random::MersenneRNG rng;
static void random_direction(float &x, float &y, float &z)
{
float vec[3];
rng.unitvector(vec, 3);
x = vec[0]; y = vec[1]; z = vec[2];
}
static double random_error()
{
// Irwin-Hall approximation to normal distribution with n = 3; varies in (-3,3)
return (rng.drandom0() + rng.drandom0() + rng.drandom0()) * 2.0 - 3.0;
}
// round() is only available in C++11
static int int_round (double val)
{
double frac = val - floor(val);
if (frac < 0.5)
return (int)floor(val);
else
return (int)ceil(val);
}
static const int WEAR_TICKS = 806400;
static bool apply_impact_damage(df::item *item, int minv, int maxv)
{
MaterialInfo info(item);
if (!info.isValid())
{
item->setWear(3);
return false;
}
auto &strength = info.material->strength;
// Use random strain type excluding COMPRESSIVE (conveniently last)
int type = rng.random(strain_type::COMPRESSIVE);
int power = minv + rng.random(maxv-minv+1);
// High elasticity materials just bend
if (strength.strain_at_yield[type] >= 5000)
return true;
// Instant fracture?
int fracture = strength.fracture[type];
if (fracture <= power || info.material->flags.is_set(material_flags::IS_GLASS))
{
item->setWear(3);
return false;
}
// Impact within elastic strain range?
int yield = strength.yield[type];
if (yield > power)
return true;
// Can wear?
auto actual = virtual_cast<df::item_actual>(item);
if (!actual)
return false;
// Transform plastic deformation to wear
int max_wear = WEAR_TICKS * 4;
int cur_wear = WEAR_TICKS * actual->wear + actual->wear_timer;
cur_wear += int64_t(power - yield)*max_wear/(fracture - yield);
if (cur_wear >= max_wear)
{
actual->wear = 3;
return false;
}
else
{
actual->wear = cur_wear / WEAR_TICKS;
actual->wear_timer = cur_wear % WEAR_TICKS;
return true;
}
}
/*
* Configuration object
*/
static bool enable_plugin();
struct EngineInfo {
int id;
df::building_siegeenginest *bld;
df::coord center;
coord_range building_rect;
float quality;
bool is_catapult;
int proj_speed, hit_delay;
std::pair<int, int> fire_range;
double sigma_coeff;
coord_range target;
df::job_item_vector_id ammo_vector_id;
df::item_type ammo_item_type;
int operator_id, operator_frame;
std::set<int> stockpiles;
df::stockpile_links links;
df::workshop_profile profile;
bool hasTarget() { return is_range_valid(target); }
bool onTarget(df::coord pos) { return is_in_range(target, pos); }
df::coord getTargetSize() { return target.second - target.first; }
bool isInRange(int dist) {
return dist >= fire_range.first && dist <= fire_range.second;
}
};
static std::map<df::building*, EngineInfo*> engines;
static std::map<df::coord, df::building*> coord_engines;
static EngineInfo *find_engine(df::building *bld, bool create = false)
{
auto ebld = strict_virtual_cast<df::building_siegeenginest>(bld);
if (!ebld)
return NULL;
auto &obj = engines[bld];
if (obj)
{
obj->bld = ebld;
return obj;
}
if (!create || !is_build_complete(bld))
return NULL;
obj = new EngineInfo();
obj->id = bld->id;
obj->bld = ebld;
obj->center = df::coord(bld->centerx, bld->centery, bld->z);
obj->building_rect = coord_range(
df::coord(bld->x1, bld->y1, bld->z),
df::coord(bld->x2, bld->y2, bld->z)
);
obj->quality = average_quality(ebld);
obj->is_catapult = (ebld->type == siegeengine_type::Catapult);
obj->proj_speed = 2;
obj->hit_delay = obj->is_catapult ? 2 : -1;
obj->fire_range = get_engine_range(ebld, obj->quality);
// Base coefficients per engine type, plus 6% exponential bonus per quality level
obj->sigma_coeff = (obj->is_catapult ? 30.0 : 48.0) * pow(1.06f, obj->quality);
obj->ammo_vector_id = job_item_vector_id::BOULDER;
obj->ammo_item_type = item_type::BOULDER;
obj->operator_id = obj->operator_frame = -1;
coord_engines[obj->center] = bld;
return obj;
}
static EngineInfo *find_engine(lua_State *L, int idx, bool create = false, bool silent = false)
{
auto bld = Lua::CheckDFObject<df::building_siegeenginest>(L, idx);
auto engine = find_engine(bld, create);
if (!engine && !silent)
luaL_error(L, "no such engine");
return engine;
}
static EngineInfo *find_engine(df::coord pos)
{
auto engine = find_engine(coord_engines[pos]);
if (engine)
{
auto bld0 = df::building::find(engine->id);
auto bld = strict_virtual_cast<df::building_siegeenginest>(bld0);
if (!bld)
return NULL;
engine->bld = bld;
}
return engine;
}
/*
* Configuration management
*/
static void clear_engines()
{
for (auto it = engines.begin(); it != engines.end(); ++it)
delete it->second;
engines.clear();
coord_engines.clear();
}
static void load_engines()
{
clear_engines();
std::vector<PersistentDataItem> vec;
World::GetPersistentData(&vec, "siege-engine/target/", true);
for (auto it = vec.begin(); it != vec.end(); ++it)
{
auto engine = find_engine(df::building::find(it->ival(0)), true);
if (!engine) continue;
engine->target.first = df::coord(it->ival(1), it->ival(2), it->ival(3));
engine->target.second = df::coord(it->ival(4), it->ival(5), it->ival(6));
}
World::GetPersistentData(&vec, "siege-engine/ammo/", true);
for (auto it = vec.begin(); it != vec.end(); ++it)
{
auto engine = find_engine(df::building::find(it->ival(0)), true);
if (!engine) continue;
engine->ammo_vector_id = (df::job_item_vector_id)it->ival(1);
engine->ammo_item_type = (df::item_type)it->ival(2);
}
World::GetPersistentData(&vec, "siege-engine/stockpiles/", true);
for (auto it = vec.begin(); it != vec.end(); ++it)
{
auto engine = find_engine(df::building::find(it->ival(0)), true);
if (!engine)
continue;
auto pile = df::building::find(it->ival(1));
if (!pile || pile->getType() != building_type::Stockpile)
{
World::DeletePersistentData(*it);
continue;;
}
engine->stockpiles.insert(it->ival(1));
}
World::GetPersistentData(&vec, "siege-engine/profiles/", true);
for (auto it = vec.begin(); it != vec.end(); ++it)
{
auto engine = find_engine(df::building::find(it->ival(0)), true);
if (!engine) continue;
engine->profile.min_level = it->ival(1);
engine->profile.max_level = it->ival(2);
}
World::GetPersistentData(&vec, "siege-engine/profile-workers/", true);
for (auto it = vec.begin(); it != vec.end(); ++it)
{
auto engine = find_engine(df::building::find(it->ival(0)), true);
if (!engine)
continue;
auto unit = df::unit::find(it->ival(1));
if (!unit || !Units::isCitizen(unit))
{
World::DeletePersistentData(*it);
continue;
}
engine->profile.permitted_workers.push_back(it->ival(1));
}
}
static int getTargetArea(lua_State *L)
{
auto engine = find_engine(L, 1, false, true);
if (engine && engine->hasTarget())
{
Lua::Push(L, engine->target.first);
Lua::Push(L, engine->target.second);
}
else
{
lua_pushnil(L);
lua_pushnil(L);
}
return 2;
}
static void clearTargetArea(df::building_siegeenginest *bld)
{
CHECK_NULL_POINTER(bld);
if (auto engine = find_engine(bld))
engine->target = coord_range();
auto key = stl_sprintf("siege-engine/target/%d", bld->id);
World::DeletePersistentData(World::GetPersistentData(key));
}
static bool setTargetArea(df::building_siegeenginest *bld, df::coord target_min, df::coord target_max)
{
CHECK_NULL_POINTER(bld);
CHECK_INVALID_ARGUMENT(target_min.isValid() && target_max.isValid());
CHECK_INVALID_ARGUMENT(is_build_complete(bld));
if (!enable_plugin())
return false;
auto key = stl_sprintf("siege-engine/target/%d", bld->id);
auto entry = World::GetPersistentData(key, NULL);
if (!entry.isValid())
return false;
auto engine = find_engine(bld, true);
set_range(&engine->target, target_min, target_max);
entry.ival(0) = bld->id;
entry.ival(1) = engine->target.first.x;
entry.ival(2) = engine->target.first.y;
entry.ival(3) = engine->target.first.z;
entry.ival(4) = engine->target.second.x;
entry.ival(5) = engine->target.second.y;
entry.ival(6) = engine->target.second.z;
df::coord sum = target_min + target_max;
orient_engine(bld, df::coord(sum.x/2, sum.y/2, sum.z/2));
return true;
}
static int getAmmoItem(lua_State *L)
{
auto engine = find_engine(L, 1, false, true);
if (!engine)
Lua::Push(L, item_type::BOULDER);
else
Lua::Push(L, engine->ammo_item_type);
return 1;
}
static int setAmmoItem(lua_State *L)
{
if (!enable_plugin())
return 0;
auto engine = find_engine(L, 1, true);
auto item_type = (df::item_type)luaL_optint(L, 2, item_type::BOULDER);
if (!is_valid_enum_item(item_type))
luaL_argerror(L, 2, "invalid item type");
auto key = stl_sprintf("siege-engine/ammo/%d", engine->id);
auto entry = World::GetPersistentData(key, NULL);
if (!entry.isValid())
return 0;
engine->ammo_vector_id = job_item_vector_id::IN_PLAY;
engine->ammo_item_type = item_type;
FOR_ENUM_ITEMS(job_item_vector_id, id)
{
auto other = ENUM_ATTR(job_item_vector_id, other, id);
auto type = ENUM_ATTR(items_other_id, item, other);
if (type == item_type)
{
engine->ammo_vector_id = id;
break;
}
}
entry.ival(0) = engine->id;
entry.ival(1) = engine->ammo_vector_id;
entry.ival(2) = engine->ammo_item_type;
lua_pushboolean(L, true);
return 1;
}
static void forgetStockpileLink(EngineInfo *engine, int pile_id)
{
engine->stockpiles.erase(pile_id);
auto key = stl_sprintf("siege-engine/stockpiles/%d/%d", engine->id, pile_id);
World::DeletePersistentData(World::GetPersistentData(key));
}
static void update_stockpile_links(EngineInfo *engine)
{
engine->links.take_from_pile.clear();
for (auto it = engine->stockpiles.begin(); it != engine->stockpiles.end(); )
{
int id = *it; ++it;
auto pile = df::building::find(id);
if (!pile || pile->getType() != building_type::Stockpile)
forgetStockpileLink(engine, id);
else
// The vector is sorted, but we are iterating through a sorted set
engine->links.take_from_pile.push_back(pile);
}
}
static int getStockpileLinks(lua_State *L)
{
auto engine = find_engine(L, 1, false, true);
if (!engine || engine->stockpiles.empty())
return 0;
update_stockpile_links(engine);
auto &links = engine->links.take_from_pile;
lua_createtable(L, links.size(), 0);
for (size_t i = 0; i < links.size(); i++)
{
Lua::Push(L, links[i]);
lua_rawseti(L, -2, i+1);
}
return 1;
}
static bool isLinkedToPile(df::building_siegeenginest *bld, df::building_stockpilest *pile)
{
CHECK_NULL_POINTER(bld);
CHECK_NULL_POINTER(pile);
auto engine = find_engine(bld);
return engine && engine->stockpiles.count(pile->id);
}
static bool addStockpileLink(df::building_siegeenginest *bld, df::building_stockpilest *pile)
{
CHECK_NULL_POINTER(bld);
CHECK_NULL_POINTER(pile);
CHECK_INVALID_ARGUMENT(is_build_complete(bld));
if (!enable_plugin())
return false;
auto key = stl_sprintf("siege-engine/stockpiles/%d/%d", bld->id, pile->id);
auto entry = World::GetPersistentData(key, NULL);
if (!entry.isValid())
return false;
auto engine = find_engine(bld, true);
entry.ival(0) = bld->id;
entry.ival(1) = pile->id;
engine->stockpiles.insert(pile->id);
return true;
}
static bool removeStockpileLink(df::building_siegeenginest *bld, df::building_stockpilest *pile)
{
CHECK_NULL_POINTER(bld);
CHECK_NULL_POINTER(pile);
if (auto engine = find_engine(bld))
{
forgetStockpileLink(engine, pile->id);
return true;
}
return false;
}
static df::workshop_profile *saveWorkshopProfile(df::building_siegeenginest *bld)
{
CHECK_NULL_POINTER(bld);
CHECK_INVALID_ARGUMENT(is_build_complete(bld));
if (!enable_plugin())
return NULL;
// Save skill limits
auto key = stl_sprintf("siege-engine/profiles/%d", bld->id);
auto entry = World::GetPersistentData(key, NULL);
if (!entry.isValid())
return NULL;
auto engine = find_engine(bld, true);
entry.ival(0) = engine->id;
entry.ival(1) = engine->profile.min_level;
entry.ival(2) = engine->profile.max_level;
// Save worker list
std::vector<PersistentDataItem> vec;
auto &workers = engine->profile.permitted_workers;
key = stl_sprintf("siege-engine/profile-workers/%d", bld->id);
World::GetPersistentData(&vec, key, true);
for (auto it = vec.begin(); it != vec.end(); ++it)
{
if (linear_index(workers, it->ival(1)) < 0)
World::DeletePersistentData(*it);
}
for (size_t i = 0; i < workers.size(); i++)
{
key = stl_sprintf("siege-engine/profile-workers/%d/%d", bld->id, workers[i]);
entry = World::GetPersistentData(key, NULL);
if (!entry.isValid())
continue;
entry.ival(0) = engine->id;
entry.ival(1) = workers[i];
}
return &engine->profile;
}
static df::unit *getOperatorUnit(df::building_siegeenginest *bld, bool force = false)
{
CHECK_NULL_POINTER(bld);
auto engine = find_engine(bld);
if (!engine)
return NULL;
if (engine->operator_id != -1 &&
(world->frame_counter - engine->operator_frame) <= 5)
{
auto op_unit = df::unit::find(engine->operator_id);
if (op_unit)
return op_unit;
}
if (force)
{
color_ostream_proxy out(Core::getInstance().getConsole());
out.print("Forced siege operator search\n");
auto &active = world->units.active;
for (size_t i = 0; i < active.size(); i++)
if (active[i]->pos == engine->center && Units::isCitizen(active[i]))
return active[i];
}
return NULL;
}
/*
* Trajectory raytracing
*/
struct ProjectilePath {
static const int DEFAULT_FUDGE = 31;
df::coord origin, goal, target, fudge_delta;
int divisor, fudge_factor;
df::coord speed, direction;
ProjectilePath(df::coord origin, df::coord goal) :
origin(origin), goal(goal), fudge_factor(1)
{
fudge_delta = df::coord(0,0,0);
calc_line();
}
ProjectilePath(df::coord origin, df::coord goal, df::coord delta, int factor) :
origin(origin), goal(goal), fudge_delta(delta), fudge_factor(factor)
{
calc_line();
}
ProjectilePath(df::coord origin, df::coord goal, float zdelta, int factor = DEFAULT_FUDGE) :
origin(origin), goal(goal), fudge_factor(factor)
{
fudge_delta = df::coord(0,0,int(factor * zdelta));
calc_line();
}
void calc_line()
{
speed = goal - origin;
speed.x *= fudge_factor;
speed.y *= fudge_factor;
speed.z *= fudge_factor;
speed = speed + fudge_delta;
target = origin + speed;
divisor = point_distance(speed);
if (divisor <= 0) divisor = 1;
direction = df::coord(speed.x>=0?1:-1,speed.y>=0?1:-1,speed.z>=0?1:-1);
}
df::coord operator[] (int i) const
{
int div2 = divisor * 2;
int bias = divisor-1;
return origin + df::coord(
(2*speed.x*i + direction.x*bias)/div2,
(2*speed.y*i + direction.y*bias)/div2,
(2*speed.z*i + direction.z*bias)/div2
);
}
};
static ProjectilePath decode_path(lua_State *L, int idx, df::coord origin)
{
idx = lua_absindex(L, idx);
Lua::StackUnwinder frame(L);
df::coord goal;
lua_getfield(L, idx, "target");
Lua::CheckDFAssign(L, &goal, frame[1]);
lua_getfield(L, idx, "delta");
if (!lua_isnil(L, frame[2]))
{
lua_getfield(L, idx, "factor");
int factor = luaL_optnumber(L, frame[3], ProjectilePath::DEFAULT_FUDGE);
if (lua_isnumber(L, frame[2]))
return ProjectilePath(origin, goal, lua_tonumber(L, frame[2]), factor);
df::coord delta;
Lua::CheckDFAssign(L, &delta, frame[2]);
return ProjectilePath(origin, goal, delta, factor);
}
return ProjectilePath(origin, goal);
}
static int projPosAtStep(lua_State *L)
{
auto engine = find_engine(L, 1);
auto path = decode_path(L, 2, engine->center);
int step = luaL_checkint(L, 3);
Lua::Push(L, path[step]);
return 1;
}
static bool isPassableTile(df::coord pos)
{
auto ptile = Maps::getTileType(pos);
return !ptile || FlowPassable(*ptile);
}
static bool isTargetableTile(df::coord pos)
{
auto ptile = Maps::getTileType(pos);
return ptile && FlowPassable(*ptile) && !isOpenTerrain(*ptile);
}
static bool isTreeTile(df::coord pos)
{
auto ptile = Maps::getTileType(pos);
return ptile &&
(tileShape(*ptile) == tiletype_shape::BRANCH ||
tileShape(*ptile) == tiletype_shape::TRUNK_BRANCH ||
tileShape(*ptile) == tiletype_shape::TWIG);
}
static bool adjustToTarget(EngineInfo *engine, df::coord *pos)
{
if (isTargetableTile(*pos))
return true;
for (df::coord fudge = *pos;
fudge.z <= engine->target.second.z; fudge.z++)
{
if (!isTargetableTile(fudge))
continue;
*pos = fudge;
return true;
}
for (df::coord fudge = *pos;
fudge.z >= engine->target.first.z; fudge.z--)
{
if (!isTargetableTile(fudge))
continue;
*pos = fudge;
return true;
}
return false;
}
static int adjustToTarget(lua_State *L)
{
auto engine = find_engine(L, 1, true);
df::coord pos;
Lua::CheckDFAssign(L, &pos, 2);
bool ok = adjustToTarget(engine, &pos);
Lua::Push(L, pos);
Lua::Push(L, ok);
return 2;
}
static const char* const hit_type_names[] = {
"wall", "floor", "ceiling", "map_edge", "tree"
};
struct PathMetrics {
enum CollisionType {
Impassable,
Floor,
Ceiling,
MapEdge,
Tree
} hit_type;
int collision_step, collision_z_step;
int goal_step, goal_z_step, goal_distance;
bool hits() const { return collision_step > goal_step; }
PathMetrics(const ProjectilePath &path)
{
compute(path);
}
void compute(const ProjectilePath &path)
{
hit_type = Impassable;
collision_step = goal_step = goal_z_step = 1000000;
collision_z_step = 0;
goal_distance = point_distance(path.origin - path.goal);
int step = 0;
df::coord prev_pos = path.origin;
for (;;) {
df::coord cur_pos = path[++step];
if (cur_pos == prev_pos)
break;
if (cur_pos.z == path.goal.z)
{
goal_z_step = std::min(step, goal_z_step);
if (cur_pos == path.goal)
goal_step = step;
}
if (!Maps::isValidTilePos(cur_pos))
{
hit_type = PathMetrics::MapEdge;
break;
}
if (!isPassableTile(cur_pos))
{