shithub: nanobsp

ref: dcd0398ab4aad2103d4ab3eca677850087bc28c0
dir: /nano_bsp.c/

View raw version
//----------------------------------------------------------------------------
//
//  Copyright (c) 2023  Andrew Apted
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  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 General Public License for more details.
//
//----------------------------------------------------------------------------

#include "i_system.h"

#include <stdlib.h>
#include <assert.h>

#include "doomtype.h"
#include "doomstat.h"
#include "d_ticcmd.h"
#include "d_event.h"
#include "m_fixed.h"
#include "m_bbox.h"
#include "m_misc.h"
#include "m_random.h"
#include "z_zone.h"

#include "p_local.h"
#include "p_mobj.h"

#include "nano_bsp.h"


#define DIST_EPSILON  (FRACUNIT / 64)

#define FAST_THRESHOLD  64


#undef MAX
#define MAX(a, b)  ((a) > (b) ? (a) : (b))

#undef MIN
#define MIN(a, b)  ((a) < (b) ? (a) : (b))


vertex_t * BSP_NewVertex (fixed_t x, fixed_t y)
{
	vertex_t * vert = Z_Malloc(sizeof(vertex_t), PU_LEVEL, NULL);
	vert->x = x;
	vert->y = y;
	return vert;
}

seg_t * BSP_NewSeg (void)
{
	seg_t * seg = Z_Malloc (sizeof(seg_t), PU_LEVEL, NULL);
	memset (seg, 0, sizeof(*seg));
	return seg;
}

subsector_t * BSP_NewSubsector (void)
{
	subsector_t * sub = Z_Malloc (sizeof(subsector_t), PU_LEVEL, NULL);
	memset (sub, 0, sizeof(*sub));
	return sub;
}

node_t * BSP_NewNode (void)
{
	node_t * node = Z_Malloc (sizeof(node_t), PU_LEVEL, NULL);
	memset (node, 0, sizeof(*node));
	return node;
}

//----------------------------------------------------------------------------

void BSP_SegForLineSide (int i, int side, seg_t ** list_var)
{
	line_t * ld = &lines[i];

	if (ld->sidenum[side] < 0)
		return;

	// create the seg
	seg_t * seg = BSP_NewSeg ();

	seg->v1 = side ? ld->v2 : ld->v1;
	seg->v2 = side ? ld->v1 : ld->v2;

	seg->offset = 0;
	seg->angle  = R_PointToAngle2 (seg->v1->x, seg->v1->y, seg->v2->x, seg->v2->y);

	seg->sidedef = &sides[ld->sidenum[side]];
	seg->linedef = ld;

	seg->frontsector = side ? ld->backsector  : ld->frontsector;
	seg->backsector  = side ? ld->frontsector : ld->backsector;

	// link into the list
	seg->next   = (*list_var);
	(*list_var) = seg;
}

seg_t * BSP_CreateSegs (void)
{
	seg_t * list = NULL;

	int i;
	for (i = 0 ; i < numlines ; i++)
	{
		BSP_SegForLineSide (i, 0, &list);
		BSP_SegForLineSide (i, 1, &list);
	}

	return list;
}

node_t * BSP_CreateLeaf (seg_t * soup)
{
	subsector_t * sub  = BSP_NewSubsector ();
	node_t      * node = BSP_NewNode ();

	sub->segs = soup;

	// TODO: better method, try to avoid self-ref lines
	sub->sector = soup->frontsector;

	node->sub = sub;
	return node;
}

//----------------------------------------------------------------------------

struct NodeEval
{
	int left, right, split;
};

