aboutsummaryrefslogtreecommitdiff
path: root/advtrains/models/advtrains_dtrack_vst2_45.obj
blob: 5dc708b78c4ec755c85eaefdb2ef67b413e8f688 (plain)
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
# Blender v2.78 (sub 0) OBJ File: 'rail_redo.blend'
# www.blender.org
o dtrack_vst2_45_Cube.035
v 0.111416 0.278660 0.354093
v 0.111416 0.442721 0.354093
v 0.354093 0.157340 0.111416
v 0.354093 0.321400 0.111416
v 0.205542 0.278660 0.448220
v 0.205542 0.442721 0.448220
v 0.448220 0.157340 0.205543
v 0.448220 0.321400 0.205543
v -0.208358 0.539814 0.791422
v 0.791423 0.040000 -0.208357
v 0.896243 0.040000 -0.103536
v -0.103538 0.539814 0.896242
v -0.164683 0.559814 0.835097
v 0.835098 0.060000 -0.164682
v 0.852568 0.060000 -0.147212
v -0.147213 0.559814 0.852567
v -0.164683 0.609814 0.835097
v 0.835098 0.110000 -0.164682
v 0.852568 0.110000 -0.147212
v -0.147213 0.609814 0.852567
v 0.874406 0.115000 -0.125374
v -0.125375 0.614814 0.874405
v -0.186520 0.614814 0.813259
v 0.813260 0.115000 -0.186519
v 0.874406 0.140000 -0.125374
v -0.125375 0.639814 0.874405
v -0.186520 0.639814 0.813259
v 0.813260 0.140000 -0.186519
v 0.476117 0.313896 0.572089
v -0.572088 0.313896 -0.476117
v -0.656942 0.356316 -0.391265
v 0.391264 0.356316 0.656941
v 0.476117 0.263896 0.572089
v -0.572088 0.263896 -0.476117
v -0.656941 0.306316 -0.391265
v 0.391264 0.306316 0.656942
v -0.508186 3.379001 0.491594
v 0.491594 2.879186 -0.508186
v -0.508186 3.400629 0.491593
v 0.491594 2.900814 -0.508186
v 0.508186 2.879186 -0.491594
v -0.491594 3.379001 0.508186
v 0.508186 2.900814 -0.491594
v -0.491594 3.400629 0.508186
v 0.208358 0.040000 -0.791421
v -0.791423 0.539814 0.208357
v -0.896244 0.539814 0.103537
v 0.103537 0.040000 -0.896242
v 0.164682 0.060000 -0.835097
v -0.835099 0.559815 0.164682
v -0.852568 0.559814 0.147212
v 0.147212 0.060000 -0.852567
v 0.164682 0.110000 -0.835097
v -0.835099 0.609815 0.164682
v -0.852568 0.609814 0.147212
v 0.147212 0.110000 -0.852567
v -0.874406 0.614814 0.125374
v 0.125375 0.115000 -0.874404
v 0.186520 0.115000 -0.813259
v -0.813261 0.614815 0.186520
v -0.874406 0.639814 0.125374
v 0.125375 0.140000 -0.874404
v 0.186520 0.140000 -0.813259
v -0.813261 0.639814 0.186520
v -0.230055 0.092905 -0.818151
v 0.818151 0.092905 0.230055
v 0.733298 0.135325 0.314908
v -0.314908 0.135325 -0.733299
v -0.230055 0.142905 -0.818151
v 0.818151 0.142905 0.230056
v 0.733298 0.185325 0.314908
v -0.314908 0.185325 -0.733298
v 0.314908 0.394489 0.733298
v -0.733298 0.394489 -0.314908
v -0.818151 0.436909 -0.230056
v 0.230055 0.436909 0.818151
v 0.314908 0.344489 0.733298
v -0.733298 0.344489 -0.314908
v -0.818151 0.386909 -0.230055
v 0.230055 0.386909 0.818151
v -0.391264 0.173498 -0.656942
v 0.656941 0.173498 0.391265
v 0.572089 0.215918 0.476118
v -0.476117 0.215918 -0.572089
v -0.391264 0.223498 -0.656941
v 0.656942 0.223498 0.391265
v 0.572088 0.265918 0.476117
v -0.476117 0.265918 -0.572089
v -0.354093 0.278660 -0.111416
v -0.354093 0.442721 -0.111416
v -0.111416 0.157340 -0.354093
v -0.111416 0.321400 -0.354093
v -0.448220 0.278660 -0.205543
v -0.448220 0.442721 -0.205543
v -0.205543 0.157340 -0.448220
v -0.205543 0.321400 -0.448220
v -0.069408 0.012594 -0.978798
v 0.978798 0.012594 0.069409
v 0.893945 0.055014 0.154261
v -0.154261 0.055014 -0.893945
v -0.069408 0.062594 -0.978798
v 0.978798 0.062594 0.069409
v 0.893945 0.105014 0.154261
v -0.154261 0.105014 -0.893945
v 0.069408 0.467220 0.978798
v -0.978798 0.467220 -0.069409
v -0.893945 0.424800 -0.154261
v 0.154261 0.424800 0.893945
v 0.069408 0.517220 0.978797
v -0.978798 0.517220 -0.069409
v -0.893945 0.474800 -0.154261
v 0.154261 0.474800 0.893945
v -0.029561 -0.000000 -1.029558
v 1.029558 0.000000 0.029561
v -1.029558 -0.000000 -0.029561
v -1.029558 0.500000 -0.029561
v 0.029561 0.000000 1.029558
v 0.029561 0.500000 1.029558
v -0.500000 0.500000 1.559119
v -1.559119 0.500000 0.500000
v -0.499999 0.500000 0.499999
v -1.559120 -0.000000 0.500000
v -0.500000 0.000000 1.559119
v -0.500003 0.000000 0.500000
v 1.029558 -0.500000 0.029561
v -0.029561 -0.500000 -1.029558
v 0.029561 -0.500000 1.029558
v -1.029558 -0.500000 -0.029561
v -0.500003 -0.500000 0.500000
v -0.500000 -0.500000 1.559119
v -1.559120 -0.500000 0.500000
vt 0.7427 0.1169
vt 0.7427 0.3317
vt 0.6400 0.3317
vt 0.6400 0.1169
vt 0.8260 0.3317
vt 0.8260 0.4343
vt 0.7427 0.4343
vt 0.8260 0.1169
vt 0.7427 0.0142
vt 0.8260 0.0142
vt 0.5691 0.2971
vt 0.5691 0.9229
vt 0.5378 0.9229
vt 0.5378 0.2971
vt 0.3413 0.2971
vt 0.3819 0.2971
vt 0.3819 0.9229
vt 0.3413 0.9229
vt 0.4291 0.9855
vt 0.4678 0.9730
vt 0.4833 0.9730
vt 0.5219 0.9855
vt 0.6097 0.9229
vt 0.6097 0.2971
vt 0.4678 0.2470
vt 0.4291 0.2345
vt 0.5219 0.2345
vt 0.4833 0.2470
vt 0.4833 0.2783
vt 0.4678 0.2783
vt 0.4132 0.2971
vt 0.4132 0.9229
vt 0.4678 0.9417
vt 0.4833 0.9417
vt 0.5182 0.9229
vt 0.5182 0.2971
vt 0.4328 0.2971
vt 0.4328 0.9229
vt 0.5026 0.9229
vt 0.5026 0.2971
vt 0.4485 0.2971
vt 0.4485 0.9229
vt 0.5026 0.2814
vt 0.4485 0.2814
vt 0.4485 0.9386
vt 0.5026 0.9386
vt 0.9588 0.9625
vt 0.9588 0.9938
vt 0.8837 0.9938
vt 0.8837 0.9625
vt 0.8524 0.0348
vt 0.8837 0.0348
vt 0.8524 0.9625
vt 0.9588 0.0035
vt 0.9588 0.0348
vt 0.8837 0.0035
vt 0.9901 0.9625
vt 0.9901 0.0348
vt 0.6554 0.3627
vt 0.6690 0.3627
vt 0.6690 0.9885
vt 0.6554 0.9885
vt 0.6972 0.9885
vt 0.6837 0.9885
vt 0.6837 0.3627
vt 0.6972 0.3627
vt 0.7119 0.3627
vt 0.7119 0.9885
vt 0.5691 0.2971
vt 0.5691 0.9229
vt 0.5378 0.9229
vt 0.5378 0.2971
vt 0.3413 0.2971
vt 0.3819 0.2971
vt 0.3819 0.9229
vt 0.3413 0.9229
vt 0.4291 0.9855
vt 0.4678 0.9730
vt 0.4833 0.9730
vt 0.5219 0.9855
vt 0.6097 0.9229
vt 0.6097 0.2971
vt 0.4678 0.2470
vt 0.4291 0.2345
vt 0.5219 0.2345
vt 0.4833 0.2470
vt 0.4833 0.2783
vt 0.4678 0.2783
vt 0.4132 0.2971
vt 0.4132 0.9229
vt 0.4678 0.9417
vt 0.4833 0.9417
vt 0.5182 0.9229
vt 0.5182 0.2971
vt 0.4328 0.2971
vt 0.4328 0.9229
vt 0.5026 0.9229
vt 0.5026 0.2971
vt 0.4485 0.2971
vt 0.4485 0.9229
vt 0.5026 0.2814
vt 0.4485 0.2814
vt 0.4485 0.9386
vt 0.5026 0.9386
vt 0.9588 0.9625
vt 0.8837 0.9625
vt 0.8837 0.0348
vt 0.9588 0.0348
vt 0.9901 0.9625
vt 0.9901 0.0348
vt 0.9588 0.0035
vt 0.8837 0.0035
vt 0.8524 0.0348
vt 0.8524 0.9625
vt 0.9588 0.9938
vt 0.8837 0.9938
vt 0.9588 0.9625
vt 0.9588 0.9938
vt 0.8837 0.9938
vt 0.8837 0.9625
vt 0.8524 0.0348
vt 0.8837 0.0348
vt 0.8524 0.9625
vt 0.9588 0.0035
vt 0.9588 0.0348
vt 0.8837 0.0035
vt 0.9901 0.9625
vt 0.9901 0.0348
vt 0.9588 0.9625
vt 0.8837 0.9625
vt 0.8837 0.0348
vt 0.9588 0.0348
vt 0.9901 0.9625
vt 0.9901 0.0348
vt 0.9588 0.0035
vt 0.8837 0.0035
vt 0.8524 0.0348
vt 0.8524 0.9625
vt 0.9588 0.9938
vt 0.8837 0.9938
vt 0.7427 0.1169
vt 0.6400 0.1169
vt 0.6400 0.3317
vt 0.7427 0.3317
vt 0.7427 0.4343
vt 0.8260 0.4343
vt 0.8260 0.3317
vt 0.8260 0.1169
vt 0.8260 0.0142
vt 0.7427 0.0142
vt 0.9588 0.9625
vt 0.8837 0.9625
vt 0.8837 0.0348
vt 0.9588 0.0348
vt 0.9901 0.9625
vt 0.9901 0.0348
vt 0.9588 0.0035
vt 0.8837 0.0035
vt 0.8524 0.0348
vt 0.8524 0.9625
vt 0.9588 0.9938
vt 0.8837 0.9938
vt 0.9588 0.9625
vt 0.8837 0.9625
vt 0.8837 0.0348
vt 0.9588 0.0348
vt 0.9901 0.9625
vt 0.9901 0.0348
vt 0.9588 0.0035
vt 0.8837 0.0035
vt 0.8524 0.0348
vt 0.8524 0.9625
vt 0.9588 0.9938
vt 0.8837 0.9938
vt -0.2938 0.5095
vt 0.6540 0.0358
vt 0.6540 0.5096
vt 0.6549 0.9852
vt -0.2928 0.5114
vt 0.6549 0.5114
vt 0.1047 0.9953
vt 0.1047 0.4934
vt 0.1047 -0.0085
vt 1.1643 -0.0085
vt 1.1643 0.9953
vt 1.1568 0.5114
vt 0.6549 0.0377
vt 1.1568 0.0377
vt -0.3972 0.9953
vt -0.3972 -0.0085
vt 1.1431 0.5009
vt 0.4334 0.5009
vt 0.4334 0.0272
vt 1.1431 0.0272
vt 1.1431 0.9747
vt 0.4334 0.9747
vt 0.7633 0.9654
vt 0.0536 0.9654
vt 0.0536 0.4916
vt 0.7633 0.4916
vt 1.1559 0.5096
vt 1.1559 0.9833
vt 0.6540 0.9833
vt 0.1053 -0.0176
vt 0.1052 0.4843
vt -0.3966 -0.0176
vt 1.0530 -0.0176
vt 1.0530 0.9861
vt 0.1053 0.9861
vt -0.3966 0.9861
vt 0.0536 0.0179
vt 0.7633 0.0179
vt -0.2928 0.0377
vt -0.2938 0.9833
vt 0.0455 0.1273
vt 1.0492 0.1273
vt 1.0492 0.6011
vt 0.0455 0.6011
vt 1.1568 0.9852
vt 1.1559 0.0358
vn -0.7071 0.0000 -0.7071
vn 0.7071 0.0000 -0.7071
vn -0.7071 0.0000 0.7071
vn 0.2357 0.9428 -0.2357
vn 0.7071 0.0000 0.7071
vn 0.0189 0.9017 -0.4319
vn 0.4319 0.9017 -0.0189
vn -0.1263 -0.9320 0.3397
vn -0.3397 -0.9320 0.1263
vn -0.2357 -0.9428 0.2357
vn 0.0000 1.0000 0.0000
vn -0.0000 0.0000 1.0000
vn -1.0000 0.0000 0.0000
vn 0.0000 -1.0000 0.0000
g dtrack_vst2_45_Cube.035_SlopeRailMaterial
s off
f 2/1/1 4/2/1 3/3/1 1/4/1
f 4/2/2 8/5/2 7/6/2 3/7/2
f 6/8/3 2/1/3 1/9/3 5/10/3
f 6/8/4 8/5/4 4/2/4 2/1/4
f 16/11/5 15/12/5 19/13/5 20/14/5
f 9/15/6 13/16/6 14/17/6 10/18/6
f 10/19/2 14/20/2 15/21/2 11/22/2
f 11/23/7 15/12/7 16/11/7 12/24/7
f 13/25/3 9/26/3 12/27/3 16/28/3
f 20/29/3 17/30/3 13/25/3 16/28/3
f 13/16/1 17/31/1 18/32/1 14/17/1
f 15/21/2 14/20/2 18/33/2 19/34/2
f 20/14/8 19/13/8 21/35/8 22/36/8
f 18/32/9 17/31/9 23/37/9 24/38/9
f 22/36/5 21/35/5 25/39/5 26/40/5
f 24/38/1 23/37/1 27/41/1 28/42/1
f 25/39/4 28/42/4 27/41/4 26/40/4
f 17/30/3 20/29/3 22/43/3 26/40/3 27/41/3 23/44/3
f 18/33/2 24/45/2 28/42/2 25/39/2 21/46/2 19/34/2
f 32/47/5 36/48/5 33/49/5 29/50/5
f 34/51/2 30/52/2 29/50/2 33/53/2
f 35/54/1 31/55/1 30/52/1 34/56/1
f 36/57/3 32/47/3 31/55/3 35/58/3
f 32/47/4 29/50/4 30/52/4 31/55/4
f 37/59/1 39/60/1 40/61/1 38/62/1
f 41/63/5 43/64/5 44/65/5 42/66/5
f 37/67/10 38/68/10 41/63/10 42/66/10
f 39/60/4 44/65/4 43/64/4 40/61/4
f 52/69/1 51/70/1 55/71/1 56/72/1
f 45/73/7 49/74/7 50/75/7 46/76/7
f 46/77/3 50/78/3 51/79/3 47/80/3
f 47/81/6 51/70/6 52/69/6 48/82/6
f 49/83/2 45/84/2 48/85/2 52/86/2
f 56/87/2 53/88/2 49/83/2 52/86/2
f 49/74/5 53/89/5 54/90/5 50/75/5
f 51/79/3 50/78/3 54/91/3 55/92/3
f 56/72/9 55/71/9 57/93/9 58/94/9
f 54/90/8 53/89/8 59/95/8 60/96/8
f 58/94/1 57/93/1 61/97/1 62/98/1
f 60/96/5 59/95/5 63/99/5 64/100/5
f 61/97/4 64/100/4 63/99/4 62/98/4
f 53/88/2 56/87/2 58/101/2 62/98/2 63/99/2 59/102/2
f 54/91/3 60/103/3 64/100/3 61/97/3 57/104/3 55/92/3
f 69/105/4 72/106/4 71/107/4 70/108/4
f 65/109/2 69/105/2 70/108/2 66/110/2
f 66/111/5 70/108/5 71/107/5 67/112/5
f 67/113/3 71/107/3 72/106/3 68/114/3
f 69/105/1 65/115/1 68/116/1 72/106/1
f 76/117/5 80/118/5 77/119/5 73/120/5
f 78/121/2 74/122/2 73/120/2 77/123/2
f 79/124/1 75/125/1 74/122/1 78/126/1
f 80/127/3 76/117/3 75/125/3 79/128/3
f 76/117/4 73/120/4 74/122/4 75/125/4
f 85/129/4 88/130/4 87/131/4 86/132/4
f 81/133/2 85/129/2 86/132/2 82/134/2
f 82/135/5 86/132/5 87/131/5 83/136/5
f 83/137/3 87/131/3 88/130/3 84/138/3
f 85/129/1 81/139/1 84/140/1 88/130/1
f 90/141/5 89/142/5 91/143/5 92/144/5
f 92/144/2 91/145/2 95/146/2 96/147/2
f 94/148/3 93/149/3 89/150/3 90/141/3
f 94/148/4 90/141/4 92/144/4 96/147/4
f 101/151/4 104/152/4 103/153/4 102/154/4
f 97/155/2 101/151/2 102/154/2 98/156/2
f 98/157/5 102/154/5 103/153/5 99/158/5
f 99/159/3 103/153/3 104/152/3 100/160/3
f 101/151/1 97/161/1 100/162/1 104/152/1
f 109/163/4 112/164/4 111/165/4 110/166/4
f 105/167/3 109/163/3 110/166/3 106/168/3
f 106/169/1 110/166/1 111/165/1 107/170/1
f 107/171/2 111/165/2 112/164/2 108/172/2
f 109/163/5 105/173/5 108/174/5 112/164/5
g dtrack_vst2_45_Cube.035_SlopeGravelMaterial
f 114/175/5 118/176/5 117/177/5
f 116/178/1 113/179/1 115/180/1
f 116/181/4 121/182/4 118/183/4 114/184/4 113/185/4
f 122/186/1 115/180/1 128/187/1 131/188/1
f 116/181/11 120/189/11 121/182/11
f 118/183/11 121/182/11 119/190/11
f 124/191/12 122/192/12 131/193/12 129/194/12
f 121/195/12 120/196/12 122/192/12 124/191/12
f 119/197/13 121/198/13 124/199/13 123/200/13
f 117/177/5 123/201/5 130/202/5 127/203/5
f 128/204/14 129/205/14 131/206/14
f 126/207/14 125/208/14 127/209/14 129/205/14 128/204/14
f 130/210/14 129/205/14 127/209/14
f 123/200/13 124/199/13 129/211/13 130/212/13
f 115/180/1 113/179/1 126/213/1 128/187/1
f 114/175/5 117/177/5 127/203/5 125/214/5
f 113/215/2 114/216/2 125/217/2 126/218/2
f 116/178/1 115/180/1 122/186/1 120/219/1
f 117/177/5 118/176/5 119/220/5 123/201/5
a> 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
--trainlogic.lua
--controls train entities stuff about connecting/disconnecting/colliding trains and other things

