Repository navigation
Expand file tree
/
Copy pathlibrail.lua
More file actions
1104 lines (971 loc) · 41.7 KB
/
Copy pathlibrail.lua
File metadata and controls
1104 lines (971 loc) · 41.7 KB
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('util')
local sqrt2 = math.sqrt(2)
local curve_length = 7.7 -- 7.7288196964265417438549920430937
-- Defines we use a lot, so abbreviate and reference them.
local rd = defines.rail_direction
local rcd = defines.rail_connection_direction
local dir = defines.direction
--
-- Private functions/tables
--
-- We supply offsets for north and northeast facings only. All others are generated by calculating rotations, using
-- this table.
local _rotations = {
{dir.north, dir.east},
{dir.northeast, dir.southeast},
{dir.east, dir.south},
{dir.southeast, dir.southwest},
{dir.south, dir.west},
{dir.southwest, dir.northwest},
}
local function each_rotation()
local i = 0
return function()
i = i + 1
if _rotations[i] then return unpack(_rotations[i]) end
return nil
end
end
-- Performs a 90 degree rotation of src
local function rotate_cw(src)
local t = table.deepcopy(src)
t.x, t.y = -t.y, t.x
if t.d then
t.d = (t.d+2)%8
end
return t
-- return { x=-src.y, y=src.x, d=src.d and (src.d+2)%8 or nil }
end
-- Given bounds and a position, extend the bounds to fit the position.
local function expand_bounds(bounds, position)
if not bounds then
bounds = { left_top = { x = position.x, y=position.y }, right_bottom = {x=position.x, y=position.y} }
else
if position.x < bounds.left_top.x then bounds.left_top.x = position.x
elseif position.x > bounds.right_bottom.x then bounds.right_bottom.x = position.x
end
if position.y < bounds.left_top.y then bounds.left_top.y = position.y
elseif position.y > bounds.right_bottom.y then bounds.right_bottom.y = position.y
end
end
return bounds
end
-- Offset bounds by the specified offset.
local function offset_bounds(bounds, offset, t)
if not t then t = {left_top = {}, right_bottom={} } end
t.left_top.x = bounds.left_top.x + offset.x
t.left_top.y = bounds.left_top.y + offset.y
t.right_bottom.x = bounds.right_bottom.x + offset.x
t.right_bottom.y = bounds.right_bottom.y + offset.y
return t
end
local function find(haystack, needle)
for i = 1, #haystack do
if needle == haystack[i] then return i end
end
return nil
end
local librail = {
-- rail_connection_direction defines a 'none, which is useless and causes errors with get_connected_rail.
-- Add our own to deal with this.
rail_connection_directions = { rcd.left, rcd.straight, rcd.right },
rail_directions = { rd.front, rd.back },
rail_entity_types = {"straight-rail", "curved-rail" },
signal_entity_types = {"rail-signal", "rail-chain-signal"},
signal_entity_types_with_ghosts = {"rail-signal", "rail-chain-signal", "entity-ghost"},
-- Use: chiral_directions
8000
[source.chirality == dest.chirality][direction]
--[[
Chirality:
Different rail segments have different notions of where their 'front' is.
While following a circular section of track clockwise, two adjacent sections of track have the same chirality
If their fronts face the same direction -- that is, neither front points at the other track segment.
]]
chiral_directions = {
[true] = {
[rd.front] = rd.front,
[rd.back] = rd.back
},
[false] = {
[rd.front] = rd.back,
[rd.back] = rd.front
}
},
opposite_signal_offsets = {
[dir.north] = {x=3, y=0, d=dir.south},
[dir.northeast] = {x=2.5, y=2.5, d=dir.southwest},
},
connected_rail_permutations = {},
all_connected_rail_permutations = {},
--[[
rail_data format:
[entity.name] = {
[entity.direction] = {
signals = {
[rail_direction] = {
{x=xoffset, y=yoffset, d=direction},
...
}
},
length = 1,
cardinality = ...,
},
}
Signals:
Signals are listed in direction of travel. So, a train travelling along this track's "front" direction will
encounters signals in the order they appear in in that list.
Offsets are where the signals are located relative to the track.
]]
signal_blockers = {
[dir.north] = {
{ name = "curved-rail", x = 2.5, y = 0.5, d = dir.northeast },
{ name = "curved-rail", x = 2.5, y = -0.5, d = dir.northeast },
{ name = "curved-rail", x = 2.5, y = -1.5, d = dir.northeast },
{ name = "curved-rail", x = 2.5, y = -2.5, d = dir.northeast },
{ name = "curved-rail", x = 2.5, y = -0.5, d = dir.south },
{ name = "curved-rail", x = 2.5, y = 0.5, d = dir.south },
{ name = "curved-rail", x = 2.5, y = 1.5, d = dir.south },
{ name = "curved-rail", x = 2.5, y = 2.5, d = dir.south },
},
[dir.northeast] = {
{ name = "curved-rail", x = 0.5, y = 2.5, d = dir.northeast },
{ name = "curved-rail", x = 1.5, y = 1.5, d = dir.northeast },
{ name = "curved-rail", x = 2.5, y = 0.5, d = dir.west},
{ name = "curved-rail", x = 1.5, y = 1.5, d = dir.west},
{ name = "straight-rail", x = 1.5, y = 1.5, d = dir.north},
{ name = "straight-rail", x = 1.5, y = 1.5, d = dir.east},
}
},
signal_blocker_map = {},
rail_data = {
["straight-rail"] = {
[dir.north] = {
length = 2,
signals = {
[rd.front] = {
{x=1.5, y= 0.5, d=dir.south, stops=-1, starts=0}, -- Train stops 1 unit before this rail begins
{x=1.5, y=-0.5, d=dir.south, stops=1, starts=2}
},
[rd.back] = {
{x=-1.5, y=-0.5, d=dir.north, stops=-1, starts=0},
{x=-1.5, y= 0.5, d=dir.north, stops=1, starts=2},
},
},
},
[dir.northeast] = {
length = sqrt2,
signals = {
[rd.front] = {{x=1.5, y=-1.5, d=dir.southeast, stops=-1, starts=1}},
[rd.back] = {{x=-0.5, y=0.5, d=dir.northwest, stops=0, starts=1}},
},
}
},
["curved-rail"] = {
[dir.north] = {
length = curve_length,
signals = {
[rd.front] = {
{x=-2.5, y=-1.5, d=dir.northwest, stops=-1, starts=0},
{x=-0.5, y=3.5, d=dir.north, stops=curve_length-1, starts=curve_length}
},
[rd.back] = {
{x=2.5, y=3.5, d=dir.south, stops=-1, starts=0},
{x=-0.5, y=-3.5, d=dir.southeast, stops=curve_length-1, starts=curve_length}
},
},
},
[dir.northeast] = {
length = curve_length,
signals = {
[rd.front] = {
{x=0.5, y=-3.5, d=dir.northeast, stops=-1, starts=0},
{x=-2.5, y=3.5, d=dir.north, stops=curve_length-1, starts=curve_length},
},
[rd.back] = {
{x=0.5, y=3.5, d=dir.south, stops=-1, starts=0},
{x=2.5, y=-1.5, d=dir.southwest, stops=curve_length-1, starts=curve_length},
},
},
}
}
},
8000
signal_data = {}, -- To be filled later.
}
librail.opposite_direction = librail.chiral_directions[false]
-- Generate permutations of connected rail arguments.
for _, rail_direction in pairs(librail.rail_directions) do
librail.connected_rail_permutations[rail_direction] = {}
for _, rail_connection_direction in pairs(librail.rail_connection_directions) do
local t = {rail_direction=rail_direction, rail_connection_direction=rail_connection_direction }
table.insert(librail.connected_rail_permutations[rail_direction], t)
table.insert(librail.all_connected_rail_permutations, t)
end
end
--- Generates a unique key for a given offset
-- Currently assumes offsets will never be bigger than +/- 10 or so, which satisfies the needs of our library.
-- @param offset The offset to use. Must be a table with x, y and d elements.
function librail.offset_to_key(offset)
-- Offsets are no bigger than 10. Generate a reasonable key based on them for fast lookups.
-- They're also always directional...
return librail.args_to_key(offset.x, offset.y, offset.d)
end
--- Generates a unique key for a given x/y/direction
-- Currently assumes offsets will never be bigger than +/- 10 or so, which satisfies the needs of our library.
-- @param x The x coordinate
-- @param y The y coordinate
-- @param d The direction.
function librail.args_to_key(x, y, d)
-- log("x=" .. x .. "; y=" .. y .. "; d=" .. d .. "; k=" .. x*1000000 + y*1000 + d)
return (x+5)*1000000 + (y+5)*1000 + d
end
local _last_rail_data_entity, _last_rail_data_result
--- Returns the correct member of rail_data based on the provided entity.
-- The last entity requested is cached to avoid expensive Factorio API lookups later.
function librail.get_rail_data(entity)
if entity ~= _last_rail_data_entity then
_last_rail_data_entity = entity
_last_rail_data_result = librail.rail_data[entity.type] and librail.rail_data[entity.type][entity.direction]
end
return _last_rail_data_result
end
-- Finish up rail data and generate signal data.
do
-- Add rotations for other opposite signals.
for source, dest in each_rotation() do
librail.opposite_signal_offsets[dest] = rotate_cw(librail.opposite_signal_offsets[source])
librail.signal_blockers[dest] = {}
for i = 1, #librail.signal_blockers[source] do
librail.signal_blockers[dest][i] = rotate_cw(librail.signal_blockers[source][i])
end
end
-- Generate signal blocker map.
local map = librail.signal_blocker_map
for dir, blockers in pairs(librail.signal_blockers) do
local entities = {}
local bounds
for _, blocker in pairs(blockers) do
if not entities[blocker.name] then entities[blocker.name] = {} end
entities[blocker.name][librail.offset_to_key(blocker)] = blocker
bounds = expand_bounds(bounds, blocker)
end
map[dir] = {entities=entities, bounds=bounds}
end
local t
-- Arbitrary number, must be greater than the number of manually-assigned chiralities.
local number_of_chiralities = 100
for entity_type, entity_data in pairs(librail.rail_data) do
-- Add rotations for directions other than north and northeast.
-- This could be simplified, but this reads better. And it's not a performance critical segment of code.
for source, dest in each_rotation() do
t = {
length = entity_data[source].length,
signals = {}
}
for dir, signals in pairs(entity_data[source].signals) do
t.signals[dir] = {}
for i = 1, #signals do
t.signals[dir][i] = rotate_cw(signals[i])
t.signals[dir][i].stops = signals[i].stops
t.signals[dir][i].starts = signals[i].starts
end
end
entity_data[dest] = t
end
-- Second pass: Create the signal map and determine signal search areas.
for entity_direction, direction_data in pairs(entity_data) do
direction_data.chirality = number_of_chiralities
number_of_chiralities = number_of_chiralities + 1
direction_data.signal_map = {}
for rail_direction, signals in pairs(direction_data.signals) do
for i=1, #signals do
local offset = signals[i]
offset.index = i
-- Update bounds for direction search.
direction_data.bounds = expand_bounds(direction_data.bounds, offset)
-- Generate a map of where our signals are
direction_data.signal_map[librail.offset_to_key(offset)] = {
rail_direction = rail_direction, x = offset.x, y = offset.y, index = i, d = offset.d,
stops=offset.stops, starts=offset.starts
}
-- Do the same thing in reverse for signals.
local signal = librail.signal_data[offset.d]
if not signal then
signal = { rail_map = {} }
librail.signal_data[offset.d] = signal
end
signal.bounds = expand_bounds(signal.bounds, {x=-offset.x, y=-offset.y})
8BD0
if not signal.rail_map[entity_type] then
signal.rail_map[entity_type] = {}
end
local k = librail.args_to_key(-offset.x, -offset.y, entity_direction)
signal.rail_map[entity_type][k] = {
direction = entity_direction,
rail_direction = rail_direction, signal_index = i, signal = offset, rail_data = direction_data,
x = -offset.x, y = -offset.y, d = entity_direction,
}
end
end
end
end
librail.rail_data['straight-rail'][dir.north].chirality = 0
librail.rail_data['curved-rail'][dir.south].chirality = 0
librail.rail_data['curved-rail'][dir.southwest].chirality = 0
librail.rail_data['straight-rail'][dir.southeast].chirality = 0
librail.rail_data['straight-rail'][dir.east].chirality = 1
librail.rail_data['curved-rail'][dir.west].chirality = 1
librail.rail_data['curved-rail'][dir.northwest].chirality = 1
librail.rail_data['straight-rail'][dir.southwest].chirality = 1
librail.rail_data['straight-rail'][dir.northeast].chirality = 2
librail.rail_data['curved-rail'][dir.southeast].chirality = 2
librail.rail_data['straight-rail'][dir.northwest].chirality = 3
librail.rail_data['curved-rail'][dir.northeast].chirality = 3
end
--
-- Library functions
--
--- Returns whether a signal is blocked by rail placement.
-- Does NOT check for colliding entities; the caller should do that.
-- @param surface Signal surface.
-- @param position x/y coordinates of signal.
-- @param direction Direction of signal.
function librail.is_signal_blocked(surface, position, direction)
local map = librail.signal_blocker_map[direction]
--log(serpent.block(map))
local ents = surface.find_entities_filtered{
type=librail.rail_entity_types,
area=offset_bounds(map.bounds, position)
}
local ent, k
for i = 1, #ents do
ent = ents[i]
k = librail.args_to_key(ent.position.x - position.x, ent.position.y - position.y, ent.direction)
if map.entities[ent.name] and map.entities[ent.name][k] then
return true
end
end
return false
end
--- Find attached rails for a specific signal.
-- Note that a signal may be attached to more than one rail -- i.e. a signal at the base of a Y-junction.
-- @param The signal entity.
function librail.find_rail_for_signal(signal)
local rails = {}
local ent
local data = librail.signal_data[signal.direction]
local ents = signal.surface.find_entities_filtered{
area=offset_bounds(data.bounds, signal.position),
type=librail.rail_entity_types
}
local temp
local k
for i = 1, #ents do
ent = ents[i]
k = librail.args_to_key(ent.position.x - signal.position.x, ent.position.y - signal.position.y, ent.direction)
temp = data.rail_map[ent.type][k]
if temp then
rails[#rails + 1] = {
entity=ent, direction=temp.d, rail_direction=temp.rail_direction,
signal_index = temp.signal_index, signal = temp.signal,
rail_data=temp.rail_data,
}
end
end
return rails
end
do
local function _sort_signals(a, b)
return a.rail_direction < b.rail_direction or (a.rail_direction == b.rail_direction and a.index < b.index)
end
--- Returns signals that belong to a selected rail in a selected direction. Signals may belong to more than one rail.
-- @param rail Rail entity to use.
-- @param rail_direction Direction of travel for signals.
-- @param sort True to sort results by direction and then index.
-- @param data Optional rail_data table. If omitted, librail.get_rail_data will be called.
-- @param signal_types Array of signal types to return. If this includes entity-ghost, also finds signal ghosts.
function librail.get_signals(rail, rail_direction, sort, data, signal_types)
signal_types = signal_types or librail.signal_entity_types
data = data or librail.get_rail_data(rail)
if not data then return end
local ent
local signals = {}
local ents = rail.surface.find_entities_filtered{
area=offset_bounds(data.bounds, rail.position), type=signal_types
}
local k
local x, y = rail.position.x, rail.position.y
local temp
for i = 1, #ents do
ent = ents[i]
if ent.type ~= 'entity-ghost' or find(signal_types, ent.ghost_type) then
k = librail.args_to_key(ent.position.x - x, ent.position.y - y, ent.direction)
temp = data.signal_map[k]
if temp and (not rail_direction or rail_direction == temp.rail_direction) then
signals[#signals + 1] = {entity=ent, rail=rail, rail_direction=temp.rail_direction, starts=temp.starts, stops=temp.stops, index=temp.index}
end
end
end
if sort then
table.sort(signals, _sort_signals)
end
return signals
end
end
--- Find one signal that belongs to the selected rail. Signals may belong to more than one rail.
-- @param rail Rail entity to use.
-- @param rail_direction Direction of travel for signals.
-- @param data Optional rail_data table. If omitted, librail.get_rail_data will be called.
-- @param cmp If multiple signals are found, cmp is used to determine which one is returned.
-- @param signal_types Array of signal types to return. If this includes entity-ghost, also finds signal ghosts.
--
-- If a second rail signals are found, cmp(a, b) is called. It returns true to keep a, false to keep b.
function librail.get_signal_with_comparison(rail, rail_direction, data, cmp, signal_types)
signal_types = signal_types or librail.signal_entity_types
data = data or librail.get_rail_data(rail)
if not data then return end
local ent
local ents = rail.surface.find_entities_filtered{
area=offset_bounds(data.bounds, rail.position), type=signal_types
}
local k
local x, y = rail.position.x, rail.position.y
local temp
local best_signal, this_signal
for i = 1, #ents do
ent = ents[i]
if ent.type ~= 'entity-ghost' or find(signal_types, ent.ghost_type) then
k = librail.args_to_key(ent.position.x - x, ent.position.y - y, ent.direction)
temp = data.signal_map[k]
if temp and (not rail_direction or rail_direction == temp.rail_direction) then
this_signal = {entity=ent, rail=rail, rail_direction=temp.rail_direction, starts=temp.starts, stops=temp.stops, index=temp.index}
if not best_signal or cmp(this_signal, best_signal) then
best_signal = this_signal
end
end
end
end
return best_signal
end
do
local function _first(a, b) return a.index < b.index end
local function _last(a, b) return a.index > b.index end
--- Returns the first signal that belongs to the selected rail.
-- @param rail Rail entity to use.
-- @param rail_direction Direction of travel for signals.
-- @param data Optional rail_data table. If omitted, librail.get_rail_data will be called.
function librail.get_first_signal(rail, rail_direction, data, signal_types)
return librail.get_signal_with_comparison(rail, rail_direction, data, _first, signal_types)
end
--- Returns the last signal that belongs to the selected rail.
-- @param rail Rail entity to use.
-- @param rail_direction Direction of travel for signals.
-- @param data Optional rail_data table. If omitted, librail.get_rail_data will be called.
function librail.get_last_signal(rail, rail_direction, data, signal_types)
return librail.get_signal_with_comparison(rail, rail_direction, data, _last, signal_types)
end
end
-- Iterate over connected rails in one or both directions
function librail.each_connected_rail(entity, direction)
local t = direction and librail.connected_rail_permutations[direction] or librail.all_connected_rail_permutations
local i, n = 0, #t
local connected
local function iterator()
while i < n do
i = i + 1
connected = entity.get_connected_rail(t[i])
if connected then
return connected, t[i]
end
end
end
return iterator
end
--- Iterates over connecting rails until reaching the end of the tracks -- or a branch.
-- @param rail Starting rail entity.
-- @param rail_direction Direction to walk.
-- @returns Iterator function which returns rail_entity, new_direction, distance_travelled for each call.
function librail.walk_to_branch(rail, rail_direction, length)
length = length or 0
local next = rail
local temp
local first_unit_number = rail.unit_number
local nextdata = librail.get_rail_data(rail)
local function iterator()
if not next then
return
end
local data = nextdata
rail, next, temp, nextdata = next, nil, nil, nil
assert(data)
length = length + data.length
for temp in librail.each_connected_rail(rail, rail_direction) do
if next then -- More than one connected rail.
next = nil
return rail, rail_direction, length, data
else
next = temp
end
end
temp = rail_direction
if next then
if next.unit_number == first_unit_number then
next = nil
else
nextdata = librail.get_rail_data(next)
assert(nextdata)
rail_direction = librail.chiral_directions[data.chirality == nextdata.chirality][rail_direction]
end
end
return rail, temp, length, data
end
return iterator
end
--- If this signal has a counterpart on the opposite side and direction of the tracks, returns that signal.
-- @param signal Rail signal entity.
-- @param include_ghosts If true, include rail ghosts.
function librail.opposite_signal(signal, include_ghosts)
local offset = librail.opposite_signal_offsets[signal.direction]
local position = {x=signal.position.x + offset.x, y=signal.position.y + offset.y}
local ents = signal.surface.find_entities_filtered{ position=position, type=include_ghosts and librail.signal_entity_types_with_ghosts or librail.signal_entity_types }
local ent
for i = 1, #ents do
ent = ents[i]
if (
ent.position.x == position.x and ent.position.y == position.y and ent.direction == offset.d
and (ent.type ~= 'entity-ghost' or find(librail.signal_entity_types, ent.ghost_type))
) then
return ent
end
end
end
local function _always_true() return true end
local function _default_halt_function(signal, kept) return kept end
--- Returns the nearest signal from the selected rail entity.
-- @param rail Rail entity to search.
-- @param rail_direction Rail direction to travel.
-- @param signal_direction Signal direction of travel.
-- @param max_distance Maximum search distance.
-- @param add_distance Optional amount of distance to add to return result.
-- @returns signal_data_with_entity, distance
--
-- Note: max_distance exists as a sanity check, not a hard limit. The returned result may slightly exceed max_distance
-- in some situations.
function librail.find_nearest_signal(args)
return librail._find_signal_impl(args, true)
end
--- Returns the first signal OF EACH BRANCH starting at the selected rail entity and travelling a set direction.
-- @param rail Rail entity to search.
-- @param rail_direction Rail direction to travel.
-- @param signal_direction Signal direction of travel.
-- @param max_distance Maximum search distance.
-- @param added_distance Optional amount of distance to add to return result.
-- @returns Table of unit_number = {signal_data_with_entity, distance} pairs.
--
-- Note: max_distance exists as a sanity check, not a hard limit. The returned result may slightly exceed max_distance
-- in some situations.
function librail.find_signals_in_branch(args)
return librail._find_signal_impl(args, false)
end
-- Visits rails in sequence. NOTE: May visit a particular rail more than once.
function librail.visit_rails(args)
local rail = args.rail
local rail_direction = args.rail_direction
local max_distance = args.max_distance
local added_distance = args.added_distance or 0
local data
assert(not args.rail ~= not args.unvisited, 'Cannot specify both rail and unvisited parameters')
local unvisited = args.unvisited or {{rail, rail_direction, librail.get_rail_data(rail), added_distance, args.extra}}
local visited = {
[rd.front] = {},
[rd.back] = {},
}
local frontier = {}
local distance
-- Determines whether a particular rail should be revisited based on its new and previous distances.
local revisit = args.revisit or function(a, b) return a < b end
local visit = args.visit
local extra, handled
local temp
local unit_number
local next_rail, next_direction, next_data
while unvisited[1] do
frontier, unvisited = unvisited, frontier
for i = 1, #frontier do
rail, rail_direction, data, distance, extra = unpack(frontier[i])
unit_number = rail.unit_number
frontier[i] = nil -- so frontier is empty for the next loop.
temp = visited[rail_direction][unit_number]
if temp and revisit(distance, temp) then goto next_frontier end
visited[rail_direction][unit_number] = distance
handled, extra = visit(rail, rail_direction, data, distance, extra)
if handled then goto next_frontier end
distance = distance + data.length
if distance > max_distance then goto next_frontier end
for next_rail in librail.each_connected_rail(rail, rail_direction) do
next_data = librail.get_rail_data(next_rail)
next_direction = librail.chiral_directions[next_data.chirality == data.chirality][rail_direction]
temp = visited[next_direction][next_rail.unit_number]
if temp and temp < distance then goto next_frontier end
unvisited[#unvisited + 1] = {next_rail, next_direction, next_data, distance, extra}
end
::next_frontier::
end
end
end
function librail._find_signal_impl(args, nearest_only)
local rail = args.rail
local rail_direction = args.rail_direction
local signal_direction = args.signal_direction or rail_direction
local max_distance = args.max_distance
local added_distance = args.added_distance
local signal_types = args.signal_types
local signals_reversed = rail_direction ~= signal_direction
local find_signal = signals_reversed and librail.get_last_signal or librail.get_first_signal
local keep = args.keep or _always_true
local halt = args.halt or _default_halt_function
if keep == true then keep = _always_true end
if halt == true then halt = _always_true end
-- Best signal we've found, and the distance it was at. Or our other return value.
local best_signal, best_distance
local found_signals = (not nearest_only) and (args.found_signals or {})
args.found_signals = found_signals
local temp -- Short term temporary variable to avoid multiple table dereferences/etc.
local data, distance
local next_data, next_direction
local function visitor(rail, rail_direction, data, distance)
local signal, kept, unit_number
-- best_distance will always be nil when not nearest_only, so a second check is not required.
if best_distance and (best_distance < distance) then
return true
end
signal = find_signal(
rail,
signals_reversed and librail.opposite_direction[rail_direction] or rail_direction,
data,
signal_types
)
if not signal then return false end
if signals_reversed then
-- Going backwards, so concerned with where this signal 'starts'
signal.distance = distance + (data.length - signal.starts)
else
-- Going forward, so concerned with where trains stop
signal.distance = distance + signal.stops
end
kept = keep(signal)
if kept then
if nearest_only then
if not best_distance or signal.distance < best_distance then
best_signal = signal
best_distance = signal.distance
end
else
unit_number = signal.entity.unit_number
if not found_signals[unit_number] or found_signals[unit_number].distance > signal.distance then
found_signals[unit_number] = signal
end
end
end
-- If we have a signal here, nothing past this point is going to be closer... not this route anyways.
return halt(signal, kept)
end
librail.visit_rails({
rail = args.rail,
rail_direction = args.rail_direction,
max_distance = args.max_distance,
added_distance = args.added_distance,
visit = visitor
})
if nearest_only then
return best_signal
else
return found_signals
end
end
do
local _directional_functions = {
[true] = {
distance_mod = function(rail)
return rail.signal.stops
end,
signal_distance = function(rail, signal) return rail.signal.stops - signal.starts end,
is_later_signal = function(a, b)
return a > b
end,
adjust_direction = function(x)
return librail.opposite_direction[x]
end,
},
[false] = {
distance_mod = function(rail)
return rail.rail_data.length - rail.signal.starts
end,
signal_distance = function(rail, signal) return signal.stops - rail.signal.starts end,
is_later_signal = function(a, b)
return a < b
end,
adjust_direction = function(x)
return x
end,
},
}
function librail._find_signal_from_signal_impl(args, nearest_only)
local signal = args.signal
local backwards = args.backwards or false
local max_distance = args.max_distance
local signal_types = args.signal_types
local rails = librail.find_rail_for_signal(signal)
local fn = _directional_functions[backwards]
local d, rd, chirality
local distance, added_distance, signals
local best_distance, best_signal
local signal
local found_signals = (not nearest_only and {})
local keep = args.keep or _always_true
local halt = args.halt or _default_halt_function
local kept
if keep == true then keep = _always_true end
if halt == true then halt = _always_true end
local args = {
max_distance = max_distance or 100,
found_signals = found_signals,
signal_types = signal_types,
halt = halt, keep = keep
}
for i = 1, #rails do
local rail = rails[i]
rd, chirality = rail.rail_direction, rail.rail_data.chirality
signals = librail.get_signals(rail.entity, rail.rail_direction, false, rail.rail_data, signal_types)
-- Make sure there aren't any other signals on this track, since we start our search on the 'next' track.
-- FIXME: This code will break if any rail segment becomes capable of having 3 or more signals in a given direction.
-- Fortunately, there are currently no cases where this is true.
for j = 1, #signals do
signal = signals[j]
if fn.is_later_signal(rail.signal_index, signal.index) then
signal.distance = fn.signal_distance(rail, signal)
kept = keep(signal)
if kept then
if nearest_only then
if not best_distance or distance < best_distance then
best_distance = distance
best_signal = signal
end
else
found_signals[signal.entity.unit_number] = signal
end
end
if halt(signal, kept) then goto next_rail end
end
end
args.added_distance = fn.distance_mod(rail)
for next_rail in librail.each_connected_rail(rail.entity, fn.adjust_direction(rd)) do
d = librail.chiral_directions[chirality == librail.get_rail_data(next_rail).chirality][rd]
args.rail = next_rail
args.rail_direction = fn.adjust_direction(d)
args.signal_direction = d
if nearest_only then
signal, distance = librail.find_nearest_signal(args)
if distance and (not best_distance or best_distance > distance) then
best_signal, best_distance = signal, distance
args.max_distance = best_distance
end
else
librail.find_signals_in_branch(args)
end
end
::next_rail::
end
if nearest_only then
best_signal.distance = best_distance
return best_signal
end
return args.found_signals
end
function librail.find_nearest_signal_from_signal(args)
return librail._find_signal_from_signal_impl(args, true)
end
function librail.find_signals_in_branch_from_signal(args)
return librail._find_signal_from_signal_impl(args, false)
end
end
do
local function _sort_by_distance(a, b) return a.distance < b.distance end
function librail.sort_found_signals(signals)
local result
for k, v in pairs(signals) do
result[#result + 1] = v
end
table.sort(result, _sort_by_distance)
return result
end
end
-- Adapted from math shown at:
-- https://www.gamedev.net/articles/programming/general-and-gameplay-programming/2d-rotated-rectangle-collision-r2604/
local area_to_rectangle, is_overlapping_rectangle
do
local tau = 2*math.pi
local sin = math.sin
local cos = math.cos
function area_to_rectangle(box, t)
local x1 = box.left_top.x
local x2 = box.right_bottom.x
local y1 = box.left_top.y
local y2 = box.right_bottom.y
if not t then
-- No table to reuse, so create a new one.
t = {1, 2, 3, 4, 5, 6, 7, 8, xmin=nil, xmax=nil, ymin=nil, ymax=nil}
end
if (not box.orientation) or (box.orientation == 0) then
t[1], t[2] = x1, y1
t[3], t[4] = x2, y1
t[5], t[6] = x2, y2
t[7], t[8] = x1, y2
t.xmin, t.xmax = x1, x2
t.ymin, t.ymax = y1, y2
return t
end
local xo = (x1 + x2) / 2
local yo = (y1 + y2) / 2
x1, x2, y1, y2 = x1 - xo, x2 - xo, y1 - yo, y2 - yo
local theta = box.orientation * tau
local sin_theta = sin(theta)
local cos_theta = cos(theta)
local xmin, xmax, ymin, ymax
local function _r(i, x, y)
x, y = xo + x*cos_theta - y*sin_theta, yo + x*sin_theta + y*cos_theta
if i == 1 then
xmin, xmax = x, x
ymin, ymax = y, y
else
if xmin > x then xmin = x end
if ymin > y then ymin = y end
if xmax < x then xmax = x end
if ymax < y then ymax = y end
end
t[i], t[i+1] = x, y
end
_r(1, x1, y1)
_r(3, x2, y1)
_r(5, x2, y2)
_r(7, x1, y2)
t.xmin, t.xmax = xmin, xmax
t.ymin, t.ymax = ymin, ymax
return t
end
local function _extents(ax, ay, rect)
local n, x, y, px, py, dot, min, max
local divisor = ax*ax+ay*ay
for i = 1, 8, 2 do
--x, y = unpack(rect[i])
n = (rect[i]*ax + rect[i+1]*ay) / divisor
--px = n*ax
--py = n*ay
--dot = px*ax + py*ay
dot = n*ax*ax + n*ay*ay
if i == 1 then
min, max = dot, dot
else
if min > dot then min = dot end
if max < dot then max = dot end
end
end
return min, max
end
function is_overlapping_rectangle(a, b)
if not (a.xmax >= b.xmin and b.xmax >= a.xmin and a.ymax >= b.ymin and b.ymax >= a.ymin) then
return false
end
local function check_axis(ax, ay)
local amin, amax = _extents(ax, ay, a)