int BSP_PointOnSide (seg_t * part, fixed_t x, fixed_t y)
{
	x -= part->v1->x;
	y -= part->v1->y;

	fixed_t	dx = part->v2->x - part->v1->x;
	fixed_t	dy = part->v2->y - part->v1->y;

	if (dx == 0)
	{
		if (x < - DIST_EPSILON)
			return (dy < 0) ? +1 : -1;

		if (x > + DIST_EPSILON)
			return (dy > 0) ? +1 : -1;

		return 0;
	}

	if (dy == 0)
	{
		if (y < - DIST_EPSILON)
			return (dx > 0) ? +1 : -1;

		if (y > + DIST_EPSILON)
			return (dx < 0) ? +1 : -1;

		return 0;
	}

	// note that we compute the distance to the partition along an axis
	// (rather than perpendicular to it), which can give values smaller
	// than the true distance.  for our purposes, that is okay.

	if (abs (dx) >= abs (dy))
	{
		fixed_t slope = FixedDiv (dy, dx);

		y -= FixedMul (x, slope);

		if (y < - DIST_EPSILON)
			return (dx > 0) ? +1 : -1;

		if (y > + DIST_EPSILON)
			return (dx < 0) ? +1 : -1;
	}
	else
	{
		fixed_t slope = FixedDiv (dx, dy);

		x -= FixedMul (y, slope);

		if (x < - DIST_EPSILON)
			return (dy < 0) ? +1 : -1;

		if (x > + DIST_EPSILON)
			return (dy > 0) ? +1 : -1;
	}

	return 0;
}

boolean BSP_SameDirection (seg_t * part, seg_t * seg)
{
	fixed_t	pdx = part->v2->x - part->v1->x;
	fixed_t	pdy = part->v2->y - part->v1->y;

	fixed_t sdx = seg->v2->x - seg->v1->x;
	fixed_t sdy = seg->v2->y - seg->v1->y;

	int64_t n = (int64_t)sdx * (int64_t)pdx + (int64_t)sdy * (int64_t)pdy;

	return (n > 0);
}

int BSP_SegOnSide (seg_t * part, seg_t * seg)
{
	int side1 = BSP_PointOnSide (part, seg->v1->x, seg->v1->y);
	int side2 = BSP_PointOnSide (part, seg->v2->x, seg->v2->y);

	// colinear?
	if (side1 == 0 && side2 == 0)
		return BSP_SameDirection (part, seg) ? +1 : -1;

	// splits the seg?
	if ((side1 *= side2) < 0)
		return 0;

	return (side1 >= 0 && side2 >= 0) ? +1 : -1;
}

void BSP_BoundingBox (seg_t * soup, fixed_t * bbox)
{
	bbox[BOXLEFT]   = INT_MAX;
	bbox[BOXBOTTOM] = INT_MAX;
	bbox[BOXRIGHT]  = INT_MIN;
	bbox[BOXTOP]    = INT_MIN;

	seg_t * S;
	for (S = soup ; S != NULL ; S = S->next)
	{
		M_AddToBox (bbox, S->v1->x, S->v1->y);
		M_AddToBox (bbox, S->v2->x, S->v2->y);
	}
}

//
// Evaluate a seg as a partition candidate, storing the results in `eval`.
// returns true if the partition is viable, false otherwise.
//
boolean BSP_EvalPartition (seg_t * part, seg_t * soup, struct NodeEval * eval)
{
	eval->left  = 0;
	eval->right = 0;
	eval->split = 0;

	seg_t * S;
	for (S = soup ; S != NULL ; S = S->next)
	{
		if (S == part)
			continue;

		switch (BSP_SegOnSide (part, S))
		{
			case  0: eval->split += 1; break;
			case -1: eval->left  += 1; break;
			case +1: eval->right += 1; break;
		}
	}

	// a viable partition either splits something, or has other segs
	// lying on both the left and right sides.

	if (eval->split == 0 && (eval->left == 0 || eval->right == 0))
		return false;

	return true;
}