local setting_overrun_mode = minetest.settings:get("advtrains_overrun_mode")

local benchmark=false
local bm={}
local bmlt=0
local bmsteps=0
local bmstepint=200
atprintbm=function(action, ta)
	if not benchmark then return end
	local t=(os.clock()-ta)*1000
	if not bm[action] then
		bm[action]=t
	else
		bm[action]=bm[action]+t
	end
	bmlt=bmlt+t
end
function endstep()
	if not benchmark then return end
	bmsteps=bmsteps-1
	if bmsteps<=0 then
		bmsteps=bmstepint
		for key, value in pairs(bm) do
			minetest.chat_send_all(key.." "..(value/bmstepint).." ms avg.")
		end
		minetest.chat_send_all("Total time consumed by all advtrains actions per step: "..(bmlt/bmstepint).." ms avg.")
		bm={}
		bmlt=0
	end
end

--acceleration for lever modes (trainhud.lua), per wagon
local t_accel_all={
	[0] = -10,
	[1] = -3,
	[2] = -0.5,
	[4] = 0.5,
}
--acceleration per engine
local t_accel_eng={
	[0] = 0,
	[1] = 0,
	[2] = 0,
	[4] = 1.5,
}

tp_player_tmr = 0

advtrains.mainloop_trainlogic=function(dtime)
	--build a table of all players indexed by pts. used by damage and door system.
	advtrains.playersbypts={}
	for _, player in pairs(minetest.get_connected_players()) do
		if not advtrains.player_to_train_mapping[player:get_player_name()] then
			--players in train are not subject to damage
			local ptspos=minetest.pos_to_string(vector.round(player:getpos()))
			advtrains.playersbypts[ptspos]=player
		end
	end
	
	if tp_player_tmr<=0 then
		-- teleport players to their train every 2 seconds
		for _, player in pairs(minetest.get_connected_players()) do
			advtrains.tp_player_to_train(player)
		end
		tp_player_tmr = 2
	else
		tp_player_tmr = tp_player_tmr - dtime
	end
	--regular train step
	--[[ structure:
	1. make trains calculate their occupation windows when needed (a)
	2. when occupation tells us so, restore the occupation tables (a)
	4. make trains move and update their new occupation windows and write changes
	   to occupation tables (b)
	5. make trains do other stuff (c)
	]]--
	local t=os.clock()
	
	for k,v in pairs(advtrains.trains) do
		advtrains.atprint_context_tid=k
		advtrains.train_ensure_init(k, v)
	end
	
	advtrains.lock_path_inval = true
	
	for k,v in pairs(advtrains.trains) do
		advtrains.atprint_context_tid=k
		advtrains.train_step_b(k, v, dtime)
	end
	
	for k,v in pairs(advtrains.trains) do
		advtrains.atprint_context_tid=k
		advtrains.train_step_c(k, v, dtime)
	end
	
	advtrains.lock_path_inval = false
	
	advtrains.atprint_context_tid=nil
	
	atprintbm("trainsteps", t)
	endstep()
