p_polyobj.c 67.9 KB
Newer Older
Alam Ed Arias committed
1 2 3
// SONIC ROBO BLAST 2
//-----------------------------------------------------------------------------
// Copyright (C) 2006      by James Haley
James R. committed
4
// Copyright (C) 2006-2020 by Sonic Team Junior.
Alam Ed Arias committed
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
//
// This program is free software distributed under the
// terms of the GNU General Public License, version 2.
// See the 'LICENSE' file for more details.
//-----------------------------------------------------------------------------
/// \file  p_polyobj.c
/// \brief Movable segs like in Hexen, but more flexible
///        due to application of dynamic binary space partitioning theory.

// haleyjd: temporary define

#include "z_zone.h"

#include "doomstat.h"
#include "g_game.h"
#include "m_bbox.h"
#include "m_queue.h"
#include "p_maputl.h"
#include "p_setup.h"
#include "p_tick.h"
#include "p_local.h"
#include "p_polyobj.h"
#include "r_main.h"
#include "r_state.h"
#include "r_defs.h"

/*
   Theory behind Polyobjects:

      "The BSP tree hidden surface removal algorithm can easily be
      extended to allow for dynamic objects. For each frame, start with
      a BSP tree containing all the static objects in the scene, and
      reinsert the dynamic objects. While this is straightforward to
      implement, it can involve substantial computation.

      "If a dynamic object is separated from each static object by a
      plane, the dynamic object can be represented as a single point
      regardless of its complexity. This can dramatically reduce the
      computation per frame because only one node per dynamic object is
      inserted into the BSP tree. Compare that to one node for every
      polygon in the object, and the reason for the savings is obvious.
      During tree traversal, each point is expanded into the original
      object...

      "Inserting a point into the BSP tree is very cheap, because there
      is only one front/back test at each node. Points are never split,
      which explains the requirement of separation by a plane. The
      dynamic object will always be drawn completely in front of the
      static objects behind it.

      "...a different front/back test is necessary, because a point
      doesn't partition three dimesnional (sic) space. The correct
      front/back test is to simply compare distances to the eye. Once
      computed, this distance can be cached at the node until the frame
      is drawn."

   From http://www.faqs.org/faqs/graphics/bsptree-faq/ (The BSP FAQ)

   While Hexen had polyobjects, it put severe and artificial limits upon
   them by keeping them attached to one subsector, and allowing only one
   per subsector. Neither is necessary, and removing those limitations
   results in the free-moving polyobjects implemented here. The only
   true - and unavoidable - restriction is that polyobjects should never
   overlap with each other or with static walls.

   The reason that multiple polyobjects per subsector is viable is that
   with the above assumption that the objects will not overlap, if the
   center point of one polyobject is closer to the viewer than the center
   point of another, then the entire polyobject is closer to the viewer.
   In this way it is possible to impose an order on polyobjects within a
   subsector, as well as allowing the BSP tree to impose its natural
   ordering on polyobjects amongst all subsectors.
*/

//
// Defines
//

#define BYTEANGLEMUL     (ANGLE_11hh/8)

//
// Globals
//

// The Polyobjects
polyobj_t *PolyObjects;
INT32 numPolyObjects;

// Polyobject Blockmap -- initialized in P_LoadBlockMap
polymaplink_t **polyblocklinks;


//
// Static Data
//

// Polyobject Blockmap
static polymaplink_t *bmap_freelist; // free list of blockmap links


//
// Static Functions
//

FUNCINLINE static ATTRINLINE void Polyobj_bboxAdd(fixed_t *bbox, vertex_t *add)
{
	bbox[BOXTOP]    += add->y;
	bbox[BOXBOTTOM] += add->y;
	bbox[BOXLEFT]   += add->x;
	bbox[BOXRIGHT]  += add->x;
}

FUNCINLINE static ATTRINLINE void Polyobj_bboxSub(fixed_t *bbox, vertex_t *sub)
{
	bbox[BOXTOP]    -= sub->y;
	bbox[BOXBOTTOM] -= sub->y;
	bbox[BOXLEFT]   -= sub->x;
	bbox[BOXRIGHT]  -= sub->x;
}

FUNCINLINE static ATTRINLINE void Polyobj_vecAdd(vertex_t *dst, vertex_t *add)
{
	dst->x += add->x;
	dst->y += add->y;
}

FUNCINLINE static ATTRINLINE void Polyobj_vecSub(vertex_t *dst, vertex_t *sub)
{
	dst->x -= sub->x;
	dst->y -= sub->y;
}

FUNCINLINE static ATTRINLINE void Polyobj_vecSub2(vertex_t *dst, vertex_t *v1, vertex_t *v2)
{
	dst->x = v1->x - v2->x;
	dst->y = v1->y - v2->y;
}

boolean P_PointInsidePolyobj(polyobj_t *po, fixed_t x, fixed_t y)
{
	size_t i;

	for (i = 0; i < po->numLines; i++)
	{
		if (P_PointOnLineSide(x, y, po->lines[i]) == 0)
			return false;
	}

	return true;
}

boolean P_MobjTouchingPolyobj(polyobj_t *po, mobj_t *mo)
{
	fixed_t mbbox[4];
	size_t i;

	mbbox[BOXTOP] = mo->y + mo->radius;
	mbbox[BOXBOTTOM] = mo->y - mo->radius;
	mbbox[BOXRIGHT] = mo->x + mo->radius;
	mbbox[BOXLEFT] = mo->x - mo->radius;

	for (i = 0; i < po->numLines; i++)
	{
		if (P_BoxOnLineSide(mbbox, po->lines[i]) == -1)
			return true;
	}

	return false;
}

boolean P_MobjInsidePolyobj(polyobj_t *po, mobj_t *mo)
{
	fixed_t mbbox[4];
	size_t i;

	mbbox[BOXTOP] = mo->y + mo->radius;
	mbbox[BOXBOTTOM] = mo->y - mo->radius;
	mbbox[BOXRIGHT] = mo->x + mo->radius;
	mbbox[BOXLEFT] = mo->x - mo->radius;

	for (i = 0; i < po->numLines; i++)
	{
		if (P_BoxOnLineSide(mbbox, po->lines[i]) == 0)
			return false;
	}

	return true;
}

boolean P_BBoxInsidePolyobj(polyobj_t *po, fixed_t *bbox)
{
	size_t i;

	for (i = 0; i < po->numLines; i++)
	{
		if (P_BoxOnLineSide(bbox, po->lines[i]) == 0)
			return false;
	}

	return true;
}

207 208 209
// Gets the polyobject's settings from its first line
// args[0] of the first line should be the polyobject's id
static void Polyobj_GetInfo(polyobj_t *po, line_t *line)
Alam Ed Arias committed
210
{
211
	po->parent = line->args[1];
MascaraSnake committed
212 213
	if (po->parent == po->id) // do not allow a self-reference
		po->parent = -1;
Alam Ed Arias committed
214

215
	po->translucency = max(min(line->args[2], NUMTRANSMAPS), 0);
Alam Ed Arias committed
216

217
	po->flags = POF_SOLID|POF_TESTHEIGHT|POF_RENDERSIDES|POF_RENDERPLANES;
Alam Ed Arias committed
218

219
	if (line->args[3] & TMPF_NOINSIDES)
MascaraSnake committed
220
		po->flags |= POF_ONESIDE;
Alam Ed Arias committed
221

222
	if (line->args[3] & TMPF_INTANGIBLE)
MascaraSnake committed
223
		po->flags &= ~POF_SOLID;
Alam Ed Arias committed
224

225
	if (line->args[3] & TMPF_PUSHABLESTOP)
MascaraSnake committed
226
		po->flags |= POF_PUSHABLESTOP;
227

228 229
	if (line->args[3] & TMPF_INVISIBLEPLANES)
		po->flags &= ~POF_RENDERPLANES;
230

231
	/*if (line->args[3] & TMPF_DONTCLIPPLANES)
MascaraSnake committed
232
		po->flags &= ~POF_CLIPPLANES;*/
233

MascaraSnake committed
234
	if (line->args[3] & TMPF_SPLAT)
235
		po->flags |= POF_SPLAT;
236

237
	if (line->args[3] & TMPF_EXECUTOR) // Has a linedef executor
MascaraSnake committed
238
		po->flags |= POF_LDEXEC;
239

240 241 242 243
	// TODO: support customized damage somehow?
	if (line->args[3] & TMPF_CRUSH)
		po->damage = 3;

244
	po->triggertag = line->args[4];
Alam Ed Arias committed
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
}

// Reallocating array maintenance

// Adds a vertex to a polyobject's reallocating vertex arrays, provided
// that such a vertex isn't already in the array. Each vertex must only
// be translated once during polyobject movement. Keeping track of them
// this way results in much more clear and efficient code than what
// Hexen used.
static void Polyobj_addVertex(polyobj_t *po, vertex_t *v)
{
	size_t i;

	// First: search the existing vertex pointers for a match. If one is found,
	// do not add this vertex again.
	for (i = 0; i < po->numVertices; ++i)
	{
		if (po->vertices[i] == v)
			return;
	}

	// add the vertex to all arrays (translation for origVerts is done later)
	if (po->numVertices >= po->numVerticesAlloc)
	{
		po->numVerticesAlloc = po->numVerticesAlloc ? po->numVerticesAlloc * 2 : 4;
		po->vertices =
			(vertex_t **)Z_Realloc(po->vertices,
			                       po->numVerticesAlloc * sizeof(vertex_t *),
			                       PU_LEVEL, NULL);
		po->origVerts =
			(vertex_t *)Z_Realloc(po->origVerts,
			                      po->numVerticesAlloc * sizeof(vertex_t),
			                      PU_LEVEL, NULL);

		po->tmpVerts =
			(vertex_t *)Z_Realloc(po->tmpVerts,
			                      po->numVerticesAlloc * sizeof(vertex_t),
			                      PU_LEVEL, NULL);
	}
	po->vertices[po->numVertices] = v;
	po->origVerts[po->numVertices] = *v;
	po->numVertices++;
}