//
// Look for an axis-aligned seg which can divide the other segs
// in a "nice" way.  returns NULL if none found.
//
seg_t * BSP_PickNode_Fast (seg_t * soup)
{
	// use slower method when number of segs is below a threshold
	int count = 0;

	seg_t * S;
	for (S = soup ; S != NULL ; S = S->next)
		count += 1;

	if (count < FAST_THRESHOLD)
		return NULL;

	// determine bounding box of segs
	fixed_t bbox[4];

	BSP_BoundingBox (soup, bbox);

	fixed_t mid_x = bbox[BOXLEFT]   / 2 + bbox[BOXRIGHT] / 2;
	fixed_t mid_y = bbox[BOXBOTTOM] / 2 + bbox[BOXTOP]   / 2;

	seg_t * vert_part = NULL;
	fixed_t vert_dist = (1 << 30);

	seg_t * horiz_part = NULL;
	fixed_t horiz_dist = (1 << 30);

	// find the segs closest to middle of bbox
	seg_t * part;
	for (part = soup ; part != NULL ; part = part->next)
	{
		if (part->v1->x == part->v2->x)
		{
			fixed_t dist = abs (part->v1->x - mid_x);

			if (dist < vert_dist)
			{
				vert_part = part;
				vert_dist = dist;
			}
		}
		else if (part->v1->y == part->v2->y)
		{
			fixed_t dist = abs (part->v1->y - mid_y);

			if (dist < horiz_dist)
			{
				horiz_part = part;
				horiz_dist = dist;
			}
		}
	}

	// check that each partition is viable
	struct NodeEval v_eval;
	struct NodeEval h_eval;

	boolean vert_ok  = (vert_part  != NULL) && BSP_EvalPartition (vert_part,  soup, &v_eval);
	boolean horiz_ok = (horiz_part != NULL) && BSP_EvalPartition (horiz_part, soup, &h_eval);

	if (vert_ok && horiz_ok)
	{
		int vert_cost  = abs (v_eval.left - v_eval.right) * 100 + v_eval.split * 17;
		int horiz_cost = abs (h_eval.left - h_eval.right) * 100 + h_eval.split * 17;

		return (horiz_cost < vert_cost) ? horiz_part : vert_part;
	}

	if (vert_ok)  return vert_part;
	if (horiz_ok) return horiz_part;

	return NULL;
}

//
// Evaluate *every* seg in the list as a partition candidate,
// returning the best one, or NULL if none found (which means
// the remaining segs form a subsector).
//
seg_t * BSP_PickNode_Slow (seg_t * soup)
{
	seg_t * part;
	seg_t * best  = NULL;
	int best_cost = (1 << 30);

	for (part = soup ; part != NULL ; part = part->next)
	{
		struct NodeEval eval;

		if (BSP_EvalPartition (part, soup, &eval))
		{
			int cost = abs (eval.left - eval.right) * 100 + eval.split * 17;

			if (cost < best_cost)
			{
				best = part;
				best_cost = cost;
			}
		}
	}

	return best;
}

//----------------------------------------------------------------------------

fixed_t BSP_VertIntersection (fixed_t part_x, seg_t * seg)
{
	// horizontal seg?
	if (seg->v1->y == seg->v2->y)
		return seg->v1->y;

	fixed_t a = abs (seg->v1->x - part_x);
	fixed_t b = abs (seg->v2->x - part_x);

	fixed_t along = FixedDiv (a, a + b);

	return seg->v1->y + FixedMul (seg->v2->y - seg->v1->y, along);
}


fixed_t BSP_HorizIntersection (fixed_t part_y, seg_t * seg)
{
	// vertical seg?
	if (seg->v1->x == seg->v2->x)
		return seg->v1->x;

	fixed_t a = abs (seg->v1->y - part_y);
	fixed_t b = abs (seg->v2->y - part_y);

	fixed_t along = FixedDiv (a, a + b);

	return seg->v1->x + FixedMul (seg->v2->x - seg->v1->x, along);
}


