aboutsummaryrefslogtreecommitdiff
path: root/src/collision.cpp
blob: 12eabff090dd6dd433e4ae30748be786720bf1f8 (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
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
/*
Minetest
Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "collision.h"
#include "mapblock.h"
#include "map.h"
#include "nodedef.h"
#include "gamedef.h"
#include "log.h"
#include "environment.h"
#include "serverobject.h"
#include <vector>
#include <set>
#include "util/timetaker.h"
#include "main.h" // g_profiler
#include "profiler.h"

// float error is 10 - 9.96875 = 0.03125
//#define COLL_ZERO 0.032 // broken unit tests
#define COLL_ZERO 0

// Helper function:
// Checks for collision of a moving aabbox with a static aabbox
// Returns -1 if no collision, 0 if X collision, 1 if Y collision, 2 if Z collision
// The time after which the collision occurs is stored in dtime.
int axisAlignedCollision(
		const aabb3f &staticbox, const aabb3f &movingbox,
		const v3f &speed, f32 d, f32 &dtime)
{
	//TimeTaker tt("axisAlignedCollision");

	f32 xsize = (staticbox.MaxEdge.X - staticbox.MinEdge.X) - COLL_ZERO;     // reduce box size for solve collision stuck (flying sand)
	f32 ysize = (staticbox.MaxEdge.Y - staticbox.MinEdge.Y); // - COLL_ZERO; // Y - no sense for falling, but maybe try later
	f32 zsize = (staticbox.MaxEdge.Z - staticbox.MinEdge.Z) - COLL_ZERO;

	aabb3f relbox(
			movingbox.MinEdge.X - staticbox.MinEdge.X,
			movingbox.MinEdge.Y - staticbox.MinEdge.Y,
			movingbox.MinEdge.Z - staticbox.MinEdge.Z,
			movingbox.MaxEdge.X - staticbox.MinEdge.X,
			movingbox.MaxEdge.Y - staticbox.MinEdge.Y,
			movingbox.MaxEdge.Z - staticbox.MinEdge.Z
	);

	if(speed.X > 0) // Check for collision with X- plane
	{
		if(relbox.MaxEdge.X <= d)
		{
			dtime = - relbox.MaxEdge.X / speed.X;
			if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
					(relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO) &&
					(relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
					(relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
				return 0;
		}
		else if(relbox.MinEdge.X > xsize)
		{
			return -1;
		}
	}
	else if(speed.X < 0) // Check for collision with X+ plane
	{
		if(relbox.MinEdge.X >= xsize - d)
		{
			dtime = (xsize - relbox.MinEdge.X) / speed.X;
			if((relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
					(relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO) &&
					(relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
					(relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
				return 0;
		}
		else if(relbox.MaxEdge.X < 0)
		{
			return -1;
		}
	}

	// NO else if here

	if(speed.Y > 0) // Check for collision with Y- plane
	{
		if(relbox.MaxEdge.Y <= d)
		{
			dtime = - relbox.MaxEdge.Y / speed.Y;
			if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
					(relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
					(relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
					(relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
				return 1;
		}
		else if(relbox.MinEdge.Y > ysize)
		{
			return -1;
		}
	}
	else if(speed.Y < 0) // Check for collision with Y+ plane
	{
		if(relbox.MinEdge.Y >= ysize - d)
		{
			dtime = (ysize - relbox.MinEdge.Y) / speed.Y;
			if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
					(relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
					(relbox.MinEdge.Z + speed.Z * dtime < zsize) &&
					(relbox.MaxEdge.Z + speed.Z * dtime > COLL_ZERO))
				return 1;
		}
		else if(relbox.MaxEdge.Y < 0)
		{
			return -1;
		}
	}

	// NO else if here

	if(speed.Z > 0) // Check for collision with Z- plane
	{
		if(relbox.MaxEdge.Z <= d)
		{
			dtime = - relbox.MaxEdge.Z / speed.Z;
			if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
					(relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
					(relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
					(relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO))
				return 2;
		}
		//else if(relbox.MinEdge.Z > zsize)
		//{
		//	return -1;
		//}
	}
	else if(speed.Z < 0) // Check for collision with Z+ plane
	{
		if(relbox.MinEdge.Z >= zsize - d)
		{
			dtime = (zsize - relbox.MinEdge.Z) / speed.Z;
			if((relbox.MinEdge.X + speed.X * dtime < xsize) &&
					(relbox.MaxEdge.X + speed.X * dtime > COLL_ZERO) &&
					(relbox.MinEdge.Y + speed.Y * dtime < ysize) &&
					(relbox.MaxEdge.Y + speed.Y * dtime > COLL_ZERO))
				return 2;
		}
		//else if(relbox.MaxEdge.Z < 0)
		//{
		//	return -1;
		//}
	}

	return -1;
}

// Helper function:
// Checks if moving the movingbox up by the given distance would hit a ceiling.
bool wouldCollideWithCeiling(
		const std::vector<aabb3f> &staticboxes,
		const aabb3f &movingbox,
		f32 y_increase, f32 d)
{
	//TimeTaker tt("wouldCollideWithCeiling");

	assert(y_increase >= 0);	// pre-condition

	for(std::vector<aabb3f>::const_iterator
			i = staticboxes.begin();
			i != staticboxes.end(); i++)
	{
		const aabb3f& staticbox = *i;
		if((movingbox.MaxEdge.Y - d <= staticbox.MinEdge.Y) &&
				(movingbox.MaxEdge.Y + y_increase > staticbox.MinEdge.Y) &&
				(movingbox.MinEdge.X < staticbox.MaxEdge.X) &&
				(movingbox.MaxEdge.X > staticbox.MinEdge.X) &&
				(movingbox.MinEdge.Z < staticbox.MaxEdge.Z) &&
				(movingbox.MaxEdge.Z > staticbox.MinEdge.Z))
			return true;
	}

	return false;
}


collisionMoveResult collisionMoveSimple(Environment *env, IGameDef *gamedef,
		f32 pos_max_d, const aabb3f &box_0,
		f32 stepheight, f32 dtime,
		v3f &pos_f, v3f &speed_f,
		v3f &accel_f,ActiveObject* self,
		bool collideWithObjects)
{
	Map *map = &env->getMap();
	//TimeTaker tt("collisionMoveSimple");
    ScopeProfiler sp(g_profiler, "collisionMoveSimple avg", SPT_AVG);

	collisionMoveResult result;

	/*
		Calculate new velocity
	*/
	if( dtime > 0.5 ) {
		infostream<<"collisionMoveSimple: WARNING: maximum step interval exceeded, lost movement details!"<<std::endl;
		dtime = 0.5;
	}
	speed_f += accel_f * dtime;

	// If there is no speed, there are no collisions
	if(speed_f.getLength() == 0)
		return result;

	// Limit speed for avoiding hangs
	speed_f.Y=rangelim(speed_f.Y,-5000,5000);
	speed_f.X=rangelim(speed_f.X,-5000,5000);
	speed_f.Z=rangelim(speed_f.Z,-5000,5000);

	/*
		Collect node boxes in movement range
	*/
	std::vector<aabb3f> cboxes;
	std::vector<bool> is_unloaded;
	std::vector<bool> is_step_up;
	std::vector<bool> is_object;
	std::vector<int> bouncy_values;
	std::vector<v3s16> node_positions;
	{
	//TimeTaker tt2("collisionMoveSimple collect boxes");
    ScopeProfiler sp(g_profiler, "collisionMoveSimple collect boxes avg", SPT_AVG);

	v3s16 oldpos_i = floatToInt(pos_f, BS);
	v3s16 newpos_i = floatToInt(pos_f + speed_f * dtime, BS);
	s16 min_x = MYMIN(oldpos_i.X, newpos_i.X) + (box_0.MinEdge.X / BS) - 1;
	s16 min_y = MYMIN(oldpos_i.Y, newpos_i.Y) + (box_0.MinEdge.Y / BS) - 1;
	s16 min_z = MYMIN(oldpos_i.Z, newpos_i.Z) + (box_0.MinEdge.Z / BS) - 1;
	s16 max_x = MYMAX(oldpos_i.X, newpos_i.X) + (box_0.MaxEdge.X / BS) + 1;
	s16 max_y = MYMAX(oldpos_i.Y, newpos_i.Y) + (box_0.MaxEdge.Y / BS) + 1;
	s16 max_z = MYMAX(oldpos_i.Z, newpos_i.Z) + (box_0.MaxEdge.Z / BS) + 1;

	for(s16 x = min_x; x <= max_x; x++)
	for(s16 y = min_y; y <= max_y; y++)
	for(s16 z = min_z; z <= max_z; z++)
	{
		v3s16 p(x,y,z);

		bool is_position_valid;
		MapNode n = map->getNodeNoEx(p, &is_position_valid);

		if (is_position_valid) {
			// Object collides into walkable nodes

			const ContentFeatures &f = gamedef->getNodeDefManager()->get(n);
			if(f.walkable == false)
				continue;
			int n_bouncy_value = itemgroup_get(f.groups, "bouncy");

			std::vector<aabb3f> nodeboxes = n.getCollisionBoxes(gamedef->ndef());
			for(std::vector<aabb3f>::iterator
					i = nodeboxes.begin();
					i != nodeboxes.end(); i++)
			{
				aabb3f box = *i;
				box.MinEdge += v3f(x, y, z)*BS;
				box.MaxEdge += v3f(x, y, z)*BS;
				cboxes.push_back(box);
				is_unloaded.push_back(false);
				is_step_up.push_back(false);
				bouncy_values.push_back(n_bouncy_value);
				node_positions.push_back(p);
				is_object.push_back(false);
			}
		}
		else {
			// Collide with unloaded nodes
			aabb3f box = getNodeBox(p, BS);
			cboxes.push_back(box);
			is_unloaded.push_back(true);
			is_step_up.push_back(false);
			bouncy_values.push_back(0);
			node_positions.push_back(p);
			is_object.push_back(false);
		}
	}
	} // tt2

	if(collideWithObjects)
	{
		ScopeProfiler sp(g_profiler, "collisionMoveSimple objects avg", SPT_AVG);
		//TimeTaker tt3("collisionMoveSimple collect object boxes");

		/* add object boxes to cboxes */


		std::vector<ActiveObject*> objects;
#ifndef SERVER
		ClientEnvironment *c_env = dynamic_cast<ClientEnvironment*>(env);
		if (c_env != 0) {
			f32 distance = speed_f.getLength();
			std::vector<DistanceSortedActiveObject> clientobjects;
			c_env->getActiveObjects(pos_f,distance * 1.5,clientobjects);
			for (size_t i=0; i < clientobjects.size(); i++) {
				if ((self == 0) || (self != clientobjects[i].obj)) {
					objects.push_back((ActiveObject*)clientobjects[i].obj);
				}
			}
		}
		else
#endif
		{
			ServerEnvironment *s_env = dynamic_cast<ServerEnvironment*>(env);
			if (s_env != 0) {
				f32 distance = speed_f.getLength();
				std::set<u16> s_objects = s_env->getObjectsInsideRadius(pos_f,distance * 1.5);
				for (std::set<u16>::iterator iter = s_objects.begin(); iter != s_objects.end(); iter++) {
					ServerActiveObject *current = s_env->getActiveObject(*iter);
					if ((self == 0) || (self != current)) {
						objects.push_back((ActiveObject*)current);
					}
				}
			}
		}

		for (std::vector<ActiveObject*>::const_iterator iter = objects.begin();
				iter != objects.end(); ++iter) {
			ActiveObject *object = *iter;

			if (object != NULL) {
				aabb3f object_collisionbox;
				if (object->getCollisionBox(&object_collisionbox) &&
						object->collideWithObjects()) {
					cboxes.push_back(object_collisionbox);
					is_unloaded.push_back(false);
					is_step_up.push_back(false);
					bouncy_values.push_back(0);
					node_positions.push_back(v3s16(0,0,0));
					is_object.push_back(true);
				}
			}
		}
	} //tt3

	assert(cboxes.size() == is_unloaded.size());    // post-condition
	assert(cboxes.size() == is_step_up.size());     // post-condition
	assert(cboxes.size() == bouncy_values.size());  // post-condition
	assert(cboxes.size() == node_positions.size()); // post-condition
	assert(cboxes.size() == is_object.size());      // post-condition

	/*
		Collision detection
	*/

	/*
		Collision uncertainty radius
		Make it a bit larger than the maximum distance of movement
	*/
	f32 d = pos_max_d * 1.1;
	// A fairly large value in here makes moving smoother
	//f32 d = 0.15*BS;

	// This should always apply, otherwise there are glitches
	assert(d > pos_max_d);	// invariant

	int loopcount = 0;

	while(dtime > BS*1e-10)
	{
		//TimeTaker tt3("collisionMoveSimple dtime loop");
        ScopeProfiler sp(g_profiler, "collisionMoveSimple dtime loop avg", SPT_AVG);

		// Avoid infinite loop
		loopcount++;
		if(loopcount >= 100)
		{
			infostream<<"collisionMoveSimple: WARNING: Loop count exceeded, aborting to avoid infiniite loop"<<std::endl;
			dtime = 0;
			break;
		}

		aabb3f movingbox = box_0;
		movingbox.MinEdge += pos_f;
		movingbox.MaxEdge += pos_f;

		int nearest_collided = -1;
		f32 nearest_dtime = dtime;
		u32 nearest_boxindex = -1;

		/*
			Go through every nodebox, find nearest collision
		*/
		for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
		{
			// Ignore if already stepped up this nodebox.
			if(is_step_up[boxindex])
				continue;

			// Find nearest collision of the two boxes (raytracing-like)
			f32 dtime_tmp;
			int collided = axisAlignedCollision(
					cboxes[boxindex], movingbox, speed_f, d, dtime_tmp);

			if(collided == -1 || dtime_tmp >= nearest_dtime)
				continue;

			nearest_dtime = dtime_tmp;
			nearest_collided = collided;
			nearest_boxindex = boxindex;
		}

		if(nearest_collided == -1)
		{
			// No collision with any collision box.
			pos_f += speed_f * dtime;
			dtime = 0;  // Set to 0 to avoid "infinite" loop due to small FP numbers
		}
		else
		{
			// Otherwise, a collision occurred.

			const aabb3f& cbox = cboxes[nearest_boxindex];

			// Check for stairs.
			bool step_up = (nearest_collided != 1) && // must not be Y direction
					(movingbox.MinEdge.Y < cbox.MaxEdge.Y) &&
					(movingbox.MinEdge.Y + stepheight > cbox.MaxEdge.Y) &&
					(!wouldCollideWithCeiling(cboxes, movingbox,
							cbox.MaxEdge.Y - movingbox.MinEdge.Y,
							d));

			// Get bounce multiplier
			bool bouncy = (bouncy_values[nearest_boxindex] >= 1);
			float bounce = -(float)bouncy_values[nearest_boxindex] / 100.0;

			// Move to the point of collision and reduce dtime by nearest_dtime
			if(nearest_dtime < 0)
			{
				// Handle negative nearest_dtime (can be caused by the d allowance)
				if(!step_up)
				{
					if(nearest_collided == 0)
						pos_f.X += speed_f.X * nearest_dtime;
					if(nearest_collided == 1)
						pos_f.Y += speed_f.Y * nearest_dtime;
					if(nearest_collided == 2)
						pos_f.Z += speed_f.Z * nearest_dtime;
				}
			}
			else
			{
				pos_f += speed_f * nearest_dtime;
				dtime -= nearest_dtime;
			}
			
			bool is_collision = true;
			if(is_unloaded[nearest_boxindex])
				is_collision = false;

			CollisionInfo info;
			if (is_object[nearest_boxindex]) {
				info.type = COLLISION_OBJECT;
			}
			else {
				info.type = COLLISION_NODE;
			}
			info.node_p = node_positions[nearest_boxindex];
			info.bouncy = bouncy;
			info.old_speed = speed_f;

			// Set the speed component that caused the collision to zero
			if(step_up)
			{
				// Special case: Handle stairs
				is_step_up[nearest_boxindex] = true;
				is_collision = false;
			}
			else if(nearest_collided == 0) // X
			{
				if(fabs(speed_f.X) > BS*3)
					speed_f.X *= bounce;
				else
					speed_f.X = 0;
				result.collides = true;
				result.collides_xz = true;
			}
			else if(nearest_collided == 1) // Y
			{
				if(fabs(speed_f.Y) > BS*3)
					speed_f.Y *= bounce;
				else
					speed_f.Y = 0;
				result.collides = true;
			}
			else if(nearest_collided == 2) // Z
			{
				if(fabs(speed_f.Z) > BS*3)
					speed_f.Z *= bounce;
				else
					speed_f.Z = 0;
				result.collides = true;
				result.collides_xz = true;
			}

			info.new_speed = speed_f;
			if(info.new_speed.getDistanceFrom(info.old_speed) < 0.1*BS)
				is_collision = false;

			if(is_collision){
				result.collisions.push_back(info);
			}
		}
	}

	/*
		Final touches: Check if standing on ground, step up stairs.
	*/
	aabb3f box = box_0;
	box.MinEdge += pos_f;
	box.MaxEdge += pos_f;
	for(u32 boxindex = 0; boxindex < cboxes.size(); boxindex++)
	{
		const aabb3f& cbox = cboxes[boxindex];

		/*
			See if the object is touching ground.

			Object touches ground if object's minimum Y is near node's
			maximum Y and object's X-Z-area overlaps with the node's
			X-Z-area.

			Use 0.15*BS so that it is easier to get on a node.
		*/
		if(
				cbox.MaxEdge.X-d > box.MinEdge.X &&
				cbox.MinEdge.X+d < box.MaxEdge.X &&
				cbox.MaxEdge.Z-d > box.MinEdge.Z &&
				cbox.MinEdge.Z+d < box.MaxEdge.Z
		){
			if(is_step_up[boxindex])
			{
				pos_f.Y += (cbox.MaxEdge.Y - box.MinEdge.Y);
				box = box_0;
				box.MinEdge += pos_f;
				box.MaxEdge += pos_f;
			}
			if(fabs(cbox.MaxEdge.Y-box.MinEdge.Y) < 0.15*BS)
			{
				result.touching_ground = true;
				if(is_unloaded[boxindex])
					result.standing_on_unloaded = true;
			}
		}
	}

	return result;
}