// Adds a linedef to a polyobject's reallocating linedefs array, provided
// that such a linedef isn't already in the array. Each linedef must only
// be adjusted once during polyobject movement. Keeping track of them
// this way provides the same benefits as for vertices.
static void Polyobj_addLine(polyobj_t *po, line_t *l)
{
	size_t i;

	// First: search the existing line pointers for a match. If one is found,
	// do not add this line again.
	for (i = 0; i < po->numLines; ++i)
	{
		if (po->lines[i] == l)
			return;
	}

	// add the line to the array
	if (po->numLines >= po->numLinesAlloc)
	{
		po->numLinesAlloc = po->numLinesAlloc ? po->numLinesAlloc * 2 : 4;
		po->lines = (line_t **)Z_Realloc(po->lines,
										po->numLinesAlloc * sizeof(line_t *),
										PU_LEVEL, NULL);
	}
	l->polyobj = po;
	po->lines[po->numLines++] = l;
}

// Adds a single seg to a polyobject's reallocating seg pointer array.
// Most polyobjects will have between 4 and 16 segs, so the array size
// begins much smaller than usual. Calls Polyobj_addVertex and Polyobj_addLine
// to add those respective structures for this seg, as well.
static void Polyobj_addSeg(polyobj_t *po, seg_t *seg)
{
	if (po->segCount >= po->numSegsAlloc)
	{
		po->numSegsAlloc = po->numSegsAlloc ? po->numSegsAlloc * 2 : 4;
		po->segs = (seg_t **)Z_Realloc(po->segs,
										po->numSegsAlloc * sizeof(seg_t *),
										PU_LEVEL, NULL);
	}

	seg->polyseg = po;

	po->segs[po->segCount++] = seg;

	// possibly add the lines and vertices for this seg. It may be technically
	// unnecessary to add the v2 vertex of segs, but this makes sure that even
	// erroneously open "explicit" segs will have both vertices added and will
	// reduce problems.
	Polyobj_addVertex(po, seg->v1);
	Polyobj_addVertex(po, seg->v2);
	Polyobj_addLine(po, seg->linedef);
}

// Seg-finding functions

// This method adds segs to a polyobject by following segs from vertex to
// vertex.  The process stops when the original starting point is reached
// or if a particular search ends unexpectedly (ie, the polyobject is not
// closed).
static void Polyobj_findSegs(polyobj_t *po, seg_t *seg)
{
	fixed_t startx, starty;
	size_t i;
	size_t s;

	Polyobj_addSeg(po, seg);

	if (!(po->flags & POF_ONESIDE))
	{
		// Find backfacings
		for (s = 0;  s < numsegs; s++)
		{
MascaraSnake committed
363 364
			size_t r;

365 366
			if (segs[s].glseg)
				continue;
Alam Ed Arias committed
367

MascaraSnake committed
368 369
			if (segs[s].linedef != seg->linedef)
				continue;
Alam Ed Arias committed
370

MascaraSnake committed
371 372
			if (segs[s].side != 1)
				continue;
Alam Ed Arias committed
373

MascaraSnake committed
374 375 376 377
			for (r = 0; r < po->segCount; r++)
			{
				if (po->segs[r] == &segs[s])
					break;
Alam Ed Arias committed
378
			}
MascaraSnake committed
379 380 381 382 383 384 385

			if (r != po->segCount)
				continue;

			segs[s].dontrenderme = true;

			Polyobj_addSeg(po, &segs[s]);
Alam Ed Arias committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
		}
	}

	// on first seg, save the initial vertex
	startx = seg->v1->x;
	starty = seg->v1->y;

	// use goto instead of recursion for maximum efficiency - thanks to lament
newseg:

	// terminal case: we have reached a seg where v2 is the same as v1 of the
	// initial seg
	if (seg->v2->x == startx && seg->v2->y == starty)
		return;

	// search the segs for one whose starting vertex is equal to the current
	// seg's ending vertex.
	for (i = 0; i < numsegs; ++i)
	{
MascaraSnake committed
405 406
		size_t q;

407 408
		if (segs[i].glseg)
			continue;
409 410
		if (segs[i].side != 0) // needs to be frontfacing
			continue;
MascaraSnake committed
411 412 413 414 415 416 417
		if (segs[i].v1->x != seg->v2->x)
			continue;
		if (segs[i].v1->y != seg->v2->y)
			continue;

		// Make sure you didn't already add this seg...
		for (q = 0; q < po->segCount; q++)
Alam Ed Arias committed
418
		{
MascaraSnake committed
419 420 421
			if (po->segs[q] == &segs[i])
				break;
		}
Alam Ed Arias committed
422

MascaraSnake committed
423 424
		if (q != po->segCount)
			continue;
Alam Ed Arias committed
425

MascaraSnake committed
426 427 428
		// add the new seg and recurse
		Polyobj_addSeg(po, &segs[i]);
		seg = &segs[i];
Alam Ed Arias committed
429

MascaraSnake committed
430 431 432 433
		if (!(po->flags & POF_ONESIDE))
		{
			// Find backfacings
			for (q = 0; q < numsegs; q++)
Alam Ed Arias committed
434
			{
MascaraSnake committed
435
				size_t r;
436

MascaraSnake committed
437 438 439 440 441 442
				if (segs[q].glseg)
					continue;
				if (segs[q].linedef != segs[i].linedef)
					continue;
				if (segs[q].side != 1)
					continue;
Alam Ed Arias committed
443

MascaraSnake committed
444
				for (r = 0; r < po->segCount; r++)
Alam Ed Arias committed
445
				{
MascaraSnake committed
446 447
					if (po->segs[r] == &segs[q])
						break;
Alam Ed Arias committed
448 449
				}

MascaraSnake committed
450 451 452 453 454 455
				if (r != po->segCount)
					continue;

				segs[q].dontrenderme = true;
				Polyobj_addSeg(po, &segs[q]);
			}
Alam Ed Arias committed
456
		}
MascaraSnake committed
457 458

		goto newseg;
Alam Ed Arias committed
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
	}

	// error: if we reach here, the seg search never found another seg to
	// continue the loop, and thus the polyobject is open. This isn't allowed.
	po->isBad = true;
	CONS_Debug(DBG_POLYOBJ, "Polyobject %d is not closed\n", po->id);
}

// Setup functions

static void Polyobj_spawnPolyObj(INT32 num, mobj_t *spawnSpot, INT32 id)
{
	size_t i;
	polyobj_t *po = &PolyObjects[num];

	// don't spawn a polyobject more than once
	if (po->segCount)
	{
		CONS_Debug(DBG_POLYOBJ, "Polyobj %d has more than one spawn spot", po->id);
		return;
	}

	po->id = id;

	// set to default thrust; may be modified by attached thinkers
	// TODO: support customized thrust?
	po->thrust = FRACUNIT;
Alam Ed Arias committed
486
	po->spawnflags = po->flags = 0;
Alam Ed Arias committed
487

488 489 490
	// Search segs for "line start" special with tag matching this
	// polyobject's id number. If found, iterate through segs which
	// share common vertices and record them into the polyobject.
Alam Ed Arias committed
491 492 493 494
	for (i = 0; i < numsegs; ++i)
	{
		seg_t *seg = &segs[i];

495 496 497
		if (seg->glseg)
			continue;

498 499 500
		if (seg->side != 0) // needs to be frontfacing
			continue;

Alam Ed Arias committed
501 502
		if (seg->linedef->special != POLYOBJ_START_LINE)
			continue;
503

504
		if (seg->linedef->args[0] != po->id)
505
			continue;
Alam Ed Arias committed
506

507
		Polyobj_GetInfo(po, seg->linedef); // apply extra settings if they exist!
508

509
		// save original flags and translucency to reference later for netgames!
MascaraSnake committed
510 511
		po->spawnflags = po->flags;
		po->spawntrans = po->translucency;
Alam Ed Arias committed
512

513 514
		Polyobj_findSegs(po, seg);
		break;
Alam Ed Arias committed
515 516 517 518 519 520 521 522
	}

	CONS_Debug(DBG_POLYOBJ, "PO ID: %d; Num verts: %s\n", po->id, sizeu1(po->numVertices));

	// if an error occurred above, quit processing this object
	if (po->isBad)
		return;

523 524 525 526 527 528 529
	// make sure array isn't empty
	if (po->segCount == 0)
	{
		po->isBad = true;
		CONS_Debug(DBG_POLYOBJ, "Polyobject %d is empty\n", po->id);
		return;
	}
Alam Ed Arias committed
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

	// set the polyobject's spawn spot
	po->spawnSpot.x = spawnSpot->x;
	po->spawnSpot.y = spawnSpot->y;

	// hash the polyobject by its numeric id
	if (Polyobj_GetForNum(po->id))
	{
		// bad polyobject due to id conflict
		po->isBad = true;
		CONS_Debug(DBG_POLYOBJ, "Polyobject id conflict: %d\n", id);
	}
	else
	{
		INT32 hashkey = po->id % numPolyObjects;
		po->next = PolyObjects[hashkey].first;
		PolyObjects[hashkey].first = num;
	}
}

