configuration fixes
[btb/d2x.git] / main / render.c
1 /*
2 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
3 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
4 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
5 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
6 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
7 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
8 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
9 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
10 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.  
11 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 #ifdef RCS
15 static char rcsid[] = "$Id: render.c,v 1.2 2001-01-22 13:22:40 bradleyb Exp $";
16 #endif
17
18 #include <conf.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
22
23 #include "pa_enabl.h"                   //$$POLY_ACC
24 #include "inferno.h"
25 #include "segment.h"
26 #include "error.h"
27 #include "bm.h"
28 #include "texmap.h"
29 #include "mono.h"
30 #include "render.h"
31 #include "game.h"
32 #include "object.h"
33 #include "laser.h"
34 #include "textures.h"
35 #include "screens.h"
36 #include "segpoint.h"
37 #include "wall.h"
38 #include "texmerge.h"
39 #include "physics.h"
40 #include "3d.h"
41 #include "gameseg.h"
42 #include "vclip.h"
43 #include "lighting.h"
44 #include        "cntrlcen.h"
45 #include "newdemo.h"
46 #include "automap.h"
47 #include "endlevel.h"
48 #include "key.h"
49 #include "newmenu.h"
50 #include "u_mem.h"
51 #include "piggy.h"
52
53 #ifdef OGL
54 #include "ogl_init.h"
55 #endif
56
57 #define INITIAL_LOCAL_LIGHT     (F1_0/4)                // local light value in segment of occurence (of light emission)
58
59 #ifdef EDITOR
60 #include "editor\editor.h"
61 #endif
62
63 #if defined(POLY_ACC)
64 #include "poly_acc.h"
65 #endif
66
67 //used for checking if points have been rotated
68 int     Clear_window_color=-1;
69 int     Clear_window=2;                 //      1 = Clear whole background window, 2 = clear view portals into rest of world, 0 = no clear
70
71 int RL_framecount=-1;
72 short Rotated_last[MAX_VERTICES];
73
74 // When any render function needs to know what's looking at it, it should 
75 // access Viewer members.
76 object * Viewer = NULL;
77
78 vms_vector Viewer_eye;  //valid during render
79
80 int     N_render_segs;
81
82 #ifndef MACINTOSH
83 fix Render_zoom = 0x9000;                                                       //the player's zoom factor
84 #else
85 fix Render_zoom = 0xB000;
86 #endif
87
88 #ifndef NDEBUG
89 ubyte object_rendered[MAX_OBJECTS];
90 #endif
91
92 #define DEFAULT_RENDER_DEPTH 16
93 int Render_depth=DEFAULT_RENDER_DEPTH;                  //how many segments deep to render
94
95 int     Detriangulation_on = 1;                                 // 1 = allow rendering of triangulated side as a quad, 0 = don't allow
96
97 #ifdef EDITOR
98 int     Render_only_bottom=0;
99 int     Bottom_bitmap_num = 9;
100 #endif
101
102 fix     Face_reflectivity = (F1_0/2);
103
104 #if 0           //this stuff could probably just be deleted
105
106 int inc_render_depth(void)
107 {
108         return ++Render_depth;
109 }
110
111 int dec_render_depth(void)
112 {
113         return Render_depth==1?Render_depth:--Render_depth;
114 }
115
116 int reset_render_depth(void)
117 {
118         return Render_depth = DEFAULT_RENDER_DEPTH;
119 }
120
121 #endif
122
123 #ifdef EDITOR
124 int _search_mode = 0;                   //true if looking for curseg,side,face
125 short _search_x,_search_y;      //pixel we're looking at
126 int found_seg,found_side,found_face,found_poly;
127 #else
128 #define _search_mode 0
129 #endif
130
131 #ifdef NDEBUG           //if no debug code, set these vars to constants
132
133 #define Outline_mode 0
134 #define Show_only_curside 0
135
136 #else
137
138 int Outline_mode=0,Show_only_curside=0;
139
140 int toggle_outline_mode(void)
141 {
142         return Outline_mode = !Outline_mode;
143 }
144
145 int toggle_show_only_curside(void)
146 {
147         return Show_only_curside = !Show_only_curside;
148 }
149
150 void draw_outline(int nverts,g3s_point **pointlist)
151 {
152         int i;
153
154         gr_setcolor(BM_XRGB(63,63,63));
155
156         for (i=0;i<nverts-1;i++)
157                 g3_draw_line(pointlist[i],pointlist[i+1]);
158
159         g3_draw_line(pointlist[i],pointlist[0]);
160
161 }
162 #endif
163
164 grs_canvas * reticle_canvas = NULL;
165
166 void free_reticle_canvas()
167 {
168         if (reticle_canvas)     {
169                 d_free( reticle_canvas->cv_bitmap.bm_data );
170                 d_free( reticle_canvas );
171                 reticle_canvas  = NULL;
172         }
173 }
174
175 extern void show_reticle(int force_big);
176
177 // Draw the reticle in 3D for head tracking
178 void draw_3d_reticle(fix eye_offset)
179 {
180         g3s_point       reticle_points[4];
181         g3s_uvl         uvl[4];
182         g3s_point       *pointlist[4];
183         int                     i;
184         vms_vector v1, v2;
185         grs_canvas *saved_canvas;
186         int saved_interp_method;
187
188 //      if (!Use_player_head_angles) return;
189         
190         for (i=0; i<4; i++ )    {
191                 pointlist[i] = &reticle_points[i];
192                 uvl[i].l = MAX_LIGHT;
193         }
194         uvl[0].u = 0; uvl[0].v = 0;
195         uvl[1].u = F1_0; uvl[1].v = 0;
196         uvl[2].u = F1_0; uvl[2].v = F1_0;
197         uvl[3].u = 0; uvl[3].v = F1_0;
198
199         vm_vec_scale_add( &v1, &Viewer->pos, &Viewer->orient.fvec, F1_0*4 );
200         vm_vec_scale_add2(&v1,&Viewer->orient.rvec,eye_offset);
201
202         vm_vec_scale_add( &v2, &v1, &Viewer->orient.rvec, -F1_0*1 );
203         vm_vec_scale_add2( &v2, &Viewer->orient.uvec, F1_0*1 );
204         g3_rotate_point(&reticle_points[0],&v2);
205
206         vm_vec_scale_add( &v2, &v1, &Viewer->orient.rvec, +F1_0*1 );
207         vm_vec_scale_add2( &v2, &Viewer->orient.uvec, F1_0*1 );
208         g3_rotate_point(&reticle_points[1],&v2);
209
210         vm_vec_scale_add( &v2, &v1, &Viewer->orient.rvec, +F1_0*1 );
211         vm_vec_scale_add2( &v2, &Viewer->orient.uvec, -F1_0*1 );
212         g3_rotate_point(&reticle_points[2],&v2);
213
214         vm_vec_scale_add( &v2, &v1, &Viewer->orient.rvec, -F1_0*1 );
215         vm_vec_scale_add2( &v2, &Viewer->orient.uvec, -F1_0*1 );
216         g3_rotate_point(&reticle_points[3],&v2);
217
218         if ( reticle_canvas == NULL )   {
219                 reticle_canvas = gr_create_canvas(64,64);
220                 if ( !reticle_canvas )
221                         Error( "Couldn't malloc reticle_canvas" );
222                 atexit( free_reticle_canvas );
223                 reticle_canvas->cv_bitmap.bm_handle = 0;
224                 reticle_canvas->cv_bitmap.bm_flags = BM_FLAG_TRANSPARENT;
225         }
226
227         saved_canvas = grd_curcanv;
228         gr_set_current_canvas(reticle_canvas);
229         gr_clear_canvas( TRANSPARENCY_COLOR );          // Clear to Xparent
230         show_reticle(1);
231         gr_set_current_canvas(saved_canvas);
232         
233         saved_interp_method=Interpolation_method;
234         Interpolation_method    = 3;            // The best, albiet slowest.
235         g3_draw_tmap(4,pointlist,uvl,&reticle_canvas->cv_bitmap);
236         Interpolation_method    = saved_interp_method;
237 }
238
239
240 extern fix Seismic_tremor_magnitude;
241
242 fix flash_scale;
243
244 #define FLASH_CYCLE_RATE f1_0
245
246 fix Flash_rate = FLASH_CYCLE_RATE;
247
248 //cycle the flashing light for when mine destroyed
249 void flash_frame()
250 {
251         static fixang flash_ang=0;
252
253         if (!Control_center_destroyed && !Seismic_tremor_magnitude)
254                 return;
255
256         if (Endlevel_sequence)
257                 return;
258
259         if (PaletteBlueAdd > 10 )               //whiting out
260                 return;
261
262 //      flash_ang += fixmul(FLASH_CYCLE_RATE,FrameTime);
263         if (Seismic_tremor_magnitude) {
264                 fix     added_flash;
265
266                 added_flash = abs(Seismic_tremor_magnitude);
267                 if (added_flash < F1_0)
268                         added_flash *= 16;
269
270                 flash_ang += fixmul(Flash_rate, fixmul(FrameTime, added_flash+F1_0));
271                 fix_fastsincos(flash_ang,&flash_scale,NULL);
272                 flash_scale = (flash_scale + F1_0*3)/4; //      gets in range 0.5 to 1.0
273         } else {
274                 flash_ang += fixmul(Flash_rate,FrameTime);
275                 fix_fastsincos(flash_ang,&flash_scale,NULL);
276                 flash_scale = (flash_scale + f1_0)/2;
277                 if (Difficulty_level == 0)
278                         flash_scale = (flash_scale+F1_0*3)/4;
279         }
280
281
282 }
283
284 // -----------------------------------------------------------------------------------
285 //      Render a face.
286 //      It would be nice to not have to pass in segnum and sidenum, but they are used for our
287 //      hideously hacked in headlight system.
288 //      vp is a pointer to vertex ids.
289 //      tmap1, tmap2 are texture map ids.  tmap2 is the pasty one.
290 void render_face(int segnum, int sidenum, int nv, short *vp, int tmap1, int tmap2, uvl *uvlp, int wid_flags)
291 {
292         // -- Using new headlight system...fix                  face_light;
293         grs_bitmap      *bm;
294 #ifdef OGL
295         grs_bitmap      *bm2=NULL;
296 #endif
297
298         fix                     reflect;
299         uvl                     uvl_copy[8];
300         int                     i;
301         g3s_point       *pointlist[8];
302
303         Assert(nv <= 8);
304
305         for (i=0; i<nv; i++) {
306                 uvl_copy[i] = uvlp[i];
307                 pointlist[i] = &Segment_points[vp[i]];
308         }
309
310         //handle cloaked walls
311         if (wid_flags & WID_CLOAKED_FLAG) {
312                 int wall_num = Segments[segnum].sides[sidenum].wall_num;
313                 Assert(wall_num != -1);
314                 Gr_scanline_darkening_level = Walls[wall_num].cloak_value;
315                 gr_setcolor(BM_XRGB(0,0,0));    //set to black (matters for s3)
316
317                 g3_draw_poly(nv,pointlist);             //draw as flat poly
318
319                 Gr_scanline_darkening_level = GR_FADE_LEVELS;
320
321                 return;
322         }
323
324         // -- Using new headlight system...face_light = -vm_vec_dot(&Viewer->orient.fvec,norm);
325
326         if (tmap1 >= NumTextures) {
327                 mprintf((0,"Invalid tmap number %d, NumTextures=%d, changing to 0\n",tmap1,NumTextures));
328
329         #ifndef RELEASE
330                 Int3();
331         #endif
332
333                 Segments[segnum].sides[sidenum].tmap_num = 0;
334         }
335
336 #ifdef OGL
337         if (ogl_alttexmerge){
338                 PIGGY_PAGE_IN(Textures[tmap1]);
339                 bm = &GameBitmaps[Textures[tmap1].index];
340                 if (tmap2){
341                         PIGGY_PAGE_IN(Textures[tmap2&0x3FFF]);
342                         bm2 = &GameBitmaps[Textures[tmap2&0x3FFF].index];
343                 }
344                 if (bm2 && (bm2->bm_flags&BM_FLAG_SUPER_TRANSPARENT)){
345                         bm = texmerge_get_cached_bitmap( tmap1, tmap2 );
346                         bm2 = NULL;
347                 }
348         }else                                                           
349 #endif
350
351         // New code for overlapping textures...
352         if (tmap2 != 0)
353    {
354                 bm = texmerge_get_cached_bitmap( tmap1, tmap2 );
355    }
356         else    {
357                 bm = &GameBitmaps[Textures[tmap1].index];
358                 PIGGY_PAGE_IN(Textures[tmap1]);
359         }
360
361         Assert( !(bm->bm_flags & BM_FLAG_PAGED_OUT) );
362
363         //reflect = fl2f((1.0-TmapInfo[p->tmap_num].reflect)/2.0 + 0.5);
364         //reflect = fl2f((1.0-TmapInfo[p->tmap_num].reflect));
365
366         reflect = Face_reflectivity;            // f1_0;        //until we figure this stuff out...
367
368         //set light values for each vertex & build pointlist
369         {
370                 int i;
371
372                 // -- Using new headlight system...face_light = fixmul(face_light,reflect);
373
374                 for (i=0;i<nv;i++) {
375
376                         //the uvl struct has static light already in it
377
378                         //scale static light for destruction effect
379                         if (Control_center_destroyed || Seismic_tremor_magnitude)       //make lights flash
380                                 uvl_copy[i].l = fixmul(flash_scale,uvl_copy[i].l);
381
382                         //add in dynamic light (from explosions, etc.)
383                         uvl_copy[i].l += Dynamic_light[vp[i]];
384
385                         //add in light from player's headlight
386                         // -- Using new headlight system...uvl_copy[i].l += compute_headlight_light(&Segment_points[vp[i]].p3_vec,face_light);
387
388                         //saturate at max value
389                         if (uvl_copy[i].l > MAX_LIGHT)
390                                 uvl_copy[i].l = MAX_LIGHT;
391
392                 }
393         }
394
395 #ifdef EDITOR
396         if ((Render_only_bottom) && (sidenum == WBOTTOM))
397                 g3_draw_tmap(nv,pointlist,(g3s_uvl *) uvl_copy,&GameBitmaps[Textures[Bottom_bitmap_num].index]);
398         else
399 #endif
400
401 #ifdef OGL
402                 if (bm2){
403                         g3_draw_tmap_2(nv,pointlist,(g3s_uvl *) uvl_copy,bm,bm2,((tmap2&0xC000)>>14) & 3);
404                 }else
405 #endif
406                 g3_draw_tmap(nv,pointlist,(g3s_uvl *) uvl_copy,bm);
407
408         #ifndef NDEBUG
409         if (Outline_mode) draw_outline(nv, pointlist);
410         #endif
411 }
412
413 #ifdef EDITOR
414 // -----------------------------------------------------------------------------------
415 //      Only called if editor active.
416 //      Used to determine which face was clicked on.
417 void check_face(int segnum, int sidenum, int facenum, int nv, short *vp, int tmap1, int tmap2, uvl *uvlp)
418 {
419         int     i;
420
421         if (_search_mode) {
422                 int save_lighting;
423                 grs_bitmap *bm;
424                 uvl uvl_copy[8];
425                 g3s_point *pointlist[4];
426
427                 if (tmap2 > 0 )
428                         bm = texmerge_get_cached_bitmap( tmap1, tmap2 );
429                 else
430                         bm = &GameBitmaps[Textures[tmap1].index];
431
432                 for (i=0; i<nv; i++) {
433                         uvl_copy[i] = uvlp[i];
434                         pointlist[i] = &Segment_points[vp[i]];
435                 }
436
437                 gr_setcolor(0);
438                 gr_pixel(_search_x,_search_y);  //set our search pixel to color zero
439                 gr_setcolor(1);                                 //and render in color one
440  save_lighting = Lighting_on;
441  Lighting_on = 2;
442                 //g3_draw_poly(nv,vp);
443                 g3_draw_tmap(nv,pointlist, (g3s_uvl *)uvl_copy, bm);
444  Lighting_on = save_lighting;
445
446                 if (gr_ugpixel(&grd_curcanv->cv_bitmap,_search_x,_search_y) == 1) {
447                         found_seg = segnum;
448                         found_side = sidenum;
449                         found_face = facenum;
450                 }
451                 
452         }
453 }
454 #endif
455
456 fix     Tulate_min_dot = (F1_0/4);
457 //--unused-- fix        Tulate_min_ratio = (2*F1_0);
458 fix     Min_n0_n1_dot   = (F1_0*15/16);
459
460 extern int contains_flare(segment *segp, int sidenum);
461 extern fix      Obj_light_xlate[16];
462
463 // -----------------------------------------------------------------------------------
464 //      Render a side.
465 //      Check for normal facing.  If so, render faces on side dictated by sidep->type.
466 void render_side(segment *segp, int sidenum)
467 {
468         short                   vertnum_list[4];
469         side                    *sidep = &segp->sides[sidenum];
470         vms_vector      tvec;
471         fix                     v_dot_n0, v_dot_n1;
472         uvl                     temp_uvls[3];
473         fix                     min_dot, max_dot;
474         vms_vector  normals[2];
475         int                     wid_flags;
476
477
478         wid_flags = WALL_IS_DOORWAY(segp,sidenum);
479
480         if (!(wid_flags & WID_RENDER_FLAG))             //if (WALL_IS_DOORWAY(segp, sidenum) == WID_NO_WALL)
481                 return;
482
483         #ifdef COMPACT_SEGS     
484                 get_side_normals(segp, sidenum, &normals[0], &normals[1] );
485         #else
486                 normals[0] = segp->sides[sidenum].normals[0];
487                 normals[1] = segp->sides[sidenum].normals[1];
488         #endif
489
490         //      ========== Mark: Here is the change...beginning here: ==========
491
492         if (sidep->type == SIDE_IS_QUAD) {
493
494                 vm_vec_sub(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][0]]]);
495
496                 // -- Old, slow way --  //      Regardless of whether this side is comprised of a single quad, or two triangles, we need to know one normal, so
497                 // -- Old, slow way --  //      deal with it, get the dot product.
498                 // -- Old, slow way --  if (sidep->type == SIDE_IS_TRI_13)
499                 // -- Old, slow way --          vm_vec_normalized_dir(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][1]]]);
500                 // -- Old, slow way --  else
501                 // -- Old, slow way --          vm_vec_normalized_dir(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][0]]]);
502
503                 get_side_verts(vertnum_list,segp-Segments,sidenum);
504                 v_dot_n0 = vm_vec_dot(&tvec, &normals[0]);
505
506 // -- flare creates point -- {
507 // -- flare creates point --    int     flare_index;
508 // -- flare creates point -- 
509 // -- flare creates point --    flare_index = contains_flare(segp, sidenum);
510 // -- flare creates point -- 
511 // -- flare creates point --    if (flare_index != -1) {
512 // -- flare creates point --            int                     tri;
513 // -- flare creates point --            fix                     u, v, l;
514 // -- flare creates point --            vms_vector      *hit_point;
515 // -- flare creates point --            short                   vertnum_list[4];
516 // -- flare creates point -- 
517 // -- flare creates point --            hit_point = &Objects[flare_index].pos;
518 // -- flare creates point -- 
519 // -- flare creates point --            find_hitpoint_uv( &u, &v, &l, hit_point, segp, sidenum, 0);     //      last parm means always use face 0.
520 // -- flare creates point -- 
521 // -- flare creates point --            get_side_verts(vertnum_list, segp-Segments, sidenum);
522 // -- flare creates point -- 
523 // -- flare creates point --            g3_rotate_point(&Segment_points[MAX_VERTICES-1], hit_point);
524 // -- flare creates point -- 
525 // -- flare creates point --            for (tri=0; tri<4; tri++) {
526 // -- flare creates point --                    short   tri_verts[3];
527 // -- flare creates point --                    uvl     tri_uvls[3];
528 // -- flare creates point -- 
529 // -- flare creates point --                    tri_verts[0] = vertnum_list[tri];
530 // -- flare creates point --                    tri_verts[1] = vertnum_list[(tri+1) % 4];
531 // -- flare creates point --                    tri_verts[2] = MAX_VERTICES-1;
532 // -- flare creates point -- 
533 // -- flare creates point --                    tri_uvls[0] = sidep->uvls[tri];
534 // -- flare creates point --                    tri_uvls[1] = sidep->uvls[(tri+1)%4];
535 // -- flare creates point --                    tri_uvls[2].u = u;
536 // -- flare creates point --                    tri_uvls[2].v = v;
537 // -- flare creates point --                    tri_uvls[2].l = F1_0;
538 // -- flare creates point -- 
539 // -- flare creates point --                    render_face(segp-Segments, sidenum, 3, tri_verts, sidep->tmap_num, sidep->tmap_num2, tri_uvls, &normals[0]);
540 // -- flare creates point --            }
541 // -- flare creates point -- 
542 // -- flare creates point --    return;
543 // -- flare creates point --    }
544 // -- flare creates point -- }
545
546                 if (v_dot_n0 >= 0) {
547                         render_face(segp-Segments, sidenum, 4, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls, wid_flags);
548                         #ifdef EDITOR
549                         check_face(segp-Segments, sidenum, 0, 4, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
550                         #endif
551                 }
552         } else {
553                 //      Regardless of whether this side is comprised of a single quad, or two triangles, we need to know one normal, so
554                 //      deal with it, get the dot product.
555                 if (sidep->type == SIDE_IS_TRI_13)
556                         vm_vec_normalized_dir_quick(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][1]]]);
557                 else
558                         vm_vec_normalized_dir_quick(&tvec, &Viewer_eye, &Vertices[segp->verts[Side_to_verts[sidenum][0]]]);
559
560                 get_side_verts(vertnum_list,segp-Segments,sidenum);
561
562                 v_dot_n0 = vm_vec_dot(&tvec, &normals[0]);
563
564                 //      ========== Mark: The change ends here. ==========
565
566                 //      Although this side has been triangulated, because it is not planar, see if it is acceptable
567                 //      to render it as a single quadrilateral.  This is a function of how far away the viewer is, how non-planar
568                 //      the face is, how normal to the surfaces the view is.
569                 //      Now, if both dot products are close to 1.0, then render two triangles as a single quad.
570                 v_dot_n1 = vm_vec_dot(&tvec, &normals[1]);
571
572                 if (v_dot_n0 < v_dot_n1) {
573                         min_dot = v_dot_n0;
574                         max_dot = v_dot_n1;
575                 } else {
576                         min_dot = v_dot_n1;
577                         max_dot = v_dot_n0;
578                 }
579
580                 //      Determine whether to detriangulate side: (speed hack, assumes Tulate_min_ratio == F1_0*2, should fixmul(min_dot, Tulate_min_ratio))
581                 if (Detriangulation_on && ((min_dot+F1_0/256 > max_dot) || ((Viewer->segnum != segp-Segments) &&  (min_dot > Tulate_min_dot) && (max_dot < min_dot*2)))) {
582                         fix     n0_dot_n1;
583
584                         //      The other detriangulation code doesn't deal well with badly non-planar sides.
585                         n0_dot_n1 = vm_vec_dot(&normals[0], &normals[1]);
586                         if (n0_dot_n1 < Min_n0_n1_dot)
587                                 goto im_so_ashamed;
588
589                         render_face(segp-Segments, sidenum, 4, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls, wid_flags);
590                         #ifdef EDITOR
591                         check_face(segp-Segments, sidenum, 0, 4, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
592                         #endif
593                 } else {
594 im_so_ashamed: ;
595                         if (sidep->type == SIDE_IS_TRI_02) {
596                                 if (v_dot_n0 >= 0) {
597                                         render_face(segp-Segments, sidenum, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls, wid_flags);
598                                         #ifdef EDITOR
599                                         check_face(segp-Segments, sidenum, 0, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
600                                         #endif
601                                 }
602
603                                 if (v_dot_n1 >= 0) {
604                                         temp_uvls[0] = sidep->uvls[0];          temp_uvls[1] = sidep->uvls[2];          temp_uvls[2] = sidep->uvls[3];
605                                         vertnum_list[1] = vertnum_list[2];      vertnum_list[2] = vertnum_list[3];      // want to render from vertices 0, 2, 3 on side
606                                         render_face(segp-Segments, sidenum, 3, &vertnum_list[0], sidep->tmap_num, sidep->tmap_num2, temp_uvls, wid_flags);
607                                         #ifdef EDITOR
608                                         check_face(segp-Segments, sidenum, 1, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
609                                         #endif
610                                 }
611                         } else if (sidep->type ==  SIDE_IS_TRI_13) {
612                                 if (v_dot_n1 >= 0) {
613                                         render_face(segp-Segments, sidenum, 3, &vertnum_list[1], sidep->tmap_num, sidep->tmap_num2, &sidep->uvls[1], wid_flags);        // rendering 1,2,3, so just skip 0
614                                         #ifdef EDITOR
615                                         check_face(segp-Segments, sidenum, 1, 3, &vertnum_list[1], sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
616                                         #endif
617                                 }
618
619                                 if (v_dot_n0 >= 0) {
620                                         temp_uvls[0] = sidep->uvls[0];          temp_uvls[1] = sidep->uvls[1];          temp_uvls[2] = sidep->uvls[3];
621                                         vertnum_list[2] = vertnum_list[3];              // want to render from vertices 0,1,3
622                                         render_face(segp-Segments, sidenum, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, temp_uvls, wid_flags);
623                                         #ifdef EDITOR
624                                         check_face(segp-Segments, sidenum, 0, 3, vertnum_list, sidep->tmap_num, sidep->tmap_num2, sidep->uvls);
625                                         #endif
626                                 }
627
628                         } else
629                                 Error("Illegal side type in render_side, type = %i, segment # = %i, side # = %i\n", sidep->type, segp-Segments, sidenum);
630                 }
631         }
632
633 }
634
635 #ifdef EDITOR
636 void render_object_search(object *obj)
637 {
638         int changed=0;
639
640         //note that we draw each pixel object twice, since we cannot control
641         //what color the object draws in, so we try color 0, then color 1,
642         //in case the object itself is rendering color 0
643
644         gr_setcolor(0);
645         gr_pixel(_search_x,_search_y);  //set our search pixel to color zero
646         render_object(obj);
647         if (gr_ugpixel(&grd_curcanv->cv_bitmap,_search_x,_search_y) != 0)
648                 changed=1;
649
650         gr_setcolor(1);
651         gr_pixel(_search_x,_search_y);  //set our search pixel to color zero
652         render_object(obj);
653         if (gr_ugpixel(&grd_curcanv->cv_bitmap,_search_x,_search_y) != 1)
654                 changed=1;
655
656         if (changed) {
657                 if (obj->segnum != -1)
658                         Cursegp = &Segments[obj->segnum];
659                 found_seg = -(obj-Objects+1);
660         }
661 }
662 #endif
663
664 extern ubyte DemoDoingRight,DemoDoingLeft;
665
666 void do_render_object(int objnum, int window_num)
667 {
668         #ifdef EDITOR
669         int save_3d_outline;
670         #endif
671         object *obj = &Objects[objnum];
672         int count = 0;
673         int n;
674
675         Assert(objnum < MAX_OBJECTS);
676
677         #ifndef NDEBUG
678         if (object_rendered[objnum]) {          //already rendered this...
679                 Int3();         //get Matt!!!
680                 return;
681         }
682
683         object_rendered[objnum] = 1;
684         #endif
685
686    if (Newdemo_state==ND_STATE_PLAYBACK)  
687          {
688           if ((DemoDoingLeft==6 || DemoDoingRight==6) && Objects[objnum].type==OBJ_PLAYER)
689                 {
690                         // A nice fat hack: keeps the player ship from showing up in the
691                         // small extra view when guiding a missile in the big window
692                         
693                         mprintf ((0,"Returning from render_object prematurely...\n"));
694                         return; 
695                 }
696          }
697
698         //      Added by MK on 09/07/94 (at about 5:28 pm, CDT, on a beautiful, sunny late summer day!) so
699         //      that the guided missile system will know what objects to look at.
700         //      I didn't know we had guided missiles before the release of D1. --MK
701         if ((Objects[objnum].type == OBJ_ROBOT) || (Objects[objnum].type == OBJ_PLAYER)) {
702                 //Assert(Window_rendered_data[window_num].rendered_objects < MAX_RENDERED_OBJECTS);
703                 //      This peculiar piece of code makes us keep track of the most recently rendered objects, which
704                 //      are probably the higher priority objects, without overflowing the buffer
705                 if (Window_rendered_data[window_num].num_objects >= MAX_RENDERED_OBJECTS) {
706                         Int3();
707                         Window_rendered_data[window_num].num_objects /= 2;
708                 }
709                 Window_rendered_data[window_num].rendered_objects[Window_rendered_data[window_num].num_objects++] = objnum;
710         }
711
712         if ((count++ > MAX_OBJECTS) || (obj->next == objnum)) {
713                 Int3();                                 // infinite loop detected
714                 obj->next = -1;         // won't this clean things up?
715                 return;                                 // get out of this infinite loop!
716         }
717
718                 //g3_draw_object(obj->class_id,&obj->pos,&obj->orient,obj->size);
719
720         //check for editor object
721
722         #ifdef EDITOR
723         if (Function_mode==FMODE_EDITOR && objnum==Cur_object_index) {
724                 save_3d_outline = g3d_interp_outline;
725                 g3d_interp_outline=1;
726         }
727         #endif
728
729         #ifdef EDITOR
730         if (_search_mode)
731                 render_object_search(obj);
732         else
733         #endif
734                 //NOTE LINK TO ABOVE
735                 render_object(obj);
736
737         for (n=obj->attached_obj;n!=-1;n=Objects[n].ctype.expl_info.next_attach) {
738
739                 Assert(Objects[n].type == OBJ_FIREBALL);
740                 Assert(Objects[n].control_type == CT_EXPLOSION);
741                 Assert(Objects[n].flags & OF_ATTACHED);
742
743                 render_object(&Objects[n]);
744         }
745
746
747         #ifdef EDITOR
748         if (Function_mode==FMODE_EDITOR && objnum==Cur_object_index)
749                 g3d_interp_outline = save_3d_outline;
750         #endif
751
752
753         //DEBUG mprintf( (0, "%d ", objnum ));
754
755 }
756
757 #ifndef NDEBUG
758 int     draw_boxes=0;
759 int window_check=1,draw_edges=0,new_seg_sorting=1,pre_draw_segs=0;
760 int no_migrate_segs=1,migrate_objects=1,behind_check=1;
761 int check_window_check=0;
762 #else
763 #define draw_boxes                      0
764 #define window_check                    1
765 #define draw_edges                      0
766 #define new_seg_sorting         1
767 #define pre_draw_segs           0
768 #define no_migrate_segs         1
769 #define migrate_objects         1
770 #define behind_check                    1
771 #define check_window_check      0
772 #endif
773
774 //increment counter for checking if points rotated
775 //This must be called at the start of the frame if rotate_list() will be used
776 void render_start_frame()
777 {
778         RL_framecount++;
779
780         if (RL_framecount==0) {         //wrap!
781
782                 memset(Rotated_last,0,sizeof(Rotated_last));            //clear all to zero
783                 RL_framecount=1;                                                                                        //and set this frame to 1
784         }
785 }
786
787 //Given a lit of point numbers, rotate any that haven't been rotated this frame
788 g3s_codes rotate_list(int nv,short *pointnumlist)
789 {
790         int i,pnum;
791         g3s_point *pnt;
792         g3s_codes cc;
793
794         cc.and = 0xff;  cc.or = 0;
795
796         for (i=0;i<nv;i++) {
797
798                 pnum = pointnumlist[i];
799
800                 pnt = &Segment_points[pnum];
801
802                 if (Rotated_last[pnum] != RL_framecount) {
803
804                         g3_rotate_point(pnt,&Vertices[pnum]);
805
806                         Rotated_last[pnum] = RL_framecount;
807                 }
808
809                 cc.and &= pnt->p3_codes;
810                 cc.or  |= pnt->p3_codes;
811         }
812
813         return cc;
814
815 }
816
817 //Given a lit of point numbers, project any that haven't been projected
818 void project_list(int nv,short *pointnumlist)
819 {
820         int i,pnum;
821
822         for (i=0;i<nv;i++) {
823
824                 pnum = pointnumlist[i];
825
826                 if (!(Segment_points[pnum].p3_flags & PF_PROJECTED))
827
828                         g3_project_point(&Segment_points[pnum]);
829
830         }
831 }
832
833
834 // -----------------------------------------------------------------------------------
835 void render_segment(int segnum, int window_num)
836 {
837         segment         *seg = &Segments[segnum];
838         g3s_codes       cc;
839         int                     sn;
840
841         Assert(segnum!=-1 && segnum<=Highest_segment_index);
842
843         cc=rotate_list(8,seg->verts);
844
845         if (! cc.and) {         //all off screen?
846
847 //mprintf( (0, "!"));
848                 //DEBUG mprintf( (0, "[Segment %d: ", segnum ));
849
850                 // set_segment_local_light_value(segnum,INITIAL_LOCAL_LIGHT);
851
852       if (Viewer->type!=OBJ_ROBOT)
853                 Automap_visited[segnum]=1;
854
855                 for (sn=0; sn<MAX_SIDES_PER_SEGMENT; sn++)
856                         render_side(seg, sn);
857         }
858
859         //draw any objects that happen to be in this segment
860
861         //sort objects!
862         //object_sort_segment_objects( seg );
863                 
864         #ifndef NDEBUG
865         if (!migrate_objects) {
866                 int objnum;
867                 for (objnum=seg->objects;objnum!=-1;objnum=Objects[objnum].next)
868                         do_render_object(objnum, window_num);
869         }
870         #endif
871
872         //DEBUG mprintf( (0, "]\n", segnum ));
873
874 }
875
876 // ----- This used to be called when Show_only_curside was set.
877 // ----- It is wholly and superiorly replaced by render_side.
878 // -- //render one side of one segment
879 // -- void render_seg_side(segment *seg,int _side)
880 // -- {
881 // --   g3s_codes cc;
882 // --   short vertnum_list[4];
883 // -- 
884 // --   cc=g3_rotate_list(8,&seg->verts);
885 // -- 
886 // --   if (! cc.and) {         //all off screen?
887 // --           int fn,pn,i;
888 // --           side *s;
889 // --           face *f;
890 // --           poly *p;
891 // -- 
892 // --           s=&seg->sides[_side];
893 // -- 
894 // --           for (f=s->faces,fn=s->num_faces;fn;fn--,f++)
895 // --                   for (p=f->polys,pn=f->num_polys;pn;pn--,p++) {
896 // --                           grs_bitmap *tmap;
897 // --   
898 // --                           for (i=0;i<p->num_vertices;i++) vertnum_list[i] = seg->verts[p->verts[i]];
899 // --   
900 // --                           if (p->tmap_num >= NumTextures) {
901 // --                                   Warning("Invalid tmap number %d, NumTextures=%d\n...Changing in poly structure to tmap 0",p->tmap_num,NumTextures);
902 // --                                   p->tmap_num = 0;                //change it permanantly
903 // --                           }
904 // --   
905 // --                           tmap = Textures[p->tmap_num];
906 // --   
907 // --                           g3_check_and_draw_tmap(p->num_vertices,vertnum_list,(g3s_uvl *) &p->uvls,tmap,&f->normal);
908 // --   
909 // --                           if (Outline_mode) draw_outline(p->num_vertices,vertnum_list);
910 // --                   }
911 // --           }
912 // -- 
913 // -- }
914
915 #define CROSS_WIDTH  i2f(8)
916 #define CROSS_HEIGHT i2f(8)
917
918 #ifndef NDEBUG
919
920 //draw outline for curside
921 void outline_seg_side(segment *seg,int _side,int edge,int vert)
922 {
923         g3s_codes cc;
924
925         cc=rotate_list(8,seg->verts);
926
927         if (! cc.and) {         //all off screen?
928                 side *s;
929                 g3s_point *pnt;
930
931                 s=&seg->sides[_side];
932
933                 //render curedge of curside of curseg in green
934
935                 gr_setcolor(BM_XRGB(0,63,0));
936                 g3_draw_line(&Segment_points[seg->verts[Side_to_verts[_side][edge]]],&Segment_points[seg->verts[Side_to_verts[_side][(edge+1)%4]]]);
937
938                 //draw a little cross at the current vert
939
940                 pnt = &Segment_points[seg->verts[Side_to_verts[_side][vert]]];
941
942                 g3_project_point(pnt);          //make sure projected
943
944 //              gr_setcolor(BM_XRGB(0,0,63));
945 //              gr_line(pnt->p3_sx-CROSS_WIDTH,pnt->p3_sy,pnt->p3_sx+CROSS_WIDTH,pnt->p3_sy);
946 //              gr_line(pnt->p3_sx,pnt->p3_sy-CROSS_HEIGHT,pnt->p3_sx,pnt->p3_sy+CROSS_HEIGHT);
947
948                 gr_line(pnt->p3_sx-CROSS_WIDTH,pnt->p3_sy,pnt->p3_sx,pnt->p3_sy-CROSS_HEIGHT);
949                 gr_line(pnt->p3_sx,pnt->p3_sy-CROSS_HEIGHT,pnt->p3_sx+CROSS_WIDTH,pnt->p3_sy);
950                 gr_line(pnt->p3_sx+CROSS_WIDTH,pnt->p3_sy,pnt->p3_sx,pnt->p3_sy+CROSS_HEIGHT);
951                 gr_line(pnt->p3_sx,pnt->p3_sy+CROSS_HEIGHT,pnt->p3_sx-CROSS_WIDTH,pnt->p3_sy);
952         }
953 }
954
955 #endif
956
957 #if 0           //this stuff could probably just be deleted
958
959 #define DEFAULT_PERSPECTIVE_DEPTH 6
960
961 int Perspective_depth=DEFAULT_PERSPECTIVE_DEPTH;        //how many levels deep to render in perspective
962
963 int inc_perspective_depth(void)
964 {
965         return ++Perspective_depth;
966
967 }
968
969 int dec_perspective_depth(void)
970 {
971         return Perspective_depth==1?Perspective_depth:--Perspective_depth;
972
973 }
974
975 int reset_perspective_depth(void)
976 {
977         return Perspective_depth = DEFAULT_PERSPECTIVE_DEPTH;
978
979 }
980 #endif
981
982 typedef struct window {
983         short left,top,right,bot;
984 } window;
985
986 ubyte code_window_point(fix x,fix y,window *w)
987 {
988         ubyte code=0;
989
990         if (x <= w->left)  code |= 1;
991         if (x >= w->right) code |= 2;
992
993         if (y <= w->top) code |= 4;
994         if (y >= w->bot) code |= 8;
995
996         return code;
997 }
998
999 #ifndef NDEBUG
1000 void draw_window_box(int color,short left,short top,short right,short bot)
1001 {
1002         short l,t,r,b;
1003
1004         gr_setcolor(color);
1005
1006         l=left; t=top; r=right; b=bot;
1007
1008         if ( r<0 || b<0 || l>=grd_curcanv->cv_bitmap.bm_w || (t>=grd_curcanv->cv_bitmap.bm_h && b>=grd_curcanv->cv_bitmap.bm_h))
1009                 return;
1010
1011         if (l<0) l=0;
1012         if (t<0) t=0;
1013         if (r>=grd_curcanv->cv_bitmap.bm_w) r=grd_curcanv->cv_bitmap.bm_w-1;
1014         if (b>=grd_curcanv->cv_bitmap.bm_h) b=grd_curcanv->cv_bitmap.bm_h-1;
1015
1016         gr_line(i2f(l),i2f(t),i2f(r),i2f(t));
1017         gr_line(i2f(r),i2f(t),i2f(r),i2f(b));
1018         gr_line(i2f(r),i2f(b),i2f(l),i2f(b));
1019         gr_line(i2f(l),i2f(b),i2f(l),i2f(t));
1020
1021 }
1022 #endif
1023
1024 int matt_find_connect_side(int seg0,int seg1);
1025
1026 #ifndef NDEBUG
1027 char visited2[MAX_SEGMENTS];
1028 #endif
1029
1030 char visited[MAX_SEGMENTS];
1031 short Render_list[MAX_RENDER_SEGS];
1032 short Seg_depth[MAX_RENDER_SEGS];               //depth for each seg in Render_list
1033 ubyte processed[MAX_RENDER_SEGS];               //whether each entry has been processed
1034 int     lcnt_save,scnt_save;
1035 //@@short *persp_ptr;
1036 short render_pos[MAX_SEGMENTS]; //where in render_list does this segment appear?
1037 //ubyte no_render_flag[MAX_RENDER_SEGS];
1038 window render_windows[MAX_RENDER_SEGS];
1039
1040 short render_obj_list[MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS][OBJS_PER_SEG];
1041
1042 //for objects
1043
1044
1045
1046 #define RED   BM_XRGB(63,0,0)
1047 #define WHITE BM_XRGB(63,63,63)
1048
1049 //Given two sides of segment, tell the two verts which form the 
1050 //edge between them
1051 short Two_sides_to_edge[6][6][2] = {
1052         { {-1,-1}, {3,7}, {-1,-1}, {2,6}, {6,7}, {2,3} },
1053         { {3,7}, {-1,-1}, {0,4}, {-1,-1}, {4,7}, {0,3} },
1054         { {-1,-1}, {0,4}, {-1,-1}, {1,5}, {4,5}, {0,1} },
1055         { {2,6}, {-1,-1}, {1,5}, {-1,-1}, {5,6}, {1,2} },
1056         { {6,7}, {4,7}, {4,5}, {5,6}, {-1,-1}, {-1,-1} },
1057         { {2,3}, {0,3}, {0,1}, {1,2}, {-1,-1}, {-1,-1} }
1058 };
1059
1060 //given an edge specified by two verts, give the two sides on that edge
1061 int Edge_to_sides[8][8][2] = {
1062         { {-1,-1}, {2,5}, {-1,-1}, {1,5}, {1,2}, {-1,-1}, {-1,-1}, {-1,-1} },
1063         { {2,5}, {-1,-1}, {3,5}, {-1,-1}, {-1,-1}, {2,3}, {-1,-1}, {-1,-1} },
1064         { {-1,-1}, {3,5}, {-1,-1}, {0,5}, {-1,-1}, {-1,-1}, {0,3}, {-1,-1} },
1065         { {1,5}, {-1,-1}, {0,5}, {-1,-1}, {-1,-1}, {-1,-1}, {-1,-1}, {0,1} },
1066         { {1,2}, {-1,-1}, {-1,-1}, {-1,-1}, {-1,-1}, {2,4}, {-1,-1}, {1,4} },
1067         { {-1,-1}, {2,3}, {-1,-1}, {-1,-1}, {2,4}, {-1,-1}, {3,4}, {-1,-1} },
1068         { {-1,-1}, {-1,-1}, {0,3}, {-1,-1}, {-1,-1}, {3,4}, {-1,-1}, {0,4} },
1069         { {-1,-1}, {-1,-1}, {-1,-1}, {0,1}, {1,4}, {-1,-1}, {0,4}, {-1,-1} },
1070 };
1071
1072 //@@//perform simple check on tables
1073 //@@check_check()
1074 //@@{
1075 //@@    int i,j;
1076 //@@
1077 //@@    for (i=0;i<8;i++)
1078 //@@            for (j=0;j<8;j++)
1079 //@@                    Assert(Edge_to_sides[i][j][0] == Edge_to_sides[j][i][0] && 
1080 //@@                                    Edge_to_sides[i][j][1] == Edge_to_sides[j][i][1]);
1081 //@@
1082 //@@    for (i=0;i<6;i++)
1083 //@@            for (j=0;j<6;j++)
1084 //@@                    Assert(Two_sides_to_edge[i][j][0] == Two_sides_to_edge[j][i][0] && 
1085 //@@                                    Two_sides_to_edge[i][j][1] == Two_sides_to_edge[j][i][1]);
1086 //@@
1087 //@@
1088 //@@}
1089
1090
1091 //given an edge, tell what side is on that edge
1092 int find_seg_side(segment *seg,short *verts,int notside)
1093 {
1094         int i;
1095         int vv0=-1,vv1=-1;
1096         int side0,side1;
1097         int *eptr;
1098         int     v0,v1;
1099         short   *vp;
1100
1101 //@@    check_check();
1102
1103         v0 = verts[0];
1104         v1 = verts[1];
1105         vp = seg->verts;
1106
1107         for (i=0; i<8; i++) {
1108                 int svv = *vp++;        // seg->verts[i];
1109
1110                 if (vv0==-1 && svv == v0) {
1111                         vv0 = i;
1112                         if (vv1 != -1)
1113                                 break;
1114                 }
1115
1116                 if (vv1==-1 && svv == v1) {
1117                         vv1 = i;
1118                         if (vv0 != -1)
1119                                 break;
1120                 }
1121         }
1122
1123         Assert(vv0!=-1 && vv1!=-1);
1124
1125         eptr = Edge_to_sides[vv0][vv1];
1126
1127         side0 = eptr[0];
1128         side1 = eptr[1];
1129
1130         Assert(side0!=-1 && side1!=-1);
1131
1132         if (side0 != notside) {
1133                 Assert(side1==notside);
1134                 return side0;
1135         }
1136         else {
1137                 Assert(side0==notside);
1138                 return side1;
1139         }
1140
1141 }
1142
1143 //find the two segments that join a given seg though two sides, and
1144 //the sides of those segments the abut. 
1145 int find_joining_side_norms(vms_vector *norm0_0,vms_vector *norm0_1,vms_vector *norm1_0,vms_vector *norm1_1,vms_vector **pnt0,vms_vector **pnt1,segment *seg,int s0,int s1)
1146 {
1147         segment *seg0,*seg1;
1148         short edge_verts[2];
1149         int notside0,notside1;
1150         int edgeside0,edgeside1;
1151
1152         Assert(s0!=-1 && s1!=-1);
1153
1154         seg0 = &Segments[seg->children[s0]];
1155         seg1 = &Segments[seg->children[s1]];
1156
1157         edge_verts[0] = seg->verts[Two_sides_to_edge[s0][s1][0]];
1158         edge_verts[1] = seg->verts[Two_sides_to_edge[s0][s1][1]];
1159
1160         Assert(edge_verts[0]!=-1 && edge_verts[1]!=-1);
1161
1162         notside0 = find_connect_side(seg,seg0);
1163         Assert(notside0 != -1);
1164         notside1 = find_connect_side(seg,seg1);
1165         Assert(notside1 != -1);
1166
1167         edgeside0 = find_seg_side(seg0,edge_verts,notside0);
1168         edgeside1 = find_seg_side(seg1,edge_verts,notside1);
1169
1170         //deal with the case where an edge is shared by more than two segments
1171
1172 //@@    if (IS_CHILD(seg0->children[edgeside0])) {
1173 //@@            segment *seg00;
1174 //@@            int notside00;
1175 //@@
1176 //@@            seg00 = &Segments[seg0->children[edgeside0]];
1177 //@@
1178 //@@            if (seg00 != seg1) {
1179 //@@
1180 //@@                    notside00 = find_connect_side(seg0,seg00);
1181 //@@                    Assert(notside00 != -1);
1182 //@@
1183 //@@                    edgeside0 = find_seg_side(seg00,edge_verts,notside00);
1184 //@@                    seg0 = seg00;
1185 //@@            }
1186 //@@
1187 //@@    }
1188 //@@
1189 //@@    if (IS_CHILD(seg1->children[edgeside1])) {
1190 //@@            segment *seg11;
1191 //@@            int notside11;
1192 //@@
1193 //@@            seg11 = &Segments[seg1->children[edgeside1]];
1194 //@@
1195 //@@            if (seg11 != seg0) {
1196 //@@                    notside11 = find_connect_side(seg1,seg11);
1197 //@@                    Assert(notside11 != -1);
1198 //@@
1199 //@@                    edgeside1 = find_seg_side(seg11,edge_verts,notside11);
1200 //@@                    seg1 = seg11;
1201 //@@            }
1202 //@@    }
1203
1204 //      if ( IS_CHILD(seg0->children[edgeside0]) ||
1205 //                IS_CHILD(seg1->children[edgeside1])) 
1206 //              return 0;
1207
1208         #ifdef COMPACT_SEGS
1209                 get_side_normals(seg0, edgeside0, norm0_0, norm0_1 );
1210                 get_side_normals(seg1, edgeside1, norm1_0, norm1_1 );
1211         #else 
1212                 *norm0_0 = seg0->sides[edgeside0].normals[0];
1213                 *norm0_1 = seg0->sides[edgeside0].normals[1];
1214                 *norm1_0 = seg1->sides[edgeside1].normals[0];
1215                 *norm1_1 = seg1->sides[edgeside1].normals[1];
1216         #endif
1217
1218         *pnt0 = &Vertices[seg0->verts[Side_to_verts[edgeside0][seg0->sides[edgeside0].type==3?1:0]]];
1219         *pnt1 = &Vertices[seg1->verts[Side_to_verts[edgeside1][seg1->sides[edgeside1].type==3?1:0]]];
1220
1221         return 1;
1222 }
1223
1224 //see if the order matters for these two children.
1225 //returns 0 if order doesn't matter, 1 if c0 before c1, -1 if c1 before c0
1226 int compare_children(segment *seg,short c0,short c1)
1227 {
1228         vms_vector norm0_0,norm0_1,*pnt0,temp;
1229         vms_vector norm1_0,norm1_1,*pnt1;
1230         fix d0_0,d0_1,d1_0,d1_1,d0,d1;
1231 int t;
1232
1233         if (Side_opposite[c0] == c1) return 0;
1234
1235         Assert(c0!=-1 && c1!=-1);
1236
1237         //find normals of adjoining sides
1238
1239         t = find_joining_side_norms(&norm0_0,&norm0_1,&norm1_0,&norm1_1,&pnt0,&pnt1,seg,c0,c1);
1240
1241 //if (!t)
1242 // return 0;
1243
1244         vm_vec_sub(&temp,&Viewer_eye,pnt0);
1245         d0_0 = vm_vec_dot(&norm0_0,&temp);
1246         d0_1 = vm_vec_dot(&norm0_1,&temp);
1247
1248         vm_vec_sub(&temp,&Viewer_eye,pnt1);
1249         d1_0 = vm_vec_dot(&norm1_0,&temp);
1250         d1_1 = vm_vec_dot(&norm1_1,&temp);
1251
1252         d0 = (d0_0 < 0 || d0_1 < 0)?-1:1;
1253         d1 = (d1_0 < 0 || d1_1 < 0)?-1:1;
1254
1255         if (d0 < 0 && d1 < 0)
1256                 return 0;
1257
1258         if (d0 < 0)
1259                 return 1;
1260         else if (d1 < 0)
1261                 return -1;
1262         else
1263                 return 0;
1264
1265 }
1266
1267 int ssc_total=0,ssc_swaps=0;
1268
1269 //short the children of segment to render in the correct order
1270 //returns non-zero if swaps were made
1271 int sort_seg_children(segment *seg,int n_children,short *child_list)
1272 {
1273         int i,j;
1274         int r;
1275         int made_swaps,count;
1276
1277         if (n_children == 0) return 0;
1278
1279  ssc_total++;
1280
1281         //for each child,  compare with other children and see if order matters
1282         //if order matters, fix if wrong
1283
1284         count = 0;
1285
1286         do {
1287                 made_swaps = 0;
1288
1289                 for (i=0;i<n_children-1;i++)
1290                         for (j=i+1;child_list[i]!=-1 && j<n_children;j++)
1291                                 if (child_list[j]!=-1) {
1292                                         r = compare_children(seg,child_list[i],child_list[j]);
1293
1294                                         if (r == 1) {
1295                                                 int temp = child_list[i];
1296                                                 child_list[i] = child_list[j];
1297                                                 child_list[j] = temp;
1298                                                 made_swaps=1;
1299                                         }
1300                                 }
1301
1302         } while (made_swaps && ++count<n_children);
1303
1304  if (count)
1305   ssc_swaps++;
1306
1307         return count;
1308 }
1309
1310 void add_obj_to_seglist(int objnum,int listnum)
1311 {
1312         int i,checkn,marker;
1313
1314         checkn = listnum;
1315
1316         //first, find a slot
1317
1318 //mprintf((0,"adding obj %d to %d",objnum,listnum));
1319
1320         do {
1321
1322                 for (i=0;render_obj_list[checkn][i] >= 0;i++);
1323         
1324                 Assert(i < OBJS_PER_SEG);
1325         
1326                 marker = render_obj_list[checkn][i];
1327
1328                 if (marker != -1) {
1329                         checkn = -marker;
1330                         //Assert(checkn < MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS);
1331                         if (checkn >= MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS) {
1332                                 Int3();
1333                                 return;
1334                         }
1335                 }
1336
1337         } while (marker != -1);
1338
1339 //mprintf((0,"  slot %d,%d",checkn,i));
1340
1341
1342         //now we have found a slot.  put object in it
1343
1344         if (i != OBJS_PER_SEG-1) {
1345
1346                 render_obj_list[checkn][i] = objnum;
1347                 render_obj_list[checkn][i+1] = -1;
1348         }
1349         else {                          //chain to additional list
1350                 int lookn;
1351
1352                 //find an available sublist
1353
1354                 for (lookn=MAX_RENDER_SEGS;render_obj_list[lookn][0]!=-1 && lookn<MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS;lookn++);
1355
1356                 //Assert(lookn<MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS);
1357                 if (lookn >= MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS) {
1358                         Int3();
1359                         return;
1360                 }
1361
1362                 render_obj_list[checkn][i] = -lookn;
1363                 render_obj_list[lookn][0] = objnum;
1364                 render_obj_list[lookn][1] = -1;
1365
1366         }
1367
1368 //mprintf((0,"  added!\n"));
1369
1370 }
1371
1372 #define SORT_LIST_SIZE 100
1373
1374 typedef struct sort_item {
1375         int objnum;
1376         fix dist;
1377 } sort_item;
1378
1379 sort_item sort_list[SORT_LIST_SIZE];
1380 int n_sort_items;
1381
1382 //compare function for object sort. 
1383 int sort_func(const sort_item *a,const sort_item *b)
1384 {
1385         fix delta_dist;
1386         object *obj_a,*obj_b;
1387
1388         delta_dist = a->dist - b->dist;
1389
1390         obj_a = &Objects[a->objnum];
1391         obj_b = &Objects[b->objnum];
1392
1393         if (abs(delta_dist) < (obj_a->size + obj_b->size)) {            //same position
1394
1395                 //these two objects are in the same position.  see if one is a fireball
1396                 //or laser or something that should plot on top.  Don't do this for
1397                 //the afterburner blobs, though.
1398
1399                 if (obj_a->type == OBJ_WEAPON || (obj_a->type == OBJ_FIREBALL && obj_a->id != VCLIP_AFTERBURNER_BLOB))
1400                         if (!(obj_b->type == OBJ_WEAPON || obj_b->type == OBJ_FIREBALL))
1401                                 return -1;      //a is weapon, b is not, so say a is closer
1402                         else;                           //both are weapons 
1403                 else
1404                         if (obj_b->type == OBJ_WEAPON || (obj_b->type == OBJ_FIREBALL && obj_b->id != VCLIP_AFTERBURNER_BLOB))
1405                                 return 1;       //b is weapon, a is not, so say a is farther
1406
1407                 //no special case, fall through to normal return
1408         }
1409
1410         return delta_dist;      //return distance
1411 }
1412
1413 void build_object_lists(int n_segs)
1414 {
1415         int nn;
1416
1417 //mprintf((0,"build n_segs=%d",n_segs));
1418
1419         for (nn=0;nn<MAX_RENDER_SEGS+N_EXTRA_OBJ_LISTS;nn++)
1420                 render_obj_list[nn][0] = -1;
1421
1422         for (nn=0;nn<n_segs;nn++) {
1423                 int segnum;
1424
1425                 segnum = Render_list[nn];
1426
1427 //mprintf((0,"nn=%d seg=%d ",nn,segnum));
1428
1429                 if (segnum != -1) {
1430                         int objnum;
1431                         object *obj;
1432
1433                         for (objnum=Segments[segnum].objects;objnum!=-1;objnum = obj->next) {
1434                                 int new_segnum,did_migrate,list_pos;
1435
1436                                 obj = &Objects[objnum];
1437
1438                                 Assert( obj->segnum == segnum );
1439
1440                                 if (obj->flags & OF_ATTACHED)
1441                                         continue;               //ignore this object
1442
1443                                 new_segnum = segnum;
1444                                 list_pos = nn;
1445
1446 //mprintf((0,"objnum=%d ",objnum));
1447                                 if (obj->type != OBJ_CNTRLCEN && !(obj->type==OBJ_ROBOT && obj->id==65))                //don't migrate controlcen
1448                                 do {
1449                                         segmasks m;
1450
1451                                         did_migrate = 0;
1452         
1453                                         m = get_seg_masks(&obj->pos,new_segnum,obj->size);
1454         
1455                                         if (m.sidemask) {
1456                                                 int sn,sf;
1457
1458                                                 for (sn=0,sf=1;sn<6;sn++,sf<<=1)
1459                                                         if (m.sidemask & sf) {
1460                                                                 segment *seg = &Segments[new_segnum];
1461                 
1462                                                                 if (WALL_IS_DOORWAY(seg,sn) & WID_FLY_FLAG) {           //can explosion migrate through
1463                                                                         int child = seg->children[sn];
1464                                                                         int checknp;
1465                 
1466                                                                         for (checknp=list_pos;checknp--;)
1467                                                                                 if (Render_list[checknp] == child) {
1468 //mprintf((0,"mig from %d to %d ",new_segnum,child));
1469                                                                                         new_segnum = child;
1470                                                                                         list_pos = checknp;
1471                                                                                         did_migrate = 1;
1472                                                                                 }
1473                                                                 }
1474                                                         }
1475                                         }
1476         
1477                                 } while (0);    //while (did_migrate);
1478
1479                                 add_obj_to_seglist(objnum,list_pos);
1480         
1481                         }
1482
1483                 }
1484         }
1485
1486 //mprintf((0,"done build "));
1487
1488         //now that there's a list for each segment, sort the items in those lists
1489         for (nn=0;nn<n_segs;nn++) {
1490                 int segnum;
1491
1492                 segnum = Render_list[nn];
1493
1494 //mprintf((0,"nn=%d seg=%d ",nn,segnum));
1495
1496                 if (segnum != -1) {
1497                         int t,lookn,i,n;
1498
1499                         //first count the number of objects & copy into sort list
1500
1501                         lookn = nn;
1502                         i = n_sort_items = 0;
1503                         while ((t=render_obj_list[lookn][i++])!=-1)
1504                                 if (t<0)
1505                                         {lookn = -t; i=0;}
1506                                 else
1507                                         if (n_sort_items < SORT_LIST_SIZE-1) {          //add if room
1508                                                 sort_list[n_sort_items].objnum = t;
1509                                                 //NOTE: maybe use depth, not dist - quicker computation
1510                                                 sort_list[n_sort_items].dist = vm_vec_dist_quick(&Objects[t].pos,&Viewer_eye);
1511                                                 n_sort_items++;
1512                                         }
1513                                         else {                  //no room for object
1514                                                 int ii;
1515
1516                                                 #ifndef NDEBUG
1517                                                 FILE *tfile=fopen("sortlist.out","wt");
1518
1519                                                 //I find this strange, so I'm going to write out
1520                                                 //some information to look at later
1521                                                 if (tfile) {
1522                                                         for (ii=0;ii<SORT_LIST_SIZE;ii++) {
1523                                                                 int objnum = sort_list[ii].objnum;
1524
1525                                                                 fprintf(tfile,"Obj %3d  Type = %2d  Id = %2d  Dist = %08x  Segnum = %3d\n",
1526                                                                         objnum,Objects[objnum].type,Objects[objnum].id,sort_list[ii].dist,Objects[objnum].segnum);
1527                                                         }
1528                                                         fclose(tfile);
1529                                                 }
1530                                                 #endif
1531
1532                                                 Int3(); //Get Matt!!!
1533
1534                                                 //Now try to find a place for this object by getting rid
1535                                                 //of an object we don't care about
1536
1537                                                 for (ii=0;ii<SORT_LIST_SIZE;ii++) {
1538                                                         int objnum = sort_list[ii].objnum;
1539                                                         object *obj = &Objects[objnum];
1540                                                         int type = obj->type;
1541
1542                                                         //replace debris & fireballs
1543                                                         if (type == OBJ_DEBRIS || type == OBJ_FIREBALL) {
1544                                                                 fix dist = vm_vec_dist_quick(&Objects[t].pos,&Viewer_eye);
1545
1546                                                                 //don't replace same kind of object unless new 
1547                                                                 //one is closer
1548
1549                                                                 if (Objects[t].type != type || dist < sort_list[ii].dist) {
1550                                                                         sort_list[ii].objnum = t;
1551                                                                         sort_list[ii].dist = dist;
1552                                                                         break;
1553                                                                 }
1554                                                         }
1555                                                 }
1556
1557                                                 Int3(); //still couldn't find a slot
1558                                         }
1559
1560
1561                         //now call qsort
1562                 #if defined(__WATCOMC__) || defined(MACINTOSH)
1563                         qsort(sort_list,n_sort_items,sizeof(*sort_list),
1564                                    sort_func);
1565                 #else
1566                         qsort(sort_list,n_sort_items,sizeof(*sort_list),
1567                                         (int (*)(const void*,const void*))sort_func);
1568                 #endif  
1569
1570                         //now copy back into list
1571
1572                         lookn = nn;
1573                         i = 0;
1574                         n = n_sort_items;
1575                         while ((t=render_obj_list[lookn][i])!=-1 && n>0)
1576                                 if (t<0)
1577                                         {lookn = -t; i=0;}
1578                                 else
1579                                         render_obj_list[lookn][i++] = sort_list[--n].objnum;
1580                         render_obj_list[lookn][i] = -1; //mark (possibly new) end
1581                 }
1582         }
1583 }
1584
1585 int Use_player_head_angles = 0;
1586 vms_angvec Player_head_angles;
1587
1588 extern int Num_tmaps_drawn;
1589 extern int Total_pixels;
1590 //--unused-- int Total_num_tmaps_drawn=0;
1591
1592 int Rear_view=0;
1593 extern ubyte RenderingType;
1594
1595 void start_lighting_frame(object *viewer);
1596
1597 #ifdef JOHN_ZOOM
1598 fix Zoom_factor=F1_0;
1599 #endif
1600 //renders onto current canvas
1601 void render_frame(fix eye_offset, int window_num)
1602 {
1603         int start_seg_num;
1604
1605 #if defined(POLY_ACC)
1606 //$$ not needed for Verite, probably optional for ViRGE.    pa_flush();
1607 #endif
1608
1609 //Total_num_tmaps_drawn += Num_tmaps_drawn;
1610 //if ((FrameCount > 0) && (Total_num_tmaps_drawn))
1611 //      mprintf((0, "Frame: %4i, total = %6i, Avg = %7.3f, Avgpix=%7.3f\n", Num_tmaps_drawn, Total_num_tmaps_drawn, (float) Total_num_tmaps_drawn/FrameCount, (float) Total_pixels/Total_num_tmaps_drawn));
1612 //Num_tmaps_drawn = 0;
1613
1614         if (Endlevel_sequence) {
1615                 render_endlevel_frame(eye_offset);
1616                 FrameCount++;
1617                 return;
1618         }
1619
1620 #ifdef NEWDEMO
1621         if ( Newdemo_state == ND_STATE_RECORDING && eye_offset >= 0 )   {
1622      
1623           //    mprintf ((0,"Objnum=%d objtype=%d objid=%d\n",Viewer-Objects,Viewer->type,Viewer->id));
1624                 
1625       if (RenderingType==0)
1626                 newdemo_record_start_frame(FrameCount, FrameTime );
1627       if (RenderingType!=255)
1628                 newdemo_record_viewer_object(Viewer);
1629         }
1630 #endif
1631   
1632    //Here:
1633
1634         start_lighting_frame(Viewer);           //this is for ugly light-smoothing hack
1635   
1636         g3_start_frame();
1637
1638         Viewer_eye = Viewer->pos;
1639
1640 //      if (Viewer->type == OBJ_PLAYER && (Cockpit_mode!=CM_REAR_VIEW))
1641 //              vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.fvec,(Viewer->size*3)/4);
1642
1643         if (eye_offset) {
1644                 vm_vec_scale_add2(&Viewer_eye,&Viewer->orient.rvec,eye_offset);
1645         }
1646
1647         #ifdef EDITOR
1648         if (Function_mode==FMODE_EDITOR)
1649                 Viewer_eye = Viewer->pos;
1650         #endif
1651
1652         start_seg_num = find_point_seg(&Viewer_eye,Viewer->segnum);
1653
1654         if (start_seg_num==-1)
1655                 start_seg_num = Viewer->segnum;
1656
1657         if (Viewer==ConsoleObject && Use_player_head_angles) {
1658                 vms_matrix headm,viewm;
1659                 vm_angles_2_matrix(&headm,&Player_head_angles);
1660                 vm_matrix_x_matrix(&viewm,&Viewer->orient,&headm);
1661                 g3_set_view_matrix(&Viewer_eye,&viewm,Render_zoom);
1662         //@@} else if ((Cockpit_mode==CM_REAR_VIEW) && (Viewer==ConsoleObject)) {
1663         } else if (Rear_view && (Viewer==ConsoleObject)) {
1664                 vms_matrix headm,viewm;
1665                 Player_head_angles.p = Player_head_angles.b = 0;
1666                 Player_head_angles.h = 0x7fff;
1667                 vm_angles_2_matrix(&headm,&Player_head_angles);
1668                 vm_matrix_x_matrix(&viewm,&Viewer->orient,&headm);
1669                 g3_set_view_matrix(&Viewer_eye,&viewm,Render_zoom);
1670         } else  {
1671 #ifdef JOHN_ZOOM
1672                 if (keyd_pressed[KEY_RSHIFT] )  {
1673                         Zoom_factor += FrameTime*4;
1674                         if (Zoom_factor > F1_0*5 ) Zoom_factor=F1_0*5;
1675                 } else {
1676                         Zoom_factor -= FrameTime*4;
1677                         if (Zoom_factor < F1_0 ) Zoom_factor = F1_0;
1678                 }
1679                 g3_set_view_matrix(&Viewer_eye,&Viewer->orient,fixdiv(Render_zoom,Zoom_factor));
1680 #else
1681                 g3_set_view_matrix(&Viewer_eye,&Viewer->orient,Render_zoom);
1682 #endif
1683         }
1684
1685         if (Clear_window == 1) {
1686                 if (Clear_window_color == -1)
1687                         Clear_window_color = BM_XRGB(0, 0, 0);  //BM_XRGB(31, 15, 7);
1688                 gr_clear_canvas(Clear_window_color);
1689         }
1690         #ifndef NDEBUG
1691         if (Show_only_curside)
1692                 gr_clear_canvas(Clear_window_color);
1693         #endif
1694
1695         render_mine(start_seg_num,eye_offset, window_num);
1696
1697         if (Use_player_head_angles ) 
1698                 draw_3d_reticle(eye_offset);
1699
1700         g3_end_frame();
1701
1702    //RenderingType=0;
1703
1704         // -- Moved from here by MK, 05/17/95, wrong if multiple renders/frame! FrameCount++;           //we have rendered a frame
1705 }
1706
1707 int first_terminal_seg;
1708
1709 void update_rendered_data(int window_num, object *viewer, int rear_view_flag, int user)
1710 {
1711         Assert(window_num < MAX_RENDERED_WINDOWS);
1712         Window_rendered_data[window_num].frame = FrameCount;
1713         Window_rendered_data[window_num].viewer = viewer;
1714         Window_rendered_data[window_num].rear_view = rear_view_flag;
1715         Window_rendered_data[window_num].user = user;
1716 }
1717
1718 //build a list of segments to be rendered
1719 //fills in Render_list & N_render_segs
1720 void build_segment_list(int start_seg_num, int window_num)
1721 {
1722         int     lcnt,scnt,ecnt;
1723         int     l,c;
1724         int     ch;
1725
1726         memset(visited, 0, sizeof(visited[0])*(Highest_segment_index+1));
1727         memset(render_pos, -1, sizeof(render_pos[0])*(Highest_segment_index+1));
1728         //memset(no_render_flag, 0, sizeof(no_render_flag[0])*(MAX_RENDER_SEGS));
1729         memset(processed, 0, sizeof(processed));
1730
1731         #ifndef NDEBUG
1732         memset(visited2, 0, sizeof(visited2[0])*(Highest_segment_index+1));
1733         #endif
1734
1735         lcnt = scnt = 0;
1736
1737         Render_list[lcnt] = start_seg_num; visited[start_seg_num]=1;
1738         Seg_depth[lcnt] = 0;
1739         lcnt++;
1740         ecnt = lcnt;
1741         render_pos[start_seg_num] = 0;
1742
1743         #ifndef NDEBUG
1744         if (pre_draw_segs)
1745                 render_segment(start_seg_num, window_num);
1746         #endif
1747
1748         render_windows[0].left=render_windows[0].top=0;
1749         render_windows[0].right=grd_curcanv->cv_bitmap.bm_w-1;
1750         render_windows[0].bot=grd_curcanv->cv_bitmap.bm_h-1;
1751
1752         //breadth-first renderer
1753
1754         //build list
1755
1756         for (l=0;l<Render_depth;l++) {
1757
1758                 //while (scnt < ecnt) {
1759                 for (scnt=0;scnt < ecnt;scnt++) {
1760                         int rotated,segnum;
1761                         window *check_w;
1762                         short child_list[MAX_SIDES_PER_SEGMENT];                //list of ordered sides to process
1763                         int n_children;                                                                         //how many sides in child_list
1764                         segment *seg;
1765
1766                         if (processed[scnt])
1767                                 continue;
1768
1769                         processed[scnt]=1;
1770
1771                         segnum = Render_list[scnt];
1772                         check_w = &render_windows[scnt];
1773
1774                         #ifndef NDEBUG
1775                         if (draw_boxes)
1776                                 draw_window_box(RED,check_w->left,check_w->top,check_w->right,check_w->bot);
1777                         #endif
1778
1779                         if (segnum == -1) continue;
1780
1781                         seg = &Segments[segnum];
1782                         rotated=0;
1783
1784                         //look at all sides of this segment.
1785                         //tricky code to look at sides in correct order follows
1786
1787                         for (c=n_children=0;c<MAX_SIDES_PER_SEGMENT;c++) {              //build list of sides
1788                                 int wid;
1789
1790                                 wid = WALL_IS_DOORWAY(seg, c);
1791
1792                                 ch=seg->children[c];
1793
1794                                 if ( (window_check || !visited[ch]) && (wid & WID_RENDPAST_FLAG) ) {
1795                                         if (behind_check) {
1796                                                 byte *sv = Side_to_verts[c];
1797                                                 ubyte codes_and=0xff;
1798                                                 int i;
1799
1800                                                 rotate_list(8,seg->verts);
1801                                                 rotated=1;
1802
1803                                                 for (i=0;i<4;i++)
1804                                                         codes_and &= Segment_points[seg->verts[sv[i]]].p3_codes;
1805
1806                                                 if (codes_and & CC_BEHIND) continue;
1807
1808                                         }
1809                                         child_list[n_children++] = c;
1810                                 }
1811                         }
1812
1813                         //now order the sides in some magical way
1814
1815                         if (new_seg_sorting)
1816                                 sort_seg_children(seg,n_children,child_list);
1817
1818                         //for (c=0;c<MAX_SIDES_PER_SEGMENT;c++) {
1819                         //      ch=seg->children[c];
1820
1821                         for (c=0;c<n_children;c++) {
1822                                 int siden;
1823
1824                                 siden = child_list[c];
1825                                 ch=seg->children[siden];
1826                                 //if ( (window_check || !visited[ch])&& (WALL_IS_DOORWAY(seg, c))) {
1827                                 {
1828                                         if (window_check) {
1829                                                 int i;
1830                                                 ubyte codes_and_3d,codes_and_2d;
1831                                                 short _x,_y,min_x=32767,max_x=-32767,min_y=32767,max_y=-32767;
1832                                                 int no_proj_flag=0;     //a point wasn't projected
1833
1834                                                 if (rotated<2) {
1835                                                         if (!rotated)
1836                                                                 rotate_list(8,seg->verts);
1837                                                         project_list(8,seg->verts);
1838                                                         rotated=2;
1839                                                 }
1840
1841                                                 for (i=0,codes_and_3d=codes_and_2d=0xff;i<4;i++) {
1842                                                         int p = seg->verts[Side_to_verts[siden][i]];
1843                                                         g3s_point *pnt = &Segment_points[p];
1844
1845                                                         if (! (pnt->p3_flags&PF_PROJECTED)) {no_proj_flag=1; break;}
1846
1847                                                         _x = f2i(pnt->p3_sx);
1848                                                         _y = f2i(pnt->p3_sy);
1849
1850                                                         codes_and_3d &= pnt->p3_codes;
1851                                                         codes_and_2d &= code_window_point(_x,_y,check_w);
1852
1853                                                         #ifndef NDEBUG
1854                                                         if (draw_edges) {
1855                                                                 gr_setcolor(BM_XRGB(31,0,31));
1856                                                                 gr_line(pnt->p3_sx,pnt->p3_sy,
1857                                                                         Segment_points[seg->verts[Side_to_verts[siden][(i+1)%4]]].p3_sx,
1858                                                                         Segment_points[seg->verts[Side_to_verts[siden][(i+1)%4]]].p3_sy);
1859                                                         }
1860                                                         #endif
1861
1862                                                         if (_x < min_x) min_x = _x;
1863                                                         if (_x > max_x) max_x = _x;
1864
1865                                                         if (_y < min_y) min_y = _y;
1866                                                         if (_y > max_y) max_y = _y;
1867
1868                                                 }
1869
1870                                                 #ifndef NDEBUG
1871                                                 if (draw_boxes)
1872                                                         draw_window_box(WHITE,min_x,min_y,max_x,max_y);
1873                                                 #endif
1874
1875                                                 if (no_proj_flag || (!codes_and_3d && !codes_and_2d)) { //maybe add this segment
1876                                                         int rp = render_pos[ch];
1877                                                         window *new_w = &render_windows[lcnt];
1878
1879                                                         if (no_proj_flag) *new_w = *check_w;
1880                                                         else {
1881                                                                 new_w->left  = max(check_w->left,min_x);
1882                                                                 new_w->right = min(check_w->right,max_x);
1883                                                                 new_w->top   = max(check_w->top,min_y);
1884                                                                 new_w->bot   = min(check_w->bot,max_y);
1885                                                         }
1886
1887                                                         //see if this seg already visited, and if so, does current window
1888                                                         //expand the old window?
1889                                                         if (rp != -1) {
1890                                                                 if (new_w->left < render_windows[rp].left ||
1891                                                                                  new_w->top < render_windows[rp].top ||
1892                                                                                  new_w->right > render_windows[rp].right ||
1893                                                                                  new_w->bot > render_windows[rp].bot) {
1894
1895                                                                         new_w->left  = min(new_w->left,render_windows[rp].left);
1896                                                                         new_w->right = max(new_w->right,render_windows[rp].right);
1897                                                                         new_w->top   = min(new_w->top,render_windows[rp].top);
1898                                                                         new_w->bot   = max(new_w->bot,render_windows[rp].bot);
1899
1900                                                                         if (no_migrate_segs) {
1901                                                                                 //no_render_flag[lcnt] = 1;
1902                                                                                 Render_list[lcnt] = -1;
1903                                                                                 render_windows[rp] = *new_w;            //get updated window
1904                                                                                 processed[rp] = 0;              //force reprocess
1905                                                                                 goto no_add;
1906                                                                         }
1907                                                                         else
1908                                                                                 Render_list[rp]=-1;
1909                                                                 }
1910                                                                 else goto no_add;
1911                                                         }
1912
1913                                                         #ifndef NDEBUG
1914                                                         if (draw_boxes)
1915                                                                 draw_window_box(5,new_w->left,new_w->top,new_w->right,new_w->bot);
1916                                                         #endif
1917
1918                                                         render_pos[ch] = lcnt;
1919                                                         Render_list[lcnt] = ch;
1920                                                         Seg_depth[lcnt] = l;
1921                                                         lcnt++;
1922                                                         if (lcnt >= MAX_RENDER_SEGS) {mprintf((0,"Too many segs in render list!!\n")); goto done_list;}
1923                                                         visited[ch] = 1;
1924
1925                                                         #ifndef NDEBUG
1926                                                         if (pre_draw_segs)
1927                                                                 render_segment(ch, window_num);
1928                                                         #endif
1929 no_add:
1930         ;
1931
1932                                                 }
1933                                         }
1934                                         else {
1935                                                 Render_list[lcnt] = ch;
1936                                                 Seg_depth[lcnt] = l;
1937                                                 lcnt++;
1938                                                 if (lcnt >= MAX_RENDER_SEGS) {mprintf((0,"Too many segs in render list!!\n")); goto done_list;}
1939                                                 visited[ch] = 1;
1940                                         }
1941                                 }
1942                         }
1943                 }
1944
1945                 scnt = ecnt;
1946                 ecnt = lcnt;
1947
1948         }
1949 done_list:
1950
1951         lcnt_save = lcnt;
1952         scnt_save = scnt;
1953
1954         first_terminal_seg = scnt;
1955         N_render_segs = lcnt;
1956
1957 }
1958
1959 //renders onto current canvas
1960 void render_mine(int start_seg_num,fix eye_offset, int window_num)
1961 {
1962 #ifndef NDEBUG
1963         int             i;
1964 #endif
1965         int             nn;
1966
1967         //      Initialize number of objects (actually, robots!) rendered this frame.
1968         Window_rendered_data[window_num].num_objects = 0;
1969
1970 #ifdef LASER_HACK
1971         Hack_nlasers = 0;
1972 #endif
1973
1974         #ifndef NDEBUG
1975         for (i=0;i<=Highest_object_index;i++)
1976                 object_rendered[i] = 0;
1977         #endif
1978
1979         //set up for rendering
1980
1981         render_start_frame();
1982
1983
1984         #if defined(EDITOR) && !defined(NDEUBG)
1985         if (Show_only_curside) {
1986                 rotate_list(8,Cursegp->verts);
1987                 render_side(Cursegp,Curside);
1988                 goto done_rendering;
1989         }
1990         #endif
1991
1992
1993         #ifdef EDITOR
1994         if (_search_mode)       {
1995                 //lcnt = lcnt_save;
1996                 //scnt = scnt_save;
1997         }
1998         else
1999         #endif
2000                 //NOTE LINK TO ABOVE!!
2001                 build_segment_list(start_seg_num, window_num);          //fills in Render_list & N_render_segs
2002
2003         //render away
2004
2005         #ifndef NDEBUG
2006         if (!window_check) {
2007                 Window_clip_left  = Window_clip_top = 0;
2008                 Window_clip_right = grd_curcanv->cv_bitmap.bm_w-1;
2009                 Window_clip_bot   = grd_curcanv->cv_bitmap.bm_h-1;
2010         }
2011         #endif
2012
2013         #ifndef NDEBUG
2014         if (!(_search_mode)) {
2015                 int i;
2016
2017                 for (i=0;i<N_render_segs;i++) {
2018                         int segnum;
2019
2020                         segnum = Render_list[i];
2021
2022                         if (segnum != -1)
2023                         {
2024                                 if (visited2[segnum])
2025                                         Int3();         //get Matt
2026                                 else
2027                                         visited2[segnum] = 1;
2028                         }
2029                 }
2030         }
2031         #endif
2032
2033         if (!(_search_mode))
2034                 build_object_lists(N_render_segs);
2035
2036         if (eye_offset<=0)              // Do for left eye or zero.
2037                 set_dynamic_light();
2038
2039         if (!_search_mode && Clear_window == 2) {
2040                 if (first_terminal_seg < N_render_segs) {
2041                         int i;
2042
2043                         if (Clear_window_color == -1)
2044                                 Clear_window_color = BM_XRGB(0, 0, 0);  //BM_XRGB(31, 15, 7);
2045         
2046                         gr_setcolor(Clear_window_color);
2047         
2048                         for (i=first_terminal_seg; i<N_render_segs; i++) {
2049                                 if (Render_list[i] != -1) {
2050                                         #ifndef NDEBUG
2051                                         if ((render_windows[i].left == -1) || (render_windows[i].top == -1) || (render_windows[i].right == -1) || (render_windows[i].bot == -1))
2052                                                 Int3();
2053                                         else
2054                                         #endif
2055                                                 //NOTE LINK TO ABOVE!
2056                                                 gr_rect(render_windows[i].left, render_windows[i].top, render_windows[i].right, render_windows[i].bot);
2057                                 }
2058                         }
2059                 }
2060         }
2061
2062         for (nn=N_render_segs;nn--;) {
2063                 int segnum;
2064                 int objnp;
2065
2066                 // Interpolation_method = 0;
2067                 segnum = Render_list[nn];
2068                 Current_seg_depth = Seg_depth[nn];
2069
2070                 //if (!no_render_flag[nn])
2071                 if (segnum!=-1 && (_search_mode || visited[segnum]!=-1)) {
2072                         //set global render window vars
2073
2074                         if (window_check) {
2075                                 Window_clip_left  = render_windows[nn].left;
2076                                 Window_clip_top   = render_windows[nn].top;
2077                                 Window_clip_right = render_windows[nn].right;
2078                                 Window_clip_bot   = render_windows[nn].bot;
2079                         }
2080
2081                         //mprintf((0," %d",segnum));
2082
2083                         render_segment(segnum, window_num);
2084                         visited[segnum]=255;
2085
2086                         if (window_check) {             //reset for objects
2087                                 Window_clip_left  = Window_clip_top = 0;
2088                                 Window_clip_right = grd_curcanv->cv_bitmap.bm_w-1;
2089                                 Window_clip_bot   = grd_curcanv->cv_bitmap.bm_h-1;
2090                         }
2091
2092                         if (migrate_objects) {
2093                                 //int n_expl_objs=0,expl_objs[5],i;
2094                                 int listnum;
2095                                 int save_linear_depth = Max_linear_depth;
2096
2097                                 Max_linear_depth = Max_linear_depth_objects;
2098
2099                                 listnum = nn;
2100
2101                                 //mprintf((0,"render objs seg %d",segnum));
2102
2103                                 for (objnp=0;render_obj_list[listnum][objnp]!=-1;)      {
2104                                         int ObjNumber = render_obj_list[listnum][objnp];
2105
2106                                         if (ObjNumber >= 0) {
2107
2108                                                 //mprintf( (0, "Type: %d\n", Objects[ObjNumber].type ));
2109         
2110                                                 //if (Objects[ObjNumber].type == OBJ_FIREBALL && n_expl_objs<5) {
2111                                                 //      expl_objs[n_expl_objs++] = ObjNumber;
2112                                                 //} else
2113                                                 #ifdef LASER_HACK
2114                                                 if (    (Objects[ObjNumber].type==OBJ_WEAPON) &&                                                                //if its a weapon
2115                                                                 (Objects[ObjNumber].lifeleft==Laser_max_time ) &&       //  and its in it's first frame
2116                                                                 (Hack_nlasers< MAX_HACKED_LASERS) &&                                                                    //  and we have space for it
2117                                                                 (Objects[ObjNumber].laser_info.parent_num>-1) &&                                        //  and it has a parent
2118                                                                 ((Viewer-Objects)==Objects[ObjNumber].laser_info.parent_num)    //  and it's parent is the viewer
2119                                                    )            {
2120                                                         Hack_laser_list[Hack_nlasers++] = ObjNumber;                                                            //then make it draw after everything else.
2121                                                         //mprintf( (0, "O%d ", ObjNumber ));
2122                                                 } else  
2123                                                 #endif
2124                                                         do_render_object(ObjNumber, window_num);        // note link to above else
2125
2126                                                 objnp++;
2127                                         }
2128                                         else {
2129
2130                                                 listnum = -ObjNumber;
2131                                                 objnp = 0;
2132
2133                                         }
2134
2135                                 }
2136
2137                                 //for (i=0;i<n_expl_objs;i++)
2138                                 //      do_render_object(expl_objs[i], window_num);
2139
2140                                 //mprintf((0,"done seg %d\n",segnum));
2141
2142                                 Max_linear_depth = save_linear_depth;
2143
2144                         }
2145
2146                 }
2147         }
2148
2149         //mprintf((0,"\n"));
2150
2151                                                                 
2152 #ifdef LASER_HACK                                                               
2153         // Draw the hacked lasers last
2154         for (i=0; i < Hack_nlasers; i++ )       {
2155                 //mprintf( (0, "D%d ", Hack_laser_list[i] ));
2156                 do_render_object(Hack_laser_list[i], window_num);
2157         }
2158 #endif
2159
2160         // -- commented out by mk on 09/14/94...did i do a good thing??  object_render_targets();
2161
2162 #ifdef EDITOR
2163         #ifndef NDEUBG
2164         //draw curedge stuff
2165         if (Outline_mode) outline_seg_side(Cursegp,Curside,Curedge,Curvert);
2166         #endif
2167
2168 done_rendering:
2169         ;
2170
2171 #endif
2172
2173 }
2174 #ifdef EDITOR
2175
2176 extern int render_3d_in_big_window;
2177
2178 //finds what segment is at a given x&y -  seg,side,face are filled in
2179 //works on last frame rendered. returns true if found
2180 //if seg<0, then an object was found, and the object number is -seg-1
2181 int find_seg_side_face(short x,short y,int *seg,int *side,int *face,int *poly)
2182 {
2183         _search_mode = -1;
2184
2185         _search_x = x; _search_y = y;
2186
2187         found_seg = -1;
2188
2189         if (render_3d_in_big_window) {
2190                 grs_canvas temp_canvas;
2191
2192                 gr_init_sub_canvas(&temp_canvas,canv_offscreen,0,0,
2193                         LargeView.ev_canv->cv_bitmap.bm_w,LargeView.ev_canv->cv_bitmap.bm_h);
2194
2195                 gr_set_current_canvas(&temp_canvas);
2196
2197                 render_frame(0, 0);
2198         }
2199         else {
2200                 gr_set_current_canvas(&VR_render_sub_buffer[0]);        //render off-screen
2201                 render_frame(0, 0);
2202         }
2203
2204         _search_mode = 0;
2205
2206         *seg = found_seg;
2207         *side = found_side;
2208         *face = found_face;
2209         *poly = found_poly;
2210
2211 //      mprintf((0,"found seg=%d, side=%d, face=%d, poly=%d\n",found_seg,found_side,found_face,found_poly));
2212
2213         return (found_seg!=-1);
2214
2215 }
2216
2217 #endif