end

function advtrains.tp_player_to_train(player)
	local pname = player:get_player_name()
	local id=advtrains.player_to_train_mapping[pname]
	if id then
		local train=advtrains.trains[id]
		if not train then advtrains.player_to_train_mapping[pname]=nil return end
		--set the player to the train position.
		--minetest will emerge the area and load the objects, which then will call reattach_all().
		--because player is in mapping, it will not be subject to dying.
		player:setpos(train.last_pos)
	end
end
minetest.register_on_joinplayer(function()
	return advtrains.pcall(function()
		--independent of this, cause all wagons of the train which are loaded to reattach their players
		--needed because already loaded wagons won't call reattach_all()
		for _,wagon in pairs(minetest.luaentities) do
			if wagon.is_wagon and wagon.initialized and wagon.train_id==id then
				wagon:reattach_all()
			end
		end
	end)
end)


minetest.register_on_dieplayer(function(player)
	return advtrains.pcall(function()
		local pname=player:get_player_name()
		local id=advtrains.player_to_train_mapping[pname]
		if id then
			local train=advtrains.trains[id]
			if not train then advtrains.player_to_train_mapping[pname]=nil return end
			for _,wagon in pairs(minetest.luaentities) do
				if wagon.is_wagon and wagon.initialized and wagon.train_id==id then
					--when player dies, detach him from the train
					--call get_off_plr on every wagon since we don't know which one he's on.
					wagon:get_off_plr(pname)
				end
			end
		end
	end)
end)