static void Polyobj_attachToSubsec(polyobj_t *po);

// Translates the polyobject's vertices with respect to the difference between
// the anchor and spawn spots. Updates linedef bounding boxes as well.
static void Polyobj_moveToSpawnSpot(mapthing_t *anchor)
{
	polyobj_t *po;
	vertex_t  dist, sspot;
	size_t i;
559
	mtag_t tag = Tag_FGet(&anchor->tags);
Alam Ed Arias committed
560

561
	if (!(po = Polyobj_GetForNum(tag)))
Alam Ed Arias committed
562
	{
563
		CONS_Debug(DBG_POLYOBJ, "Bad polyobject %d for anchor point\n", tag);
Alam Ed Arias committed
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
		return;
	}

	// don't move any bad polyobject that may have gotten through
	if (po->isBad)
		return;

	// don't move any polyobject more than once
	if (po->attached)
	{
		CONS_Debug(DBG_POLYOBJ, "Polyobj %d has more than one anchor\n", po->id);
		return;
	}

	sspot.x = po->spawnSpot.x;
	sspot.y = po->spawnSpot.y;

	// calculate distance from anchor to spawn spot
	dist.x = (anchor->x << FRACBITS) - sspot.x;
	dist.y = (anchor->y << FRACBITS) - sspot.y;

	// update linedef bounding boxes
	for (i = 0; i < po->numLines; ++i)
		Polyobj_bboxSub(po->lines[i]->bbox, &dist);

	// translate vertices and record original coordinates relative to spawn spot
	for (i = 0; i < po->numVertices; ++i)
	{
		Polyobj_vecSub(po->vertices[i], &dist);

		Polyobj_vecSub2(&(po->origVerts[i]), po->vertices[i], &sspot);
	}

	// attach to subsector
	Polyobj_attachToSubsec(po);
}

// Attaches a polyobject to its appropriate subsector.
static void Polyobj_attachToSubsec(polyobj_t *po)
{
	subsector_t  *ss;
	fixed_t center_x = 0, center_y = 0;
	fixed_t numVertices;
	size_t i;

	// never attach a bad polyobject
	if (po->isBad)
		return;

	numVertices = (fixed_t)(po->numVertices*FRACUNIT);

	for (i = 0; i < po->numVertices; ++i)
	{
		center_x += FixedDiv(po->vertices[i]->x, numVertices);
		center_y += FixedDiv(po->vertices[i]->y, numVertices);
	}

	po->centerPt.x = center_x;
	po->centerPt.y = center_y;

	ss = R_PointInSubsector(po->centerPt.x, po->centerPt.y);

	M_DLListInsert(&po->link, (mdllistitem_t **)(void *)(&ss->polyList));

#ifdef R_LINKEDPORTALS
	// set spawnSpot's groupid for correct portal sound behavior
	po->spawnSpot.groupid = ss->sector->groupid;
#endif

	po->attached = true;
}

// Removes a polyobject from the subsector to which it is attached.
static void Polyobj_removeFromSubsec(polyobj_t *po)
{
	if (po->attached)
	{
		M_DLListRemove(&po->link);
		po->attached = false;
	}
}

// Blockmap Functions

// Retrieves a polymaplink object from the free list or creates a new one.
static polymaplink_t *Polyobj_getLink(void)
{
	polymaplink_t *l;

	if (bmap_freelist)
	{
		l = bmap_freelist;
		bmap_freelist = (polymaplink_t *)(l->link.next);
	}
	else
	{
		l = Z_Malloc(sizeof(*l), PU_LEVEL, NULL);
		memset(l, 0, sizeof(*l));
	}

	return l;
}

// Puts a polymaplink object into the free list.
static void Polyobj_putLink(polymaplink_t *l)
{
	memset(l, 0, sizeof(*l));
	l->link.next = (mdllistitem_t *)bmap_freelist;
	bmap_freelist = l;
}

// Inserts a polyobject into the polyobject blockmap. Unlike, mobj_t's,
// polyobjects need to be linked into every blockmap cell which their
// bounding box intersects. This ensures the accurate level of clipping
// which is present with linedefs but absent from most mobj interactions.
static void Polyobj_linkToBlockmap(polyobj_t *po)
{
	fixed_t *blockbox = po->blockbox;
	size_t i;
	fixed_t x, y;

	// never link a bad polyobject or a polyobject already linked
	if (po->isBad || po->linked)
		return;

	// 2/26/06: start line box with values of first vertex, not INT32_MIN/INT32_MAX
	blockbox[BOXLEFT]   = blockbox[BOXRIGHT] = po->vertices[0]->x;
	blockbox[BOXBOTTOM] = blockbox[BOXTOP]   = po->vertices[0]->y;

	// add all vertices to the bounding box
	for (i = 1; i < po->numVertices; ++i)
		M_AddToBox(blockbox, po->vertices[i]->x, po->vertices[i]->y);

	// adjust bounding box relative to blockmap
698 699 700 701
	blockbox[BOXRIGHT]  = (unsigned)(blockbox[BOXRIGHT]  - bmaporgx) >> MAPBLOCKSHIFT;
	blockbox[BOXLEFT]   = (unsigned)(blockbox[BOXLEFT]   - bmaporgx) >> MAPBLOCKSHIFT;
	blockbox[BOXTOP]    = (unsigned)(blockbox[BOXTOP]    - bmaporgy) >> MAPBLOCKSHIFT;
	blockbox[BOXBOTTOM] = (unsigned)(blockbox[BOXBOTTOM] - bmaporgy) >> MAPBLOCKSHIFT;
Alam Ed Arias committed
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809

	// link polyobject to every block its bounding box intersects
	for (y = blockbox[BOXBOTTOM]; y <= blockbox[BOXTOP]; ++y)
	{
		for (x = blockbox[BOXLEFT]; x <= blockbox[BOXRIGHT]; ++x)
		{
			if (!(x < 0 || y < 0 || x >= bmapwidth || y >= bmapheight))
			{
				polymaplink_t  *l = Polyobj_getLink();

				l->po = po;

				M_DLListInsert(&l->link,
							(mdllistitem_t **)(&polyblocklinks[y*bmapwidth + x]));
			}
		}
	}

	po->linked = true;
}

// Unlinks a polyobject from all blockmap cells it intersects and returns
// its polymaplink objects to the free list.
static void Polyobj_removeFromBlockmap(polyobj_t *po)
{
	polymaplink_t *rover;
	fixed_t *blockbox = po->blockbox;
	INT32 x, y;

	// don't bother trying to unlink one that's not linked
	if (!po->linked)
		return;

	// search all cells the polyobject touches
	for (y = blockbox[BOXBOTTOM]; y <= blockbox[BOXTOP]; ++y)
	{
		for (x = blockbox[BOXLEFT]; x <= blockbox[BOXRIGHT]; ++x)
		{
			if (!(x < 0 || y < 0 || x >= bmapwidth || y >= bmapheight))
			{
				rover = polyblocklinks[y * bmapwidth + x];

				while (rover && rover->po != po)
					rover = (polymaplink_t *)(rover->link.next);

				// polyobject not in this cell? go on to next.
				if (!rover)
					continue;

				// remove this link from the blockmap and put it on the freelist
				M_DLListRemove(&rover->link);
				Polyobj_putLink(rover);
			}
		}
	}

	po->linked = false;
}

// Movement functions

// A version of Lee's routine from p_maputl.c that accepts an mobj pointer
// argument instead of using tmthing. Returns true if the line isn't contacted
// and false otherwise.
static inline boolean Polyobj_untouched(line_t *ld, mobj_t *mo)
{
	fixed_t x, y, ptmbbox[4];

	return
		(ptmbbox[BOXRIGHT]  = (x = mo->x) + mo->radius) <= ld->bbox[BOXLEFT]   ||
		(ptmbbox[BOXLEFT]   =           x - mo->radius) >= ld->bbox[BOXRIGHT]  ||
		(ptmbbox[BOXTOP]    = (y = mo->y) + mo->radius) <= ld->bbox[BOXBOTTOM] ||
		(ptmbbox[BOXBOTTOM] =           y - mo->radius) >= ld->bbox[BOXTOP]    ||
		P_BoxOnLineSide(ptmbbox, ld) != -1;
}

// Inflicts thrust and possibly damage on a thing which has been found to be
// blocking the motion of a polyobject. The default thrust amount is only one
// unit, but the motion of the polyobject can be used to change this.
static void Polyobj_pushThing(polyobj_t *po, line_t *line, mobj_t *mo)
{
	angle_t lineangle;
	fixed_t momx, momy;
	vertex_t closest;

	// calculate angle of line and subtract 90 degrees to get normal
	lineangle = R_PointToAngle2(0, 0, line->dx, line->dy) - ANGLE_90;
	lineangle >>= ANGLETOFINESHIFT;
	momx = FixedMul(po->thrust, FINECOSINE(lineangle));
	momy = FixedMul(po->thrust, FINESINE(lineangle));
	mo->momx += momx;
	mo->momy += momy;

	// Prevent 'sticking'
	P_UnsetThingPosition(mo);
	P_ClosestPointOnLine(mo->x, mo->y, line, &closest);
	mo->x = closest.x + FixedMul(mo->radius, FINECOSINE(lineangle));
	mo->y = closest.y + FixedMul(mo->radius, FINESINE(lineangle));
	mo->x += momx;
	mo->y += momy;
	P_SetThingPosition(mo);

	// if object doesn't fit at desired location, possibly hurt it
	if (po->damage && (mo->flags & MF_SHOOTABLE))
	{
		P_CheckPosition(mo, mo->x + momx, mo->y + momy);
		mo->floorz = tmfloorz;
		mo->ceilingz = tmceilingz;
810 811
		mo->floorrover = tmfloorrover;
		mo->ceilingrover = tmceilingrover;
Alam Ed Arias committed
812 813 814
	}
}

