-
Notifications
You must be signed in to change notification settings - Fork 21
/
FARL.lua
3253 lines (3076 loc) · 141 KB
/
FARL.lua
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
require "__core__/lualib/util"
local Position = require '__FARL__/stdlib/area/position'
local Area = require '__FARL__/stdlib/area/area'
local Blueprint = require "__FARL__/Blueprint"
local lib = require "__FARL__/lib_control"
local debugDump = lib.debugDump
local debugLog = lib.debugLog
local endsWith = lib.endsWith
local diagonal_to_real_pos = lib.diagonal_to_real_pos
--local saveVar = lib.saveVar
local math = math
local floor, ceil = math.floor, math.ceil
local abs, min, max = math.abs, math.min, math.max
local function round(num, idp)
local mult = 10 ^ (idp or 0)
return floor(num * mult + 0.5) / mult
end
local sqrt2 = math.sqrt(2)/2
local curved_l = 3--7.7288196964265417438549920430937/2
local function get_signal_weight(rail, settings)
-- curve length from https://github.com/dewiniaid/RailTools/blob/master/librail.lua#L5
local weight = rail.name == settings.rail.curved and curved_l or 1
if rail.name ~= settings.rail.curved and rail.direction % 2 == 1 then
return sqrt2
end
return weight
end
local rot = {}
for i = 0, 7 do
local rad = i * (math.pi / 4)
rot[rad] = { cos = math.cos(rad), sin = math.sin(rad) }
end
local function rotate(pos, rad)
if not rot[rad] then error("rot[" .. rad .. "]", 2) end
local cos, sin = rot[rad].cos, rot[rad].sin
local r = { { x = cos, y = -sin }, { x = sin, y = cos } }
local ret = { x = 0, y = 0 }
ret.x = pos.x * r[1].x + pos.y * r[1].y
ret.y = pos.x * r[2].x + pos.y * r[2].y
return ret
end
local function get_fake_rail(rail, position)
return {name = rail.name, type = rail.type, direction = rail.direction, position = position or Position.copy(rail.position)}
end
local function move_right_forward(pos, direction, right, forward)
local dir = (direction + 2) % 8
return Position.translate(Position.translate(pos, dir, right), direction, forward)
end
local function protectedKey(ent)
if ent.valid then
return ent.name .. ":" .. ent.position.x .. ":" .. ent.position.y .. ":" .. ent.direction
end
return false
end
local function get_item_name(some_name)
if not some_name then return end
local name = false
local count = 1
if game.item_prototypes[some_name] then
name = game.item_prototypes[some_name].name
elseif game.entity_prototypes[some_name] then
local entityProto = game.entity_prototypes[some_name]
local item = entityProto.items_to_place_this and entityProto.items_to_place_this[1]
name = item and item.name
if name and entityProto.mineable_properties and entityProto.mineable_properties.minable and entityProto.mineable_properties.products then
for _, item1 in pairs(entityProto.mineable_properties.products) do
if item1.name == name then
count = item1.amount or item1.amount_max
end
end
end
elseif game.tile_prototypes[some_name] then
local tileProto = game.tile_prototypes[some_name].items_to_place_this
name = tileProto and tileProto[1] and tileProto[1].name
if name == "landfill" or name == "fertiliser" then
name = false
end
end
return name, count
end
--apiCalls = {find={item=0,tree=0,stone=0,other=0},canplace=0,create=0,count={item=0,tree=0,stone=0,other=0}}
local RED = { r = 0.9 }
local GREEN = { g = 0.7 }
local YELLOW = { r = 0.8, g = 0.8 }
FARL = {}--luacheck: allow defined
FARL.curvePositions = {
[0] = { straight = { dir = 0, off = { x = 1, y = 3 } }, diagonal = { dir = 5, off = { x = -1, y = -3 } } },
[1] = { straight = { dir = 0, off = { x = -1, y = 3 } }, diagonal = { dir = 3, off = { x = 1, y = -3 } } },
[2] = { straight = { dir = 2, off = { x = -3, y = 1 } }, diagonal = { dir = 7, off = { x = 3, y = -1 } } },
[3] = { straight = { dir = 2, off = { x = -3, y = -1 } }, diagonal = { dir = 5, off = { x = 3, y = 1 } } },
[4] = { straight = { dir = 0, off = { x = -1, y = -3 } }, diagonal = { dir = 1, off = { x = 1, y = 3 } } },
[5] = { straight = { dir = 0, off = { x = 1, y = -3 } }, diagonal = { dir = 7, off = { x = -1, y = 3 } } },
[6] = { straight = { dir = 2, off = { x = 3, y = -1 } }, diagonal = { dir = 3, off = { x = -3, y = 1 } } },
[7] = { straight = { dir = 2, off = { x = 3, y = 1 } }, diagonal = { dir = 1, off = { x = -3, y = -1 } } }
}
--local direction ={ N=0, NE=1, E=2, SE=3, S=4, SW=5, W=6, NW=7}
FARL.input2dir = { [0] = -1, [1] = 0, [2] = 1 }
--[traveldir] ={[raildir]
-- TODO use this to get corresponding rail, instead of relying on the array order to be the same for rails and signals (messed up by 180° rotation)
FARL.signalOffset =
{
[0] = {
[0] = { pos = { x = 1.5, y = 0.5 }, dir = 4 }
},
[1] = {
[3] = { pos = { x = 1.5, y = 1.5 }, dir = 5 },
[7] = { pos = { x = 0.5, y = 0.5 }, dir = 5 }
},
[2] = {
[2] = { pos = { x = -0.5, y = 1.5 }, dir = 6 }
},
[3] = {
[1] = { pos = { x = -0.5, y = 0.5 }, dir = 7 },
[5] = { pos = { x = -1.5, y = 1.5 }, dir = 7 }
},
[4] = {
[0] = { pos = { x = -1.5, y = -0.5 }, dir = 0 }
},
[5] = {
[3] = { pos = { x = -0.5, y = -0.5 }, dir = 1 },
[7] = { pos = { x = -1.5, y = -1.5 }, dir = 1 }
},
[6] = {
[2] = { pos = { x = 0.5, y = -1.5 }, dir = 2 }
},
[7] = {
[1] = { pos = { x = 1.5, y = -1.5 }, dir = 3 },
[5] = { pos = { x = 0.5, y = -0.5 }, dir = 3 }
},
}
FARL.real_signalOffset =
{
[0] = {
[0] = { x = 1.5, y = 0.5 }
},
[1] = {
[3] = { x = 1, y = 1 },
[7] = { x = 1, y = 1 }
},
[2] = {
[2] = { x = -0.5, y = 1.5 }
},
[3] = {
[1] = { x = -1, y = 1 },
[5] = { x = -1, y = 1 }
},
[4] = {
[0] = { x = -1.5, y = -0.5 }
},
[5] = {
[3] = { x = -1, y = -1 },
[7] = { x = -1, y = -1 }
},
[6] = {
[2] = { x = 0.5, y = -1.5 }
},
[7] = {
[1] = { x = 1, y = -1 },
[5] = { x = 1, y = -1 }
},
}
local function moveRail(rail, direction, distance)
local data = lib.diagonal_data
distance = (rail.type == "straight-rail" and rail.direction % 2 == 1) and distance or distance * 2
local off = data[rail.direction] and data[rail.direction] or { x = 0, y = 0 }
local pos = Position.add(off, rail.position)
pos = Position.translate(pos, direction, distance)
local newRail = get_fake_rail(rail, pos)
if rail.type == "straight-rail" and rail.direction % 2 == 1 and distance % 2 == 1 then
newRail.direction = (rail.direction + 4) % 8
end
off = data[newRail.direction] or { x = 0, y = 0 }
pos = Position.subtract(pos, off)
newRail.position = pos
return newRail
end
local function get_signal_for_rail(rail, traveldir, end_of_rail)
local rail_pos = diagonal_to_real_pos(rail)
local offset = FARL.real_signalOffset[traveldir][rail.direction]
local pos = Position.add(rail_pos, offset)
local dir = (traveldir + 4) % 8
local signal = { name = "rail-signal", position = pos, direction = dir }
if rail.force then
signal.force = rail.force
end
if end_of_rail and rail.direction % 2 == 0 then
signal.position = move_right_forward(signal.position, traveldir, 0, 1)
end
return signal
end
FARL.find_entities_filtered = function(self, args, from)
log(game.tick .. " " .. from .. " " .. serpent.line(args, {comment=false}) .. " found: " .. self.surface.count_entities_filtered(args))
return self.surface.find_entities_filtered(args)
end
FARL.getIdFromTrain = function(train)
if train and train.valid and train.locomotives then
return #train.locomotives.front_movers > 0 and train.locomotives.front_movers[1].unit_number or train.locomotives.back_movers[1].unit_number
end
end
FARL.isFARLLocomotive = function(loco)
if not loco or not loco.valid or not loco.type == "locomotive" then
return false
end
if loco.name == "farl" or loco.name == "farl-mu" then
return true
end
if loco.grid then
for _, equipment in pairs(loco.grid.equipment) do
if equipment.name == "farl-roboport" then
return true
end
end
end
return false
end
FARL.newByLocomotive = function(loco)
local new = {
locomotive = loco,
train = loco.train,
driver = false,
active = false,
lastrail = false,
direction = false,
input = 1,
signalCount = { main = 0 },
cruise = false,
cruiseInterrupt = 0,
lastposition = false,
surface = loco.surface,
concrete_queue = {},
rail_queue = {},
}
setmetatable(new, { __index = FARL })
local idLoco = FARL.getIdFromTrain(loco.train)
global.farl[idLoco] = new
return new
end
FARL.new = function(player)
local farl = FARL.newByLocomotive(player.vehicle)
farl.driver = player
farl.cheat_mode = player.cheat_mode
farl.settings = Settings.loadByPlayer(player)
return farl
end
FARL.setup = function(loco)
local farl = FARL.findByLocomotive(loco)
if farl then
if not farl.active then
farl.train = loco.train
farl.frontmover = false
farl.locomotive = loco
for _, l in pairs(farl.train.locomotives.front_movers) do
if l == loco then
farl.frontmover = true
break
end
end
end
farl.max_speed = math.huge
farl.max_speed_loco = false
for _, l in pairs(farl.train.locomotives.front_movers) do
if l.prototype.speed < farl.max_speed then
farl.max_speed = l.prototype.speed
farl.max_speed_burner = l.burner
end
end
for _, l in pairs(farl.train.locomotives.back_movers) do
farl.max_speed = l.prototype.speed < farl.max_speed and l.prototype.speed or farl.max_speed
end
--log('max :' .. farl.max_speed)
end
return farl
end
FARL.onPlayerEnter = function(player, loco)
--TODO fix train/farl tracking
local status, err = pcall(function()
local farl = FARL.setup(loco or player.vehicle)
if farl and not farl.active then
farl.driver = player
farl.settings = Settings.loadByPlayer(player)
farl.cheat_mode = player.cheat_mode
farl.read_blueprints = 0
if farl.settings.bulldozer and not farl:bulldozerModeAllowed() then
farl.settings.bulldozer = false
farl:print({ "msg-bulldozer-error" })
farl:print({ "msg-bulldozer-disabled" })
end
if remote.interfaces.YARM and remote.interfaces.YARM.hide_expando and player.name ~= "farl_player" then
farl.settings.YARM_old_expando = remote.call("YARM", "hide_expando", player.index)
end
global.activeFarls[FARL.getIdFromTrain(farl.train)] = farl
farl.settings.cruiseSpeed = farl.settings.fullCruise and farl.train.max_forward_speed or 0.4
return farl
end
end)
if not status then
debugDump("Unexpected error:",true)
debugDump(err,true)
else
return err
end
end
FARL.onPlayerLeave = function(player)
--TODO fix train/farl tracking
local status, err = pcall(function()
for _, f in pairs(global.farl) do
if f.driver and f.driver == player then
f:deactivate()
global.activeFarls[FARL.getIdFromTrain(f.train)] = nil
f.driver = false
f.lastMove = nil
f.railBelow = nil
f.next_rail = nil
f.read_blueprints = 0
if remote.interfaces.YARM and remote.interfaces.YARM.show_expando and f.settings.YARM_old_expando and player.name ~= "farl_player" then
remote.call("YARM", "show_expando", player.index)
end
--f.settings = false
break
end
end
end)
if not status then
debugDump("Unexpected error:",true)
debugDump(err,true)
end
--debugDump(apiCalls,true)
--apiCalls = {find={item=0,tree=0,stone=0,other=0},canplace=0,create=0,count={item=0,tree=0,stone=0,other=0}}
end
FARL.findByLocomotive = function(loco)
local idLoco = FARL.getIdFromTrain(loco.train)
return global.farl[idLoco] or FARL.newByLocomotive(loco)
end
FARL.findByPlayer = function(player)
local farl
if player.vehicle then
local id = FARL.getIdFromTrain(player.vehicle.train)
farl = global.farl[id]
if farl and farl.locomotive == player.vehicle then
farl.driver = player
return farl
else
return FARL.new(player)
end
else
if player.opened and FARL.isFARLLocomotive(player.opened) then
farl = global.farl[player.opened.unit_number]
if farl and farl.locomotive == player.opened then
return farl
else
return FARL.newByLocomotive(player.opened)
end
end
end
return false
end
FARL.update = function(self, _)
if not self.driver then
return
end
if not self.train.valid then
if self.locomotive.valid then
self.train = self.locomotive.train
else
--self:deactivate("Error (invalid train)2")
for i, farl in pairs(global.activeFarls) do
if not farl.train or (farl.train and not farl.train.valid) then
if farl.driver and farl.driver.valid then
GUI.destroyGui(farl.driver)
end
log("Error update (invalid train): " .. i .. " tick: " .. game.tick)
farl:deactivate("Error (invalid train): " .. i .. " tick: " .. game.tick)
global.activeFarls[i] = nil
global.farl[i] = nil
end
end
return true
end
end
if self.active and not self.train.manual_mode then
self:deactivate()
self.train.manual_mode = true
return true
end
self.cruiseInterrupt = self.driver.riding_state.acceleration
if self.cruise then
self:cruiseControl()
end
if self.active then
self.input = self.driver.riding_state.direction
--local next_rail = self:findNeighbour(below, self.direction, self.input) or self:get_connected_rail(below, false, self.direction)
--if not next_rail then
if not self.lastrail.valid then
self:deactivate({ "msg-error-2" })
return true
end
local firstWagon = self.frontmover and self.train.carriages[1] or self.train.carriages[#self.train.carriages]
if Position.distance_squared(self.lastrail.position, firstWagon.position) < 36 then
--log("start update")
--debugDump(#self.path, true)
--if not self.last_moved then self.last_moved = game.tick end
--local diff = game.tick - self.last_moved
--self:print(diff.."@"..game.tick)
--self.last_moved = game.tick
self.acc = self.driver.riding_state.acceleration
if ((self.acc ~= 3 and self.frontmover) or (self.acc ~= 1 and not self.frontmover)) then
--autopilot
if self.ghostPath then
local data = self.ghostPath[#self.ghostPath]
self.input = data.input
self.ghostPath[#self.ghostPath] = nil
end
--check if previous curve is far enough behind if input is the same
if self.lastCurve and self.lastCurve.input == self.input and self.settings.parallelTracks
and #self.settings.activeBP.straight.lanes > 0 and not self.settings.bulldozer then
--self:print("curveblock:"..self.lastCurve.curveblock.."dist:"..self.lastCurve.dist)
if self.lastCurve.dist < self.lastCurve.curveblock then
self.input = 1
--deactivate if it's a scripted player, as the path gets messed up
if self.ghostPath or self.driver.name == "farl_player" then
self:deactivate("Curves to close to each other.")
return true
end
end
end
local newTravelDir, nextRail = self:getRail(self.lastrail, self.direction, self.input)
if not nextRail then
--log("Need extra rail "..serpent.block(self.lastrail))
newTravelDir, nextRail = self:getRail(self.lastrail, self.direction, 1)
if not nextRail then
--self:print("What happened?")
return true
end
end
--log("start placeRails")
local dir_, last = self:placeRails(nextRail, newTravelDir)
--log("end placeRails")
if dir_ then
if not last.position and not last.name then
self:deactivate({ "msg-no-entity" })
return true
end
if self.ghostPath then
self.ghostProgress = self.ghostProgress + 1
end
self.protected_index = self.protected_index + 1
if self.protected_index == 7 then
self.protected_index = 1
self.protected[self.protected_index] = {}
self.protected_tiles[self.protected_index] = {}
end
--debugDump(self.protected_index,true)
-- add created rail to path
table.insert(self.path, { rail = last, travel_dir = newTravelDir, input = self.input })
-- remove rails behind train from path
local behind = self:rail_behind_train()
local found = false
local max_path = #self.path
for i = max_path, 1, -1 do
if self.path[i].rail == behind and i > 1 then
found = i
end
if found and found > i then
local name = self.path[i].rail.name
local rail = self.path[i].rail
self:protect(rail)
if self.settings.bulldozer then
self:bulldoze_area(rail, self.path[i].travel_dir)
local addAmount = self.path[i].rail.type == "straight-rail" and 1 or 4
if self.path[i].rail.destroy({raise_destroy = true}) then
self:addItemToCargo(name, addAmount, true) --TODO addAmount shouldn't be needed
else
self:deactivate({ "msg-cant-remove" })
return true
end
end
table.remove(self.path, i)
end
end
--self:flyingText2("X", RED, true,self.path[1].rail.position)
if last.type == "curved-rail" then
self.lastCurve = { dist = -1, input = self.input, direction = self.direction, blocked = {}, curveblock = 0 }
else
self.lastCurve.dist = self.lastCurve.dist + 1
end
if not self.settings.bulldozer then
--add concrete to the queue to be placed in a tick without track placement (probably the next one)
if self.settings.concrete then
table.insert(self.concrete_queue, {
travelDir = newTravelDir,
rail = get_fake_rail(last)
})
end
--place rail entities (only walls for now), place on the mainrail euqal to the furthest lagging parallel track
if self.settings.railEntities and #self.settings.activeBP.straight.lanes == 0 then
local c = #self.path - 1
if c > 0 and self.path[c] and self.path[c].rail.type ~= "curved-rail" then
local rail = self.path[c].rail
table.insert(self.rail_queue, { travelDir = self.path[c].travel_dir, rail = get_fake_rail(rail) })
end
end
--debugLog("Path length: "..#self.path)
if self.settings.poles and #self.path > 2 then
local c = #self.path
local rail = self.path[c - 1].rail
local dir = self.path[c - 1].travel_dir
--debugLog("calculating pole for rail@"..Position.tostring(self.path[c-1].rail.position))
local rails = self:getPoleRails(rail, dir, self.path[c - 2].travel_dir)
if self.path[c - 2].rail.type == "curved-rail" and #rails > 0 then
rails[1].range[1] = -1
end
--local bestpole, bestrail = self:getBestPole(self.lastPole, rails, newTravelDir)
local bestpole, bestrail = self:getBestPole(self.lastPole, rails, dir)
if bestpole then
--debugLog("--pole: "..Position.tostring(bestpole.p))
self.lastCheckPole = bestpole.p
self.lastCheckDir = bestpole.dir
self.lastCheckRail = bestrail
--if global.debug_log then
--self:flyingText2("bp", RED, true, bestpole.p)
--self:flyingText2("br", RED, true, bestrail.position)
--end
else
--self:print("should place pole")
--self:flyingText2("sp", RED, true, self.lastCheckPole)
if self.lastCheckPole.x then
--debugLog("--Should be placing pole @"..Position.tostring(self.lastCheckPole))
local status, err = pcall(function() self:placePole(self.lastCheckPole, self.lastCheckDir) end)
if not status then
error(err, 2)
end
end
end
end
if self.settings.signals then
self.signalCount.main = self.signalCount.main + get_signal_weight(last, self.settings)
if last.type == "curved-rail" then
self.signalCount.main = self.signalCount.main - self.lanes.max_lag[newTravelDir % 2] - get_signal_weight(last, self.settings)
end
if self:placeSignal(newTravelDir, nextRail) then
self.signalCount.main = 0
end
end
if self.settings.parallelTracks and #self.settings.activeBP.straight.lanes > 0 then
max_path = -1
local all_placed = 0
for i, _ in pairs(self.settings.activeBP.straight.lanes) do
if last.type == "curved-rail" then
local traveldir = newTravelDir
local block = self:placeParallelCurve(newTravelDir, last, i)
if block then
local lag = abs(self.lanes["d" .. traveldir % 2]["i" .. self.input]["l" .. i].lag) + block - 1
max_path = lag > max_path and lag or max_path
self.lastCurve.curveblock = max_path
end
else
local placed = self:placeParallelTrack(newTravelDir, last, i)
if placed then
self.lanerails[i] = placed
all_placed = self.lanerails[i] and all_placed + 1 or all_placed
end
end
end
if self.settings.railEntities and all_placed == #self.settings.activeBP.straight.lanes then
local lag = self.lanes.max_lag[newTravelDir % 2]
local c = #self.path - lag
if c > 0 and self.path[c] and self.lastCurve.dist > lag then
local rail = self.path[c].rail
rail = get_fake_rail(rail)
table.insert(self.rail_queue, { travelDir = self.path[c].travel_dir, rail = rail })
end
end
end
end
self.direction = newTravelDir
self.lastrail = last
--log("end update success")
return true
else
self:deactivate(last)
--log("end update fail:"..last)
return true
end
end
else
-- if bulldoze mode is on, prepare the area for the next rail after self.lastrail according to input
if self.settings.bulldozer or self.settings.maintenance then
local _, next = self:getRail(self.lastrail, self.direction, 1)
if next and self.already_prepared ~= Position.tostring(next.position) then
--self:flyingText2("R", RED,true, next.position)
self.already_prepared = Position.tostring(next.position)
self:bulldoze_area(next, self.direction)
end
end
if self.settings.concrete and #self.concrete_queue > 0 then
for _, queue in pairs(self.concrete_queue) do
self:placeConcrete(queue.travelDir, queue.rail)
end
self.concrete_queue = {}
end
if self.settings.railEntities and #self.rail_queue > 0 then
for _, queue in pairs(self.rail_queue) do
self:placeRailEntities(queue.travelDir, queue.rail)
end
self.rail_queue = {}
end
end
if self.ghostPath then
if #self.ghostPath == 0 then
self:deactivate("Finished path")
return true
end
end
end
end
FARL.show_path = function(self)
for i = 1, #self.path do
self:flyingText2(i, RED, true, diagonal_to_real_pos(self.path[i].rail))
--self:flyingText(i..":"..self.path[i].travel_dir, RED, true, self.path[i].rail.position)
--debugDump(path[i].rail.position,true)
end
end
FARL.createBoundingBox = function(self, rail, direction)
local bb = direction % 2 == 1 and self.settings.activeBP.diagonal.boundingBox or self.settings.activeBP.straight.boundingBox
local realpos = diagonal_to_real_pos(rail)
local area = {
move_right_forward(realpos, direction, bb.tl.x, bb.tl.y),
move_right_forward(realpos, direction, bb.br.x, bb.br.y)
}
local tl = { x = min(area[1].x, area[2].x), y = min(area[1].y, area[2].y) }
local br = { x = max(area[1].x, area[2].x), y = max(area[1].y, area[2].y) }
return { left_top = tl, right_bottom = br }
end
--prepare an area for entity so it can be placed
FARL.prepareArea = function(self, entity, rangeOrArea)
local pos = entity.position
local area = (type(rangeOrArea) == "table") and rangeOrArea or false
local range = (type(rangeOrArea) ~= "number") and 1.5 or 0.5
area = area and area or Position.expand_to_area(pos, range)
--if force or not self:genericCanPlace(entity) then
--debugDump(area,true)
--self:showArea2(area)
--log(game.tick.." prepArea")
self:removeTrees(area)
self:pickupItems(area)
self:removeStone(area)
self:removeCliffs(area)
--log(game.tick.." prepArea done")
--else
--return true
--end
if entity and entity.name and not self:genericCanPlace(entity) then
self:fillWater(area)
end
return self:genericCanPlace(entity)
end
FARL.prepareAreaForCurve = function(self, newRail)
local areas = FARL.clearAreas[newRail.direction % 4]
for i = 1, 2 do
local area = areas[i]
local tl, lr = Position.add(newRail.position, area[1]), Position.add(newRail.position, area[2])
area = { left_top = { x = tl.x - 1, y = tl.y - 1 }, right_bottom = { x = lr.x + 1, y = lr.y + 1 } }
self:removeTrees(area)
self:pickupItems(area)
self:removeStone(area)
self:removeCliffs(area)
if self.settings.bulldozer or self.settings.maintenance then
local types = { "straight-rail", "curved-rail", "rail-signal", "rail-chain-signal", "electric-pole", "lamp", "wall" }
for _, t in pairs(types) do
self:removeEntitiesFiltered({ area = area, type = t }, self.protected)
end
end
if not self:genericCanPlace(newRail) then
self:fillWater(area)
end
end
end
FARL.removeTrees = function(self, area)
--apiCalls.count.tree = apiCalls.count.tree + 1
local amount, name, proto
local random = math.random
--log(game.tick .. ' removeTrees start ' .. tostring(self.surface.count_entities_filtered { area = area, type = "tree" }))
for _, entity in pairs(self.surface.find_entities_filtered { area = area, type = "tree" }) do
--for _, entity in pairs(self:find_entities_filtered({ area = area, type = "tree" }, "removeTrees")) do
local stat = global.statistics[self.locomotive.force.name].removed["tree-01"] or 0
global.statistics[self.locomotive.force.name].removed["tree-01"] = stat + 1
proto = entity.prototype.mineable_properties
if proto and proto.minable and proto.products and (not self.cheat_mode) and self.settings.collectWood then
local products = proto.products
if products then
for _, product in pairs(products) do
if product.type == "item" then
if product.name == "wood" then
self:addItemToCargo("wood", 1)
else
if product.probability then
if product.probability == 1 or (product.probability >= random()) then
name = product.name
end
if name then
if product.amount_max == product.amount_min then
amount = product.amount_max
else
amount = random(product.amount_min, product.amount_max)
end
if amount and amount > 0 then
self:addItemToCargo(name, ceil(amount/2))
end
name = false
end
elseif product.name and product.amount then
name = product.name
amount = product.amount
if amount and amount > 0 then
self:addItemToCargo(name, ceil(amount/2))
end
name = false
end
end
end
end
end
end
entity.die() -- using die() here, because destroy() doesn't leave tree stumps
end
--log(game.tick .. ' removeTrees end')
end
FARL.removeCreep = function(self, area)
if self.surface.count_tiles_filtered{area = area, name = "kr-creep"} > 0 then
local tiles = {}
local tiles_filtered = self.surface.find_tiles_filtered{area = area, name = "kr-creep"}
local collected = 0
for _, tile in pairs(tiles_filtered) do
table.insert(tiles, {name = "landfill", position = tile.position})
collected = collected + 1
end
if collected > 0 and not self.cheat_mode then
collected = round(collected * (math.random(30,80)/100))
if collected > 0 then
self:addItemToCargo("biomass", collected)
end
end
if #tiles > 0 then
self.surface.set_tiles(tiles)
end
end
end
FARL.removeStone = function(self, area)
self:removeCreep(area)
local amount, name, proto
local random = math.random
for _, entity in pairs(self.surface.find_entities_filtered { area = area, type = "simple-entity", force = "neutral" }) do
proto = entity.prototype.mineable_properties
if proto and proto.minable and proto.products then
if entity.destroy() and self.settings.collectWood and not self.cheat_mode then
local products = proto.products
for _, product in pairs(products) do
if product.type == "item" then
if product.probability then
if product.probability == 1 or (product.probability >= random()) then
name = product.name
end
if name then
if product.amount_max == product.amount_min then
amount = product.amount_max
else
amount = random(product.amount_min, product.amount_max)
end
if amount and amount > 0 then
--log(string.format("added %s %s", amount, name))
self:addItemToCargo(name, ceil(amount/2))
end
name = false
end
elseif product.name and product.amount then
name = product.name
amount = product.amount
if amount and amount > 0 then
--log(string.format("added %s %s", amount, name))
self:addItemToCargo(name, ceil(amount/2))
end
name = false
end
end
end
local stat = global.statistics[self.locomotive.force.name].removed["stone-rock"] or 0
global.statistics[self.locomotive.force.name].removed["stone-rock"] = stat + 1
end
end
end
end
FARL.removeCliffs = function(self, area)
if not self.settings.remove_cliffs then
return
end
local cliffs = self.surface.find_entities_filtered { area = area, type = "cliff" }
if #cliffs == 0 then
return
end
local amount = ceil(#cliffs / 3)
local explosives = self:getCargoCount("cliff-explosives")
if explosives >= amount then
local stat = global.statistics[self.locomotive.force.name].removed["cliff"] or 0
global.statistics[self.locomotive.force.name].removed["cliff"] = stat + #cliffs
local removed = 0
for _, entity in pairs(cliffs) do
if entity.destroy({do_cliff_correction = true}) then
removed = removed + 1
end
--entity.destroy{do_cliff_correction = true}
end
self:removeItemFromCargo("cliff-explosives", amount, explosives)
else
self:print_out_of_item("cliff-explosives")
end
end
-- args = {area=area, name="name"} or {area=area,type="type"}
-- exclude: table with entities as keys
FARL.removeEntitiesFiltered = function(self, args)
local force = self.locomotive.force
local neutral_force = game.forces.neutral
local count
for _, entity in pairs(self.surface.find_entities_filtered(args)) do
count = 1
--for _, entity in pairs(self:find_entities_filtered(args, "removeEntitiesFiltered")) do
if not self:isProtected(entity) and (entity.force == force or entity.force == neutral_force) then
local item = false
local name = entity.name
if entity.type == "straight-rail" or entity.type == "curved-rail" then
item = entity.name
else
if entity.prototype.items_to_place_this then
local item_stacks = entity.prototype.items_to_place_this
if item_stacks and #item_stacks > 0 then
item = item_stacks[1].name
count = item_stacks[1].count
end
end
end
if not entity.destroy({raise_destroy = true}) then
self:deactivate({ "msg-cant-remove" })
return
else
if item and name ~= "concrete-lamp" then
self:addItemToCargo(item, count)
local stat = global.statistics[self.locomotive.force.name].removed[item] or 0
global.statistics[self.locomotive.force.name].removed[item] = stat + 1
end
end
end
end
end
FARL.fillWater = function(self, area)
local status, err = pcall(function()
-- check if bridging is turned on in settings
if self.settings.bridge then
-- following code mostly pulled from landfill mod itself and adjusted to fit
local tiles = {}
area = Area.to_table(area)
local st, ft = area.left_top, area.right_bottom
local dw, w = 0, 0
local water_tiles = {water = true, deepwater = true, ['water-shallow'] = true, ['water-mud'] = true}
local place_result = game.item_prototypes["landfill"] and game.item_prototypes["landfill"].place_as_tile_result
place_result = place_result and place_result.result.name or "landfill"
local _tile_prototypes = game.tile_prototypes
local tile_prototypes = {}
for x = st.x, ft.x, 1 do
for y = st.y, ft.y, 1 do
local tileName = self.surface.get_tile(x, y).name
-- check that tile is water, if it is add it to a list of tiles to be changed to grass
if water_tiles[tileName] then
if tileName ~= "deepwater" then
w = w + 1
else
dw = dw + 1
end
tile_prototypes[tileName] = tile_prototypes[tileName] or _tile_prototypes[tileName]
table.insert(tiles, { name = place_result, position = { x=x, y=y } })
end
end
end
self:replaceWater(tiles, w, dw)
end
end)
if not status then
debugDump(area, true)
error(err, 3)
end
end
FARL.replaceWater = function(self, tiles, w, dw)
-- check to make sure water tiles were found
if #tiles ~= 0 then
-- if they were calculate the minimum number of landfills to fill them in ( quick and dirty at the moment may need tweeking to prevent overusage)
local lfills = ceil(w / 2 + dw * 1.5)
lfills = lfills > 20 and 20 or lfills
-- check to make sure there is enough landfill in the FARL and if there is apply the changes, remove landfill. if not then show error message
if self:getCargoCount("landfill") >= lfills then
self.surface.set_tiles(tiles, true, true, true, true)
self:removeItemFromCargo("landfill", lfills)
--script.raise_event(defines.events.script_raised_set_tiles, {surface_index = self.surface.index, tiles = tiles,})
end
end
end
FARL.placeConcrete = function(self, dir, rail)
if rail.type == "curved-rail" then return end
local type = rail.direction % 2 == 1 and "diagonal" or "straight"
local concrete = self.settings.activeBP[type].concrete
if not concrete then return end
local diff = dir % 2 == 0 and dir or dir - 1
local rad = diff * (math.pi / 4)
local tiles = {}
local pave = {}
local w, dw = 0, 0
local railpos = diagonal_to_real_pos(rail)
--mirror directional concrete from color-coding
local textured = {}
textured["concrete-hazard-left"] = "concrete-hazard-right"
textured["concrete-hazard-right"] = "concrete-hazard-left"
textured["concrete-fire-left"] = "concrete-fire-right"
textured["concrete-fire-right"] = "concrete-fire-left"
--vanilla hazard concrete
textured["hazard-concrete-left"] = "hazard-concrete-right"
textured["hazard-concrete-right"] = "hazard-concrete-left"
local tile_prototypes = {}
local _tile_prototypes = game.tile_prototypes
local water_tiles = {water = true, deepwater = true, ['water-shallow'] = true, ['water-mud'] = true}
local place_result = game.item_prototypes["landfill"] and game.item_prototypes["landfill"].place_as_tile_result
place_result = place_result and place_result.name or "grass-1"
for _, c in pairs(concrete) do
local name = c.name
if self.settings.mirrorConcrete and endsWith(name, "-left") or endsWith(name, "-right") then
if (type == "straight" and dir % 4 == 2) or (type == "diagonal" and (dir == 3 or dir == 7)) then
name = textured[name] or name
end
end
local entity = { name = name }
local offset = c.position
offset = rotate(offset, rad)
local pos = Position.add(railpos, offset)