--[[

Zone diagram of a train (copy from occupation.lua!):
              |___| |___| --> Direction of travel
              oo oo+oo oo
=|=======|===|===========|===|=======|===================|========|===
 |SafetyB|CpB|   Train   |CpF|SafetyF|        Brake      |Aware   |
[1]     [2] [3]         [4] [5]     [6]                 [7]      [8]
This mapping from indices in occwindows to zone ids is contained in WINDOW_ZONE_IDS


The occupation system has been abandoned. The constants will still be used
to determine the couple distance
(because of the reverse lookup, the couple system simplifies a lot...)

]]--
-- unless otherwise stated, in meters.
local SAFETY_ZONE = 10
local COUPLE_ZONE = 2 --value in index positions!
local BRAKE_SPACE = 10
local AWARE_ZONE = 10
local WINDOW_ZONE_IDS = {
	2, -- 1 - SafetyB
	4, -- 2 - CpB
	1, -- 3 - Train
	5, -- 4 - CpF
	3, -- 5 - SafetyF
	6, -- 6 - Brake
	7, -- 7 - Aware
}


-- If a variable does not exist in the table, it is assigned the default value
local function assertdef(tbl, var, def)
	if not tbl[var] then
		tbl[var] = def
	end
end

function advtrains.get_acceleration(train, lever)
	local acc_all = t_accel_all[lever]
	local acc_eng = t_accel_eng[lever]
	local nwagons = #train.trainparts
	if nwagons == 0 then
		-- empty train! avoid division through zero
		return -1
	end
	local acc = acc_all + (acc_eng*train.locomotives_in_train)/nwagons
	return acc
end

-- Small local util function to recalculate train's end index
local function recalc_end_index(train)
	train.end_index = advtrains.path_get_index_by_offset(train, train.index, -train.trainlen)
end

-- Occupation Callback system
-- see occupation.lua
-- signature is advtrains.te_register_on_<?>(function(id, train) ... end)

local function mkcallback(name)
	local callt = {}
	advtrains["te_register_on_"..name] = function(func)
		assertt(func, "function")
		table.insert(callt, func)
	end
	return callt, function(id, train)
		for _,f in ipairs(callt) do
			f(id, train)
		end
	end
end

local callbacks_new_path, run_callbacks_new_path = mkcallback("new_path")
local callbacks_update, run_callbacks_update = mkcallback("update")
local callbacks_create, run_callbacks_create = mkcallback("create")
local callbacks_remove, run_callbacks_remove = mkcallback("remove")