Alam Ed Arias committed
815 816 817
// Moves an object resting on top of a polyobject by (x, y). Template function to make alteration easier.
static void Polyobj_slideThing(mobj_t *mo, fixed_t dx, fixed_t dy)
{
818 819
	if (mo->player) { // Finally this doesn't suck eggs -fickle
		fixed_t cdx, cdy;
Alam Ed Arias committed
820

821 822
		cdx = FixedMul(dx, FRACUNIT-CARRYFACTOR);
		cdy = FixedMul(dy, FRACUNIT-CARRYFACTOR);
Alam Ed Arias committed
823

824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
		if (mo->player->onconveyor == 1)
		{
			mo->momx += cdx;
			mo->momy += cdy;

			// Multiple slides in the same tic, somehow
			mo->player->cmomx += cdx;
			mo->player->cmomy += cdy;
		}
		else
		{
			if (mo->player->onconveyor == 3)
			{
				mo->momx += cdx - mo->player->cmomx;
				mo->momy += cdy - mo->player->cmomy;
			}

			mo->player->cmomx = cdx;
			mo->player->cmomy = cdy;
		}

		dx = FixedMul(dx, FRACUNIT - mo->friction);
		dy = FixedMul(dy, FRACUNIT - mo->friction);
Alam Ed Arias committed
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862

		if (mo->player->pflags & PF_SPINNING && (mo->player->rmomx || mo->player->rmomy) && !(mo->player->pflags & PF_STARTDASH)) {
#define SPINMULT 5184 // Consider this a substitute for properly calculating FRACUNIT-friction. I'm tired. -Red
			dx = FixedMul(dx, SPINMULT);
			dy = FixedMul(dy, SPINMULT);
#undef SPINMULT
		}

		mo->momx += dx;
		mo->momy += dy;

		mo->player->onconveyor = 1;
	} else
		P_TryMove(mo, mo->x+dx, mo->y+dy, true);
}

Alam Ed Arias committed
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
// Causes objects resting on top of the polyobject to 'ride' with its movement.
static void Polyobj_carryThings(polyobj_t *po, fixed_t dx, fixed_t dy)
{
	static INT32 pomovecount = 0;
	INT32 x, y;

	pomovecount++;

	if (!(po->flags & POF_SOLID))
		return;

	for (y = po->blockbox[BOXBOTTOM]; y <= po->blockbox[BOXTOP]; ++y)
	{
		for (x = po->blockbox[BOXLEFT]; x <= po->blockbox[BOXRIGHT]; ++x)
		{
			mobj_t *mo;

			if (x < 0 || y < 0 || x >= bmapwidth || y >= bmapheight)
				continue;

			mo = blocklinks[y * bmapwidth + x];

			for (; mo; mo = mo->bnext)
			{
				if (mo->lastlook == pomovecount)
					continue;

				mo->lastlook = pomovecount;

892 893
				// Don't scroll objects that aren't affected by gravity
				if (mo->flags & MF_NOGRAVITY)
Alam Ed Arias committed
894
					continue;
895
				// (The above check used to only move MF_SOLID objects, but that's inconsistent with conveyor behavior. -Red)
Alam Ed Arias committed
896 897 898 899 900 901 902 903 904 905 906 907 908

				if (mo->flags & MF_NOCLIP)
					continue;

				if ((mo->eflags & MFE_VERTICALFLIP) && mo->z + mo->height != po->lines[0]->backsector->floorheight)
					continue;

				if (!(mo->eflags & MFE_VERTICALFLIP) && mo->z != po->lines[0]->backsector->ceilingheight)
					continue;

				if (!P_MobjInsidePolyobj(po, mo))
					continue;

Alam Ed Arias committed
909
				Polyobj_slideThing(mo, dx, dy);
Alam Ed Arias committed
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
			}
		}
	}
}

// Checks for things that are in the way of a polyobject line move.
// Returns true if something was hit.
static INT32 Polyobj_clipThings(polyobj_t *po, line_t *line)
{
	INT32 hitflags = 0;
	fixed_t linebox[4];
	INT32 x, y;

	if (!(po->flags & POF_SOLID))
		return hitflags;

	// adjust linedef bounding box to blockmap, extend by MAXRADIUS
927 928 929 930
	linebox[BOXLEFT]   = (unsigned)(line->bbox[BOXLEFT]   - bmaporgx - MAXRADIUS) >> MAPBLOCKSHIFT;
	linebox[BOXRIGHT]  = (unsigned)(line->bbox[BOXRIGHT]  - bmaporgx + MAXRADIUS) >> MAPBLOCKSHIFT;
	linebox[BOXBOTTOM] = (unsigned)(line->bbox[BOXBOTTOM] - bmaporgy - MAXRADIUS) >> MAPBLOCKSHIFT;
	linebox[BOXTOP]    = (unsigned)(line->bbox[BOXTOP]    - bmaporgy + MAXRADIUS) >> MAPBLOCKSHIFT;
Alam Ed Arias committed
931 932 933 934 935 936 937 938 939 940 941 942

	// check all mobj blockmap cells the line contacts
	for (y = linebox[BOXBOTTOM]; y <= linebox[BOXTOP]; ++y)
	{
		for (x = linebox[BOXLEFT]; x <= linebox[BOXRIGHT]; ++x)
		{
			if (!(x < 0 || y < 0 || x >= bmapwidth || y >= bmapheight))
			{
				mobj_t *mo = blocklinks[y * bmapwidth + x];

				for (; mo; mo = mo->bnext)
				{
943 944 945

					// Don't scroll objects that aren't affected by gravity
					if (mo->flags & MF_NOGRAVITY)
Alam Ed Arias committed
946
						continue;
947
					// (The above check used to only move MF_SOLID objects, but that's inconsistent with conveyor behavior. -Red)
Alam Ed Arias committed
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

					if (mo->flags & MF_NOCLIP)
						continue;

					if (mo->z + mo->height <= line->backsector->floorheight)
						continue;

					if (mo->z >= line->backsector->ceilingheight)
						continue;

					if (Polyobj_untouched(line, mo))
						continue;

					if (mo->flags & MF_PUSHABLE && (po->flags & POF_PUSHABLESTOP))
						hitflags |= 2;
					else
						Polyobj_pushThing(po, line, mo);

					if (mo->player && (po->lines[0]->backsector->flags & SF_TRIGGERSPECIAL_TOUCH) && !(po->flags & POF_NOSPECIALS))
						P_ProcessSpecialSector(mo->player, mo->subsector->sector, po->lines[0]->backsector);

					hitflags |= 1;
				}
			} // end if
		} // end for (y)
	} // end for (x)

	return hitflags;
}

978

Alam Ed Arias committed
979
// Moves a polyobject on the x-y plane.
980
boolean Polyobj_moveXY(polyobj_t *po, fixed_t x, fixed_t y, boolean checkmobjs)
Alam Ed Arias committed
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
{
	size_t i;
	vertex_t vec;
	INT32 hitflags = 0;

	vec.x = x;
	vec.y = y;

	// don't move bad polyobjects
	if (po->isBad)
		return false;

	// translate vertices
	for (i = 0; i < po->numVertices; ++i)
		Polyobj_vecAdd(po->vertices[i], &vec);

	// translate each line
	for (i = 0; i < po->numLines; ++i)
		Polyobj_bboxAdd(po->lines[i]->bbox, &vec);

1001 1002 1003 1004 1005 1006
	if (checkmobjs)
	{
		// check for blocking things (yes, it needs to be done separately)
		for (i = 0; i < po->numLines; ++i)
			hitflags |= Polyobj_clipThings(po, po->lines[i]);
	}
Alam Ed Arias committed
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

	if (hitflags & 2)
	{
		// reset vertices
		for (i = 0; i < po->numVertices; ++i)
			Polyobj_vecSub(po->vertices[i], &vec);

		// reset lines that have been moved
		for (i = 0; i < po->numLines; ++i)
			Polyobj_bboxSub(po->lines[i]->bbox, &vec);
	}
	else
	{
		// translate the spawnSpot as well
		po->spawnSpot.x += vec.x;
		po->spawnSpot.y += vec.y;

1024 1025
		if (checkmobjs)
			Polyobj_carryThings(po, x, y);
Alam Ed Arias committed
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
		Polyobj_removeFromBlockmap(po); // unlink it from the blockmap
		Polyobj_removeFromSubsec(po);   // unlink it from its subsector
		Polyobj_linkToBlockmap(po);     // relink to blockmap
		Polyobj_attachToSubsec(po);     // relink to subsector
	}

	return !(hitflags & 2);
}

// Rotates a point and then translates it relative to point c.
// The formula for this can be found here:
// http://www.inversereality.org/tutorials/graphics%20programming/2dtransformations.html
// It is, of course, just a vector-matrix multiplication.
1039
static inline void Polyobj_rotatePoint(vertex_t *v, const vector2_t *c, angle_t ang)
Alam Ed Arias committed
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
{
	vertex_t tmp = *v;

	v->x = FixedMul(tmp.x, FINECOSINE(ang)) - FixedMul(tmp.y,   FINESINE(ang));
	v->y = FixedMul(tmp.x,   FINESINE(ang)) + FixedMul(tmp.y, FINECOSINE(ang));

	v->x += c->x;
	v->y += c->y;
}