#if 0
// This doesn't seem to work and isn't used
collisionMoveResult collisionMovePrecise(Map *map, IGameDef *gamedef,
		f32 pos_max_d, const aabb3f &box_0,
		f32 stepheight, f32 dtime,
		v3f &pos_f, v3f &speed_f, v3f &accel_f)
{
	//TimeTaker tt("collisionMovePrecise");
    ScopeProfiler sp(g_profiler, "collisionMovePrecise avg", SPT_AVG);
	
	collisionMoveResult final_result;

	// If there is no speed, there are no collisions
	if(speed_f.getLength() == 0)
		return final_result;

	// Don't allow overly huge dtime
	if(dtime > 2.0)
		dtime = 2.0;

	f32 dtime_downcount = dtime;

	u32 loopcount = 0;
	do
	{
		loopcount++;

		// Maximum time increment (for collision detection etc)
		// time = distance / speed
		f32 dtime_max_increment = 1.0;
		if(speed_f.getLength() != 0)
			dtime_max_increment = pos_max_d / speed_f.getLength();

		// Maximum time increment is 10ms or lower
		if(dtime_max_increment > 0.01)
			dtime_max_increment = 0.01;

		f32 dtime_part;
		if(dtime_downcount > dtime_max_increment)
		{
			dtime_part = dtime_max_increment;
			dtime_downcount -= dtime_part;
		}
		else
		{
			dtime_part = dtime_downcount;
			/*
				Setting this to 0 (no -=dtime_part) disables an infinite loop
				when dtime_part is so small that dtime_downcount -= dtime_part
				does nothing
			*/
			dtime_downcount = 0;
		}

		collisionMoveResult result = collisionMoveSimple(map, gamedef,
				pos_max_d, box_0, stepheight, dtime_part,
				pos_f, speed_f, accel_f);

		if(result.touching_ground)
			final_result.touching_ground = true;
		if(result.collides)
			final_result.collides = true;
		if(result.collides_xz)
			final_result.collides_xz = true;
		if(result.standing_on_unloaded)
			final_result.standing_on_unloaded = true;
	}
	while(dtime_downcount > 0.001);

	return final_result;
}
#endif
span class="hl kwa">true ctrl_lever = VLEVER_ACCEL elseif train.tarvelocity and train.tarvelocity<v0 then ctrl_braking = true if (braketar and braketar<v0) then if emerg then --atprint("in train_step_b: applying ATC EMERG", train.tarvelocity) ctrl_lever = VLEVER_EMERG else --atprint("in train_step_b: applying ATC BRAKE", train.tarvelocity) ctrl_v_tar = braketar ctrl_lever = VLEVER_BRAKE end else --atprint("in train_step_b: applying ATC ROLL", train.tarvelocity) ctrl_v_tar = train.tarvelocity ctrl_lever = VLEVER_ROLL end end end --- 2b. look at v_target, determine the effective v_target and desired acceleration --- --atprint("in train_step_b: Resulting control before LZB: accelerating",ctrl_accelerating,"braking",ctrl_braking,"lever", ctrl_lever, "target", ctrl_v_tar) --train.debug = dump({tv_target,tv_lever}) --atprint("in train_step_b: Current index",train.index,"end",train.end_index,"vel",v0) --- 3a. calculate the acceleration required to reach the speed restriction in path_speed (LZB) --- -- Iterates over the path nodes we WOULD pass if we were continuing with the current speed -- and determines the MINIMUM of path_speed in this range. -- Then, determines acceleration so that we can reach this 'overridden' target speed in this step (but short-circuited) local lzb_next_zero_barrier -- if defined, train should not pass this point as it's a 0-LZB local new_index_curr_tv -- pre-calculated new train index in lzb check local lzb_v_cap -- the maximum speed that LZB dictates local dst_curr_v = v0 * dtime new_index_curr_tv = advtrains.path_get_index_by_offset(train, train.index, dst_curr_v) local i = atfloor(train.index) local psp while true do psp = train.path_speed[i] if psp then lzb_v_cap = lzb_v_cap and math.min(lzb_v_cap, psp) or psp if psp == 0 and not lzb_next_zero_barrier then --atprint("in train_step_b: Found zero barrier: ",i) lzb_next_zero_barrier = i - LZB_ZERO_APPROACH_DIST end end if i > new_index_curr_tv then break end i = i + 1 end if lzb_next_zero_barrier and train.index < lzb_next_zero_barrier then lzb_v_cap = LZB_ZERO_APPROACH_SPEED end --atprint("in train_step_b: LZB calculation yields newindex=",new_index_curr_tv,"lzbtarget=",lzb_v_cap,"zero_barr=",lzb_next_zero_barrier,"") -- LZB HUD: decrement timer and delete when 0 if train.hud_lzb_effect_tmr then if train.hud_lzb_effect_tmr <=0 then train.hud_lzb_effect_tmr = nil else train.hud_lzb_effect_tmr = train.hud_lzb_effect_tmr - 1 end end -- We now need to bring ctrl_*, sit_v_cap and lzb_v_cap together to determine the final controls. local v_cap = sit_v_cap -- always defined, by default train.max_speed if lzb_v_cap and lzb_v_cap < v_cap then v_cap = lzb_v_cap lever = VLEVER_BRAKE -- actually irrelevant, acceleration is not considered anyway unless v_tar is also set. -- display LZB control override in the HUD if lzb_v_cap <= v0 then train.hud_lzb_effect_tmr = 1 -- This is to signal the HUD that LZB is active. This works as a timer to avoid HUD blinking end end v_tar = ctrl_v_tar -- if v_cap is smaller than the current speed, we need to brake in all cases. if v_cap < v0 then braking = true lever = VLEVER_BRAKE -- set v_tar to v_cap to not slow down any further than required. -- unless control wants us to brake too, then we use control's v_tar. if not ctrl_v_tar or ctrl_v_tar > v_cap then v_tar = v_cap end else -- else, use what the ctrl says braking = ctrl_braking accelerating = ctrl_accelerating and not braking lever = ctrl_lever end train.lever = lever --atprint("in train_step_b: final control: accelerating",accelerating,"braking",braking,"lever", lever, "target", v_tar) -- reset train acceleration when holding speed if not braking and not accelerating then train.acceleration = 0 end --- 3b. if braking, modify the velocity BEFORE the movement if braking then local dv = advtrains.get_acceleration(train, lever) * dtime local v1 = v0 + dv if v_tar and v1 < v_tar then --atprint("in train_step_b: Braking: Hit v_tar!") v1 = v_tar end if v1 > v_cap then --atprint("in train_step_b: Braking: Hit v_cap!") v1 = v_cap end if v1 < 0 then --atprint("in train_step_b: Braking: Hit 0!") v1 = 0 end train.acceleration = (v1 - v0) / dtime train.velocity = v1 --atprint("in train_step_b: Braking: New velocity",v1," (yields acceleration",train.acceleration,")") -- make saved new_index_curr_tv invalid because speed has changed new_index_curr_tv = nil end --- 4. move train --- -- if we have calculated the new end index before, don't do that again if not new_index_curr_tv then local dst_curr_v = train.velocity * dtime new_index_curr_tv = advtrains.path_get_index_by_offset(train, train.index, dst_curr_v) --atprint("in train_step_b: movement calculation (re)done, yields newindex=",new_index_curr_tv) else --atprint("in train_step_b: movement calculation reusing from LZB newindex=",new_index_curr_tv) end -- if the zeroappr mechanism has hit, go no further than zeroappr index if lzb_next_zero_barrier and new_index_curr_tv > lzb_next_zero_barrier then --atprint("in train_step_b: Zero barrier hit, clipping to newidx_tv=",new_index_curr_tv, "zb_idx=",lzb_next_zero_barrier) new_index_curr_tv = lzb_next_zero_barrier end train.index = new_index_curr_tv recalc_end_index(train) --atprint("in train_step_b: New index",train.index,"end",train.end_index,"vel",train.velocity) --- 4a. if accelerating, modify the velocity AFTER the movement if accelerating then local dv = advtrains.get_acceleration(train, lever) * dtime local v1 = v0 + dv if v_tar and v1 > v_tar then --atprint("in train_step_b: Accelerating: Hit v_tar!") v1 = v_tar end if v1 > v_cap then --atprint("in train_step_b: Accelerating: Hit v_cap!") v1 = v_cap end train.acceleration = (v1 - v0) / dtime train.velocity = v1 --atprint("in train_step_b: Accelerating: New velocity",v1," (yields acceleration",train.acceleration,")") end 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 = advtrains.is_node_loaded(rcollpos) 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 then local col_tr = advtrains.occ.check_collision(testpos, id) if col_tr then advtrains.train_check_couples(train) train.velocity = 0 advtrains.atc.train_reset_command(train) collided = true end --- 8b damage players --- if is_loaded_area and train.velocity > 3 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 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 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. Also called for the first node the train is standing on, then has_entered is true. -- signature is function(pos, id, train, index, has_entered, lzbdata) -- has_entered: true if the "enter" callback has already been executed for this train in this location -- 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) -- check for split points if mregnode and mregnode.at_conns and #mregnode.at_conns == 3 and train.path_cp[index] == 3 then -- train came from connection 3 of a switch, so it split points. if not train.points_split then train.points_split = {} end train.points_split[advtrains.encode_pos(pos)] = true --atdebug(train_id,"split points at",pos) end 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) -- split points do not matter anymore. clear them if train.points_split then if train.points_split[advtrains.encode_pos(pos)] then train.points_split[advtrains.encode_pos(pos)] = nil --atdebug(train_id,"has passed split points at",pos) end -- any entries left? for _,_ in pairs(train.points_split) do return end train.points_split = nil end -- WARNING possibly unreachable place! end function advtrains.tnc_call_approach_callback(pos, train_id, train, index, lzbdata) --atdebug("tnc approach",pos,train_id, lzbdata) local has_entered = atround(train.index) == index 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, has_entered, lzbdata) end -- call other registered callbacks run_callbacks_approach_node(pos, train_id, train, index, has_entered, lzbdata) end -- === te callback definition for tnc node callbacks === 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) --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 = advtrains.wagon_load_range -- 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 #",i,": 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]:get_yaw() 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)) if advtrains.position_in_range(pos, ablkrng) then --atdebug("wagon",w_id,"spawning") 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_fc(train, count_empty, length_limit) -- splits train at first different current FC by convention, -- locomotives have empty FC so are ignored -- count_empty is used to split off locomotives -- length_limit limits the length of the first train to length_limit wagons local train_id = train.id local fc = false local ind = 0 for i = 1, #train.trainparts do local w_id = train.trainparts[i] local data = advtrains.wagons[w_id] if length_limit and i > length_limit then ind = i break end if data then local wfc = advtrains.get_cur_fc(data) if wfc ~= "" or count_empty then if fc then if fc ~= wfc then ind = i break end else fc = wfc end end end end if ind > 0 then return advtrains.split_train_at_index(train, ind), fc end if fc then return nil, fc end end function advtrains.train_step_fc(train) for i=1,#train.trainparts do local w_id = train.trainparts[i] local data = advtrains.wagons[w_id] if data then advtrains.step_fc(data) end end end function advtrains.split_train_at_index(train, index) -- this function splits a train at index, creating a new train from the back part of the train. local train_id=train.id if index > #train.trainparts then -- index specified too long return end local w_id = train.trainparts[index] local data = advtrains.wagons[w_id] local _, wagon = advtrains.get_wagon_prototype(data) if not advtrains.train_ensure_init(train_id, train) then atwarn("Train",train_id,"is not initialized! Operation aborted!") return end -- make sure that the train is fully on track before splitting. May cause problems otherwise if train.index > train.path_trk_f or train.end_index < train.path_trk_b then atwarn("Train",train_id,": cannot split train because it is off track!") return end local p_index=advtrains.path_get_index_by_offset(train, train.index, - data.pos_in_train + wagon.wagon_span) local pos, connid, frac = advtrains.path_getrestore(train, p_index) local tp = {} for k,v in ipairs(train.trainparts) do if k >= index then table.insert(tp, v) train.trainparts[k] = nil end end advtrains.update_trainpart_properties(train_id) recalc_end_index(train) run_callbacks_update(train_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 return newtrain_id -- return new train ID, so new train can be manipulated end function advtrains.split_train_at_wagon(wagon_id) --get train local data = advtrains.wagons[wagon_id] advtrains.split_train_at_index(advtrains.trains[data.train_id], data.pos_in_trainparts) 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 id1 = train1.id local id2 = train2.id if train1.autocouple or train2.autocouple then -- couple trains train1.autocouple = nil train2.autocouple = nil minetest.after(0, advtrains.safe_couple_trains, id1, id2, t1_is_front, t2_is_front, false, false, train1.velocity, train2.velocity) return end 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=id1 le.train_id_2=id2 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:get_yaw() 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) if advtrains.is_node_loaded(pos) then -- if the position is loaded... 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 end if train.cpl_back then if not train.cpl_back:get_yaw() 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) if advtrains.is_node_loaded(pos) then -- if the position is loaded... 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 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 train.cpl_front:remove() train.cpl_front = nil end train.was_standing = nil end -- relevant code for this comment is in couple.lua --there are 4 cases: --1/2. F<->R F<->R regular, put second train behind first --->frontpos of first train will match backpos of second --3. F<->R R<->F flip one of these trains, take the other as new train --->backpos's will match --4. R<->F F<->R flip one of these trains and take it as new parent --->frontpos's will match function advtrains.do_connect_trains(first_id, second_id, vel) local first, second=advtrains.trains[first_id], advtrains.trains[second_id] if not advtrains.train_ensure_init(first_id, first) then atwarn("Train",first_id,"is not initialized! Operation aborted!") return end if not advtrains.train_ensure_init(second_id, second) then atwarn("Train",second_id,"is not initialized! Operation aborted!") return end local first_wagoncnt=#first.trainparts local second_wagoncnt=#second.trainparts for _,v in ipairs(second.trainparts) do table.insert(first.trainparts, v) end advtrains.remove_train(second_id) if vel < 0 then advtrains.invert_train(first_id) vel = -vel end first.velocity= vel or 0 advtrains.update_trainpart_properties(first_id) advtrains.couple_invalidate(first) return true end function advtrains.invert_train(train_id) 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 advtrains.path_setrestore(train, true) -- rotate some other stuff if train.door_open then train.door_open = - train.door_open end if train.atc_command then train.atc_arrow = not train.atc_arrow end advtrains.path_invalidate(train, true) advtrains.couple_invalidate(train) local old_trainparts=train.trainparts train.trainparts={} for k,v in ipairs(old_trainparts) do table.insert(train.trainparts, 1, v)--notice insertion at first place end advtrains.update_trainpart_properties(train_id, true) -- recalculate path advtrains.train_ensure_init(train_id, train) -- If interlocking present, check whether this train is in a section and then set as shunt move after reversion if advtrains.interlocking and train.il_sections and #train.il_sections > 0 then train.is_shunt = true train.speed_restriction = advtrains.SHUNT_SPEED_MAX else train.is_shunt = false train.speed_restriction = nil end end -- returns: train id, index of one of the trains that stand at this position. function advtrains.get_train_at_pos(pos) local t = advtrains.occ.get_trains_at(pos) for tid,idx in pairs(t) do return tid, idx end end -- ehm... I never adapted this function to the new path system ?! function advtrains.invalidate_all_paths(pos) local tab if pos then -- if position given, check occupation system tab = advtrains.occ.get_trains_over(pos) else tab = advtrains.trains end for id, _ in pairs(tab) do advtrains.invalidate_path(id) end end -- Calls invalidate_path_ahead on all trains occupying (having paths over) this node -- Can be called during train step. function advtrains.invalidate_all_paths_ahead(pos) local tab = advtrains.occ.get_trains_over(pos) for id,index in pairs(tab) do local train = advtrains.trains[id] advtrains.path_invalidate_ahead(train, index, true) end end function advtrains.invalidate_path(id) --atdebug("Path invalidate:",id) local v=advtrains.trains[id] if not v then return end advtrains.path_invalidate(v) advtrains.couple_invalidate(v) v.dirty = true end --not blocking trains group function advtrains.train_collides(node) if node and minetest.registered_nodes[node.name] and minetest.registered_nodes[node.name].walkable then if not minetest.registered_nodes[node.name].groups.not_blocking_trains then return true end end return false end local nonblocknodes={ "default:fence_wood", "default:fence_acacia_wood", "default:fence_aspen_wood", "default:fence_pine_wood", "default:fence_junglewood", "default:torch", "bones:bones", "default:sign_wall", "signs:sign_wall", "signs:sign_wall_blue", "signs:sign_wall_brown", "signs:sign_wall_orange", "signs:sign_wall_green", "signs:sign_yard", "signs:sign_wall_white_black", "signs:sign_wall_red", "signs:sign_wall_white_red", "signs:sign_wall_yellow", "signs:sign_post", "signs:sign_hanging", } minetest.after(0, function() for _,name in ipairs(nonblocknodes) do if minetest.registered_nodes[name] then minetest.registered_nodes[name].groups.not_blocking_trains=1 end end end)