-- train_ensure_init: responsible for creating a state that we can work on, after one of the following events has happened:
-- - the train's path got cleared
-- - save files were loaded
-- Additionally, this gets called outside the step cycle to initialize and/or remove a train, then occ_write_mode is set.
function advtrains.train_ensure_init(id, train)
	if not train then
		atwarn("train_ensure_init: Called with id =",id,"but a nil train!")
		atwarn(debug.traceback())
		return nil
	end
	
	train.dirty = true
	if train.no_step then return nil end

	assertdef(train, "velocity", 0)
	--assertdef(train, "tarvelocity", 0)
	assertdef(train, "acceleration", 0)
	assertdef(train, "id", id)
	assertdef(train, "ctrl", {})
	
	
	if not train.drives_on or not train.max_speed then
		advtrains.update_trainpart_properties(id)
	end
	
	--restore path
	if not train.path then
		if not train.last_pos then
			atlog("Train",id,": Restoring path failed, no last_pos set! Train will be disabled. You can try to fix the issue in the save file.")
			train.no_step = true
			return nil
		end
		if not train.last_connid then
			atwarn("Train",id,": Restoring path: no last_connid set! Will assume 1")
			train.last_connid = 1
			--[[
			Why this fix was necessary:
			Issue: Migration problems on Grand Theft Auto Minetest
			1. Run of this code, warning printed.
			2. path_create failed with result==nil (there was an unloaded node, wait_for_path set)
			3. in consequence, the supposed call to path_setrestore does not happen
			4. train.last_connid is still unset
			5. next step, warning is printed again
			Result: log flood.
			]]
		end
		
		local result = advtrains.path_create(train, train.last_pos, train.last_connid or 1, train.last_frac or 0)
		
		if result==false then
			atlog("Train",id,": Restoring path failed, node at",train.last_pos,"is gone! Train will be disabled. You can try to place a rail at this position and restart the server.")
			train.no_step = true
			return nil
		elseif result==nil then
			if not train.wait_for_path then
				atlog("Train",id,": Can't initialize: Waiting for the (yet unloaded) node at",train.last_pos," to be loaded.")
			end
			train.wait_for_path = true
			return false
		end
		-- by now, we should have a working initial path
		train.wait_for_path = false
		
		advtrains.update_trainpart_properties(id)
		recalc_end_index(train)
		
		--atdebug("Train",id,": Successfully restored path at",train.last_pos," connid",train.last_connid," frac",train.last_frac)
		
		-- run on_new_path callbacks
		run_callbacks_new_path(id, train)
	end
	
	train.dirty = false -- TODO einbauen!
	return true
end

function advtrains.train_step_b(id, train, dtime)
	if train.no_step or train.wait_for_path or not train.path then return end
	
	-- in this code, we check variables such as path_trk_? and path_dist. We need to ensure that the path is known for the whole 'Train' zone
	advtrains.path_get(train, atfloor(train.index + 2))
	advtrains.path_get(train, atfloor(train.end_index - 1))
	
	--- 3. handle velocity influences ---
	local train_moves=(train.velocity~=0)
	local tarvel_cap = train.speed_restriction
	
	if train.recently_collided_with_env then
		tarvel_cap=0
		if not train_moves then
			train.recently_collided_with_env=nil--reset status when stopped
		end
	end
	if train.locomotives_in_train==0 then
		tarvel_cap=0
	end
	
	--- 3a. this can be useful for debugs/warnings and is used for check_trainpartload ---
	local t_info, train_pos=sid(id), advtrains.path_get(train, atfloor(train.index))
	if train_pos then
		t_info=t_info.." @"..minetest.pos_to_string(train_pos)
		--atprint("train_pos:",train_pos)
	end
	
	--apply off-track handling:
	local front_off_track = train.index>train.path_trk_f
	local back_off_track=train.end_index<train.path_trk_b
	train.off_track = front_off_track or back_off_track
	
	if front_off_track then
		tarvel_cap=0
	end
	if back_off_track then -- eventually overrides front_off_track restriction
		tarvel_cap=1
	end
	
	-- Driving control rework:
	--[[
	Items are only defined when something is controlling them.
	In order of precedence.
	train.ctrl = {
		lzb  = restrictive override from LZB
		user = User input from driverstand
		atc  = ATC command override (determined here)
	}
	The code here determines the precedence and writes the final control into train.lever
	]]
	
	--interpret ATC command and apply auto-lever control when not actively controlled
	local trainvelocity = train.velocity
	
	if train.ctrl.user then
		advtrains.atc.train_reset_command(train)
	else
		local braketar = train.atc_brake_target
		local emerg = false -- atc_brake_target==-1 means emergency brake (BB command)
		if braketar == -1 then
			braketar = 0
			emerg = true
		end
		if braketar and braketar>=trainvelocity then
			train.atc_brake_target=nil
			braketar = nil
		end
		--if train.tarvelocity and train.velocity==train.tarvelocity then
		--	train.tarvelocity = nil
		--end
		if train.atc_wait_finish then
			if not train.atc_brake_target and (not train.tarvelocity or train.velocity==train.tarvelocity) then
				train.atc_wait_finish=nil
			end
		end
		if train.atc_command then
			if (not train.atc_delay or train.atc_delay<=0) and not train.atc_wait_finish then
				advtrains.atc.execute_atc_command(id, train)
			else
				train.atc_delay=train.atc_delay-dtime
			end
		elseif train.atc_delay then
			train.atc_delay = nil
		end
		
		train.ctrl.atc = nil
		if train.tarvelocity and train.tarvelocity>trainvelocity then
			train.ctrl.atc=4
		end
		if train.tarvelocity and train.tarvelocity<trainvelocity then
			if (braketar and braketar<trainvelocity) then
				if emerg then
					train.ctrl.atc = 0
				else
					train.ctrl.atc=1
				end
			else
				train.ctrl.atc=2
			end
		end
	end
	
	--if tarvel_cap and train.tarvelocity and tarvel_cap<train.tarvelocity then
	--	train.tarvelocity=tarvel_cap
	--end
	
	local tmp_lever
	
	for _, lev in pairs(train.ctrl) do
		-- use the most restrictive of all control overrides
		tmp_lever = math.min(tmp_lever or 4, lev)
	end
	
	if not tmp_lever then
		-- if there was no control at all, default to 3
		tmp_lever = 3
	end
	
	if tarvel_cap and trainvelocity>tarvel_cap then
		tmp_lever = 0
	end
	
	train.lever = tmp_lever
	
	--- 3a. actually calculate new velocity ---
	if tmp_lever~=3 then
		local accel = advtrains.get_acceleration(train, tmp_lever)
		local vdiff = accel*dtime
		
		-- This should only be executed when we are accelerating
		-- I suspect that this causes the braking bugs
		if tmp_lever == 4 then
		
			-- ATC control exception: don't cross tarvelocity if
			-- atc provided a target_vel
			if train.tarvelocity then
				local tvdiff = train.tarvelocity - trainvelocity
				if tvdiff~=0 and math.abs(vdiff) > math.abs(tvdiff) then
					--applying this change would cross tarvelocity
					--atdebug("In Tvdiff condition, clipping",vdiff,"to",tvdiff)
					--atdebug("vel=",trainvelocity,"tvel=",train.tarvelocity)
					vdiff=tvdiff
				end
			end
			if tarvel_cap and trainvelocity<=tarvel_cap and trainvelocity+vdiff>tarvel_cap then
				vdiff = tarvel_cap - train.velocity
			end
			local mspeed = (train.max_speed or 10)
			if trainvelocity+vdiff > mspeed then
				vdiff = mspeed - trainvelocity
			end
		end
		
		if trainvelocity+vdiff < 0 then
			vdiff = - trainvelocity
		end


		train.acceleration=vdiff
		train.velocity=train.velocity+vdiff
		--if train.ctrl.user then
		--	train.tarvelocity = train.velocity
		--end
	else
		train.acceleration = 0
	end
	
	--- 4. move train ---
	
	local pdist = train.path_dist[math.floor(train.index)] or 1
	local distance = (train.velocity*dtime) / pdist
	
	--debugging code
	--train.debug = atdump(train.ctrl).."step_dist: "..math.floor(distance*1000)
	
	train.index=train.index+distance
	
	recalc_end_index(train)