// Taken from P_LoadLineDefs; simply updates the linedef's dx, dy, slopetype,
// and bounding box to be consistent with its vertices.
static void Polyobj_rotateLine(line_t *ld)
{
	vertex_t *v1, *v2;

	v1 = ld->v1;
	v2 = ld->v2;

	// set dx, dy
	ld->dx = v2->x - v1->x;
	ld->dy = v2->y - v1->y;

	// determine slopetype
	ld->slopetype = !ld->dx ? ST_VERTICAL : !ld->dy ? ST_HORIZONTAL :
1065
			((ld->dy > 0) == (ld->dx > 0)) ? ST_POSITIVE : ST_NEGATIVE;
Alam Ed Arias committed
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

	// update bounding box
	if (v1->x < v2->x)
	{
		ld->bbox[BOXLEFT]  = v1->x;
		ld->bbox[BOXRIGHT] = v2->x;
	}
	else
	{
		ld->bbox[BOXLEFT]  = v2->x;
		ld->bbox[BOXRIGHT] = v1->x;
	}

	if (v1->y < v2->y)
	{
		ld->bbox[BOXBOTTOM] = v1->y;
		ld->bbox[BOXTOP]    = v2->y;
	}
	else
	{
		ld->bbox[BOXBOTTOM] = v2->y;
		ld->bbox[BOXTOP]    = v1->y;
	}
}

Alam Ed Arias committed
1091
// Causes objects resting on top of the rotating polyobject to 'ride' with its movement.
1092
static void Polyobj_rotateThings(polyobj_t *po, vector2_t origin, angle_t delta, UINT8 turnthings)
Alam Ed Arias committed
1093 1094 1095
{
	static INT32 pomovecount = 10000;
	INT32 x, y;
1096 1097
	angle_t deltafine = (((po->angle + delta) >> ANGLETOFINESHIFT) - (po->angle >> ANGLETOFINESHIFT)) & FINEMASK;
	// This fineshift trickery replaces the old delta>>ANGLETOFINESHIFT; doing it this way avoids loss of precision causing objects to slide off -fickle
Alam Ed Arias committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

	pomovecount++;

	if (!(po->flags & POF_SOLID))
		return;

	for (y = po->blockbox[BOXBOTTOM]; y <= po->blockbox[BOXTOP]; ++y)
	{
		for (x = po->blockbox[BOXLEFT]; x <= po->blockbox[BOXRIGHT]; ++x)
		{
			mobj_t *mo;

			if (x < 0 || y < 0 || x >= bmapwidth || y >= bmapheight)
				continue;

			mo = blocklinks[y * bmapwidth + x];

			for (; mo; mo = mo->bnext)
			{
				if (mo->lastlook == pomovecount)
					continue;

				mo->lastlook = pomovecount;

1122 1123
				// Don't scroll objects that aren't affected by gravity
				if (mo->flags & MF_NOGRAVITY)
Alam Ed Arias committed
1124
					continue;
1125
				// (The above check used to only move MF_SOLID objects, but that's inconsistent with conveyor behavior. -Red)
Alam Ed Arias committed
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139

				if (mo->flags & MF_NOCLIP)
					continue;

				if ((mo->eflags & MFE_VERTICALFLIP) && mo->z + mo->height != po->lines[0]->backsector->floorheight)
					continue;

				if (!(mo->eflags & MFE_VERTICALFLIP) && mo->z != po->lines[0]->backsector->ceilingheight)
					continue;

				if (!P_MobjInsidePolyobj(po, mo))
					continue;

				{
1140 1141 1142 1143 1144
					fixed_t oldxoff, oldyoff, newxoff, newyoff;
					fixed_t c, s;

					c = FINECOSINE(deltafine);
					s = FINESINE(deltafine);
Alam Ed Arias committed
1145

1146 1147
					oldxoff = mo->x-origin.x;
					oldyoff = mo->y-origin.y;
Alam Ed Arias committed
1148

1149 1150
					newxoff = FixedMul(oldxoff, c)-FixedMul(oldyoff, s) - oldxoff;
					newyoff = FixedMul(oldyoff, c)+FixedMul(oldxoff, s) - oldyoff;
Alam Ed Arias committed
1151

1152
					Polyobj_slideThing(mo, newxoff, newyoff);
Alam Ed Arias committed
1153 1154 1155

					if (turnthings == 2 || (turnthings == 1 && !mo->player)) {
						mo->angle += delta;
1156 1157
						if (mo->player)
							P_SetPlayerAngle(mo->player, (angle_t)(mo->player->angleturn << 16) + delta);
Alam Ed Arias committed
1158 1159 1160 1161 1162 1163 1164
					}
				}
			}
		}
	}
}

Alam Ed Arias committed
1165
// Rotates a polyobject around its start point.
1166
boolean Polyobj_rotate(polyobj_t *po, angle_t delta, UINT8 turnthings, boolean checkmobjs)
Alam Ed Arias committed
1167 1168 1169
{
	size_t i;
	angle_t angle;
1170
	vector2_t origin;
Alam Ed Arias committed
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
	INT32 hitflags = 0;

	// don't move bad polyobjects
	if (po->isBad)
		return false;

	angle = (po->angle + delta) >> ANGLETOFINESHIFT;

	// point about which to rotate is the spawn spot
	origin.x = po->spawnSpot.x;
	origin.y = po->spawnSpot.y;

	// save current positions and rotate all vertices
	for (i = 0; i < po->numVertices; ++i)
	{
		po->tmpVerts[i] = *(po->vertices[i]);

		// use original pts to rotate to new position
		*(po->vertices[i]) = po->origVerts[i];

		Polyobj_rotatePoint(po->vertices[i], &origin, angle);
	}

	// rotate lines
	for (i = 0; i < po->numLines; ++i)
		Polyobj_rotateLine(po->lines[i]);

1198 1199 1200 1201 1202
	if (checkmobjs)
	{
		// check for blocking things
		for (i = 0; i < po->numLines; ++i)
			hitflags |= Polyobj_clipThings(po, po->lines[i]);
Alam Ed Arias committed
1203

1204 1205
		Polyobj_rotateThings(po, origin, delta, turnthings);
	}
Alam Ed Arias committed
1206

Alam Ed Arias committed
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
	if (hitflags & 2)
	{
		// reset vertices to previous positions
		for (i = 0; i < po->numVertices; ++i)
			*(po->vertices[i]) = po->tmpVerts[i];

		// reset lines
		for (i = 0; i < po->numLines; ++i)
			Polyobj_rotateLine(po->lines[i]);
	}
	else
	{
		// update seg angles (used only by renderer)
		for (i = 0; i < po->segCount; ++i)
			po->segs[i]->angle += delta;

		// update polyobject's angle
		po->angle += delta;

		Polyobj_removeFromBlockmap(po); // unlink it from the blockmap
		Polyobj_removeFromSubsec(po);   // remove from subsector
		Polyobj_linkToBlockmap(po);     // relink to blockmap
		Polyobj_attachToSubsec(po);     // relink to subsector
	}

	return !(hitflags & 2);
}

//
// Global Functions
//

// Retrieves a polyobject by its numeric id using hashing.
// Returns NULL if no such polyobject exists.
polyobj_t *Polyobj_GetForNum(INT32 id)
{
	INT32 curidx  = PolyObjects[id % numPolyObjects].first;

	while (curidx != numPolyObjects && PolyObjects[curidx].id != id)
		curidx = PolyObjects[curidx].next;

	return curidx == numPolyObjects ? NULL : &PolyObjects[curidx];
}

1251

Alam Ed Arias committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
// Retrieves the parenting polyobject if one exists. Returns NULL
// otherwise.
#if 0 //unused function
static polyobj_t *Polyobj_GetParent(polyobj_t *po)
{
	return (po && po->parent != -1) ? Polyobj_GetForNum(po->parent) : NULL;
}
#endif

// Iteratively retrieves the children POs of a parent,
// sorta like P_FindSectorSpecialFromTag.
static polyobj_t *Polyobj_GetChild(polyobj_t *po, INT32 *start)
{
	for (; *start < numPolyObjects; (*start)++)
	{
		if (PolyObjects[*start].parent == po->id)
			return &PolyObjects[(*start)++];
	}

	return NULL;
}

// structure used to queue up mobj pointers in Polyobj_InitLevel
typedef struct mobjqitem_s
{
	mqueueitem_t mqitem;
	mobj_t *mo;
} mobjqitem_t;