void BSP_ComputeIntersection (seg_t * part, seg_t * seg, fixed_t * x, fixed_t * y)
{
	// vertical partition?
	if (part->v1->x == part->v2->x)
	{
		*x = part->v1->x;
		*y = BSP_VertIntersection (*x, seg);
		return;
	}

	// horizontal partition?
	if (part->v1->y == part->v2->y)
	{
		*y = part->v1->y;
		*x = BSP_HorizIntersection (*y, seg);
		return;
	}

	fixed_t	dx = part->v2->x - part->v1->x;
	fixed_t	dy = part->v2->y - part->v1->y;

	// compute seg coords relative to partition start
	fixed_t x1 = seg->v1->x - part->v1->x;
	fixed_t y1 = seg->v1->y - part->v1->y;

	fixed_t x2 = seg->v2->x - part->v2->x;
	fixed_t y2 = seg->v2->y - part->v2->y;

	fixed_t a, b;

	if (abs (dx) >= abs(dy))
	{
		fixed_t slope = FixedDiv (dy, dx);

		a = abs (y1 - FixedMul (x1, slope));
		b = abs (y2 - FixedMul (x2, slope));
	}
	else
	{
		fixed_t slope = FixedDiv (dx, dy);

		a = abs (x1 - FixedMul (y1, slope));
		b = abs (x2 - FixedMul (y2, slope));
	}

	fixed_t along = FixedDiv (a, a + b);

	if (seg->v1->x == seg->v2->x)
		*x = seg->v1->x;
	else
		*x = seg->v1->x + FixedMul (seg->v2->x - seg->v1->x, along);

	if (seg->v1->y == seg->v2->y)
		*y = seg->v1->y;
	else
		*y = seg->v1->y + FixedMul (seg->v2->y - seg->v1->y, along);
}


//
// For segs not intersecting the partition, just move them into the
// correct output list (`lefts` or `rights`).  otherwise split the seg
// at the intersection point, one pieces goes left, the other right.
//
void BSP_SplitSegs (seg_t * part, seg_t * soup, seg_t ** lefts, seg_t ** rights)
{
	while (soup != NULL)
	{
		seg_t * S = soup;
		soup = soup->next;

		int where = BSP_SegOnSide (part, S);

		if (where < 0)
		{
			S->next  = (*lefts);
			(*lefts) = S;
			continue;
		}

		if (where > 0)
		{
			S->next   = (*rights);
			(*rights) = S;
			continue;
		}

		// we must split this seg
		fixed_t ix, iy;

		BSP_ComputeIntersection (part, S, &ix, &iy);

		vertex_t * iv = BSP_NewVertex (ix, iy);

		seg_t * T = BSP_NewSeg ();

		T->v2 = S->v2;
		T->v1 = iv;
		S->v2 = iv;

		T->angle   = S->angle;
		T->sidedef = S->sidedef;
		T->linedef = S->linedef;

		T->frontsector = S->frontsector;
		T->backsector  = S->backsector;

		// compute offset for new seg
		viewx = T->v1->x;
		viewy = T->v1->y;

		T->offset = R_PointToDist (ix, iy);

		if (BSP_PointOnSide (part, S->v1->x, S->v1->y) < 0)
		{
			S->next  = (*lefts);
			(*lefts) = S;

			T->next   = (*rights);
			(*rights) = T;
		}
		else
		{
			S->next   = (*rights);
			(*rights) = S;

			T->next  = (*lefts);
			(*lefts) = T;
		}
	}
}

node_t * BSP_SubdivideSegs (seg_t * soup)
{
	seg_t * part = BSP_PickNode_Fast (soup);

	if (part == NULL)
		part = BSP_PickNode_Slow (soup);

	if (part == NULL)
		return BSP_CreateLeaf (soup);

	node_t * N = BSP_NewNode ();

	N->x  = part->v1->x;
	N->y  = part->v1->y;
	N->dx = part->v2->x - N->x;
	N->dy = part->v2->y - N->y;

	// these are the new lists (after splitting)
	seg_t * lefts  = NULL;
	seg_t * rights = NULL;

	BSP_SplitSegs (part, soup, &lefts, &rights);

	N->right = BSP_SubdivideSegs (rights);
	N->left  = BSP_SubdivideSegs (lefts);

	return N;
}

//----------------------------------------------------------------------------

void Nano_BuildBSP (void)
{
	seg_t * list = BSP_CreateSegs ();

	root_node = BSP_SubdivideSegs (list);
}