end

function advtrains.train_step_c(id, train, dtime)
	if train.no_step or train.wait_for_path or not train.path then return end
	
	-- all location/extent-critical actions have been done.
	-- calculate the new occupation window
	run_callbacks_update(id, train)
	
	-- Return if something(TM) damaged the path
	if train.no_step or train.wait_for_path or not train.path then return end
	
	advtrains.path_clear_unused(train)
	
	advtrains.path_setrestore(train)
	
	-- less important stuff
	
	train.check_trainpartload=(train.check_trainpartload or 0)-dtime
	if train.check_trainpartload<=0 then
		advtrains.spawn_wagons(id)
		train.check_trainpartload=2
	end
	
	--- 8. check for collisions with other trains and damage players ---
	
	local train_moves=(train.velocity~=0)
	
	--- Check whether this train can be coupled to another, and set couple entities accordingly
	if not train.was_standing and not train_moves then
		advtrains.train_check_couples(train)
	end
	train.was_standing = not train_moves
	
	if train_moves then
		
		local collided = false
		local coll_grace=1
		local collindex = advtrains.path_get_index_by_offset(train, train.index, -coll_grace)
		local collpos = advtrains.path_get(train, atround(collindex))
		if collpos then
			local rcollpos=advtrains.round_vector_floor_y(collpos)
			local is_loaded_area = minetest.get_node_or_nil(rcollpos) ~= nil
			for x=-train.extent_h,train.extent_h do
				for z=-train.extent_h,train.extent_h do
					local testpos=vector.add(rcollpos, {x=x, y=0, z=z})
					--- 8a Check collision ---
					if not collided and advtrains.occ.check_collision(testpos, id) then
						--collides
						train.velocity = 0
						advtrains.atc.train_reset_command(train)
						collided = true
					end
					--- 8b damage players ---
					if is_loaded_area and (setting_overrun_mode=="drop" or setting_overrun_mode=="normal") then
						local testpts = minetest.pos_to_string(testpos)
						local player=advtrains.playersbypts[testpts]
						if player and train.velocity>3 and player:get_hp()>0 and advtrains.is_damage_enabled(player:get_player_name()) then
							--atdebug("damage found",player:get_player_name())
							if setting_overrun_mode=="drop" then
								--instantly kill player
								--drop inventory contents first, to not to spawn bones
								local player_inv=player:get_inventory()
								for i=1,player_inv:get_size("main") do
									minetest.add_item(testpos, player_inv:get_stack("main", i))
								end
								for i=1,player_inv:get_size("craft") do
									minetest.add_item(testpos, player_inv:get_stack("craft", i))
								end
								-- empty lists main and craft
								player_inv:set_list("main", {})
								player_inv:set_list("craft", {})
							end
							player:set_hp(0)
						end
					end
				end
			end
			--- 8c damage other objects ---
			if is_loaded_area then
				local objs = minetest.get_objects_inside_radius(rcollpos, 2)
				for _,obj in ipairs(objs) do
					if not obj:is_player() and obj:get_armor_groups().fleshy and obj:get_armor_groups().fleshy > 0 
							and obj:get_luaentity() and obj:get_luaentity().name~="signs:text" then
						obj:punch(obj, 1, { full_punch_interval = 1.0, damage_groups = {fleshy = 1000}, }, nil)
					end
				end
			end
		end
	end
end

-- Default occupation callbacks for node callbacks
-- (remember, train.end_index is set separately because callbacks are
--  asserted to rely on this)

local function mknodecallback(name)
	local callt = {}
	advtrains["tnc_register_on_"..name] = function(func, prio)
		assertt(func, "function")
		if prio then
			table.insert(callt, 1, func)
		else
			table.insert(callt, func)
		end
	end
	return callt, function(pos, id, train, index, paramx1, paramx2, paramx3)
		for _,f in ipairs(callt) do
			f(pos, id, train, index, paramx1, paramx2, paramx3)
		end
	end
end

-- enter/leave-node callbacks
-- signature is advtrains.tnc_register_on_enter/leave(function(pos, id, train, index) ... end)
local callbacks_enter_node, run_callbacks_enter_node = mknodecallback("enter")
local callbacks_leave_node, run_callbacks_leave_node = mknodecallback("leave")

-- Node callback for approaching
-- Might be called multiple times, whenever path is recalculated
-- signature is function(pos, id, train, index, lzbdata)
-- lzbdata: arbitrary data (shared between all callbacks), deleted when LZB is restarted.
-- These callbacks are called in order of distance as train progresses along tracks, so lzbdata can be used to
-- keep track of a train's state once it passes this point
local callbacks_approach_node, run_callbacks_approach_node = mknodecallback("approach")


local function tnc_call_enter_callback(pos, train_id, train, index)
	--atdebug("tnc enter",pos,train_id)
	local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
	local mregnode=minetest.registered_nodes[node.name]
	if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_enter then
		mregnode.advtrains.on_train_enter(pos, train_id, train, index)
	end

	-- call other registered callbacks
	run_callbacks_enter_node(pos, train_id, train, index)
end
local function tnc_call_leave_callback(pos, train_id, train, index)
	--atdebug("tnc leave",pos,train_id)
	local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
	local mregnode=minetest.registered_nodes[node.name]
	if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_leave then
		mregnode.advtrains.on_train_leave(pos, train_id, train, index)
	end
	
	-- call other registered callbacks
	run_callbacks_leave_node(pos, train_id, train, index)
end