// Called at the beginning of each map after all other line and thing
// processing is finished.
void Polyobj_InitLevel(void)
{
	thinker_t   *th;
	mqueue_t    spawnqueue;
	mqueue_t    anchorqueue;
	mobjqitem_t *qitem;
	INT32 i, numAnchors = 0;
1290
	mobj_t *mo;
Alam Ed Arias committed
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303

	M_QueueInit(&spawnqueue);
	M_QueueInit(&anchorqueue);

	// get rid of values from previous level
	// note: as with msecnodes, it is very important to clear out the blockmap
	// node freelist, otherwise it may contain dangling pointers to old objects
	PolyObjects    = NULL;
	numPolyObjects = 0;
	bmap_freelist  = NULL;

	// run down the thinker list, count the number of spawn points, and save
	// the mobj_t pointers on a queue for use below.
1304
	for (th = thlist[THINK_MOBJ].next; th != &thlist[THINK_MOBJ]; th = th->next)
Alam Ed Arias committed
1305
	{
1306 1307 1308
		if (th->function.acp1 == (actionf_p1)P_RemoveThinkerDelayed)
			continue;

1309
		mo = (mobj_t *)th;
Alam Ed Arias committed
1310

1311
		if (mo->info->doomednum == POLYOBJ_SPAWN_DOOMEDNUM)
1312 1313
		{
			++numPolyObjects;
Alam Ed Arias committed
1314

1315 1316 1317 1318 1319 1320 1321 1322
			qitem = malloc(sizeof(mobjqitem_t));
			memset(qitem, 0, sizeof(mobjqitem_t));
			qitem->mo = mo;
			M_QueueInsert(&(qitem->mqitem), &spawnqueue);
		}
		else if (mo->info->doomednum == POLYOBJ_ANCHOR_DOOMEDNUM)
		{
			++numAnchors;
Alam Ed Arias committed
1323

1324 1325 1326 1327
			qitem = malloc(sizeof(mobjqitem_t));
			memset(qitem, 0, sizeof(mobjqitem_t));
			qitem->mo = mo;
			M_QueueInsert(&(qitem->mqitem), &anchorqueue);
Alam Ed Arias committed
1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
		}
	}

	if (numPolyObjects)
	{
		// allocate the PolyObjects array
		PolyObjects = Z_Calloc(numPolyObjects * sizeof(polyobj_t),
													PU_LEVEL, NULL);

		// setup hash fields
		for (i = 0; i < numPolyObjects; ++i)
			PolyObjects[i].first = PolyObjects[i].next = numPolyObjects;

		// setup polyobjects
		for (i = 0; i < numPolyObjects; ++i)
		{
			qitem = (mobjqitem_t *)M_QueueIterator(&spawnqueue);

1346
			Polyobj_spawnPolyObj(i, qitem->mo, Tag_FGet(&qitem->mo->spawnpoint->tags));
Alam Ed Arias committed
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
		}

		// move polyobjects to spawn points
		for (i = 0; i < numAnchors; ++i)
		{
			qitem = (mobjqitem_t *)M_QueueIterator(&anchorqueue);

			Polyobj_moveToSpawnSpot((qitem->mo->spawnpoint));
		}

		// setup polyobject clipping
		for (i = 0; i < numPolyObjects; ++i)
			Polyobj_linkToBlockmap(&PolyObjects[i]);
	}

#if 0
	// haleyjd 02/22/06: temporary debug
	printf("DEBUG: numPolyObjects = %d\n", numPolyObjects);
	for (i = 0; i < numPolyObjects; ++i)
	{
		INT32 j;
		polyobj_t *po = &PolyObjects[i];

		printf("polyobj %d:\n", i);
		printf("id = %d, first = %d, next = %d\n", po->id, po->first, po->next);
		printf("segCount = %d, numSegsAlloc = %d\n", po->segCount, po->numSegsAlloc);
		for (j = 0; j < po->segCount; ++j)
			printf("\tseg %d: %p\n", j, po->segs[j]);
		printf("numVertices = %d, numVerticesAlloc = %d\n", po->numVertices, po->numVerticesAlloc);
		for (j = 0; j < po->numVertices; ++j)
		{
			printf("\tvtx %d: (%d, %d) / orig: (%d, %d)\n",
				j, po->vertices[j]->x>>FRACBITS, po->vertices[j]->y>>FRACBITS,
				po->origVerts[j].x>>FRACBITS, po->origVerts[j].y>>FRACBITS);
		}
		printf("numLines = %d, numLinesAlloc = %d\n", po->numLines, po->numLinesAlloc);
		for (j = 0; j < po->numLines; ++j)
			printf("\tline %d: %p\n", j, po->lines[j]);
		printf("spawnSpot = (%d, %d)\n", po->spawnSpot.x >> FRACBITS, po->spawnSpot.y >> FRACBITS);
		printf("centerPt = (%d, %d)\n", po->centerPt.x >> FRACBITS, po->centerPt.y >> FRACBITS);
		printf("attached = %d, linked = %d, validcount = %d, isBad = %d\n",
			po->attached, po->linked, po->validcount, po->isBad);
		printf("blockbox: [%d, %d, %d, %d]\n",
			po->blockbox[BOXLEFT], po->blockbox[BOXRIGHT], po->blockbox[BOXBOTTOM],
			po->blockbox[BOXTOP]);
	}
#endif

	// done with mobj queues
	M_QueueFree(&spawnqueue);
	M_QueueFree(&anchorqueue);
}

// Called when a savegame is being loaded. Rotates and translates an
// existing polyobject to its position when the game was saved.
//
1403 1404 1405 1406
// Monster Iestyn 05/04/19: Please do not interact with mobjs! You
// can cause I_Error crashes that way, and all the important mobjs are
// going to be deleted afterwards anyway.
//
Alam Ed Arias committed
1407 1408 1409 1410 1411
void Polyobj_MoveOnLoad(polyobj_t *po, angle_t angle, fixed_t x, fixed_t y)
{
	fixed_t dx, dy;

	// first, rotate to the saved angle
1412
	Polyobj_rotate(po, angle, false, false);
Alam Ed Arias committed
1413 1414 1415 1416 1417 1418

	// determine component distances to translate
	dx = x - po->spawnSpot.x;
	dy = y - po->spawnSpot.y;

	// translate
1419
	Polyobj_moveXY(po, dx, dy, false);
Alam Ed Arias committed
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
}

// Thinker Functions

// Thinker function for PolyObject rotation.
void T_PolyObjRotate(polyrotate_t *th)
{
	polyobj_t *po = Polyobj_GetForNum(th->polyObjNum);

	if (!po)
#ifdef RANGECHECK
		I_Error("T_PolyObjRotate: thinker has invalid id %d\n", th->polyObjNum);
#else
	{
		CONS_Debug(DBG_POLYOBJ, "T_PolyObjRotate: thinker with invalid id %d removed.\n", th->polyObjNum);
1435
		P_RemoveThinker(&th->thinker);
Alam Ed Arias committed
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
		return;
	}
#endif

	// check for displacement due to override and reattach when possible
	if (po->thinker == NULL)
	{
		po->thinker = &th->thinker;

		// reset polyobject's thrust
		po->thrust = abs(th->speed) >> 8;
		if (po->thrust < FRACUNIT)
			po->thrust = FRACUNIT;
		else if (po->thrust > 4*FRACUNIT)
			po->thrust = 4*FRACUNIT;
	}

	// rotate by 'speed' angle per frame
	// if distance == -1, this polyobject rotates perpetually
1455
	if (Polyobj_rotate(po, th->speed, th->turnobjs, true) && th->distance != -1)
Alam Ed Arias committed
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
	{
		INT32 avel = abs(th->speed);

		// decrement distance by the amount it moved
		th->distance -= avel;

		// are we at or past the destination?
		if (th->distance <= 0)
		{
			// remove thinker
			if (po->thinker == &th->thinker)
			{
				po->thinker = NULL;
				po->thrust = FRACUNIT;
			}
			P_RemoveThinker(&th->thinker);

			// TODO: notify scripts
			// TODO: sound sequence stop event
		}
		else if (th->distance < avel)
		{
			// we have less than one multiple of 'speed' left to go,
			// so change the speed so that it doesn't pass the destination
			th->speed = th->speed >= 0 ? th->distance : -th->distance;
		}
	}
}

// Calculates the speed components from the desired resultant velocity.
FUNCINLINE static ATTRINLINE void Polyobj_componentSpeed(INT32 resVel, INT32 angle,
                                            fixed_t *xVel, fixed_t *yVel)
{
Alam Ed Arias committed
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
	if (angle == 0)
	{
		*xVel = resVel;
		*yVel = 0;
	}
	else if (angle == (INT32)(ANGLE_90>>ANGLETOFINESHIFT))
	{
		*xVel = 0;
		*yVel = resVel;
	}
	else
	{
		*xVel = FixedMul(resVel, FINECOSINE(angle));
		*yVel = FixedMul(resVel,   FINESINE(angle));
	}
Alam Ed Arias committed
1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
}

