Debian Codegraph @

Descent3/bsp.cpp

raw symbols SCIP
1 /*
2 * Descent 3
3 * Copyright (C) 2024 Parallax Software
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 --- HISTORICAL COMMENTS FOLLOW ---
19
20 * $Logfile: /DescentIII/main/bsp.cpp $
21 * $Revision: 32 $
22 * $Date: 4/19/00 10:18a $
23 * $Author: Matt $
24 *
25 * Some more of BSP tree code, I presume.
26 *
27 * $Log: /DescentIII/main/bsp.cpp $
28 *
29 * 32 4/19/00 10:18a Matt
30 * Added check for BSP tree initialized before freeing it.
31 *
32 * 31 4/21/99 11:05a Kevin
33 * new ps_rand and ps_srand to replace rand & srand
34 *
35 * 30 1/21/99 11:15p Jeff
36 * pulled out some structs and defines from header files and moved them
37 * into seperate header files so that multiplayer dlls don't require major
38 * game headers, just those new headers. Side effect is a shorter build
39 * time. Also cleaned up some header file #includes that weren't needed.
40 * This affected polymodel.h, object.h, player.h, vecmat.h, room.h,
41 * manage.h and multi.h
42 *
43 * 29 9/22/98 12:01p Matt
44 * Added SourceSafe headers
45 *
46 */
47
48 #include "bsp.h"
49 #include "room.h"
50 #include "mem.h"
51 #include "polymodel.h"
52 #include <stdlib.h>
53 #include "object.h"
54 #include "psrand.h"
55
56 #define BSP_TREE_VERSION 10003
57
58 bsptree MineBSP;
59 uint8_t BSP_initted = 0;
60 static int ConvexSubspaces = 0, ConvexPolys = 0;
61 static int Solids = 0, Empty = 0;
62
63 int BSPChecksum = -1;
64 // TODO: MTS: Only used here?
65 uint8_t UseBSP = 0;
66
67 // Goes through all the valid points in the indoor engine and returns a unique
68 // checksum
69 int BSPGetMineChecksum() {
70 int i, t, k;
71 float total = 0;
72 int checksum;
73
74 for (i = 0; i <= Highest_room_index; i++) {
75 room *rp = &Rooms[i];
76
77 if (!Rooms[i].used)
78 continue;
79
80 if (Rooms[i].flags & RF_EXTERNAL)
81 continue;
82
83 for (t = 0; t < rp->num_faces; t++) {
84 face *fp = &rp->faces[t];
85
86 for (k = 0; k < fp->num_verts; k++) {
87 total += rp->verts[fp->face_verts[k]].x;
88 total += rp->verts[fp->face_verts[k]].y;
89 total += rp->verts[fp->face_verts[k]].z;
90 }
91 }
92 }
93
94 for (t = 0; t <= Highest_object_index; t++) {
95 object *obj = &Objects[t];
96 vector vert;
97
98 if (obj->type == OBJ_NONE)
99 continue;
100
101 if (OBJECT_OUTSIDE(obj))
102 continue;
103
104 if (obj->lighting_render_type == LRT_LIGHTMAPS) {
105 poly_model *po = &Poly_models[obj->rtype.pobj_info.model_num];
106 if (!po->new_style)
107 continue;
108
109 for (k = 0; k < po->n_models; k++) {
110 bsp_info *sm = &po->submodel[k];
111
112 if (IsNonRenderableSubmodel(po, k))
113 continue;
114
115 for (int j = 0; j < sm->num_faces; j++) {
116 for (int x = 0; x < sm->faces[j].nverts; x++) {
117 GetObjectPointInWorld(&vert, obj, k, sm->faces[j].vertnums[x]);
118 total += vert.x;
119 total += vert.y;
120 total += vert.z;
121 }
122 }
123 }
124 }
125 }
126
127 checksum = total * BSP_TREE_VERSION;
128
129 return checksum;
130 }
131
132 // Allocates memory for a bspnode
133 // Returns pointer to node
134 bspnode *NewBSPNode(void) {
135 bspnode *node;
136
137 if ((node = (bspnode *)mem_malloc(sizeof(bspnode))) == NULL) {
138 return NULL;
139 }
140
141 /* Initialize the node, set its variables to zero */
142
143 node->type = BSP_NODE;
144 node->polylist = NULL;
145 node->num_polys = 0;
146 node->node_facenum = 0;
147 node->node_roomnum = 0;
148 node->node_subnum = 0;
149
150 node->plane.a = 0.0;
151 node->plane.b = 0.0;
152 node->plane.c = 0.0;
153 node->plane.d = 0.0;
154 node->front = NULL;
155 node->back = NULL;
156
157 return node;
158 }
159
160 // Allocates memory for a polygon
161 // Returns pointer to polygon
162 bsppolygon *NewPolygon(int roomnum, int facenum, int numverts) {
163 bsppolygon *newpoly;
164 vector *verts;
165
166 newpoly = (bsppolygon *)mem_malloc(sizeof(bsppolygon));
167
168 if (newpoly == NULL) {
169 mprintf(0, "NewPolygon: Couldn't allocate polygon\n");
170 return NULL;
171 }
172
173 verts = (vector *)mem_malloc(sizeof(vector) * numverts);
174 ASSERT(verts != NULL);
175
176 newpoly->nv = numverts;
177 newpoly->verts = verts;
178
179 newpoly->roomnum = roomnum;
180 newpoly->facenum = facenum;
181 newpoly->color = ps_rand() * ps_rand();
182
183 return newpoly;
184 }
185
186 // Saves and BSP node to an open file and recurses with the nodes children
187 void SaveBSPNode(CFILE *outfile, bspnode *node) {
188 if (node->type == BSP_SOLID_LEAF) {
189 cf_WriteByte(outfile, BSP_SOLID_LEAF);
190 } else if (node->type == BSP_EMPTY_LEAF) {
191 cf_WriteByte(outfile, BSP_EMPTY_LEAF);
192 } else {
193 ASSERT(node->front);
194 ASSERT(node->back);
195
196 cf_WriteByte(outfile, BSP_NODE);
197
198 // Write out this planes node
199 cf_WriteFloat(outfile, node->plane.a);
200 cf_WriteFloat(outfile, node->plane.b);
201 cf_WriteFloat(outfile, node->plane.c);
202 cf_WriteFloat(outfile, node->plane.d);
203 cf_WriteShort(outfile, node->node_roomnum);
204 cf_WriteShort(outfile, node->node_facenum);
205 cf_WriteByte(outfile, node->node_subnum);
206
207 // Write out its children
208 SaveBSPNode(outfile, node->front);
209 SaveBSPNode(outfile, node->back);
210 }
211 }
212
213 // Loads a bsp node from an open file and recurses with its children
214 void LoadBSPNode(CFILE *infile, bspnode **node) {
215 // Get the node type
216 uint8_t type = cf_ReadByte(infile);
217
218 // Allocate the node and set its type
219 *node = NewBSPNode();
220 ASSERT(*node);
221 bspnode *localnode = *node;
222
223 localnode->type = type;
224
225 if (type == BSP_EMPTY_LEAF || type == BSP_SOLID_LEAF)
226 return;
227
228 // Load the nodes plane
229 localnode->plane.a = cf_ReadFloat(infile);
230 localnode->plane.b = cf_ReadFloat(infile);
231 localnode->plane.c = cf_ReadFloat(infile);
232 localnode->plane.d = cf_ReadFloat(infile);
233 localnode->node_roomnum = cf_ReadShort(infile);
234 localnode->node_facenum = cf_ReadShort(infile);
235 localnode->node_subnum = cf_ReadByte(infile);
236
237 // Recurse to get the children
238 LoadBSPNode(infile, &localnode->front);
239 LoadBSPNode(infile, &localnode->back);
240 }
241
242 // Frees up a polygon and all the vertices associated with it
243 void FreePolygon(bsppolygon *poly) {
244 ASSERT(poly != NULL);
245 ASSERT(poly->nv > 2);
246
247 if (poly->nv > 0) {
248 mem_free(poly->verts);
249 }
250
251 mem_free(poly);
252 }
253
254 // Calculates the plane equation for a given polygon
255 void CalculatePolygonPlane(bsppolygon *poly) {
256 ASSERT(poly->nv >= 3);
257
258 vector *vec = &poly->verts[0];
259
260 poly->plane.d = -(vec->x * poly->plane.a + vec->y * poly->plane.b + vec->z * poly->plane.c);
261 }
262
263 // Classifies whether or not a point is in front,behind, or on a plane
264 int ClassifyVector(bspplane *plane, vector *vec) {
265 float dist;
266
267 dist = vec->x * plane->a + vec->y * plane->b + vec->z * plane->c + plane->d;
268
269 if (dist > BSP_EPSILON)
270 return BSP_IN_FRONT;
271 else if (dist < -BSP_EPSILON)
272 return BSP_BEHIND;
273
274 return BSP_ON_PLANE;
275 }
276
277 // Classifies whether or not a polygon is behind,in front, or straddles a plane
278 int ClassifyPolygon(bspplane *plane, bsppolygon *poly) {
279 int numfront, numback, numon;
280 int i;
281 int nv = poly->nv;
282
283 ASSERT(nv >= 3);
284
285 numfront = numback = numon = 0;
286
287 for (i = 0; i < nv; i++) {
288 int fate;
289 vector *vec = &poly->verts[i];
290
291 fate = ClassifyVector(plane, vec);
292
293 switch (fate) {
294 case BSP_IN_FRONT:
295 numfront++;
296 break;
297 case BSP_BEHIND:
298 numback++;
299 break;
300 case BSP_ON_PLANE:
301 numfront++;
302 numback++;
303 numon++;
304 break;
305 }
306 }
307
308 if (numon == nv) {
309 return BSP_COINCIDENT;
310 } else if (numfront == nv) {
311 return BSP_IN_FRONT;
312 } else if (numback == nv) {
313 return BSP_BEHIND;
314 }
315
316 // The polygon straddles the plane
317 return BSP_SPANNING;
318 }
319
320 // Tries to split a polygon across a plane
321 int SplitPolygon(bspplane *plane, bsppolygon *testpoly, bsppolygon **frontpoly, bsppolygon **backpoly) {
322 float dists[256], t;
323 int numvert, numfront, numback, i, codes[256] = {};
324 vector *frontvert[256], *backvert[256], *polyvert[256];
325 vector *vertptr1, *vertptr2;
326 vector delta, *newvert[256];
327 int num_new_verts = 0;
328
329 /* Set up the function. Set all counters, variables, lists etc to
330 * zero or NULL, which provides a fall back result, should nothing
331 * be changed, and simply means that particular result is to be
332 * ignored
333 */
334
335 numvert = testpoly->nv;
336 numfront = numback = 0;
337
338 /* Now, we shall classify each vertex in the polygon, with both
339 * a plane distance, and a classification code. This is done here,
340 * as the results are often re-used, which saves time.
341 */
342
343 for (i = 0; i < numvert; i++) {
344 vertptr1 = &testpoly->verts[i];
345 polyvert[i] = vertptr1;
346 codes[i] = ClassifyVector(plane, vertptr1);
347 dists[i] = plane->a * vertptr1->x + plane->b * vertptr1->y + plane->c * vertptr1->z + plane->d;
348 }
349
350 /* We must duplicate the first entry in the numvert+1 slot, so that
351 * we can use wraparound to easily check things
352 */
353
354 codes[numvert] = codes[0];
355 dists[numvert] = dists[0];
356
357 /* Now, the actual splitting work. We must work through each vertex
358 * of the polygon, examining it with regard to the plane
359 * Where the classification codes differ, we have to split
360 */
361
362 for (i = 0; i < numvert; i++) {
363 vertptr1 = polyvert[i];
364
365 /* A point is found to be on the plane. This counts for
366 * both polygons, as often a vertex may lie along a plane,
367 * but will not be splitting it
368 */
369
370 if (codes[i] == BSP_ON_PLANE) {
371 frontvert[numfront++] = vertptr1;
372 backvert[numback++] = vertptr1;
373 } else if (codes[i] == BSP_IN_FRONT) {
374 /* Simple cases of point being in front or behind
375 * the plane. Just insert them to the appropriate
376 * lists.
377 */
378 frontvert[numfront++] = vertptr1;
379 } else if (codes[i] == BSP_BEHIND) {
380 backvert[numback++] = vertptr1;
381 }
382
383 /* If we're on the plane, or, the next point is the same
384 * side of the plane as this point, go to the next vertex
385 */
386
387 if ((codes[i] == BSP_ON_PLANE) || (codes[i] == codes[i + 1]))
388 continue;
389
390 /* Now, we need to generate a split point. This is just
391 * standard ray-plane intersection stuff. Now this is where
392 * pre-calculating the distances etc comes in handy, as
393 * we're using them a lot...
394 */
395
396 vertptr2 = polyvert[(i + 1) % numvert];
397 t = dists[i] / (dists[i] - dists[i + 1]);
398 newvert[num_new_verts] = (vector *)mem_malloc(sizeof(vector));
399
400 /* Now we must generate the split point. This is simply
401 * an equation in the form Origin + t*Direction
402 */
403
404 delta = *vertptr2 - *vertptr1;
405 *newvert[num_new_verts] = *vertptr1 + (t * delta);
406
407 /* vector tempvec=*newvert[num_new_verts]-*vertptr1;
408 float mag=vm_GetMagnitude(&tempvec);
409 if (mag<=BSP_EPSILON)
410 Int3(); */
411
412 frontvert[numfront++] = newvert[num_new_verts];
413 backvert[numback++] = newvert[num_new_verts];
414 num_new_verts++;
415 }
416
417 /* Now, we must construct the polygons, given the vertex lists
418 * If the number of vertices is invalid, we don't do anything ...
419 */
420
421 ASSERT(numfront >= 3);
422 ASSERT(numback >= 3);
423
424 (*frontpoly) = NewPolygon(testpoly->roomnum, testpoly->facenum, numfront);
425 (*backpoly) = NewPolygon(testpoly->roomnum, testpoly->facenum, numback);
426
427 for (i = 0; i < numfront; i++) {
428 bsppolygon *temppoly = *frontpoly;
429 temppoly->verts[i] = *frontvert[i];
430 temppoly->plane = testpoly->plane;
431 temppoly->facenum = testpoly->facenum;
432 temppoly->roomnum = testpoly->roomnum;
433 temppoly->subnum = testpoly->subnum;
434 }
435
436 for (i = 0; i < numback; i++) {
437 bsppolygon *temppoly = *backpoly;
438 temppoly->verts[i] = *backvert[i];
439 temppoly->plane = testpoly->plane;
440 temppoly->facenum = testpoly->facenum;
441 temppoly->roomnum = testpoly->roomnum;
442 temppoly->subnum = testpoly->subnum;
443 }
444
445 for (i = 0; i < num_new_verts; i++)
446 mem_free(newvert[i]);
447
448 return 1;
449 }
450
451 char Twirly[] = {'|', '/', '-', '\\'};
452 uint8_t Plane_twirl = 0;
453 uint8_t Node_twirl = 0;
454
455 // Selects the best plane to partition with, returning the pointer to polygon to split with
456 bsppolygon *SelectPlane(listnode **polylist) {
457 listnode *outer, *inner;
458 bsppolygon *outerpoly, *innerpoly, *bestpoly;
459 int splits, front, back, planar, result, balance;
460 float score, bestscore;
461 float g_kbalance = 1.0;
462 float g_ksplit = 0.0;
463 float g_kplanar = 0.0;
464 int checked = 0;
465
466 bestscore = 9999999.0;
467 bestpoly = NULL;
468
469 /* Iterate through every polygon, checking its plane against all
470 * the other polygons. But don't check it against itself
471 */
472
473 mprintf_at(2, 4, 0, "Plane = %c", Twirly[(Plane_twirl++) % 4]);
474
475 for (outer = *polylist; outer != NULL; outer = outer->next) {
476 outerpoly = (bsppolygon *)outer->data;
477 splits = front = back = planar = 0;
478 score = 0.0;
479
480 if (outerpoly->plane.used)
481 continue;
482
483 // Only check 300 times
484 if (checked >= 300)
485 return bestpoly;
486
487 for (inner = *polylist; inner != NULL; inner = inner->next) {
488 innerpoly = (bsppolygon *)inner->data;
489 if (innerpoly != outerpoly) {
490 result = ClassifyPolygon(&outerpoly->plane, innerpoly);
491 switch (result) {
492 case BSP_SPANNING:
493 splits++;
494 break;
495 case BSP_IN_FRONT:
496 front++;
497 break;
498 case BSP_BEHIND:
499 back++;
500 break;
501 case BSP_COINCIDENT:
502 planar++;
503 break;
504 }
505 }
506 }
507
508 /* Calculate the score. If we have a "perfect" tree, ie
509 * it has either no splits, or is perfectly balanced,
510 * return the plane to the caller
511 */
512
513 balance = abs(front - back);
514 score = g_kbalance * balance + g_ksplit * splits + g_kplanar * planar;
515
516 checked++;
517
518 if (score < 0.005)
519 return outerpoly;
520
521 if (score < bestscore) {
522 bestscore = score;
523 bestpoly = outerpoly;
524 }
525 }
526
527 return bestpoly;
528 }
529
530 // This is the routine that recursively builds the bsptree
531 int BuildBSPNode(bspnode *tree, listnode **polylist, int numpolys) {
532 bsppolygon *partition_poly;
533 listnode *lnode = *polylist;
534 listnode *next;
535 bspnode *frontnode, *backnode;
536 listnode *frontlist = NULL, *backlist = NULL;
537 bspplane partition_plane;
538 int numfront = 0, numback = 0, numsplits = 0;
539
540 ASSERT(numpolys > 0);
541 partition_poly = SelectPlane(polylist);
542
543 mprintf_at(2, 5, 0, "Node = %c", Twirly[(Node_twirl++) % 4]);
544
545 if (partition_poly == NULL) {
546 // We hit a leaf! Fill in the appropriate leaf stuff
547
548 /*vector center;
549 int total=0;
550
551 vm_MakeZero (&center);
552
553 for (int i=0;i<numpolys;i++)
554 {
555 bsppolygon *poly=(bsppolygon *)GetListItem (polylist,i);
556 ASSERT (poly!=NULL);
557 AddListItem (&tree->polylist,poly);
558 tree->num_polys++;
559 vector polycenter;
560
561 ConvexPolys++;
562 vm_MakeZero (&polycenter);
563
564 // Find out if this is a solid or empty leaf
565 // This routine may cause some problems because of convex subspace
566 for (int t=0;t<poly->nv;t++)
567 {
568 polycenter+=poly->verts[t];
569
570 }
571
572 polycenter/=poly->nv;
573 center+=polycenter;
574
575 }
576
577 center/=numpolys;
578 int ins=0,outs=0;
579
580 for (i=0;i<numpolys;i++)
581 {
582 bsppolygon *thispoly=(bsppolygon *)GetListItem (polylist,i);
583 int fate=ClassifyVector (&thispoly->plane,&center);
584
585 if (fate==BSP_IN_FRONT || fate==BSP_ON_PLANE)
586 {
587 outs++;
588 }
589 else
590 ins++;
591
592 }
593
594 if (ins==numpolys)
595 {
596 tree->type=BSP_SOLID_LEAF;
597 Solids++;
598 }
599 else if (outs==numpolys)
600 {
601 tree->type=BSP_EMPTY_LEAF;
602 Empty++;
603 }
604 else
605 {
606 mprintf(0,"Ins/outs don't match! ins=%d outs=%d np=%d\n",ins,outs,numpolys);
607
608 for (i=0;i<numpolys;i++)
609 {
610 bsppolygon *thispoly=(bsppolygon *)GetListItem (polylist,i);
611 mprintf(0,"Poly %d: Room=%d facenum=%d\n",i,thispoly->roomnum,thispoly->facenum);
612 }
613
614 if (ins>outs)
615 {
616 tree->type=BSP_SOLID_LEAF;
617 Solids++;
618 }
619 else
620 {
621 tree->type=BSP_EMPTY_LEAF;
622 Empty++;
623 }
624
625 }*/
626
627 tree->type = BSP_EMPTY_LEAF;
628
629 ConvexSubspaces++;
630 return 1;
631 }
632
633 // We need to process this node and classify all child polygons
634 tree->node_facenum = partition_poly->facenum;
635 tree->node_roomnum = partition_poly->roomnum;
636 tree->node_subnum = partition_poly->subnum;
637
638 partition_poly->plane.used = 1;
639 tree->plane = partition_poly->plane;
640 partition_plane = partition_poly->plane;
641
642 frontlist = backlist = NULL;
643
644 for (lnode = *polylist; lnode != NULL; lnode = next) {
645 next = lnode->next;
646
647 bsppolygon *testpoly = (bsppolygon *)lnode->data;
648 int fate = ClassifyPolygon(&partition_plane, testpoly);
649
650 if (fate == BSP_IN_FRONT) {
651 AddListItem(&frontlist, testpoly);
652 numfront++;
653 } else if (fate == BSP_BEHIND) {
654 AddListItem(&backlist, testpoly);
655 numback++;
656 } else if (fate == BSP_COINCIDENT) {
657 // Test to see if this plane is exactly the same as the partition plane
658 // If so, remove it from the list. If its facing the other way, send it down the back list
659 float dot = testpoly->plane.a * partition_plane.a + testpoly->plane.b * partition_plane.b +
660 testpoly->plane.c * partition_plane.c;
661
662 if (dot > -BSP_EPSILON) {
663 // Send down front list and deactivate this plane
664 AddListItem(&frontlist, testpoly);
665 numfront++;
666 // testpoly->plane.used=1;
667 } else {
668 AddListItem(&frontlist, testpoly);
669 // testpoly->plane.used=1;
670 numfront++;
671 }
672 } else {
673 // Must split this polygon
674 ASSERT(fate == BSP_SPANNING);
675 bsppolygon *frontpoly, *backpoly;
676
677 numsplits++;
678
679 SplitPolygon(&partition_plane, testpoly, &frontpoly, &backpoly);
680
681 numfront++;
682 numback++;
683 AddListItem(&frontlist, frontpoly);
684 AddListItem(&backlist, backpoly);
685
686 RemoveListItem(polylist, testpoly);
687 FreePolygon(testpoly);
688 }
689 }
690
691 // mprintf(0,"BuildBSPNode: Incoming=%d numfront=%d numback=%d splits=%d\n",numpolys,numfront,numback,numsplits);
692
693 if (frontlist != NULL) {
694 if ((frontnode = NewBSPNode()) == NULL) {
695 mprintf(0, "BuildBSPNode: Error, can't allocate front node\n");
696 return 0;
697 }
698
699 if (!BuildBSPNode((bspnode *)frontnode, &frontlist, numfront)) {
700 mprintf(0, "BuildBSPNode: Error building front node\n");
701 return 0;
702 }
703
704 tree->front = frontnode;
705 DestroyList(&frontlist);
706 } else {
707 if ((frontnode = NewBSPNode()) == NULL) {
708 mprintf(0, "BuildBSPNode: Error, can't allocate front node\n");
709 return 0;
710 }
711 frontnode->type = BSP_EMPTY_LEAF;
712 tree->front = frontnode;
713 }
714
715 if (backlist != NULL) {
716 if ((backnode = NewBSPNode()) == NULL) {
717 mprintf(0, "BuildBSPNode: Error, can't allocate front node\n");
718 return 0;
719 }
720
721 if (!BuildBSPNode((bspnode *)backnode, &backlist, numback)) {
722 mprintf(0, "BuildBSPNode: Error building back node\n");
723 return 0;
724 }
725
726 tree->back = backnode;
727 DestroyList(&backlist);
728 } else {
729 if ((backnode = NewBSPNode()) == NULL) {
730 mprintf(0, "BuildBSPNode: Error, can't allocate front node\n");
731 return 0;
732 }
733
734 backnode->type = BSP_SOLID_LEAF;
735 tree->back = backnode;
736 }
737
738 return 1;
739 }
740
741 // Releases memory for a bspnode. This function calls itself recursively
742 void DestroyBSPNode(bspnode *node) {
743 if (node->type == BSP_NODE) {
744 if (node->front)
745 DestroyBSPNode(node->front);
746 if (node->back)
747 DestroyBSPNode(node->back);
748 }
749
750 int np = CountListItems(&node->polylist);
751
752 for (int i = 0; i < np; i++) {
753 bsppolygon *poly = (bsppolygon *)GetListItem(&node->polylist, i);
754 FreePolygon(poly);
755 }
756 if (np > 0)
757 DestroyList(&node->polylist);
758
759 mem_free(node);
760 }
761
762 // Walks the BSP tree and frees up any nodes/polygons that we might be using
763 void DestroyBSPTree(bsptree *tree) {
764 if (BSP_initted == 0)
765 return;
766
767 mprintf(0, "Destroying bsptree!\n");
768 DestroyBSPNode(tree->root);
769 BSP_initted = 0;
770 }
771
772 // Destroys the mines BSP tree at shutdown
773 void DestroyDefaultBSPTree() { DestroyBSPTree(&MineBSP); }
774
775 // Given an object, a submodel, and a vertex number, calculates the world position
776 // of that point
777 void GetObjectPointInWorld(vector *dest, object *obj, int subnum, int vertnum);
778
779 // Builds a bsp tree for the indoor rooms
780 void BuildBSPTree() {
781 int i, t, k, j, x;
782 int numpolys = 0;
783 int check;
784
785 if (!UseBSP)
786 return;
787
788 // Check to see if we even need to build a new tree
789 check = BSPGetMineChecksum();
790
791 if (check == BSPChecksum) {
792 mprintf(0, "BSP tree already built!\n");
793 return; // The BSP tree has already been built for this mine
794 }
795
796 BSPChecksum = check;
797
798 // Free up any BSP trees that we might have lying around
799 InitDefaultBSP();
800
801 MineBSP.root = NewBSPNode();
802 ASSERT(MineBSP.root);
803
804 mprintf(0, "Building BSP Tree...\n");
805
806 mprintf(0, "Adding polygons to tree\n");
807
808 // Go through the whole mine and add each polygon to the possible BSP
809 // partition list. Don't include portals...
810 for (i = 0; i <= Highest_room_index; i++) {
811 bsppolygon *newpoly;
812
813 if (Rooms[i].used == 0 || (Rooms[i].flags & RF_EXTERNAL))
814 continue;
815
816 room *rp = &Rooms[i];
817
818 for (t = rp->objects; (t != -1); t = Objects[t].next) {
819 object *obj = &Objects[t];
820
821 if (obj->type == OBJ_NONE)
822 continue;
823
824 if (OBJECT_OUTSIDE(obj))
825 continue;
826
827 if (obj->lighting_render_type == LRT_LIGHTMAPS) {
828 poly_model *po = &Poly_models[obj->rtype.pobj_info.model_num];
829
830 if (!po->new_style)
831 continue;
832
833 for (k = 0; k < po->n_models; k++) {
834 bsp_info *sm = &po->submodel[k];
835
836 if (IsNonRenderableSubmodel(po, k))
837 continue;
838
839 for (j = 0; j < sm->num_faces; j++) {
840 vector world_verts[64];
841
842 newpoly = NewPolygon(i, t, sm->faces[j].nverts);
843 if (!newpoly) {
844 mprintf(0, "Couldn't get a new polygon!\n");
845 Int3();
846 return;
847 }
848
849 ASSERT(sm->faces[j].nverts < 64);
850 for (x = 0; x < sm->faces[j].nverts; x++)
851 GetObjectPointInWorld(&world_verts[x], obj, k, sm->faces[j].vertnums[x]);
852
853 vector norm;
854
855 vm_GetNormal(&norm, &world_verts[0], &world_verts[1], &world_verts[2]);
856
857 // Add the vertices to this poly
858 for (x = 0; x < sm->faces[j].nverts; x++)
859 newpoly->verts[x] = world_verts[x];
860
861 newpoly->plane.a = norm.x;
862 newpoly->plane.b = norm.y;
863 newpoly->plane.c = norm.z;
864
865 CalculatePolygonPlane(newpoly);
866
867 // Add it to our bsp list
868 AddListItem(&MineBSP.polylist, newpoly);
869
870 newpoly->plane.used = 0;
871 numpolys++;
872
873 newpoly->roomnum = t;
874 newpoly->facenum = j;
875 newpoly->subnum = k;
876 }
877 }
878 }
879 }
880
881 for (t = 0; t < Rooms[i].num_faces; t++) {
882
883 // Don't include portals in BSP calculation
884 // Unless they go outside
885 if (Rooms[i].faces[t].portal_num != -1) {
886 if (Rooms[i].portals[Rooms[i].faces[t].portal_num].croom >= 0)
887 continue;
888 }
889
890 // Construct a new polygon
891 newpoly = NewPolygon(i, t, Rooms[i].faces[t].num_verts);
892 if (!newpoly) {
893 mprintf(0, "Couldn't get a new polygon!\n");
894 Int3();
895 return;
896 }
897
898 // Add the vertices to this poly
899 for (k = 0; k < Rooms[i].faces[t].num_verts; k++)
900 newpoly->verts[k] = Rooms[i].verts[Rooms[i].faces[t].face_verts[k]];
901
902 newpoly->plane.a = Rooms[i].faces[t].normal.x;
903 newpoly->plane.b = Rooms[i].faces[t].normal.y;
904 newpoly->plane.c = Rooms[i].faces[t].normal.z;
905
906 CalculatePolygonPlane(newpoly);
907
908 // Add it to our bsp list
909 AddListItem(&MineBSP.polylist, newpoly);
910
911 newpoly->plane.used = 0;
912
913 newpoly->roomnum = i;
914 newpoly->facenum = t;
915 newpoly->subnum = -1;
916
917 numpolys++;
918 }
919 }
920
921 ConvexSubspaces = 0;
922 ConvexPolys = 0;
923 Solids = 0;
924 Empty = 0;
925
926 mprintf(0, "%d polygons added, starting node building...\n", numpolys);
927
928 // Build the BSP tree!
929 BuildBSPNode(MineBSP.root, &MineBSP.polylist, numpolys);
930 DestroyList(&MineBSP.polylist);
931
932 // Print some stats
933 mprintf(0, "Total number of convex subspaces=%d\n", ConvexSubspaces);
934 mprintf(0, "Total number of convex polys=%d\n", ConvexPolys);
935 mprintf(0, "Solid=%d Empty=%d\n", Solids, Empty);
936 }
937
938 // Builds a bsp tree for a single room
939 void BuildSingleBSPTree(int roomnum) {
940 int i, t, k, j, x;
941 int numpolys = 0;
942
943 if (!UseBSP)
944 return;
945
946 // Free up any BSP trees that we might have lying around
947 InitDefaultBSP();
948
949 MineBSP.root = NewBSPNode();
950 ASSERT(MineBSP.root);
951
952 mprintf(0, "Building BSP Tree...\n");
953
954 // Go through the whole mine and add each polygon to the possible BSP
955 // partition list. Don't include portals...
956
957 i = roomnum;
958 bsppolygon *newpoly;
959
960 for (t = 0; t <= Highest_object_index; t++) {
961 object *obj = &Objects[t];
962
963 if (obj->type == OBJ_NONE)
964 continue;
965
966 if (OBJECT_OUTSIDE(obj))
967 continue;
968 if (obj->roomnum != i)
969 continue;
970
971 if (obj->lighting_render_type == LRT_LIGHTMAPS) {
972 poly_model *po = &Poly_models[obj->rtype.pobj_info.model_num];
973 if (!po->new_style)
974 continue;
975
976 for (k = 0; k < po->n_models; k++) {
977 bsp_info *sm = &po->submodel[k];
978
979 if (IsNonRenderableSubmodel(po, k))
980 continue;
981
982 for (j = 0; j < sm->num_faces; j++) {
983 vector world_verts[64];
984 newpoly = NewPolygon(i, t, sm->faces[j].nverts);
985 if (!newpoly) {
986 mprintf(0, "Couldn't get a new polygon!\n");
987 Int3();
988 return;
989 }
990
991 for (x = 0; x < sm->faces[j].nverts; x++)
992 GetObjectPointInWorld(&world_verts[x], obj, k, sm->faces[j].vertnums[x]);
993
994 vector norm;
995
996 vm_GetNormal(&norm, &world_verts[0], &world_verts[1], &world_verts[2]);
997
998 // Add the vertices to this poly
999 for (x = 0; x < sm->faces[j].nverts; x++)
1000 newpoly->verts[x] = world_verts[x];
1001
1002 newpoly->plane.a = norm.x;
1003 newpoly->plane.b = norm.y;
1004 newpoly->plane.c = norm.z;
1005
1006 CalculatePolygonPlane(newpoly);
1007
1008 // Add it to our bsp list
1009 AddListItem(&MineBSP.polylist, newpoly);
1010
1011 newpoly->plane.used = 0;
1012 numpolys++;
1013 }
1014 }
1015 }
1016 }
1017
1018 for (t = 0; t < Rooms[i].num_faces; t++) {
1019 // Don't include portals in BSP calculation
1020 if (Rooms[i].faces[t].portal_num != -1)
1021 continue;
1022
1023 // Construct a new polygon
1024 newpoly = NewPolygon(i, t, Rooms[i].faces[t].num_verts);
1025 if (!newpoly) {
1026 mprintf(0, "Couldn't get a new polygon!\n");
1027 Int3();
1028 return;
1029 }
1030 // Add the vertices to this poly
1031 for (k = 0; k < Rooms[i].faces[t].num_verts; k++)
1032 newpoly->verts[k] = Rooms[i].verts[Rooms[i].faces[t].face_verts[k]];
1033
1034 newpoly->plane.a = Rooms[i].faces[t].normal.x;
1035 newpoly->plane.b = Rooms[i].faces[t].normal.y;
1036 newpoly->plane.c = Rooms[i].faces[t].normal.z;
1037
1038 CalculatePolygonPlane(newpoly);
1039
1040 // Add it to our bsp list
1041 AddListItem(&MineBSP.polylist, newpoly);
1042
1043 newpoly->plane.used = 0;
1044 numpolys++;
1045 }
1046
1047 ConvexSubspaces = 0;
1048 ConvexPolys = 0;
1049 Solids = 0;
1050 Empty = 0;
1051
1052 // Build the BSP tree!
1053 BuildBSPNode(MineBSP.root, &MineBSP.polylist, numpolys);
1054 DestroyList(&MineBSP.polylist);
1055
1056 // Print some stats
1057 mprintf(0, "Total number of convex subspaces=%d\n", ConvexSubspaces);
1058 mprintf(0, "Total number of convex polys=%d\n", ConvexPolys);
1059 mprintf(0, "Solid=%d Empty=%d\n", Solids, Empty);
1060
1061 BSPChecksum = -1;
1062 }
1063
1064 // Returns true if the point is inside the min,max
1065 static inline int BSPInMinMax(vector *pos, vector *min_xyz, vector *max_xyz) {
1066 if (pos->x < min_xyz->x || pos->y < min_xyz->y || pos->z < min_xyz->z || pos->x > max_xyz->x || pos->y > max_xyz->y ||
1067 pos->z > max_xyz->z)
1068 return 0;
1069
1070 return 1;
1071 }
1072 // see if a point in inside a face by projecting into 2d
1073 extern uint32_t check_point_to_face(vector *colp, vector *face_normal, int nv, vector **vertex_ptr_list);
1074
1075 // Returns true if passed in point collides with a nodes polygon
1076 static inline int BSPPointInPolygon(vector *pos, bspnode *node) {
1077 if (node->node_subnum < 0) // Room face
1078 {
1079 room *rp = &Rooms[node->node_roomnum];
1080 face *fp = &rp->faces[node->node_facenum];
1081 if (!(BSPInMinMax(pos, &fp->min_xyz, &fp->max_xyz)))
1082 return 0;
1083
1084 // Test to see if this point in inside the polygon
1085 vector verts[MAX_VERTS_PER_FACE], *vertp[MAX_VERTS_PER_FACE];
1086 for (int i = 0; i < fp->num_verts; i++) {
1087 verts[i] = rp->verts[fp->face_verts[i]];
1088 vertp[i] = &verts[i];
1089 }
1090
1091 if ((check_point_to_face(pos, &fp->normal, fp->num_verts, vertp)))
1092 return 0;
1093
1094 return 1;
1095 } else // Object face
1096 {
1097 object *obj = &Objects[node->node_roomnum];
1098
1099 if (!(BSPInMinMax(pos, &obj->min_xyz, &obj->max_xyz)))
1100 return 0;
1101
1102 // Test to see if this point in inside the polygon
1103 vector verts[MAX_VERTS_PER_FACE], *vertp[MAX_VERTS_PER_FACE];
1104 vector norm;
1105 poly_model *po = &Poly_models[obj->rtype.pobj_info.model_num];
1106 bsp_info *sm = &po->submodel[node->node_subnum];
1107
1108 for (int i = 0; i < sm->faces[node->node_facenum].nverts; i++) {
1109 GetObjectPointInWorld(&verts[i], obj, node->node_subnum, sm->faces[node->node_facenum].vertnums[i]);
1110 vertp[i] = &verts[i];
1111 }
1112
1113 norm.x = node->plane.a;
1114 norm.y = node->plane.b;
1115 norm.z = node->plane.c;
1116
1117 if ((check_point_to_face(pos, &norm, sm->faces[node->node_facenum].nverts, vertp)))
1118 return 0;
1119
1120 return 1;
1121 }
1122
1123 return 0;
1124 }
1125
1126 // Runs a ray through the bsp tree
1127 // Returns true if a ray is occludes
1128 #define MAX_RAY_STACK 1000
1129 #define PUSH_BSP_RAY(s, e, n) \
1130 { \
1131 stack_start[si] = s; \
1132 stack_end[si] = e; \
1133 stack_node[si] = n; \
1134 si++; \
1135 ASSERT(si < MAX_RAY_STACK); \
1136 }
1137 #define POP_BSP_RAY() \
1138 { \
1139 si--; \
1140 start = stack_start[si]; \
1141 end = stack_end[si]; \
1142 node = stack_node[si]; \
1143 }
1144
1145 vector stack_start[MAX_RAY_STACK], stack_end[MAX_RAY_STACK];
1146 bspnode *stack_node[MAX_RAY_STACK];
1147 static int si;
1148
1149 int BSPRayOccluded(vector *line_start, vector *line_end, bspnode *start_node) {
1150 si = 0;
1151 vector start, end;
1152 bspnode *node;
1153
1154 PUSH_BSP_RAY(*line_start, *line_end, start_node);
1155
1156 while (si > 0) {
1157 POP_BSP_RAY();
1158 while (node->type == BSP_NODE) {
1159 float dist1 = node->plane.a * start.x + node->plane.b * start.y + node->plane.c * start.z + node->plane.d;
1160 float dist2 = node->plane.a * end.x + node->plane.b * end.y + node->plane.c * end.z + node->plane.d;
1161
1162 if (dist1 >= 0 && dist2 >= 0) {
1163 node = (bspnode *)node->front;
1164 } else if (dist1 < 0 && dist2 < 0) {
1165 node = (bspnode *)node->back;
1166 } else {
1167 vector mid, delta;
1168 float t;
1169
1170 // Generate split point
1171 t = dist1 / (dist1 - dist2);
1172 delta = end - start;
1173 mid = start + (t * delta);
1174 if (BSPPointInPolygon(&mid, node))
1175 return 1;
1176
1177 // vm_NormalizeVectorFast (&delta);
1178
1179 vector mid1 = mid; //-(delta*BSP_EPSILON);
1180 vector mid2 = mid; //+(delta*BSP_EPSILON);
1181
1182 if (dist1 >= 0.0) {
1183 PUSH_BSP_RAY(mid1, end, (bspnode *)node->back);
1184 PUSH_BSP_RAY(start, mid2, (bspnode *)node->front);
1185 } else {
1186 PUSH_BSP_RAY(mid2, end, (bspnode *)node->front);
1187 PUSH_BSP_RAY(start, mid1, (bspnode *)node->back);
1188 }
1189
1190 goto break_out;
1191 }
1192 }
1193 break_out:;
1194 }
1195
1196 return 0;
1197 }
1198
1199 // Initializes some variables for the indoor bsp tree
1200 void InitDefaultBSP() {
1201 if (BSP_initted) {
1202 DestroyBSPTree(&MineBSP);
1203 } else {
1204 atexit(DestroyDefaultBSPTree);
1205 }
1206
1207 MineBSP.polylist = NULL;
1208 MineBSP.vertlist = NULL;
1209
1210 BSP_initted = 1;
1211 }