function advtrains.tnc_call_approach_callback(pos, train_id, train, index, lzbdata)
	--atdebug("tnc approach",pos,train_id, lzbdata)
	local node = advtrains.ndb.get_node(pos) --this spares the check if node is nil, it has a name in any case
	local mregnode=minetest.registered_nodes[node.name]
	if mregnode and mregnode.advtrains and mregnode.advtrains.on_train_approach then
		mregnode.advtrains.on_train_approach(pos, train_id, train, index, lzbdata)
	end
	
	-- call other registered callbacks
	run_callbacks_approach_node(pos, train_id, train, index, lzbdata)
end


advtrains.te_register_on_new_path(function(id, train)
	train.tnc = {
		old_index = atround(train.index),
		old_end_index = atround(train.end_index),
	}
	--atdebug(id,"tnc init",train.index,train.end_index)
end)

advtrains.te_register_on_update(function(id, train)
	local new_index = atround(train.index)
	local new_end_index = atround(train.end_index)
	local old_index = train.tnc.old_index
	local old_end_index = train.tnc.old_end_index
	while old_index < new_index do
		old_index = old_index + 1
		local pos = advtrains.round_vector_floor_y(advtrains.path_get(train,old_index))
		tnc_call_enter_callback(pos, id, train, old_index)
	end
	while old_end_index < new_end_index do
		local pos = advtrains.round_vector_floor_y(advtrains.path_get(train,old_end_index))
		tnc_call_leave_callback(pos, id, train, old_end_index)
		old_end_index = old_end_index + 1
	end
	train.tnc.old_index = new_index
	train.tnc.old_end_index = new_end_index
end)

advtrains.te_register_on_create(function(id, train)
	local index = atround(train.index)
	local end_index = atround(train.end_index)
	while end_index <= index do
		local pos = advtrains.round_vector_floor_y(advtrains.path_get(train,end_index))
		tnc_call_enter_callback(pos, id, train, end_index)
		end_index = end_index + 1
	end
	--atdebug(id,"tnc create",train.index,train.end_index)
end)

advtrains.te_register_on_remove(function(id, train)
	local index = atround(train.index)
	local end_index = atround(train.end_index)
	while end_index <= index do
		local pos = advtrains.round_vector_floor_y(advtrains.path_get(train,end_index))
		tnc_call_leave_callback(pos, id, train, end_index)
		end_index = end_index + 1
	end
	--atdebug(id,"tnc remove",train.index,train.end_index)
end)

-- Calculates the indices where the window borders of the occupation windows are.
-- TODO adapt this code to new system, probably into a callback (probably only the brake distance code is needed)
local function calc_occwindows(id, train)
	local end_index = advtrains.path_get_index_by_offset(train, train.index, -train.trainlen)
	train.end_index = end_index
	local cpl_b = end_index - COUPLE_ZONE
	local safety_b = advtrains.path_get_index_by_offset(train, cpl_b, -SAFETY_ZONE)
	local cpl_f = end_index + COUPLE_ZONE
	local safety_f = advtrains.path_get_index_by_offset(train, cpl_f, SAFETY_ZONE)
	
	-- calculate brake distance
	local acc_all = t_accel_all[1]
	local acc_eng = t_accel_eng[1]
	local nwagons = #train.trainparts
	local acc = acc_all + (acc_eng*train.locomotives_in_train)/nwagons
	local vel = train.velocity
	local brakedst = (vel*vel) / (2*acc)
	
	local brake_i = math.max(advtrains.path_get_index_by_offset(train, train.index, brakedst + BRAKE_SPACE), safety_f)
	local aware_i = advtrains.path_get_index_by_offset(train, brake_i, AWARE_ZONE)
	
	return {
		safety_b,
		cpl_b,
		end_index,
		train.index,
		cpl_f,
		safety_f,
		brake_i,
		aware_i,
	}
end


--returns new id
function advtrains.create_new_train_at(pos, connid, ioff, trainparts)
	local new_id=advtrains.random_id()
	while advtrains.trains[new_id] do new_id=advtrains.random_id() end--ensure uniqueness
	
	local t={}
	t.id = new_id
	
	t.last_pos=pos
	t.last_connid=connid
	t.last_frac=ioff
	
	--t.tarvelocity=0
	t.velocity=0
	t.trainparts=trainparts
	
	advtrains.trains[new_id] = t
	--atdebug("Created new train:",t)
	
	if not advtrains.train_ensure_init(new_id, advtrains.trains[new_id]) then
		atwarn("create_new_train_at",pos,connid,"failed! This might lead to temporary bugs.")
		return
	end
	
	run_callbacks_create(new_id, advtrains.trains[new_id])
	
	return new_id
end

function advtrains.remove_train(id)
	local train = advtrains.trains[id]
	
	if not advtrains.train_ensure_init(id, train) then
		atwarn("remove_train",id,"failed! This might lead to temporary bugs.")
		return
	end
	
	run_callbacks_remove(id, train)
	
	advtrains.path_invalidate(train)
	advtrains.couple_invalidate(train)
	
	local tp = train.trainparts
	--atdebug("Removing train",id,"leftover trainparts:",tp)
	
	advtrains.trains[id] = nil
	
	return tp
	
end


function advtrains.add_wagon_to_train(wagon_id, train_id, index)
	local train=advtrains.trains[train_id]
	
	if not advtrains.train_ensure_init(train_id, train) then
		atwarn("Train",train_id,"is not initialized! Operation aborted!")
		return
	end
	
	if index then
		table.insert(train.trainparts, index, wagon_id)
	else
		table.insert(train.trainparts, wagon_id)
	end
	
	advtrains.update_trainpart_properties(train_id)
	recalc_end_index(train)
	run_callbacks_update(train_id, train)
end

-- Note: safe_decouple_wagon() has been moved to wagons.lua

-- this function sets wagon's pos_in_train(parts) properties and train's max_speed and drives_on (and more)
function advtrains.update_trainpart_properties(train_id, invert_flipstate)
	local train=advtrains.trains[train_id]
	train.drives_on=advtrains.merge_tables(advtrains.all_tracktypes)
	--FIX: deep-copy the table!!!
	train.max_speed=20
	train.extent_h = 0;
	
	local rel_pos=0
	local count_l=0
	local shift_dcpl_lock=false
	for i, w_id in ipairs(train.trainparts) do
		
		local data = advtrains.wagons[w_id]
		
		-- 1st: update wagon data (pos_in_train a.s.o)
		if data then
			local wagon = advtrains.wagon_prototypes[data.type or data.entity_name]
			if not wagon then
				atwarn("Wagon '",data.type,"' couldn't be found. Please check that all required modules are loaded!")
				wagon = advtrains.wagon_prototypes["advtrains:wagon_placeholder"]

			end
			rel_pos=rel_pos+wagon.wagon_span
			data.train_id=train_id
			data.pos_in_train=rel_pos
			data.pos_in_trainparts=i
			if wagon.is_locomotive then
				count_l=count_l+1
			end
			if invert_flipstate then
				data.wagon_flipped = not data.wagon_flipped
				shift_dcpl_lock, data.dcpl_lock = data.dcpl_lock, shift_dcpl_lock
			end
			rel_pos=rel_pos+wagon.wagon_span
			
			if wagon.drives_on then
				for k,_ in pairs(train.drives_on) do
					if not wagon.drives_on[k] then
						train.drives_on[k]=nil
					end
				end
			end
			train.max_speed=math.min(train.max_speed, wagon.max_speed)
			train.extent_h = math.max(train.extent_h, wagon.extent_h or 1);
		end
	end
	train.trainlen = rel_pos
	train.locomotives_in_train = count_l
