-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathLExecutor.java
2147 lines (1811 loc) · 75.1 KB
/
LExecutor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package mindustry.logic;
import arc.*;
import arc.audio.*;
import arc.graphics.*;
import arc.math.*;
import arc.math.geom.*;
import arc.struct.*;
import arc.util.*;
import mindustry.*;
import mindustry.ai.types.*;
import mindustry.annotations.Annotations.*;
import mindustry.content.*;
import mindustry.core.*;
import mindustry.ctype.*;
import mindustry.entities.*;
import mindustry.game.EventType.*;
import mindustry.game.*;
import mindustry.game.MapObjectives.*;
import mindustry.game.Teams.*;
import mindustry.gen.*;
import mindustry.logic.LogicFx.*;
import mindustry.type.*;
import mindustry.ui.*;
import mindustry.world.*;
import mindustry.world.blocks.environment.*;
import mindustry.world.blocks.logic.*;
import mindustry.world.blocks.logic.LogicBlock.*;
import mindustry.world.blocks.logic.LogicDisplay.*;
import mindustry.world.blocks.logic.MemoryBlock.*;
import mindustry.world.blocks.logic.MessageBlock.*;
import mindustry.world.blocks.payloads.*;
import mindustry.world.meta.*;
import static mindustry.Vars.*;
public class LExecutor{
public static final int maxInstructions = 1000;
public static final int
maxGraphicsBuffer = 256,
maxDisplayBuffer = 1024,
maxTextBuffer = 400;
public LInstruction[] instructions = {};
/** Non-constant variables used for network sync */
public LVar[] vars = {};
public LVar counter, unit, thisv, ipt;
public int[] binds;
public boolean yield;
public LongSeq graphicsBuffer = new LongSeq();
public StringBuilder textBuffer = new StringBuilder();
public Building[] links = {};
public @Nullable LogicBuild build;
public IntSet linkIds = new IntSet();
public Team team = Team.derelict;
public boolean privileged = false;
//yes, this is a minor memory leak, but it's probably not significant enough to matter
protected static IntFloatMap unitTimeouts = new IntFloatMap();
//lookup variable by name, lazy init.
protected @Nullable ObjectIntMap<String> nameMap;
static{
Events.on(ResetEvent.class, e -> unitTimeouts.clear());
}
boolean timeoutDone(Unit unit, float delay){
return Time.time >= unitTimeouts.get(unit.id) + delay;
}
void updateTimeout(Unit unit){
unitTimeouts.put(unit.id, Time.time);
}
public boolean initialized(){
return instructions.length > 0;
}
/** Runs a single instruction. */
public void runOnce(){
//reset to start
if(counter.numval >= instructions.length || counter.numval < 0){
counter.numval = 0;
}
if(counter.numval < instructions.length){
instructions[(int)(counter.numval++)].run(this);
}
}
/** Loads with a specified assembler. Resets all variables. */
public void load(LAssembler builder){
nameMap = null;
vars = builder.vars.values().toSeq().retainAll(var -> !var.constant).toArray(LVar.class);
for(int i = 0; i < vars.length; i++){
vars[i].id = i;
}
instructions = builder.instructions;
counter = builder.getVar("@counter");
unit = builder.getVar("@unit");
thisv = builder.getVar("@this");
ipt = builder.putConst("@ipt", build != null ? build.ipt : 0);
}
//region utility
public @Nullable LVar optionalVar(String name){
if(nameMap == null){
nameMap = new ObjectIntMap<>();
for(int i = 0; i < vars.length; i++){
nameMap.put(vars[i].name, i);
}
}
return optionalVar(nameMap.get(name, -1));
}
/** @return a Var from this processor. May be null if out of bounds. */
public @Nullable LVar optionalVar(int index){
return index < 0 || index >= vars.length ? null : vars[index];
}
//endregion
//region instruction types
public interface LInstruction{
void run(LExecutor exec);
}
/** Binds the processor to a unit based on some filters. */
public static class UnitBindI implements LInstruction{
public LVar type;
public UnitBindI(LVar type){
this.type = type;
}
public UnitBindI(){
}
@Override
public void run(LExecutor exec){
if(exec.binds == null || exec.binds.length != content.units().size){
exec.binds = new int[content.units().size];
}
//binding to `null` was previously possible, but was too powerful and exploitable
if(type.obj() instanceof UnitType type && type.logicControllable){
Seq<Unit> seq = exec.team.data().unitCache(type);
if(seq != null && seq.any()){
exec.binds[type.id] %= seq.size;
if(exec.binds[type.id] < seq.size){
//bind to the next unit
exec.unit.setconst(seq.get(exec.binds[type.id]));
}
exec.binds[type.id] ++;
}else{
//no units of this type found
exec.unit.setconst(null);
}
}else if(type.obj() instanceof Unit u && (u.team == exec.team || exec.privileged) && u.type.logicControllable){
//bind to specific unit object
exec.unit.setconst(u);
}else{
exec.unit.setconst(null);
}
}
}
/** Uses a unit to find something that may not be in its range. */
public static class UnitLocateI implements LInstruction{
public LLocate locate = LLocate.building;
public BlockFlag flag = BlockFlag.core;
public LVar enemy, ore;
public LVar outX, outY, outFound, outBuild;
public UnitLocateI(LLocate locate, BlockFlag flag, LVar enemy, LVar ore, LVar outX, LVar outY, LVar outFound, LVar outBuild){
this.locate = locate;
this.flag = flag;
this.enemy = enemy;
this.ore = ore;
this.outX = outX;
this.outY = outY;
this.outFound = outFound;
this.outBuild = outBuild;
}
public UnitLocateI(){
}
@Override
public void run(LExecutor exec){
Object unitObj = exec.unit.obj();
LogicAI ai = UnitControlI.checkLogicAI(exec, unitObj);
if(unitObj instanceof Unit unit && ai != null){
ai.controlTimer = LogicAI.logicControlTimeout;
Cache cache = (Cache)ai.execCache.get(this, Cache::new);
if(ai.checkTargetTimer(this)){
Tile res = null;
boolean build = false;
switch(locate){
case ore -> {
if(ore.obj() instanceof Item item){
res = indexer.findClosestOre(unit, item);
}
}
case building -> {
Building b = Geometry.findClosest(unit.x, unit.y, enemy.bool() ? indexer.getEnemy(unit.team, flag) : indexer.getFlagged(unit.team, flag));
res = b == null ? null : b.tile;
build = true;
}
case spawn -> {
res = Geometry.findClosest(unit.x, unit.y, Vars.spawner.getSpawns());
}
case damaged -> {
Building b = Units.findDamagedTile(unit.team, unit.x, unit.y);
res = b == null ? null : b.tile;
build = true;
}
}
if(res != null && (!build || res.build != null)){
cache.found = true;
//set result if found
outX.setnum(cache.x = World.conv(build ? res.build.x : res.worldx()));
outY.setnum(cache.y = World.conv(build ? res.build.y : res.worldy()));
outFound.setnum(1);
}else{
cache.found = false;
outFound.setnum(0);
}
if(res != null && res.build != null &&
(unit.within(res.build.x, res.build.y, Math.max(unit.range(), buildingRange)) || res.build.team == exec.team)){
cache.build = res.build;
outBuild.setobj(res.build);
}else{
outBuild.setobj(null);
}
}else{
outBuild.setobj(cache.build);
outFound.setbool(cache.found);
outX.setnum(cache.x);
outY.setnum(cache.y);
}
}else{
outFound.setbool(false);
}
}
static class Cache{
float x, y;
boolean found;
Building build;
}
}
/** Controls the unit based on some parameters. */
public static class UnitControlI implements LInstruction{
public LUnitControl type = LUnitControl.move;
public LVar p1, p2, p3, p4, p5;
public UnitControlI(LUnitControl type, LVar p1, LVar p2, LVar p3, LVar p4, LVar p5){
this.type = type;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
this.p5 = p5;
}
public UnitControlI(){
}
/** Checks is a unit is valid for logic AI control, and returns the controller. */
@Nullable
public static LogicAI checkLogicAI(LExecutor exec, Object unitObj){
if(unitObj instanceof Unit unit && unit.isValid() && exec.unit.obj() == unit && (unit.team == exec.team || exec.privileged) && unit.controller().isLogicControllable()){
if(unit.controller() instanceof LogicAI la){
la.controller = exec.thisv.building();
return la;
}else{
var la = new LogicAI();
la.controller = exec.thisv.building();
unit.controller(la);
//clear old state
unit.mineTile = null;
unit.clearBuilding();
return la;
}
}
return null;
}
@Override
public void run(LExecutor exec){
Object unitObj = exec.unit.obj();
LogicAI ai = checkLogicAI(exec, unitObj);
//only control standard AI units
if(unitObj instanceof Unit unit && ai != null){
ai.controlTimer = LogicAI.logicControlTimeout;
float x1 = World.unconv(p1.numf()), y1 = World.unconv(p2.numf()), d1 = World.unconv(p3.numf());
switch(type){
case idle, autoPathfind -> {
ai.control = type;
}
case move, stop, approach, pathfind -> {
ai.control = type;
ai.moveX = x1;
ai.moveY = y1;
if(type == LUnitControl.approach){
ai.moveRad = d1;
}
//stop mining/building
if(type == LUnitControl.stop){
unit.mineTile = null;
unit.clearBuilding();
}
}
case unbind -> {
//TODO is this a good idea? will allocate
unit.resetController();
}
case within -> {
p4.setnum(unit.within(x1, y1, d1) ? 1 : 0);
}
case target -> {
ai.posTarget.set(x1, y1);
ai.aimControl = type;
ai.mainTarget = null;
ai.shoot = p3.bool();
}
case targetp -> {
ai.aimControl = type;
ai.mainTarget = p1.obj() instanceof Teamc t ? t : null;
ai.shoot = p2.bool();
}
case boost -> {
ai.boost = p1.bool();
}
case flag -> {
unit.flag = p1.num();
}
case mine -> {
Tile tile = world.tileWorld(x1, y1);
if(unit.canMine()){
unit.mineTile = unit.validMine(tile) ? tile : null;
}
}
case payDrop -> {
if(!exec.timeoutDone(unit, LogicAI.transferDelay)) return;
if(unit instanceof Payloadc pay && pay.hasPayload()){
Call.payloadDropped(unit, unit.x, unit.y);
exec.updateTimeout(unit);
}
}
case payTake -> {
if(!exec.timeoutDone(unit, LogicAI.transferDelay)) return;
if(unit instanceof Payloadc pay){
//units
if(p1.bool()){
Unit result = Units.closest(unit.team, unit.x, unit.y, unit.type.hitSize * 2f, u -> u.isAI() && u.isGrounded() && pay.canPickup(u) && u.within(unit, u.hitSize + unit.hitSize * 1.2f));
if(result != null){
Call.pickedUnitPayload(unit, result);
}
}else{ //buildings
Building build = world.buildWorld(unit.x, unit.y);
//TODO copy pasted code
if(build != null && build.team == unit.team){
Payload current = build.getPayload();
if(current != null && pay.canPickupPayload(current)){
Call.pickedBuildPayload(unit, build, false);
//pick up whole building directly
}else if(build.block.buildVisibility != BuildVisibility.hidden && build.canPickup() && pay.canPickup(build)){
Call.pickedBuildPayload(unit, build, true);
}
}
}
exec.updateTimeout(unit);
}
}
case payEnter -> {
Building build = world.buildWorld(unit.x, unit.y);
if(build != null && unit.team() == build.team && build.canControlSelect(unit)){
Call.unitBuildingControlSelect(unit, build);
}
}
case build -> {
if((state.rules.logicUnitBuild || exec.privileged) && unit.canBuild() && p3.obj() instanceof Block block && block.canBeBuilt() && (block.unlockedNow() || unit.team.isAI())){
int x = World.toTile(x1 - block.offset/tilesize), y = World.toTile(y1 - block.offset/tilesize);
int rot = Mathf.mod(p4.numi(), 4);
//reset state of last request when necessary
if(ai.plan.x != x || ai.plan.y != y || ai.plan.block != block || unit.plans.isEmpty()){
ai.plan.progress = 0;
ai.plan.initialized = false;
ai.plan.stuck = false;
}
var conf = p5.obj();
ai.plan.set(x, y, rot, block);
ai.plan.config = conf instanceof Content c ? c : conf instanceof Building b ? b : null;
unit.clearBuilding();
Tile tile = ai.plan.tile();
if(tile != null && !(tile.block() == block && tile.build != null && tile.build.rotation == rot)){
unit.updateBuilding = true;
unit.addBuild(ai.plan);
}
}
}
case getBlock -> {
float range = Math.max(unit.range(), unit.type.buildRange);
if(!unit.within(x1, y1, range)){
p3.setobj(null);
p4.setobj(null);
p5.setobj(null);
}else{
Tile tile = world.tileWorld(x1, y1);
if(tile == null){
p3.setobj(null);
p4.setobj(null);
p5.setobj(null);
}else{
p3.setobj(tile.block());
p4.setobj(tile.build != null ? tile.build : null);
//Allows reading of ore tiles if they are present (overlay is not air) otherwise returns the floor
p5.setobj(tile.overlay() == Blocks.air ? tile.floor() : tile.overlay());
}
}
}
case itemDrop -> {
if(!exec.timeoutDone(unit, LogicAI.transferDelay)) return;
//clear item when dropping to @air
if(p1.obj() == Blocks.air){
//only server-side; no need to call anything, as items are synced in snapshots
if(!net.client()){
unit.clearItem();
}
exec.updateTimeout(unit);
}else{
Building build = p1.building();
int dropped = Math.min(unit.stack.amount, p2.numi());
if(build != null && build.team == unit.team && build.isValid() && dropped > 0 && unit.within(build, logicItemTransferRange + build.block.size * tilesize/2f)){
int accepted = build.acceptStack(unit.item(), dropped, unit);
if(accepted > 0){
Call.transferItemTo(unit, unit.item(), accepted, unit.x, unit.y, build);
exec.updateTimeout(unit);
}
}
}
}
case itemTake -> {
if(!exec.timeoutDone(unit, LogicAI.transferDelay)) return;
Building build = p1.building();
int amount = p3.numi();
if(build != null && build.team == unit.team && build.isValid() && build.items != null &&
p2.obj() instanceof Item item && unit.within(build, logicItemTransferRange + build.block.size * tilesize/2f)){
int taken = Math.min(build.items.get(item), Math.min(amount, unit.maxAccepted(item)));
if(taken > 0){
Call.takeItems(build, item, taken, unit);
exec.updateTimeout(unit);
}
}
}
default -> {}
}
}
}
}
/** Controls a building's state. */
public static class ControlI implements LInstruction{
public LVar target;
public LAccess type = LAccess.enabled;
public LVar p1, p2, p3, p4;
public ControlI(LAccess type, LVar target, LVar p1, LVar p2, LVar p3, LVar p4){
this.type = type;
this.target = target;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
}
ControlI(){}
@Override
public void run(LExecutor exec){
Object obj = target.obj();
if(obj instanceof Building b && (exec.privileged || (b.team == exec.team && exec.linkIds.contains(b.id)))){
if(type == LAccess.enabled && !p1.bool()){
b.lastDisabler = exec.build;
}
if(type == LAccess.enabled && p1.bool()){
b.noSleep();
}
if(type.isObj && p1.isobj){
b.control(type, p1.obj(), p2.num(), p3.num(), p4.num());
}else{
b.control(type, p1.num(), p2.num(), p3.num(), p4.num());
}
}
}
}
public static class GetLinkI implements LInstruction{
public LVar output, index;
public GetLinkI(LVar output, LVar index){
this.index = index;
this.output = output;
}
public GetLinkI(){
}
@Override
public void run(LExecutor exec){
int address = index.numi();
output.setobj(address >= 0 && address < exec.links.length ? exec.links[address] : null);
}
}
public static class ReadI implements LInstruction{
public LVar target, position, output;
public ReadI(LVar target, LVar position, LVar output){
this.target = target;
this.position = position;
this.output = output;
}
public ReadI(){
}
@Override
public void run(LExecutor exec){
int address = position.numi();
Building from = target.building();
if(from instanceof MemoryBuild mem && (exec.privileged || (from.team == exec.team && !mem.block.privileged))){
output.setnum(address < 0 || address >= mem.memory.length ? 0 : mem.memory[address]);
}else if(from instanceof LogicBuild logic && (exec.privileged || (from.team == exec.team && !from.block.privileged)) && position.isobj && position.objval instanceof String name){
LVar fromVar = logic.executor.optionalVar(name);
if(fromVar != null && !output.constant){
output.objval = fromVar.objval;
output.numval = fromVar.numval;
output.isobj = fromVar.isobj;
}
}
}
}
public static class WriteI implements LInstruction{
public LVar target, position, value;
public WriteI(LVar target, LVar position, LVar value){
this.target = target;
this.position = position;
this.value = value;
}
public WriteI(){
}
@Override
public void run(LExecutor exec){
int address = position.numi();
Building from = target.building();
if(from instanceof MemoryBuild mem && (exec.privileged || (from.team == exec.team && !mem.block.privileged)) && address >= 0 && address < mem.memory.length){
mem.memory[address] = value.num();
}else if(from instanceof LogicBuild logic && (exec.privileged || (from.team == exec.team && !from.block.privileged)) && position.isobj && position.objval instanceof String name){
LVar toVar = logic.executor.optionalVar(name);
if(toVar != null && !toVar.constant){
toVar.objval = value.objval;
toVar.numval = value.numval;
toVar.isobj = value.isobj;
}
}
}
}
public static class SenseI implements LInstruction{
public LVar from, to, type;
public SenseI(LVar from, LVar to, LVar type){
this.from = from;
this.to = to;
this.type = type;
}
public SenseI(){
}
@Override
public void run(LExecutor exec){
Object target = from.obj();
Object sense = type.obj();
if(target == null && sense == LAccess.dead){
to.setnum(1);
return;
}
//note that remote units/buildings can be sensed as well
if(target instanceof Senseable se){
if(sense instanceof Content co){
to.setnum(se.sense(co));
}else if(sense instanceof LAccess la){
Object objOut = se.senseObject(la);
if(objOut == Senseable.noSensed){
//numeric output
to.setnum(se.sense(la));
}else{
//object output
to.setobj(objOut);
}
}
}else{
to.setobj(null);
}
}
}
public static class RadarI implements LInstruction{
public RadarTarget target1 = RadarTarget.enemy, target2 = RadarTarget.any, target3 = RadarTarget.any;
public RadarSort sort = RadarSort.distance;
public LVar radar, sortOrder, output;
//radar instructions are special in that they cache their output and only change it at fixed intervals.
//this prevents lag from spam of radar instructions
public Healthc lastTarget;
public Object lastSourceBuild;
public Interval timer = new Interval();
static float bestValue = 0f;
static Unit best = null;
public RadarI(RadarTarget target1, RadarTarget target2, RadarTarget target3, RadarSort sort, LVar radar, LVar sortOrder, LVar output){
this.target1 = target1;
this.target2 = target2;
this.target3 = target3;
this.sort = sort;
this.radar = radar;
this.sortOrder = sortOrder;
this.output = output;
}
public RadarI(){
}
@Override
public void run(LExecutor exec){
Object base = radar.obj();
int sortDir = sortOrder.bool() ? 1 : -1;
LogicAI ai = null;
if(base instanceof Ranged r && (exec.privileged || r.team() == exec.team) &&
((base instanceof Building b && (!b.block.privileged || exec.privileged)) || (ai = UnitControlI.checkLogicAI(exec, base)) != null)){ //must be a building or a controllable unit
float range = r.range();
Healthc targeted;
//timers update on a fixed 30 tick interval
//units update on a special timer per controller instance
if((base instanceof Building && (timer.get(30f) || lastSourceBuild != base)) || (ai != null && ai.checkTargetTimer(this))){
//if any of the targets involve enemies
boolean enemies = target1 == RadarTarget.enemy || target2 == RadarTarget.enemy || target3 == RadarTarget.enemy;
boolean allies = target1 == RadarTarget.ally || target2 == RadarTarget.ally || target3 == RadarTarget.ally;
best = null;
bestValue = 0;
if(enemies){
Seq<TeamData> data = state.teams.present;
for(int i = 0; i < data.size; i++){
if(data.items[i].team != r.team()){
find(r, range, sortDir, data.items[i].team);
}
}
}else if(!allies){
Seq<TeamData> data = state.teams.present;
for(int i = 0; i < data.size; i++){
find(r, range, sortDir, data.items[i].team);
}
}else{
find(r, range, sortDir, r.team());
}
if(ai != null){
ai.execCache.put(this, best);
}
lastSourceBuild = base;
lastTarget = targeted = best;
}else{
if(ai != null){
targeted = (Healthc)ai.execCache.get(this);
}else{
targeted = lastTarget;
}
}
output.setobj(targeted);
}else{
output.setobj(null);
}
}
void find(Ranged b, float range, int sortDir, Team team){
Units.nearby(team, b.x(), b.y(), range, u -> {
if(!u.within(b, range) || !u.targetable(team) || b == u) return;
boolean valid =
target1.func.get(b.team(), u) &&
target2.func.get(b.team(), u) &&
target3.func.get(b.team(), u);
if(!valid) return;
float val = sort.func.get(b, u) * sortDir;
if(val > bestValue || best == null){
bestValue = val;
best = u;
}
});
}
}
public static class SetI implements LInstruction{
public LVar from, to;
public SetI(LVar from, LVar to){
this.from = from;
this.to = to;
}
SetI(){}
@Override
public void run(LExecutor exec){
if(!to.constant){
if(from.isobj){
if(to != exec.counter){
to.objval = from.objval;
to.isobj = true;
}
}else{
to.numval = LVar.invalid(from.numval) ? 0 : from.numval;
to.isobj = false;
}
}
}
}
public static class OpI implements LInstruction{
public LogicOp op = LogicOp.add;
public LVar a, b, dest;
public OpI(LogicOp op, LVar a, LVar b, LVar dest){
this.op = op;
this.a = a;
this.b = b;
this.dest = dest;
}
OpI(){}
@Override
public void run(LExecutor exec){
if(op == LogicOp.strictEqual){
dest.setnum(a.isobj == b.isobj && ((a.isobj && Structs.eq(a.objval, b.objval)) || (!a.isobj && a.numval == b.numval)) ? 1 : 0);
}else if(op.unary){
dest.setnum(op.function1.get(a.num()));
}else{
if(op.objFunction2 != null && a.isobj && b.isobj){
//use object function if both are objects
dest.setnum(op.objFunction2.get(a.obj(), b.obj()));
}else{
//otherwise use the numeric function
dest.setnum(op.function2.get(a.num(), b.num()));
}
}
}
}
public static class EndI implements LInstruction{
@Override
public void run(LExecutor exec){
exec.counter.numval = exec.instructions.length;
}
}
public static class NoopI implements LInstruction{
@Override
public void run(LExecutor exec){}
}
public static class DrawI implements LInstruction{
public byte type;
public LVar x, y, p1, p2, p3, p4;
public DrawI(byte type, LVar x, LVar y, LVar p1, LVar p2, LVar p3, LVar p4){
this.type = type;
this.x = x;
this.y = y;
this.p1 = p1;
this.p2 = p2;
this.p3 = p3;
this.p4 = p4;
}
public DrawI(){
}
@Override
public void run(LExecutor exec){
//graphics on headless servers are useless.
if(Vars.headless || exec.graphicsBuffer.size >= maxGraphicsBuffer) return;
//explicitly unpack colorPack, it's pre-processed here
if(type == LogicDisplay.commandColorPack){
double packed = x.num();
int value = (int)(Double.doubleToRawLongBits(packed)),
r = ((value & 0xff000000) >>> 24),
g = ((value & 0x00ff0000) >>> 16),
b = ((value & 0x0000ff00) >>> 8),
a = ((value & 0x000000ff));
exec.graphicsBuffer.add(DisplayCmd.get(LogicDisplay.commandColor, pack(r), pack(g), pack(b), pack(a), 0, 0));
}else if(type == LogicDisplay.commandPrint){
CharSequence str = exec.textBuffer;
if(str.length() > 0){
var data = Fonts.logic.getData();
int advance = (int)data.spaceXadvance, lineHeight = (int)data.lineHeight;
int xOffset, yOffset;
int align = p1.id; //p1 is not a variable, it's a raw align value. what a massive hack
int maxWidth = 0, lines = 1, lineWidth = 0;
for(int i = 0; i < str.length(); i++){
char next = str.charAt(i);
if(next == '\n'){
maxWidth = Math.max(maxWidth, lineWidth);
lineWidth = 0;
lines ++;
}else{
lineWidth ++;
}
}
maxWidth = Math.max(maxWidth, lineWidth);
float
width = maxWidth * advance,
height = lines * lineHeight,
ha = ((Align.isLeft(align) ? -1f : 0f) + 1f + (Align.isRight(align) ? 1f : 0f))/2f,
va = ((Align.isBottom(align) ? -1f : 0f) + 1f + (Align.isTop(align) ? 1f : 0f))/2f;
xOffset = -(int)(width * ha);
yOffset = -(int)(height * va) + (lines - 1) * lineHeight;
int curX = x.numi(), curY = y.numi();
for(int i = 0; i < str.length(); i++){
char next = str.charAt(i);
if(next == '\n'){
//move Y down when newline is encountered
curY -= lineHeight;
curX = x.numi(); //reset
continue;
}
if(Fonts.logic.getData().hasGlyph(next)){
exec.graphicsBuffer.add(DisplayCmd.get(LogicDisplay.commandPrint, packSign(curX + xOffset), packSign(curY + yOffset), next, 0, 0, 0));
}
curX += advance;
}
exec.textBuffer.setLength(0);
}
}else{
int num1 = p1.numi(), num4 = p4.numi(), xval = packSign(x.numi()), yval = packSign(y.numi());
if(type == LogicDisplay.commandImage){
if(p1.obj() instanceof UnlockableContent u){
//TODO: with mods, this will overflow (ID >= 512), but that's better than the previous system, at least
num1 = u.id;
num4 = u.getContentType().ordinal();
}else{
num1 = -1;
num4 = -1;
}
//num1 = p1.obj() instanceof UnlockableContent u ? u.iconId : 0;
}else if(type == LogicDisplay.commandScale){
xval = packSign((int)(x.numf() / LogicDisplay.scaleStep));
yval = packSign((int)(y.numf() / LogicDisplay.scaleStep));
}
//add graphics calls, cap graphics buffer size
exec.graphicsBuffer.add(DisplayCmd.get(type, xval, yval, packSign(num1), packSign(p2.numi()), packSign(p3.numi()), packSign(num4)));
}
}
static int pack(int value){
return value & 0b0111111111;
}
static int packSign(int value){
return (Math.abs(value) & 0b0111111111) | (value < 0 ? 0b1000000000 : 0);
}
}
public static class DrawFlushI implements LInstruction{
public LVar target;
public DrawFlushI(LVar target){
this.target = target;
}
public DrawFlushI(){
}
@Override
public void run(LExecutor exec){
//graphics on headless servers are useless.
if(Vars.headless) return;
if(target.building() instanceof LogicDisplayBuild d && (d.team == exec.team || exec.privileged)){
if(d.commands.size + exec.graphicsBuffer.size < maxDisplayBuffer){
for(int i = 0; i < exec.graphicsBuffer.size; i++){
d.commands.addLast(exec.graphicsBuffer.items[i]);
}
}
exec.graphicsBuffer.clear();
}
}
}
public static class PrintI implements LInstruction{
public LVar value;
public PrintI(LVar value){
this.value = value;
}
PrintI(){}
@Override
public void run(LExecutor exec){
if(exec.textBuffer.length() >= maxTextBuffer) return;
//this should avoid any garbage allocation
if(value.isobj){
String strValue = toString(value.objval);
exec.textBuffer.append(strValue);
}else{
//display integer version when possible
if(Math.abs(value.numval - Math.round(value.numval)) < 0.00001){
exec.textBuffer.append(Math.round(value.numval));
}else{
exec.textBuffer.append(value.numval);