void T_PolyObjMove(polymove_t *th)
{
	polyobj_t *po = Polyobj_GetForNum(th->polyObjNum);

	if (!po)
#ifdef RANGECHECK
		I_Error("T_PolyObjMove: thinker has invalid id %d\n", th->polyObjNum);
#else
	{
		CONS_Debug(DBG_POLYOBJ, "T_PolyObjMove: thinker with invalid id %d removed.\n", th->polyObjNum);
1516
		P_RemoveThinker(&th->thinker);
Alam Ed Arias committed
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
		return;
	}
#endif

	// check for displacement due to override and reattach when possible
	if (po->thinker == NULL)
	{
		po->thinker = &th->thinker;

		// reset polyobject's thrust
		po->thrust = abs(th->speed) >> 3;
		if (po->thrust < FRACUNIT)
			po->thrust = FRACUNIT;
		else if (po->thrust > 4*FRACUNIT)
			po->thrust = 4*FRACUNIT;
	}

	// move the polyobject one step along its movement angle
1535
	if (Polyobj_moveXY(po, th->momx, th->momy, true))
Alam Ed Arias committed
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
	{
		INT32 avel = abs(th->speed);

		// decrement distance by the amount it moved
		th->distance -= avel;

		// are we at or past the destination?
		if (th->distance <= 0)
		{
			// remove thinker
			if (po->thinker == &th->thinker)
			{
				po->thinker = NULL;
				po->thrust = FRACUNIT;
			}
			P_RemoveThinker(&th->thinker);

			// TODO: notify scripts
			// TODO: sound sequence stop event
		}
		else if (th->distance < avel)
		{
			// we have less than one multiple of 'speed' left to go,
			// so change the speed so that it doesn't pass the destination
			th->speed = th->speed >= 0 ? th->distance : -th->distance;
			Polyobj_componentSpeed(th->speed, th->angle, &th->momx, &th->momy);
		}
	}
}

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
static void T_MovePolyObj(polyobj_t *po, fixed_t distx, fixed_t disty, fixed_t distz)
{
	polyobj_t *child;
	INT32 start;

	Polyobj_moveXY(po, distx, disty, true);
	// TODO: use T_MovePlane
	po->lines[0]->backsector->floorheight += distz;
	po->lines[0]->backsector->ceilingheight += distz;
	// Sal: Remember to check your sectors!
	// Monster Iestyn: we only need to bother with the back sector, now that P_CheckSector automatically checks the blockmap
	//  updating objects in the front one too just added teleporting to ground bugs
	P_CheckSector(po->lines[0]->backsector, (boolean)(po->damage));
	// Apply action to mirroring polyobjects as well
	start = 0;
	while ((child = Polyobj_GetChild(po, &start)))
	{
		if (child->isBad)
			continue;

		Polyobj_moveXY(child, distx, disty, true);
		// TODO: use T_MovePlane
		child->lines[0]->backsector->floorheight += distz;
		child->lines[0]->backsector->ceilingheight += distz;
		P_CheckSector(child->lines[0]->backsector, (boolean)(child->damage));
	}
}

Alam Ed Arias committed
1594 1595 1596 1597
void T_PolyObjWaypoint(polywaypoint_t *th)
{
	mobj_t *target = NULL;
	polyobj_t *po = Polyobj_GetForNum(th->polyObjNum);
1598
	fixed_t speed = th->speed;
Alam Ed Arias committed
1599 1600 1601 1602 1603 1604 1605

	if (!po)
#ifdef RANGECHECK
		I_Error("T_PolyObjWaypoint: thinker has invalid id %d\n", th->polyObjNum);
#else
	{
		CONS_Debug(DBG_POLYOBJ, "T_PolyObjWaypoint: thinker with invalid id %d removed.", th->polyObjNum);
1606
		P_RemoveThinker(&th->thinker);
Alam Ed Arias committed
1607 1608 1609 1610 1611
		return;
	}
#endif

	// check for displacement due to override and reattach when possible
1612
	if (!po->thinker)
Alam Ed Arias committed
1613 1614
		po->thinker = &th->thinker;

1615
	target = waypoints[th->sequence][th->pointnum];
Alam Ed Arias committed
1616 1617 1618 1619 1620 1621 1622

	if (!target)
	{
		CONS_Debug(DBG_POLYOBJ, "T_PolyObjWaypoint: Unable to find target waypoint!\n");
		return;
	}

1623 1624
	// Move along the waypoint sequence until speed for the current tic is exhausted
	while (speed > 0)
Alam Ed Arias committed
1625
	{
1626 1627 1628
		mobj_t *waypoint = NULL;
		fixed_t pox, poy, poz;
		fixed_t distx, disty, distz, dist;
Alam Ed Arias committed
1629

1630 1631 1632 1633
		// Current position of polyobject
		pox = po->centerPt.x;
		poy = po->centerPt.y;
		poz = (po->lines[0]->backsector->floorheight + po->lines[0]->backsector->ceilingheight)/2;
Alam Ed Arias committed
1634

1635 1636 1637 1638
		// Calculate the distance between the polyobject and the waypoint
		distx = target->x - pox;
		disty = target->y - poy;
		distz = target->z - poz;
1639
		dist = P_AproxDistance(P_AproxDistance(distx, disty), distz);
Alam Ed Arias committed
1640

1641 1642
		if (dist < 1)
			dist = 1;
Alam Ed Arias committed
1643

1644
		// Will the polyobject overshoot its target?
1645
		if (speed < dist)
Alam Ed Arias committed
1646
		{
1647 1648
			// No. Move towards waypoint
			fixed_t momx, momy, momz;
Alam Ed Arias committed
1649

1650 1651 1652 1653 1654
			momx = FixedMul(FixedDiv(target->x - pox, dist), speed);
			momy = FixedMul(FixedDiv(target->y - poy, dist), speed);
			momz = FixedMul(FixedDiv(target->z - poz, dist), speed);
			T_MovePolyObj(po, momx, momy, momz);
			return;
Alam Ed Arias committed
1655
		}
1656
		else
Alam Ed Arias committed
1657
		{
1658 1659
			// Yes. Teleport to waypoint and look for the next one
			T_MovePolyObj(po, distx, disty, distz);
Alam Ed Arias committed
1660

1661
			if (!th->stophere)
Alam Ed Arias committed
1662
			{
1663 1664
				CONS_Debug(DBG_POLYOBJ, "Looking for next waypoint...\n");
				waypoint = (th->direction == -1) ? P_GetPreviousWaypoint(target, false) : P_GetNextWaypoint(target, false);
Alam Ed Arias committed
1665

1666
				if (!waypoint && th->returnbehavior == PWR_WRAP) // If specified, wrap waypoints
1667
				{
1668
					if (!th->continuous)
Alam Ed Arias committed
1669
					{
1670 1671
						th->returnbehavior = PWR_STOP;
						th->stophere = true;
Alam Ed Arias committed
1672 1673
					}

1674
					waypoint = (th->direction == -1) ? P_GetLastWaypoint(th->sequence) : P_GetFirstWaypoint(th->sequence);
Alam Ed Arias committed
1675
				}
1676
				else if (!waypoint && th->returnbehavior == PWR_COMEBACK) // Come back to the start
Alam Ed Arias committed
1677
				{
1678
					th->direction = -th->direction;
1679

1680 1681
					if (!th->continuous)
						th->returnbehavior = PWR_STOP;
Alam Ed Arias committed
1682

1683
					waypoint = (th->direction == -1) ? P_GetPreviousWaypoint(target, false) : P_GetNextWaypoint(target, false);
Alam Ed Arias committed
1684 1685 1686
				}
			}

1687 1688 1689
			if (waypoint)
			{
				CONS_Debug(DBG_POLYOBJ, "Found waypoint (sequence %d, number %d).\n", waypoint->threshold, waypoint->health);
Alam Ed Arias committed
1690

1691 1692
				target = waypoint;
				th->pointnum = target->health;
1693

1694 1695
				// Calculate remaining speed
				speed -= dist;
Alam Ed Arias committed
1696
			}
1697 1698 1699 1700
			else
			{
				if (!th->stophere)
					CONS_Debug(DBG_POLYOBJ, "Next waypoint not found!\n");
Alam Ed Arias committed
1701

1702 1703
				if (po->thinker == &th->thinker)
					po->thinker = NULL;
Alam Ed Arias committed
1704

1705 1706 1707
				P_RemoveThinker(&th->thinker);
				return;
			}
Alam Ed Arias committed
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
		}
	}
}

void T_PolyDoorSlide(polyslidedoor_t *th)
{
	polyobj_t *po = Polyobj_GetForNum(th->polyObjNum);

	if (!po)
#ifdef RANGECHECK
		I_Error("T_PolyDoorSlide: thinker has invalid id %d\n", th->polyObjNum);
#else
	{
		CONS_Debug(DBG_POLYOBJ, "T_PolyDoorSlide: thinker with invalid id %d removed.\n", th->polyObjNum);
1722
		P_RemoveThinker(&th->thinker);
Alam Ed Arias committed
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750
		return;
	}
#endif

	// check for displacement due to override and reattach when possible
	if (po->thinker == NULL)
	{
		po->thinker = &th->thinker;

		// reset polyobject's thrust
		po->thrust = abs(th->speed) >> 3;
		if (po->thrust < FRACUNIT)
			po->thrust = FRACUNIT;
		else if (po->thrust > 4*FRACUNIT)
			po->thrust = 4*FRACUNIT;
	}

	// count down wait period
	if (th->delayCount)
	{
		if (--th->delayCount == 0)
		{
			; // TODO: start sound sequence event
		}
		return;
	}

	// move the polyobject one step along its movement angle
1751
	if (Polyobj_moveXY(po, th->momx, th->momy, true))
Alam Ed Arias committed
1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
	{
		INT32 avel = abs(th->speed);

		// decrement distance by the amount it moved
		th->distance -= avel;


		// are we at or past the destination?
		if (th->distance <= 0)
		{
			// does it need to close?
			if (!th->closing)
			{
				th->closing = true;

				// reset distance and speed
				th->distance = th->initDistance;
				th->speed    = th->initSpeed;

				// start delay
				th->delayCount = th->delay;

				// reverse angle
				th->angle = th->revAngle;

				// reset component speeds
				Polyobj_componentSpeed(th->speed, th->angle, &th->momx, &th->momy);
			}
			else
			{
				// remove thinker
				if (po->thinker == &th->thinker)
				{
					po->thinker = NULL;
					po->thrust = FRACUNIT;
				}
				P_RemoveThinker(&th->thinker);
				// TODO: notify scripts
			}
			// TODO: sound sequence stop event
		}
		else if (th->distance < avel)
		{
			// we have less than one multiple of 'speed' left to go,
			// so change the speed so that it doesn't pass the
			// destination
			th->speed = th->speed >= 0
				? th->distance : -th->distance;
			Polyobj_componentSpeed(th->speed, th->angle,
				&th->momx, &th->momy);
		}
	}
	else if (th->closing && th->distance != th->initDistance)
	{
		// move was blocked, special handling required -- make it reopen
		th->distance = th->initDistance - th->distance;
		th->speed    = th->initSpeed;
		th->angle    = th->initAngle;
		Polyobj_componentSpeed(th->speed, th->angle,
			&th->momx, &th->momy);
		th->closing  = false;
		// TODO: sound sequence start event
	}
}