end


local ablkrng = minetest.settings:get("active_block_range")*16
-- This function checks whether entities need to be spawned for certain wagons, and spawns them.
-- Called from train_step_*(), not required to check init.
function advtrains.spawn_wagons(train_id)
	local train = advtrains.trains[train_id]
	
	for i = 1, #train.trainparts do
		local w_id = train.trainparts[i]
		local data = advtrains.wagons[w_id]
		if data then
			if data.train_id ~= train_id then
				atwarn("Train",train_id,"Wagon #",1,": Saved train ID",data.train_id,"did not match!")
				data.train_id = train_id
			end
			if not advtrains.wagon_objects[w_id] or not advtrains.wagon_objects[w_id]:getyaw() then
				-- eventually need to spawn new object. check if position is loaded.
				local index = advtrains.path_get_index_by_offset(train, train.index, -data.pos_in_train)
				local pos   = advtrains.path_get(train, atfloor(index))
				
				local spawn = false
				for _,p in pairs(minetest.get_connected_players()) do
					if vector.distance(p:get_pos(),pos)<=ablkrng then
						spawn = true
					end
				end
				
				if spawn then
					local wt = advtrains.get_wagon_prototype(data)
					local wagon = minetest.add_entity(pos, wt):get_luaentity()
					wagon:set_id(w_id)
				end
			end
		else
			atwarn("Train",train_id,"Wagon #",1,": A wagon with id",w_id,"does not exist! Wagon will be removed from train.")
			table.remove(train.trainparts, i)
			i = i - 1
		end
	end
end
		

function advtrains.split_train_at_wagon(wagon_id)
	--get train
	local data = advtrains.wagons[wagon_id]
	local old_id = data.train_id
	local train=advtrains.trains[old_id]
	local _, wagon = advtrains.get_wagon_prototype(data)
	
	if not advtrains.train_ensure_init(old_id, train) then
		atwarn("Train",old_id,"is not initialized! Operation aborted!")
		return
	end
	
	local index=advtrains.path_get_index_by_offset(train, train.index, - data.pos_in_train + wagon.wagon_span)
	
	-- find new initial path position for this train
	local pos, connid, frac = advtrains.path_getrestore(train, index)
	
	-- build trainparts table, passing it directly to the train constructor
	local tp = {}
	for k,v in ipairs(train.trainparts) do
		if k >= data.pos_in_trainparts then
			table.insert(tp, v)
			train.trainparts[k]=nil
		end
	end
	
	--update train parts
	advtrains.update_trainpart_properties(old_id)
	recalc_end_index(train)
	run_callbacks_update(old_id, train)
	
	--create subtrain
	local newtrain_id=advtrains.create_new_train_at(pos, connid, frac, tp)
	local newtrain=advtrains.trains[newtrain_id]
	
	newtrain.velocity=train.velocity
	
end

-- coupling
local CPL_CHK_DST = -1
local CPL_ZONE = 2

-- train.couple_* contain references to ObjectRefs of couple objects, which contain all relevant information
-- These objectRefs will delete themselves once the couples no longer match
local function createcouple(pos, train1, t1_is_front, train2, t2_is_front)
	local obj=minetest.add_entity(pos, "advtrains:couple")
	if not obj then error("Failed creating couple object!") return end
	local le=obj:get_luaentity()
	le.train_id_1=train1.id
	le.train_id_2=train2.id
	le.t1_is_front=t1_is_front
	le.t2_is_front=t2_is_front
	--atdebug("created couple between",train1.id,t1_is_front,train2.id,t2_is_front)
	if t1_is_front then
		train1.cpl_front = obj
	else
		train1.cpl_back = obj
	end
	if t2_is_front then
		train2.cpl_front = obj
	else
		train2.cpl_back = obj
	end
	
end

function advtrains.train_check_couples(train)
	--atdebug("rechecking couples")
	if train.cpl_front then
		if not train.cpl_front:getyaw() then
			-- objectref is no longer valid. reset.
			train.cpl_front = nil
		end
	end
	if not train.cpl_front then
		-- recheck front couple
		local front_trains, pos = advtrains.occ.get_occupations(train, atround(train.index) + CPL_CHK_DST)
		for tid, idx in pairs(front_trains) do
			local other_train = advtrains.trains[tid]
			if not advtrains.train_ensure_init(tid, other_train) then
				atwarn("Train",tid,"is not initialized! Couldn't check couples!")
				return
			end
			--atdebug(train.id,"front: ",idx,"on",tid,atround(other_train.index),atround(other_train.end_index))
			if other_train.velocity == 0 then
				if idx>=other_train.index and idx<=other_train.index + CPL_ZONE then
					createcouple(pos, train, true, other_train, true)
					break
				end
				if idx<=other_train.end_index and idx>=other_train.end_index - CPL_ZONE then
					createcouple(pos, train, true, other_train, false)
					break
				end
			end
		end
	end
	if train.cpl_back then
		if not train.cpl_back:getyaw() then
			-- objectref is no longer valid. reset.
			train.cpl_back = nil
		end
	end
	if not train.cpl_back then
		-- recheck back couple
		local back_trains, pos = advtrains.occ.get_occupations(train, atround(train.end_index) - CPL_CHK_DST)
		for tid, idx in pairs(back_trains) do
			local other_train = advtrains.trains[tid]
			if not advtrains.train_ensure_init(tid, other_train) then
				atwarn("Train",tid,"is not initialized! Couldn't check couples!")
				return
			end
			if other_train.velocity == 0 then
				if idx>=other_train.index and idx<=other_train.index + CPL_ZONE then
					createcouple(pos, train, false, other_train, true)
					break
				end
				if idx<=other_train.end_index and idx>=other_train.end_index - CPL_ZONE then
					createcouple(pos, train, false, other_train, false)
					break
				end
			end
		end
	end
end

function advtrains.couple_invalidate(train)
	if train.cpl_back then
		train.cpl_back:remove()
		train.cpl_back = nil
	end
	if train.cpl_front then