void T_PolyDoorSwing(polyswingdoor_t *th)
{
	polyobj_t *po = Polyobj_GetForNum(th->polyObjNum);

	if (!po)
#ifdef RANGECHECK
		I_Error("T_PolyDoorSwing: thinker has invalid id %d\n", th->polyObjNum);
#else
	{
		CONS_Debug(DBG_POLYOBJ, "T_PolyDoorSwing: thinker with invalid id %d removed.\n", th->polyObjNum);
1827
		P_RemoveThinker(&th->thinker);
Alam Ed Arias committed
1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856
		return;
	}
#endif

	// check for displacement due to override and reattach when possible
	if (po->thinker == NULL)
	{
		po->thinker = &th->thinker;

		// reset polyobject's thrust
		po->thrust = abs(th->speed) >> 3;
		if (po->thrust < FRACUNIT)
			po->thrust = FRACUNIT;
		else if (po->thrust > 4*FRACUNIT)
			po->thrust = 4*FRACUNIT;
	}

	// count down wait period
	if (th->delayCount)
	{
		if (--th->delayCount == 0)
		{
			; // TODO: start sound sequence event
		}
		return;
	}

	// rotate by 'speed' angle per frame
	// if distance == -1, this polyobject rotates perpetually
1857
	if (Polyobj_rotate(po, th->speed, false, true) && th->distance != -1)
Alam Ed Arias committed
1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
	{
		INT32 avel = abs(th->speed);

		// decrement distance by the amount it moved
		th->distance -= avel;

		// are we at or past the destination?
		if (th->distance <= 0)
		{
			// does it need to close?
			if (!th->closing)
			{
				th->closing = true;

				// reset distance and speed
				th->distance =  th->initDistance;
				th->speed    = -th->initSpeed; // reverse speed on close

				// start delay
				th->delayCount = th->delay;
			}
			else
			{
				// remove thinker
				if (po->thinker == &th->thinker)
				{
					po->thinker = NULL;
					po->thrust = FRACUNIT;
				}
				P_RemoveThinker(&th->thinker);
				// TODO: notify scripts
			}
			// TODO: sound sequence stop event
		}
		else if (th->distance < avel)
		{
			// we have less than one multiple of 'speed' left to go,
			// so change the speed so that it doesn't pass the
			// destination
			th->speed = th->speed >= 0
				? th->distance : -th->distance;
		}
	}
	else if (th->closing && th->distance != th->initDistance)
	{
		// move was blocked, special handling required -- make it reopen

		th->distance = th->initDistance - th->distance;
		th->speed    = th->initSpeed;
		th->closing  = false;

		// TODO: sound sequence start event
	}
}

1913
// Shift a polyobject based on a control sector's heights.
Alam Ed Arias committed
1914 1915 1916 1917 1918 1919 1920 1921
void T_PolyObjDisplace(polydisplace_t *th)
{
	polyobj_t *po = Polyobj_GetForNum(th->polyObjNum);
	fixed_t newheights, delta;
	fixed_t dx, dy;

	if (!po)
#ifdef RANGECHECK
1922
		I_Error("T_PolyObjDisplace: thinker has invalid id %d\n", th->polyObjNum);
Alam Ed Arias committed
1923 1924
#else
	{
1925
		CONS_Debug(DBG_POLYOBJ, "T_PolyObjDisplace: thinker with invalid id %d removed.\n", th->polyObjNum);
1926
		P_RemoveThinker(&th->thinker);
Alam Ed Arias committed
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
		return;
	}
#endif

	// check for displacement due to override and reattach when possible
	if (po->thinker == NULL)
	{
		po->thinker = &th->thinker;

		// reset polyobject's thrust
		po->thrust = FRACUNIT;
	}

	newheights = th->controlSector->floorheight+th->controlSector->ceilingheight;
	delta = newheights-th->oldHeights;

	if (!delta)
		return;

	dx = FixedMul(th->dx, delta);
	dy = FixedMul(th->dy, delta);

1949
	if (Polyobj_moveXY(po, dx, dy, true))
Alam Ed Arias committed
1950 1951 1952
		th->oldHeights = newheights;
}

1953
// Rotate a polyobject based on a control sector's heights.
1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
void T_PolyObjRotDisplace(polyrotdisplace_t *th)
{
	polyobj_t *po = Polyobj_GetForNum(th->polyObjNum);
	fixed_t newheights, delta;
	fixed_t rotangle;

	if (!po)
#ifdef RANGECHECK
		I_Error("T_PolyObjRotDisplace: thinker has invalid id %d\n", th->polyObjNum);
#else
	{
		CONS_Debug(DBG_POLYOBJ, "T_PolyObjRotDisplace: thinker with invalid id %d removed.\n", th->polyObjNum);
1966
		P_RemoveThinker(&th->thinker);
1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987
		return;
	}
#endif

	// check for displacement due to override and reattach when possible
	if (po->thinker == NULL)
	{
		po->thinker = &th->thinker;

		// reset polyobject's thrust
		po->thrust = FRACUNIT;
	}

	newheights = th->controlSector->floorheight+th->controlSector->ceilingheight;
	delta = newheights-th->oldHeights;

	if (!delta)
		return;

	rotangle = FixedMul(th->rotscale, delta);

1988
	if (Polyobj_rotate(po, FixedAngle(rotangle), th->turnobjs, true))
1989 1990 1991
		th->oldHeights = newheights;
}

Alam Ed Arias committed
1992 1993 1994 1995 1996 1997 1998
static inline INT32 Polyobj_AngSpeed(INT32 speed)
{
	return (speed*ANG1)>>3; // no FixedAngle()
}

// Linedef Handlers

1999
boolean EV_DoPolyObjRotate(polyrotdata_t *prdata)
Alam Ed Arias committed
2000 2001 2002 2003 2004 2005 2006 2007 2008
{
	polyobj_t *po;
	polyobj_t *oldpo;
	polyrotate_t *th;
	INT32 start;

	if (!(po = Polyobj_GetForNum(prdata->polyObjNum)))
	{
		CONS_Debug(DBG_POLYOBJ, "EV_DoPolyObjRotate: bad polyobj %d\n", prdata->polyObjNum);
2009
		return false;
Alam Ed Arias committed
2010 2011 2012 2013
	}

	// don't allow line actions to affect bad polyobjects
	if (po->isBad)
2014
		return false;
Alam Ed Arias committed
2015 2016 2017

	// check for override if this polyobj already has a thinker
	if (po->thinker && !prdata->overRide)
2018
		return false;
Alam Ed Arias committed
2019 2020 2021 2022

	// create a new thinker
	th = Z_Malloc(sizeof(polyrotate_t), PU_LEVSPEC, NULL);
	th->thinker.function.acp1 = (actionf_p1)T_PolyObjRotate;
2023
	P_AddThinker(THINK_POLYOBJ, &th->thinker);
Alam Ed Arias committed
2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049
	po->thinker = &th->thinker;

	// set fields
	th->polyObjNum = prdata->polyObjNum;

	// use Hexen-style byte angles for speed and distance
	th->speed = Polyobj_AngSpeed(prdata->speed * prdata->direction);

	if (prdata->distance == 360)    // 360 means perpetual
		th->distance = -1;
	else if (prdata->distance == 0) // 0 means 360 degrees
		th->distance = 0xffffffff - 1;
	else
		th->distance = FixedAngle(prdata->distance*FRACUNIT);

	// set polyobject's thrust
	po->thrust = abs(th->speed) >> 8;
	if (po->thrust < FRACUNIT)
		po->thrust = FRACUNIT;
	else if (po->thrust > 4*FRACUNIT)
		po->thrust = 4*FRACUNIT;

	// TODO: start sound sequence event

	oldpo = po;

Alam Ed Arias committed
2050 2051
	th->turnobjs = prdata->turnobjs;

Alam Ed Arias committed
2052 2053 2054
	// apply action to mirroring polyobjects as well
	start = 0;
	while ((po = Polyobj_GetChild(oldpo, &start)))
Alam Ed Arias committed
2055 2056
	{
		prdata->polyObjNum = po->id; // change id to match child polyobject's
Alam Ed Arias committed
2057
		EV_DoPolyObjRotate(prdata);
Alam Ed Arias committed
2058
	}
Alam Ed Arias committed
2059 2060

	// action was successful
2061
	return true;
Alam Ed Arias committed
2062 2063
}

2064
boolean EV_DoPolyObjMove(polymovedata_t *pmdata)
Alam Ed Arias committed
2065 2066 2067 2068 2069 2070 2071 2072 2073
{
	polyobj_t *po;
	polyobj_t *oldpo;
	polymove_t *th;
	INT32 start;

	if (!(po = Polyobj_GetForNum(pmdata->polyObjNum)))
	{
		CONS_Debug(DBG_POLYOBJ, "EV_DoPolyObjMove: bad polyobj %d\n", pmdata->polyObjNum);
2074
		return false;
Alam Ed Arias committed
2075 2076 2077 2078
	}

	// don't allow line actions to affect bad polyobjects
	if (po->isBad)
2079
		return false;