]> icculus.org git repositories - btb/d2x.git/blob - main/editor/seguvs.c
use the orientation parameter of g3_draw_bitmap
[btb/d2x.git] / main / editor / seguvs.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-1998 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 /*
15  *
16  * u,v coordinate computation for segment faces
17  *
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include "conf.h"
22 #endif
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdarg.h>
27 #include <math.h>
28 #include <string.h>
29
30 #include "inferno.h"
31 #include "editor.h"
32 #include "maths.h"
33 #include "mono.h"
34 #include "dxxerror.h"
35
36
37 void cast_all_light_in_mine(int quick_flag);
38 //--rotate_uvs-- vms_vector Rightvec;
39
40 //      ---------------------------------------------------------------------------------------------
41 //      Returns approximate area of a side
42 fix area_on_side(side *sidep)
43 {
44         fix     du,dv,width,height;
45
46         du = sidep->uvls[1].u - sidep->uvls[0].u;
47         dv = sidep->uvls[1].v - sidep->uvls[0].v;
48
49         width = fix_sqrt(fixmul(du,du) + fixmul(dv,dv));
50
51         du = sidep->uvls[3].u - sidep->uvls[0].u;
52         dv = sidep->uvls[3].v - sidep->uvls[0].v;
53
54         height = fix_sqrt(fixmul(du,du) + fixmul(dv,dv));
55
56         return fixmul(width, height);
57 }
58
59 //      -------------------------------------------------------------------------------------------
60 //      DEBUG function -- callable from debugger.
61 //      Returns approximate area of all sides which get mapped (ie, are not a connection).
62 //      I wrote this because I was curious how much memory would be required to texture map all
63 //      sides individually with custom artwork.  For demo1.min on 2/18/94, it would be about 5 meg.
64 int area_on_all_sides(void)
65 {
66         int     i,s;
67         int     total_area = 0;
68
69         for (i=0; i<=Highest_segment_index; i++) {
70                 segment *segp = &Segments[i];
71
72                 for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
73                         if (!IS_CHILD(segp->children[s]))
74                                 total_area += f2i(area_on_side(&segp->sides[s]));
75         }
76
77         return total_area;
78 }
79
80 fix average_connectivity(void)
81 {
82         int     i,s;
83         int     total_sides = 0, total_mapped_sides = 0;
84
85         for (i=0; i<=Highest_segment_index; i++) {
86                 segment *segp = &Segments[i];
87
88                 for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
89                         if (!IS_CHILD(segp->children[s]))
90                                 total_mapped_sides++;
91                         total_sides++;
92                 }
93         }
94
95         return 6 * fixdiv(total_mapped_sides, total_sides);
96 }
97
98 #define MAX_LIGHT_SEGS 16
99
100 //      ---------------------------------------------------------------------------------------------
101 //      Scan all polys in all segments, return average light value for vnum.
102 //      segs = output array for segments containing vertex, terminated by -1.
103 fix get_average_light_at_vertex(int vnum, short *segs)
104 {
105         int     segnum, relvnum, sidenum;
106         fix     total_light;
107         int     num_occurrences;
108 //      #ifndef NDEBUG //Removed this ifdef because the version of Assert that I used to get it to compile doesn't work without this symbol. -KRB
109         short   *original_segs;
110
111         original_segs = segs;
112 //      #endif
113
114
115         num_occurrences = 0;
116         total_light = 0;
117
118         for (segnum=0; segnum<=Highest_segment_index; segnum++) {
119                 segment *segp = &Segments[segnum];
120                 short *vp = segp->verts;
121
122                 for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
123                         if (*vp++ == vnum)
124                                 break;
125
126                 if (relvnum < MAX_VERTICES_PER_SEGMENT) {
127
128                         *segs++ = segnum;
129                         Assert(segs - original_segs < MAX_LIGHT_SEGS);
130
131                         for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++) {
132                                 if (!IS_CHILD(segp->children[sidenum])) {
133                                         side    *sidep = &segp->sides[sidenum];
134                                         sbyte   *vp = Side_to_verts[sidenum];
135                                         int     v;
136
137                                         for (v=0; v<4; v++)
138                                                 if (*vp++ == relvnum) {
139                                                         total_light += sidep->uvls[v].l;
140                                                         num_occurrences++;
141                                                 }
142                                 }       // end if
143                         }       // end sidenum
144                 }
145         }       // end segnum
146
147         *segs = -1;
148
149         if (num_occurrences)
150                 return total_light/num_occurrences;
151         else
152                 return 0;
153
154 }
155
156 void set_average_light_at_vertex(int vnum)
157 {
158         int     relvnum, sidenum;
159         short   Segment_indices[MAX_LIGHT_SEGS];
160         int     segind;
161
162         fix average_light;
163
164         average_light = get_average_light_at_vertex(vnum, Segment_indices);
165
166         if (!average_light)
167                 return;
168
169         segind = 0;
170         while (Segment_indices[segind] != -1) {
171                 int segnum = Segment_indices[segind++];
172
173                 segment *segp = &Segments[segnum];
174
175                 for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
176                         if (segp->verts[relvnum] == vnum)
177                                 break;
178
179                 if (relvnum < MAX_VERTICES_PER_SEGMENT) {
180                         for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++) {
181                                 if (!IS_CHILD(segp->children[sidenum])) {
182                                         side *sidep = &segp->sides[sidenum];
183                                         sbyte   *vp = Side_to_verts[sidenum];
184                                         int     v;
185
186                                         for (v=0; v<4; v++)
187                                                 if (*vp++ == relvnum)
188                                                         sidep->uvls[v].l = average_light;
189                                 }       // end if
190                         }       // end sidenum
191                 }       // end if
192         }       // end while
193
194         Update_flags |= UF_WORLD_CHANGED;
195 }
196
197 void set_average_light_on_side(segment *segp, int sidenum)
198 {
199         int     v;
200
201         if (!IS_CHILD(segp->children[sidenum]))
202                 for (v=0; v<4; v++) {
203 //                      mprintf((0,"Vertex %i\n", segp->verts[Side_to_verts[side][v]]));
204                         set_average_light_at_vertex(segp->verts[Side_to_verts[sidenum][v]]);
205                 }
206
207 }
208
209 int set_average_light_on_curside(void)
210 {
211         set_average_light_on_side(Cursegp, Curside);
212         return 0;
213 }
214
215 //      -----------------------------------------------------------------------------------------
216 void set_average_light_on_all_fast(void)
217 {
218         int     s,v,relvnum;
219         fix     al;
220         int     alc;
221         int     seglist[MAX_LIGHT_SEGS];
222         int     *segptr;
223
224         set_vertex_counts();
225
226         //      Set total light value for all vertices in array average_light.
227         for (v=0; v<=Highest_vertex_index; v++) {
228                 al = 0;
229                 alc = 0;
230
231                 if (Vertex_active[v]) {
232                         segptr = seglist;
233
234                         for (s=0; s<=Highest_segment_index; s++) {
235                                 segment *segp = &Segments[s];
236                                 for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
237                                         if (segp->verts[relvnum] == v)
238                                                 break;
239
240                                 if (relvnum != MAX_VERTICES_PER_SEGMENT) {
241                                         int             si;
242
243                                         *segptr++ = s;  // Note this segment in list, so we can process it below.
244                                         Assert(segptr - seglist < MAX_LIGHT_SEGS);
245
246                                         for (si=0; si<MAX_SIDES_PER_SEGMENT; si++) {
247                                                 if (!IS_CHILD(segp->children[si])) {
248                                                         side    *sidep = &segp->sides[si];
249                                                         sbyte   *vp = Side_to_verts[si];
250                                                         int     vv;
251
252                                                         for (vv=0; vv<4; vv++)
253                                                                 if (*vp++ == relvnum) {
254                                                                         al += sidep->uvls[vv].l;
255                                                                         alc++;
256                                                                 }
257                                                 }       // if (segp->children[si == -1) {
258                                         }       // for (si=0...
259                                 }       // if (relvnum != ...
260                         }       // for (s=0; ...
261
262                         *segptr = -1;
263
264                         //      Now, divide average_light by number of number of occurrences for each vertex
265                         if (alc)
266                                 al /= alc;
267                         else
268                                 al = 0;
269
270                         segptr = seglist;
271                         while (*segptr != -1) {
272                                 int             segnum = *segptr++;
273                                 segment *segp = &Segments[segnum];
274                                 int             sidenum;
275
276                                 for (relvnum=0; relvnum<MAX_VERTICES_PER_SEGMENT; relvnum++)
277                                         if (segp->verts[relvnum] == v)
278                                                 break;
279
280                                 Assert(relvnum < MAX_VERTICES_PER_SEGMENT);     // IMPOSSIBLE! This segment is in seglist, but vertex v does not occur!
281                                 for (sidenum=0; sidenum < MAX_SIDES_PER_SEGMENT; sidenum++) {
282                                         int     wid_result;
283                                         wid_result = WALL_IS_DOORWAY(segp, sidenum);
284                                         if ((wid_result != WID_FLY_FLAG) && (wid_result != WID_NO_WALL)) {
285                                                 side *sidep = &segp->sides[sidenum];
286                                                 sbyte   *vp = Side_to_verts[sidenum];
287                                                 int     v;
288
289                                                 for (v=0; v<4; v++)
290                                                         if (*vp++ == relvnum)
291                                                                 sidep->uvls[v].l = al;
292                                         }       // end if
293                                 }       // end sidenum
294                         }       // end while
295
296                 }       // if (Vertex_active[v]...
297
298         }       // for (v=0...
299
300 }
301
302 extern int Doing_lighting_hack_flag;    //      If set, don't mprintf warning messages in gameseg.c/find_point_seg
303 int set_average_light_on_all(void)
304 {
305 //      set_average_light_on_all_fast();
306
307         Doing_lighting_hack_flag = 1;
308         cast_all_light_in_mine(0);
309         Doing_lighting_hack_flag = 0;
310         Update_flags |= UF_WORLD_CHANGED;
311
312 //      int seg, side;
313
314 //      for (seg=0; seg<=Highest_segment_index; seg++)
315 //              for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
316 //                      if (Segments[seg].segnum != -1)
317 //                              set_average_light_on_side(&Segments[seg], side);
318         return 0;
319 }
320
321 int set_average_light_on_all_quick(void)
322 {
323         cast_all_light_in_mine(1);
324         Update_flags |= UF_WORLD_CHANGED;
325
326         return 0;
327 }
328
329 //      ---------------------------------------------------------------------------------------------
330 fix compute_uv_dist(uvl *uv0, uvl *uv1)
331 {
332         vms_vector      v0,v1;
333
334         v0.x = uv0->u;
335         v0.y = 0;
336         v0.z = uv0->v;
337
338         v1.x = uv1->u;
339         v1.y = 0;
340         v1.z = uv1->v;
341
342         return vm_vec_dist(&v0,&v1);
343 }
344
345 //      ---------------------------------------------------------------------------------------------
346 //      Given a polygon, compress the uv coordinates so that they are as close to 0 as possible.
347 //      Do this by adding a constant u and v to each uv pair.
348 void compress_uv_coordinates(side *sidep)
349 {
350         int     v;
351         fix     uc, vc;
352
353         uc = 0;
354         vc = 0;
355
356         for (v=0; v<4; v++) {
357                 uc += sidep->uvls[v].u;
358                 vc += sidep->uvls[v].v;
359         }
360
361         uc /= 4;
362         vc /= 4;
363         uc = uc & 0xffff0000;
364         vc = vc & 0xffff0000;
365
366         for (v=0; v<4; v++) {
367                 sidep->uvls[v].u -= uc;
368                 sidep->uvls[v].v -= vc;
369         }
370
371 }
372
373 //      ---------------------------------------------------------------------------------------------
374 void compress_uv_coordinates_on_side(side *sidep)
375 {
376         compress_uv_coordinates(sidep);
377 }
378
379 //      ---------------------------------------------------------------------------------------------
380 void validate_uv_coordinates_on_side(segment *segp, int sidenum)
381 {
382 //      int                     v;
383 //      fix                     uv_dist,threed_dist;
384 //      vms_vector      tvec;
385 //      fix                     dist_ratios[MAX_VERTICES_PER_POLY];
386         side                    *sidep = &segp->sides[sidenum];
387 //      sbyte                   *vp = Side_to_verts[sidenum];
388
389 //      This next hunk doesn't seem to affect anything. @mk, 02/13/94
390 //      for (v=1; v<4; v++) {
391 //              uv_dist = compute_uv_dist(&sidep->uvls[v],&sidep->uvls[0]);
392 //              threed_dist = vm_vec_mag(vm_vec_sub(&tvec,&Vertices[segp->verts[vp[v]],&Vertices[vp[0]]));
393 //              dist_ratios[v-1] = fixdiv(uv_dist,threed_dist);
394 //      }
395
396         compress_uv_coordinates_on_side(sidep);
397 }
398
399 void compress_uv_coordinates_in_segment(segment *segp)
400 {
401         int     side;
402
403         for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
404                 compress_uv_coordinates_on_side(&segp->sides[side]);
405 }
406
407 void compress_uv_coordinates_all(void)
408 {
409         int     seg;
410
411         for (seg=0; seg<=Highest_segment_index; seg++)
412                 if (Segments[seg].segnum != -1)
413                         compress_uv_coordinates_in_segment(&Segments[seg]);
414 }
415
416 void check_lighting_side(segment *sp, int sidenum)
417 {
418         int     v;
419         side    *sidep = &sp->sides[sidenum];
420
421         for (v=0; v<4; v++)
422                 if ((sidep->uvls[v].l > F1_0*16) || (sidep->uvls[v].l < 0))
423                         Int3(); //mprintf(0, "Bogus lighting value in segment %i, side %i, vert %i = %x\n", SEGMENT_NUMBER(sp), side, v, sidep->uvls[v].l);
424 }
425
426 void check_lighting_segment(segment *segp)
427 {
428         int     side;
429
430         for (side=0; side<MAX_SIDES_PER_SEGMENT; side++)
431                 check_lighting_side(segp, side);
432 }
433
434 //      Flag bogus lighting values.
435 void check_lighting_all(void)
436 {
437         int     seg;
438
439         for (seg=0; seg<=Highest_segment_index; seg++)
440                 if (Segments[seg].segnum != -1)
441                         check_lighting_segment(&Segments[seg]);
442 }
443
444 void assign_default_lighting_on_side(segment *segp, int sidenum)
445 {
446         int     v;
447         side    *sidep = &segp->sides[sidenum];
448
449         for (v=0; v<4; v++)
450                 sidep->uvls[v].l = DEFAULT_LIGHTING;
451 }
452
453 void assign_default_lighting(segment *segp)
454 {
455         int     sidenum;
456
457         for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++)
458                 assign_default_lighting_on_side(segp, sidenum);
459 }
460
461 void assign_default_lighting_all(void)
462 {
463         int     seg;
464
465         for (seg=0; seg<=Highest_segment_index; seg++)
466                 if (Segments[seg].segnum != -1)
467                         assign_default_lighting(&Segments[seg]);
468 }
469
470 //      ---------------------------------------------------------------------------------------------
471 void validate_uv_coordinates(segment *segp)
472 {
473         int     s;
474
475         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
476                 validate_uv_coordinates_on_side(segp,s);
477
478 }
479
480 //      ---------------------------------------------------------------------------------------------
481 //      For all faces in side, copy uv coordinates from uvs array to face.
482 void copy_uvs_from_side_to_faces(segment *segp, int sidenum, uvl uvls[])
483 {
484         int     v;
485         side    *sidep = &segp->sides[sidenum];
486
487         for (v=0; v<4; v++)
488                 sidep->uvls[v] = uvls[v];
489
490 }
491
492 #ifdef __WATCOMC__
493 fix zhypot(fix a,fix b);
494 #pragma aux zhypot parm [eax] [ebx] value [eax] modify [eax ebx ecx edx] = \
495         "imul   eax" \
496         "xchg eax,ebx" \
497         "mov    ecx,edx" \
498         "imul eax" \
499         "add    eax,ebx" \
500         "adc    edx,ecx" \
501         "call   quad_sqrt";
502 #else
503 fix zhypot(fix a,fix b) {
504         double x = (double)a / 65536;
505         double y = (double)b / 65536;
506         return (fix)((long)(sqrt(x * x + y * y) * 65536));
507 }
508 #endif
509
510 //      ---------------------------------------------------------------------------------------------
511 //      Assign lighting value to side, a function of the normal vector.
512 void assign_light_to_side(segment *sp, int sidenum)
513 {
514         int     v;
515         side    *sidep = &sp->sides[sidenum];
516
517         for (v=0; v<4; v++)
518                 sidep->uvls[v].l = DEFAULT_LIGHTING;
519 }
520
521 fix     Stretch_scale_x = F1_0;
522 fix     Stretch_scale_y = F1_0;
523
524 //      ---------------------------------------------------------------------------------------------
525 //      Given u,v coordinates at two vertices, assign u,v coordinates to other two vertices on a side.
526 //      (Actually, assign them to the coordinates in the faces.)
527 //      va, vb = face-relative vertex indices corresponding to uva, uvb.  Ie, they are always in 0..3 and should be looked up in
528 //      Side_to_verts[side] to get the segment relative index.
529 void assign_uvs_to_side(segment *segp, int sidenum, uvl *uva, uvl *uvb, int va, int vb)
530 {
531         int                     vlo,vhi,v0,v1,v2,v3;
532         vms_vector      fvec,rvec,tvec;
533         vms_matrix      rotmat;
534         uvl                     uvls[4],ruvmag,fuvmag,uvlo,uvhi;
535         fix                     fmag,mag01;
536         sbyte                   *vp;
537
538         Assert( (va<4) && (vb<4) );
539         Assert((abs(va - vb) == 1) || (abs(va - vb) == 3));             // make sure the verticies specify an edge
540
541         vp = (sbyte *)&Side_to_verts[sidenum];
542
543         // We want vlo precedes vhi, ie vlo < vhi, or vlo = 3, vhi = 0
544         if (va == ((vb + 1) % 4)) {             // va = vb + 1
545                 vlo = vb;
546                 vhi = va;
547                 uvlo = *uvb;
548                 uvhi = *uva;
549         } else {
550                 vlo = va;
551                 vhi = vb;
552                 uvlo = *uva;
553                 uvhi = *uvb;
554         }
555
556         Assert(((vlo+1) % 4) == vhi);   // If we are on an edge, then uvhi is one more than uvlo (mod 4)
557         uvls[vlo] = uvlo;
558         uvls[vhi] = uvhi;
559
560         // Now we have vlo precedes vhi, compute vertices ((vhi+1) % 4) and ((vhi+2) % 4)
561
562         // Assign u,v scale to a unit length right vector.
563         fmag = zhypot(uvhi.v - uvlo.v,uvhi.u - uvlo.u);
564         if (fmag < 64) {                // this is a fix, so 64 = 1/1024
565                 mprintf((0,"Warning: fmag = %7.3f, using approximate u,v values\n",f2fl(fmag)));
566                 ruvmag.u = F1_0*256;
567                 ruvmag.v = F1_0*256;
568                 fuvmag.u = F1_0*256;
569                 fuvmag.v = F1_0*256;
570         } else {
571                 ruvmag.u = uvhi.v - uvlo.v;
572                 ruvmag.v = uvlo.u - uvhi.u;
573
574                 fuvmag.u = uvhi.u - uvlo.u;
575                 fuvmag.v = uvhi.v - uvlo.v;
576         }
577
578         v0 = segp->verts[vp[vlo]];
579         v1 = segp->verts[vp[vhi]];
580         v2 = segp->verts[vp[(vhi+1)%4]];
581         v3 = segp->verts[vp[(vhi+2)%4]];
582
583         //      Compute right vector by computing orientation matrix from:
584         //              forward vector = vlo:vhi
585         //                right vector = vlo:(vhi+2) % 4
586         vm_vec_sub(&fvec,&Vertices[v1],&Vertices[v0]);
587         vm_vec_sub(&rvec,&Vertices[v3],&Vertices[v0]);
588
589         if (((fvec.x == 0) && (fvec.y == 0) && (fvec.z == 0)) || ((rvec.x == 0) && (rvec.y == 0) && (rvec.z == 0))) {
590                 mprintf((1, "Trapped null vector in assign_uvs_to_side, using identity matrix.\n"));
591                 rotmat = vmd_identity_matrix;
592         } else
593                 vm_vector_2_matrix(&rotmat,&fvec,0,&rvec);
594
595         rvec = rotmat.rvec; vm_vec_negate(&rvec);
596         fvec = rotmat.fvec;
597
598         // mprintf((0, "va = %i, vb = %i\n", va, vb));
599         mag01 = vm_vec_dist(&Vertices[v1],&Vertices[v0]);
600         if ((va == 0) || (va == 2))
601                 mag01 = fixmul(mag01, Stretch_scale_x);
602         else
603                 mag01 = fixmul(mag01, Stretch_scale_y);
604
605         if (mag01 < F1_0/1024 )
606                 editor_status("U, V bogosity in segment #%i, probably on side #%i.  CLEAN UP YOUR MESS!", SEGMENT_NUMBER(segp), sidenum);
607         else {
608                 vm_vec_sub(&tvec,&Vertices[v2],&Vertices[v1]);
609                 uvls[(vhi+1)%4].u = uvhi.u + 
610                         fixdiv(fixmul(ruvmag.u,vm_vec_dotprod(&rvec,&tvec)),mag01) +
611                         fixdiv(fixmul(fuvmag.u,vm_vec_dotprod(&fvec,&tvec)),mag01);
612
613                 uvls[(vhi+1)%4].v = uvhi.v + 
614                         fixdiv(fixmul(ruvmag.v,vm_vec_dotprod(&rvec,&tvec)),mag01) +
615                         fixdiv(fixmul(fuvmag.v,vm_vec_dotprod(&fvec,&tvec)),mag01);
616
617
618                 vm_vec_sub(&tvec,&Vertices[v3],&Vertices[v0]);
619                 uvls[(vhi+2)%4].u = uvlo.u + 
620                         fixdiv(fixmul(ruvmag.u,vm_vec_dotprod(&rvec,&tvec)),mag01) +
621                         fixdiv(fixmul(fuvmag.u,vm_vec_dotprod(&fvec,&tvec)),mag01);
622
623                 uvls[(vhi+2)%4].v = uvlo.v + 
624                         fixdiv(fixmul(ruvmag.v,vm_vec_dotprod(&rvec,&tvec)),mag01) +
625                         fixdiv(fixmul(fuvmag.v,vm_vec_dotprod(&fvec,&tvec)),mag01);
626
627                 uvls[(vhi+1)%4].l = uvhi.l;
628                 uvls[(vhi+2)%4].l = uvlo.l;
629
630                 copy_uvs_from_side_to_faces(segp, sidenum, uvls);
631         }
632 }
633
634
635 int Vmag = VMAG;
636
637 // -----------------------------------------------------------------------------------------------------------
638 //      Assign default uvs to side.
639 //      This means:
640 //              v0 = 0,0
641 //              v1 = k,0 where k is 3d size dependent
642 //      v2, v3 assigned by assign_uvs_to_side
643 void assign_default_uvs_to_side(segment *segp,int side)
644 {
645         uvl                     uv0,uv1;
646         sbyte                   *vp;
647
648         uv0.u = 0;
649         uv0.v = 0;
650
651         vp = Side_to_verts[side];
652
653         uv1.u = 0;
654         uv1.v = Num_tilings * fixmul(Vmag, vm_vec_dist(&Vertices[segp->verts[vp[1]]],&Vertices[segp->verts[vp[0]]]));
655
656         assign_uvs_to_side(segp, side, &uv0, &uv1, 0, 1);
657 }
658
659 // -----------------------------------------------------------------------------------------------------------
660 //      Assign default uvs to side.
661 //      This means:
662 //              v0 = 0,0
663 //              v1 = k,0 where k is 3d size dependent
664 //      v2, v3 assigned by assign_uvs_to_side
665 void stretch_uvs_from_curedge(segment *segp, int side)
666 {
667         uvl                     uv0,uv1;
668         int                     v0, v1;
669
670         v0 = Curedge;
671         v1 = (v0 + 1) % 4;
672
673         uv0.u = segp->sides[side].uvls[v0].u;
674         uv0.v = segp->sides[side].uvls[v0].v;
675
676         uv1.u = segp->sides[side].uvls[v1].u;
677         uv1.v = segp->sides[side].uvls[v1].v;
678
679         assign_uvs_to_side(segp, side, &uv0, &uv1, v0, v1);
680 }
681
682 // --------------------------------------------------------------------------------------------------------------
683 //      Assign default uvs to a segment.
684 void assign_default_uvs_to_segment(segment *segp)
685 {
686         int     s;
687
688         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
689                 assign_default_uvs_to_side(segp,s);
690                 assign_light_to_side(segp, s);
691         }
692 }
693
694
695 // -- mk021394 -- // --------------------------------------------------------------------------------------------------------------
696 // -- mk021394 -- //    Find the face:poly:vertex index in base_seg:base_common_side which is segment relative vertex v1
697 // -- mk021394 -- //    This very specific routine is subsidiary to med_assign_uvs_to_side.
698 // -- mk021394 -- void get_face_and_vert(segment *base_seg, int base_common_side, int v1, int *ff, int *vv, int *pi)
699 // -- mk021394 -- {
700 // -- mk021394 --       int     p,f,v;
701 // -- mk021394 -- 
702 // -- mk021394 --       for (f=0; f<base_seg->sides[base_common_side].num_faces; f++) {
703 // -- mk021394 --               face *fp = &base_seg->sides[base_common_side].faces[f];
704 // -- mk021394 --               for (p=0; p<fp->num_polys; p++) {
705 // -- mk021394 --                       poly *pp = &fp->polys[p];
706 // -- mk021394 --                       for (v=0; v<pp->num_vertices; v++)
707 // -- mk021394 --                               if (pp->verts[v] == v1) {
708 // -- mk021394 --                                       *ff = f;
709 // -- mk021394 --                                       *vv = v;
710 // -- mk021394 --                                       *pi = p;
711 // -- mk021394 --                                       return;
712 // -- mk021394 --                               }
713 // -- mk021394 --               }
714 // -- mk021394 --       }
715 // -- mk021394 -- 
716 // -- mk021394 --       Assert(0);      // Error -- Couldn't find face:vertex which matched vertex v1 on base_seg:base_common_side
717 // -- mk021394 -- }
718
719 // -- mk021394 -- // --------------------------------------------------------------------------------------------------------------
720 // -- mk021394 -- //    Find the vertex index in base_seg:base_common_side which is segment relative vertex v1
721 // -- mk021394 -- //    This very specific routine is subsidiary to med_assign_uvs_to_side.
722 // -- mk021394 -- void get_side_vert(segment *base_seg,int base_common_side,int v1,int *vv)
723 // -- mk021394 -- {
724 // -- mk021394 --       int     p,f,v;
725 // -- mk021394 -- 
726 // -- mk021394 --       Assert((base_seg->sides[base_common_side].tri_edge == 0) || (base_seg->sides[base_common_side].tri_edge == 1));
727 // -- mk021394 --       Assert(base_seg->sides[base_common_side].num_faces <= 2);
728 // -- mk021394 -- 
729 // -- mk021394 --       for (f=0; f<base_seg->sides[base_common_side].num_faces; f++) {
730 // -- mk021394 --               face *fp = &base_seg->sides[base_common_side].faces[f];
731 // -- mk021394 --               for (p=0; p<fp->num_polys; p++) {
732 // -- mk021394 --                       poly    *pp = &fp->polys[p];
733 // -- mk021394 --                       for (v=0; v<pp->num_vertices; v++)
734 // -- mk021394 --                               if (pp->verts[v] == v1) {
735 // -- mk021394 --                                       if (pp->num_vertices == 4) {
736 // -- mk021394 --                                               *vv = v;
737 // -- mk021394 --                                               return;
738 // -- mk021394 --                                       }
739 // -- mk021394 -- 
740 // -- mk021394 --                                       if (base_seg->sides[base_common_side].tri_edge == 0) {  // triangulated 012, 023, so if f==0, *vv = v, if f==1, *vv = v if v=0, else v+1
741 // -- mk021394 --                                               if ((f == 1) && (v > 0))
742 // -- mk021394 --                                                       v++;
743 // -- mk021394 --                                               *vv = v;
744 // -- mk021394 --                                               return;
745 // -- mk021394 --                                       } else {                                                                // triangulated 013, 123
746 // -- mk021394 --                                               if (f == 0) {
747 // -- mk021394 --                                                       if (v == 2)
748 // -- mk021394 --                                                               v++;
749 // -- mk021394 --                                               } else
750 // -- mk021394 --                                                       v++;
751 // -- mk021394 --                                               *vv = v;
752 // -- mk021394 --                                               return;
753 // -- mk021394 --                                       }
754 // -- mk021394 --                               }
755 // -- mk021394 --               }
756 // -- mk021394 --       }
757 // -- mk021394 -- 
758 // -- mk021394 --       Assert(0);      // Error -- Couldn't find face:vertex which matched vertex v1 on base_seg:base_common_side
759 // -- mk021394 -- }
760
761 //--rotate_uvs-- // --------------------------------------------------------------------------------------------------------------
762 //--rotate_uvs-- //     Rotate uvl coordinates uva, uvb about their center point by heading
763 //--rotate_uvs-- void rotate_uvs(uvl *uva, uvl *uvb, vms_vector *rvec)
764 //--rotate_uvs-- {
765 //--rotate_uvs--        uvl     uvc, uva1, uvb1;
766 //--rotate_uvs-- 
767 //--rotate_uvs--        uvc.u = (uva->u + uvb->u)/2;
768 //--rotate_uvs--        uvc.v = (uva->v + uvb->v)/2;
769 //--rotate_uvs-- 
770 //--rotate_uvs--        uva1.u = fixmul(uva->u - uvc.u, rvec->x) - fixmul(uva->v - uvc.v, rvec->z);
771 //--rotate_uvs--        uva1.v = fixmul(uva->u - uvc.u, rvec->z) + fixmul(uva->v - uvc.v, rvec->x);
772 //--rotate_uvs-- 
773 //--rotate_uvs--        uva->u = uva1.u + uvc.u;
774 //--rotate_uvs--        uva->v = uva1.v + uvc.v;
775 //--rotate_uvs-- 
776 //--rotate_uvs--        uvb1.u = fixmul(uvb->u - uvc.u, rvec->x) - fixmul(uvb->v - uvc.v, rvec->z);
777 //--rotate_uvs--        uvb1.v = fixmul(uvb->u - uvc.u, rvec->z) + fixmul(uvb->v - uvc.v, rvec->x);
778 //--rotate_uvs-- 
779 //--rotate_uvs--        uvb->u = uvb1.u + uvc.u;
780 //--rotate_uvs--        uvb->v = uvb1.v + uvc.v;
781 //--rotate_uvs-- }
782
783
784 // --------------------------------------------------------------------------------------------------------------
785 void med_assign_uvs_to_side(segment *con_seg, int con_common_side, segment *base_seg, int base_common_side, int abs_id1, int abs_id2)
786 {
787         uvl             uv1,uv2;
788         int             v,bv1,bv2, vv1, vv2;
789         int             cv1=0, cv2=0;
790
791         bv1 = -1;       bv2 = -1;
792
793         // Find which vertices in segment match abs_id1, abs_id2
794         for (v=0; v<MAX_VERTICES_PER_SEGMENT; v++) {
795                 if (base_seg->verts[v] == abs_id1)
796                         bv1 = v;
797                 if (base_seg->verts[v] == abs_id2)
798                         bv2 = v;
799                 if (con_seg->verts[v] == abs_id1)
800                         cv1 = v;
801                 if (con_seg->verts[v] == abs_id2)
802                         cv2 = v;
803         }
804
805         //      Now, bv1, bv2 are segment relative vertices in base segment which are the same as absolute vertices abs_id1, abs_id2
806         //           cv1, cv2 are segment relative vertices in conn segment which are the same as absolute vertices abs_id1, abs_id2
807
808         Assert((bv1 != -1) && (bv2 != -1) && (cv1 != -1) && (cv2 != -1));
809
810         //      Now, scan 4 vertices in base side and 4 vertices in connected side.
811         //      Set uv1, uv2 to uv coordinates from base side which correspond to vertices bv1, bv2.
812         //      Set vv1, vv2 to relative vertex ids (in 0..3) in connecting side which correspond to cv1, cv2
813         vv1 = -1;       vv2 = -1;
814         for (v=0; v<4; v++) {
815                 if (bv1 == Side_to_verts[base_common_side][v])
816                         uv1 = base_seg->sides[base_common_side].uvls[v];
817
818                 if (bv2 == Side_to_verts[base_common_side][v])
819                         uv2 = base_seg->sides[base_common_side].uvls[v];
820
821                 if (cv1 == Side_to_verts[con_common_side][v])
822                         vv1 = v;
823
824                 if (cv2 == Side_to_verts[con_common_side][v])
825                         vv2 = v;
826         }
827
828         Assert((uv1.u != uv2.u) || (uv1.v != uv2.v));
829         Assert( (vv1 != -1) && (vv2 != -1) );
830         assign_uvs_to_side(con_seg, con_common_side, &uv1, &uv2, vv1, vv2);
831 }
832
833
834 // -----------------------------------------------------------------------------
835 //      Given a base and a connecting segment, a side on each of those segments and two global vertex ids,
836 //      determine which side in each of the segments shares those two vertices.
837 //      This is used to propagate a texture map id to a connecting segment in an expected and desired way.
838 //      Since we can attach any side of a segment to any side of another segment, and do so in each case in
839 //      four different rotations (for a total of 6*6*4 = 144 ways), not having this nifty function will cause
840 //      great confusion.
841 void get_side_ids(segment *base_seg, segment *con_seg, int base_side, int con_side, int abs_id1, int abs_id2, int *base_common_side, int *con_common_side)
842 {
843         sbyte   *base_vp,*con_vp;
844         int             v0,side;
845
846         *base_common_side = -1;
847
848         //      Find side in base segment which contains the two global vertex ids.
849         for (side=0; side<MAX_SIDES_PER_SEGMENT; side++) {
850                 if (side != base_side) {
851                         base_vp = Side_to_verts[side];
852                         for (v0=0; v0<4; v0++)
853                                 if (((base_seg->verts[(int) base_vp[v0]] == abs_id1) && (base_seg->verts[(int) base_vp[(v0+1) % 4]] == abs_id2)) || ((base_seg->verts[(int) base_vp[v0]] == abs_id2) && (base_seg->verts[(int)base_vp[ (v0+1) % 4]] == abs_id1))) {
854                                         Assert(*base_common_side == -1);                // This means two different sides shared the same edge with base_side == impossible!
855                                         *base_common_side = side;
856                                 }
857                 }
858         }
859
860         // Note: For connecting segment, process vertices in reversed order.
861         *con_common_side = -1;
862
863         //      Find side in connecting segment which contains the two global vertex ids.
864         for (side=0; side<MAX_SIDES_PER_SEGMENT; side++) {
865                 if (side != con_side) {
866                         con_vp = Side_to_verts[side];
867                         for (v0=0; v0<4; v0++)
868                                 if (((con_seg->verts[(int) con_vp[(v0 + 1) % 4]] == abs_id1) && (con_seg->verts[(int) con_vp[v0]] == abs_id2)) || ((con_seg->verts[(int) con_vp[(v0 + 1) % 4]] == abs_id2) && (con_seg->verts[(int) con_vp[v0]] == abs_id1))) {
869                                         Assert(*con_common_side == -1);         // This means two different sides shared the same edge with con_side == impossible!
870                                         *con_common_side = side;
871                                 }
872                 }
873         }
874
875 // mprintf((0,"side %3i adjacent to side %3i\n",*base_common_side,*con_common_side));
876
877         Assert((*base_common_side != -1) && (*con_common_side != -1));
878 }
879
880 // -----------------------------------------------------------------------------
881 //      Propagate texture map u,v coordinates from base_seg:base_side to con_seg:con_side.
882 //      The two vertices abs_id1 and abs_id2 are the only two vertices common to the two sides.
883 //      If uv_only_flag is 1, then don't assign texture map ids, only update the uv coordinates
884 //      If uv_only_flag is -1, then ONLY assign texture map ids, don't update the uv coordinates
885 void propagate_tmaps_to_segment_side(segment *base_seg, int base_side, segment *con_seg, int con_side, int abs_id1, int abs_id2, int uv_only_flag)
886 {
887         int             base_common_side,con_common_side;
888         int             tmap_num;
889
890         Assert ((uv_only_flag == -1) || (uv_only_flag == 0) || (uv_only_flag == 1));
891
892         // Set base_common_side = side in base_seg which contains edge abs_id1:abs_id2
893         // Set con_common_side = side in con_seg which contains edge abs_id1:abs_id2
894         if (base_seg != con_seg)
895                 get_side_ids(base_seg, con_seg, base_side, con_side, abs_id1, abs_id2, &base_common_side, &con_common_side);
896         else {
897                 base_common_side = base_side;
898                 con_common_side = con_side;
899         }
900
901         // Now, all faces in con_seg which are on side con_common_side get their tmap_num set to whatever tmap is assigned
902         // to whatever face I find which is on side base_common_side.
903         // First, find tmap_num for base_common_side.  If it doesn't exist (ie, there is a connection there), look at the segment
904         // that is connected through it.
905         if (!IS_CHILD(con_seg->children[con_common_side])) {
906                 if (!IS_CHILD(base_seg->children[base_common_side])) {
907                         // There is at least one face here, so get the tmap_num from there.
908                         tmap_num = base_seg->sides[base_common_side].tmap_num;
909
910                         // Now assign all faces in the connecting segment on side con_common_side to tmap_num.
911                         if ((uv_only_flag == -1) || (uv_only_flag == 0))
912                                 con_seg->sides[con_common_side].tmap_num = tmap_num;
913
914                         if (uv_only_flag != -1)
915                                 med_assign_uvs_to_side(con_seg, con_common_side, base_seg, base_common_side, abs_id1, abs_id2);
916
917                 } else {                        // There are no faces here, there is a connection, trace through the connection.
918                         int     cside;
919
920                         cside = find_connect_side(base_seg, &Segments[base_seg->children[base_common_side]]);
921                         propagate_tmaps_to_segment_side(&Segments[base_seg->children[base_common_side]], cside, con_seg, con_side, abs_id1, abs_id2, uv_only_flag);
922                 }
923         }
924
925 }
926
927 sbyte   Edge_between_sides[MAX_SIDES_PER_SEGMENT][MAX_SIDES_PER_SEGMENT][2] = {
928 //              left            top             right           bottom  back            front
929         { {-1,-1}, { 3, 7}, {-1,-1}, { 2, 6}, { 6, 7}, { 2, 3} },       // left
930         { { 3, 7}, {-1,-1}, { 0, 4}, {-1,-1}, { 4, 7}, { 0, 3} },       // top
931         { {-1,-1}, { 0, 4}, {-1,-1}, { 1, 5}, { 4, 5}, { 0, 1} },       // right
932         { { 2, 6}, {-1,-1}, { 1, 5}, {-1,-1}, { 5, 6}, { 1, 2} },       // bottom
933         { { 6, 7}, { 4, 7}, { 4, 5}, { 5, 6}, {-1,-1}, {-1,-1} },       // back
934         { { 2, 3}, { 0, 3}, { 0, 1}, { 1, 2}, {-1,-1}, {-1,-1} }};      // front
935
936 // -----------------------------------------------------------------------------
937 //      Propagate texture map u,v coordinates to base_seg:back_side from base_seg:some-other-side
938 //      There is no easy way to figure out which side is adjacent to another side along some edge, so we do a bit of searching.
939 void med_propagate_tmaps_to_back_side(segment *base_seg, int back_side, int uv_only_flag)
940 {
941         int     v1=0,v2=0;
942         int     s,ss,tmap_num,back_side_tmap;
943
944         if (IS_CHILD(base_seg->children[back_side]))
945                 return;         // connection, so no sides here.
946
947         //      Scan all sides, look for an occupied side which is not back_side or Side_opposite[back_side]
948         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
949                 if ((s != back_side) && (s != Side_opposite[back_side])) {
950                         v1 = Edge_between_sides[s][back_side][0];
951                         v2 = Edge_between_sides[s][back_side][1];
952                         goto found1;
953                 }
954         Assert(0);              // Error -- couldn't find edge != back_side and Side_opposite[back_side]
955 found1: ;
956         Assert( (v1 != -1) && (v2 != -1));              // This means there was no shared edge between the two sides.
957
958         propagate_tmaps_to_segment_side(base_seg, s, base_seg, back_side, base_seg->verts[v1], base_seg->verts[v2], uv_only_flag);
959
960         //      Assign an unused tmap id to the back side.
961         //      Note that this can get undone by the caller if this was not part of a new attach, but a rotation or a scale (which
962         //      both do attaches).
963         //      First see if tmap on back side is anywhere else.
964         if (!uv_only_flag) {
965                 back_side_tmap = base_seg->sides[back_side].tmap_num;
966                 for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
967                         if (s != back_side)
968                                 if (base_seg->sides[s].tmap_num == back_side_tmap) {
969                                         for (tmap_num=0; tmap_num < MAX_SIDES_PER_SEGMENT; tmap_num++) {
970                                                 for (ss=0; ss<MAX_SIDES_PER_SEGMENT; ss++)
971                                                         if (ss != back_side)
972                                                                 if (base_seg->sides[ss].tmap_num == New_segment.sides[tmap_num].tmap_num)
973                                                                         goto found2;            // current texture map (tmap_num) is used on current (ss) side, so try next one
974                                                 // Current texture map (tmap_num) has not been used, assign to all faces on back_side.
975                                                 base_seg->sides[back_side].tmap_num = New_segment.sides[tmap_num].tmap_num;
976                                                 goto done1;
977                                         found2: ;
978                                         }
979                                 }
980                 }
981         done1: ;
982         }
983
984 }
985
986 int fix_bogus_uvs_on_side(void)
987 {
988         med_propagate_tmaps_to_back_side(Cursegp, Curside, 1);
989         return 0;
990 }
991
992 void fix_bogus_uvs_on_side1(segment *sp, int sidenum, int uvonly_flag)
993 {
994         side    *sidep = &sp->sides[sidenum];
995
996         if ((sidep->uvls[0].u == 0) && (sidep->uvls[1].u == 0) && (sidep->uvls[2].u == 0)) {
997                 mprintf((0, "Found bogus segment %i, side %i\n", SEGMENT_NUMBER(sp), sidenum));
998                 med_propagate_tmaps_to_back_side(sp, sidenum, uvonly_flag);
999         }
1000 }
1001
1002 void fix_bogus_uvs_seg(segment *segp)
1003 {
1004         int     s;
1005
1006         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
1007                 if (!IS_CHILD(segp->children[s]))
1008                         fix_bogus_uvs_on_side1(segp, s, 1);
1009         }
1010 }
1011
1012 int fix_bogus_uvs_all(void)
1013 {
1014         int     seg;
1015
1016         for (seg=0; seg<=Highest_segment_index; seg++)
1017                 if (Segments[seg].segnum != -1)
1018                         fix_bogus_uvs_seg(&Segments[seg]);
1019         return 0;
1020 }
1021
1022 // -----------------------------------------------------------------------------
1023 //      Propagate texture map u,v coordinates to base_seg:back_side from base_seg:some-other-side
1024 //      There is no easy way to figure out which side is adjacent to another side along some edge, so we do a bit of searching.
1025 void med_propagate_tmaps_to_any_side(segment *base_seg, int back_side, int tmap_num, int uv_only_flag)
1026 {
1027         int     v1=0,v2=0;
1028         int     s;
1029
1030         //      Scan all sides, look for an occupied side which is not back_side or Side_opposite[back_side]
1031         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
1032                 if ((s != back_side) && (s != Side_opposite[back_side])) {
1033                         v1 = Edge_between_sides[s][back_side][0];
1034                         v2 = Edge_between_sides[s][back_side][1];
1035                         goto found1;
1036                 }
1037         Assert(0);              // Error -- couldn't find edge != back_side and Side_opposite[back_side]
1038 found1: ;
1039         Assert( (v1 != -1) && (v2 != -1));              // This means there was no shared edge between the two sides.
1040
1041         propagate_tmaps_to_segment_side(base_seg, s, base_seg, back_side, base_seg->verts[v1], base_seg->verts[v2], uv_only_flag);
1042
1043         base_seg->sides[back_side].tmap_num = tmap_num;
1044
1045 }
1046
1047 // -----------------------------------------------------------------------------
1048 //      Segment base_seg is connected through side base_side to segment con_seg on con_side.
1049 //      For all walls in con_seg, find the wall in base_seg which shares an edge.  Copy tmap_num
1050 //      from that side in base_seg to the wall in con_seg.  If the wall in base_seg is not present
1051 //      (ie, there is another segment connected through it), follow the connection through that
1052 //      segment to get the wall in the connected segment which shares the edge, and get tmap_num from there.
1053 void propagate_tmaps_to_segment_sides(segment *base_seg, int base_side, segment *con_seg, int con_side, int uv_only_flag)
1054 {
1055         sbyte           *base_vp,*con_vp;
1056         short           abs_id1,abs_id2;
1057         int             v;
1058
1059         base_vp = Side_to_verts[base_side];
1060         con_vp = Side_to_verts[con_side];
1061
1062         // Do for each edge on connecting face.
1063         for (v=0; v<4; v++) {
1064                 abs_id1 = base_seg->verts[(int) base_vp[v]];
1065                 abs_id2 = base_seg->verts[(int) base_vp[(v+1) % 4]];
1066                 propagate_tmaps_to_segment_side(base_seg, base_side, con_seg, con_side, abs_id1, abs_id2, uv_only_flag);
1067         }
1068
1069 }
1070
1071 // -----------------------------------------------------------------------------
1072 //      Propagate texture maps in base_seg to con_seg.
1073 //      For each wall in con_seg, find the wall in base_seg which shared an edge.  Copy tmap_num from that
1074 //      wall in base_seg to the wall in con_seg.  If the wall in base_seg is not present, then look at the
1075 //      segment connected through base_seg through the wall.  The wall with a common edge is the new wall
1076 //      of interest.  Continue searching in this way until a wall of interest is present.
1077 void med_propagate_tmaps_to_segments(segment *base_seg,segment *con_seg, int uv_only_flag)
1078 {
1079         int             s;
1080
1081 // mprintf((0, "Propagating segments from %i to %i\n", SEGMENT_NUMBER(base_seg), SEGMENT_NUMBER(con_seg)));
1082         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++)
1083                 if (base_seg->children[s] == SEGMENT_NUMBER(con_seg))
1084                         propagate_tmaps_to_segment_sides(base_seg, s, con_seg, find_connect_side(base_seg, con_seg), uv_only_flag);
1085
1086         s2s2(con_seg)->static_light = s2s2(base_seg)->static_light;
1087
1088         validate_uv_coordinates(con_seg);
1089 }
1090
1091
1092 // -------------------------------------------------------------------------------
1093 //      Copy texture map uvs from srcseg to destseg.
1094 //      If two segments have different face structure (eg, destseg has two faces on side 3, srcseg has only 1)
1095 //      then assign uvs according to side vertex id, not face vertex id.
1096 void copy_uvs_seg_to_seg(segment *destseg,segment *srcseg)
1097 {
1098         int     s;
1099
1100         for (s=0; s<MAX_SIDES_PER_SEGMENT; s++) {
1101                 destseg->sides[s].tmap_num = srcseg->sides[s].tmap_num;
1102                 destseg->sides[s].tmap_num2 = srcseg->sides[s].tmap_num2;
1103         }
1104
1105         s2s2(destseg)->static_light = s2s2(srcseg)->static_light;
1106 }
1107
1108 //      _________________________________________________________________________________________________________________________
1109 //      Maximum distance between a segment containing light to a segment to receive light.
1110 #define LIGHT_DISTANCE_THRESHOLD        (F1_0*80)
1111 fix     Magical_light_constant = (F1_0*16);
1112
1113 // int  Seg0, Seg1;
1114
1115 //int   Bugseg = 27;
1116
1117 typedef struct {
1118         sbyte                   flag, hit_type;
1119         vms_vector      vector;
1120 } hash_info;
1121
1122 #define FVI_HASH_SIZE 8
1123 #define FVI_HASH_AND_MASK (FVI_HASH_SIZE - 1)
1124
1125 //      Note: This should be malloced.
1126 //                      Also, the vector should not be 12 bytes, you should only care about some smaller portion of it.
1127 hash_info       fvi_cache[FVI_HASH_SIZE];
1128 int     Hash_hits=0, Hash_retries=0, Hash_calcs=0;
1129
1130 //      -----------------------------------------------------------------------------------------
1131 //      Set light from a light source.
1132 //      Light incident on a surface is defined by the light incident at its points.
1133 //      Light at a point = K * (V . N) / d
1134 //      where:
1135 //              K = some magical constant to make everything look good
1136 //              V = normalized vector from light source to point
1137 //              N = surface normal at point
1138 //              d = distance from light source to point
1139 //      (Note that the above equation can be simplified to K * (VV . N) / d^2 where VV = non-normalized V)
1140 //      Light intensity emitted from a light source is defined to be cast from four points.
1141 //      These four points are 1/64 of the way from the corners of the light source to the center
1142 //      of its segment.  By assuming light is cast from these points, rather than from on the
1143 //      light surface itself, light will be properly cast on the light surface.  Otherwise, the
1144 //      vector V would be the null vector.
1145 //      If quick_light set, then don't use find_vector_intersection
1146 void cast_light_from_side(segment *segp, int light_side, fix light_intensity, int quick_light)
1147 {
1148         vms_vector      segment_center;
1149         int                     segnum,sidenum,vertnum, lightnum;
1150
1151         compute_segment_center(&segment_center, segp);
1152
1153 //mprintf((0, "From [%i %i %7.3f]:  ", SEGMENT_NUMBER(segp), light_side, f2fl(light_intensity)));
1154
1155         //      Do for four lights, one just inside each corner of side containing light.
1156         for (lightnum=0; lightnum<4; lightnum++) {
1157                 int                     light_vertex_num, i;
1158                 vms_vector      vector_to_center;
1159                 vms_vector      light_location;
1160                 // fix                  inverse_segment_magnitude;
1161
1162                 light_vertex_num = segp->verts[Side_to_verts[light_side][lightnum]];
1163                 light_location = Vertices[light_vertex_num];
1164
1165
1166         //      New way, 5/8/95: Move towards center irrespective of size of segment.
1167         vm_vec_sub(&vector_to_center, &segment_center, &light_location);
1168         vm_vec_normalize_quick(&vector_to_center);
1169         vm_vec_add2(&light_location, &vector_to_center);
1170
1171 // -- Old way, before 5/8/95 --         // -- This way was kind of dumb.  In larger segments, you move LESS towards the center.
1172 // -- Old way, before 5/8/95 --         //    Main problem, though, is vertices don't illuminate themselves well in oblong segments because the dot product is small.
1173 // -- Old way, before 5/8/95 --         vm_vec_sub(&vector_to_center, &segment_center, &light_location);
1174 // -- Old way, before 5/8/95 --         inverse_segment_magnitude = fixdiv(F1_0/5, vm_vec_mag(&vector_to_center));
1175 // -- Old way, before 5/8/95 --         vm_vec_scale_add(&light_location, &light_location, &vector_to_center, inverse_segment_magnitude);
1176
1177                 for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1178                         segment         *rsegp = &Segments[segnum];
1179                         vms_vector      r_segment_center;
1180                         fix                     dist_to_rseg;
1181
1182                         for (i=0; i<FVI_HASH_SIZE; i++)
1183                                 fvi_cache[i].flag = 0;
1184
1185                         //      efficiency hack (I hope!), for faraway segments, don't check each point.
1186                         compute_segment_center(&r_segment_center, rsegp);
1187                         dist_to_rseg = vm_vec_dist_quick(&r_segment_center, &segment_center);
1188
1189                         if (dist_to_rseg <= LIGHT_DISTANCE_THRESHOLD) {
1190                                 for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++) {
1191                                         if (WALL_IS_DOORWAY(rsegp, sidenum) != WID_NO_WALL) {
1192                                                 side                    *rsidep = &rsegp->sides[sidenum];
1193                                                 vms_vector      *side_normalp = &rsidep->normals[0];    //      kinda stupid? always use vector 0.
1194
1195 //mprintf((0, "[%i %i], ", SEGMENT_NUMBER(rsegp), sidenum));
1196                                                 for (vertnum=0; vertnum<4; vertnum++) {
1197                                                         fix                     distance_to_point, light_at_point, light_dot;
1198                                                         vms_vector      vert_location, vector_to_light;
1199                                                         int                     abs_vertnum;
1200
1201                                                         abs_vertnum = rsegp->verts[Side_to_verts[sidenum][vertnum]];
1202                                                         vert_location = Vertices[abs_vertnum];
1203                                                         distance_to_point = vm_vec_dist_quick(&vert_location, &light_location);
1204                                                         vm_vec_sub(&vector_to_light, &light_location, &vert_location);
1205                                                         vm_vec_normalize(&vector_to_light);
1206
1207                                                         //      Hack: In oblong segments, it's possible to get a very small dot product
1208                                                         //      but the light source is very nearby (eg, illuminating light itself!).
1209                                                         light_dot = vm_vec_dot(&vector_to_light, side_normalp);
1210                                                         if (distance_to_point < F1_0)
1211                                                                 if (light_dot > 0)
1212                                                                         light_dot = (light_dot + F1_0)/2;
1213
1214                                                         if (light_dot > 0) {
1215                                                                 light_at_point = fixdiv(fixmul(light_dot, light_dot), distance_to_point);
1216                                                                 light_at_point = fixmul(light_at_point, Magical_light_constant);
1217                                                                 if (light_at_point >= 0) {
1218                                                                         fvi_info        hit_data;
1219                                                                         int             hit_type;
1220                                                                         vms_vector      vert_location_1, r_vector_to_center;
1221                                                                         fix             inverse_segment_magnitude;
1222
1223                                                                         vm_vec_sub(&r_vector_to_center, &r_segment_center, &vert_location);
1224                                                                         inverse_segment_magnitude = fixdiv(F1_0/3, vm_vec_mag(&r_vector_to_center));
1225                                                                         vm_vec_scale_add(&vert_location_1, &vert_location, &r_vector_to_center, inverse_segment_magnitude);
1226                                                                         vert_location = vert_location_1;
1227
1228 //if ((SEGMENT_NUMBER(segp) == 199) && (SEGMENT_NUMBER(rsegp) == 199))
1229 //      Int3();
1230 // Seg0 = SEGMENT_NUMBER(segp);
1231 // Seg1 = SEGMENT_NUMBER(rsegp);
1232                                                                         if (!quick_light) {
1233                                                                                 int hash_value = Side_to_verts[sidenum][vertnum];
1234                                                                                 hash_info       *hashp = &fvi_cache[hash_value];
1235                                                                                 while (1) {
1236                                                                                         if (hashp->flag) {
1237                                                                                                 if ((hashp->vector.x == vector_to_light.x) && (hashp->vector.y == vector_to_light.y) && (hashp->vector.z == vector_to_light.z)) {
1238 //mprintf((0, "{CACHE %4x} ", hash_value));
1239                                                                                                         hit_type = hashp->hit_type;
1240                                                                                                         Hash_hits++;
1241                                                                                                         break;
1242                                                                                                 } else {
1243                                                                                                         Int3(); // How is this possible?  Should be no hits!
1244                                                                                                         Hash_retries++;
1245                                                                                                         hash_value = (hash_value+1) & FVI_HASH_AND_MASK;
1246                                                                                                         hashp = &fvi_cache[hash_value];
1247                                                                                                 }
1248                                                                                         } else {
1249 //mprintf((0, "\nH:%04x ", hash_value));
1250                                                                                                 fvi_query fq;
1251
1252                                                                                                 Hash_calcs++;
1253                                                                                                 hashp->vector = vector_to_light;
1254                                                                                                 hashp->flag = 1;
1255
1256                                                                                                 fq.p0                                           = &light_location;
1257                                                                                                 fq.startseg         = SEGMENT_NUMBER(segp);
1258                                                                                                 fq.p1                                           = &vert_location;
1259                                                                                                 fq.rad                                  = 0;
1260                                                                                                 fq.thisobjnum                   = -1;
1261                                                                                                 fq.ignore_obj_list      = NULL;
1262                                                                                                 fq.flags                                        = 0;
1263
1264                                                                                                 hit_type = find_vector_intersection(&fq,&hit_data);
1265                                                                                                 hashp->hit_type = hit_type;
1266                                                                                                 break;
1267                                                                                         }
1268                                                                                 }
1269                                                                         } else
1270                                                                                 hit_type = HIT_NONE;
1271 //mprintf((0, "hit=%i ", hit_type));
1272                                                                         switch (hit_type) {
1273                                                                                 case HIT_NONE:
1274                                                                                         light_at_point = fixmul(light_at_point, light_intensity);
1275                                                                                         rsidep->uvls[vertnum].l += light_at_point;
1276 //mprintf((0, "(%5.2f) ", f2fl(light_at_point)));
1277                                                                                         if (rsidep->uvls[vertnum].l > F1_0)
1278                                                                                                 rsidep->uvls[vertnum].l = F1_0;
1279                                                                                         break;
1280                                                                                 case HIT_WALL:
1281                                                                                         break;
1282                                                                                 case HIT_OBJECT:
1283                                                                                         Int3(); // Hit object, should be ignoring objects!
1284                                                                                         break;
1285                                                                                 case HIT_BAD_P0:
1286                                                                                         Int3(); //      Ugh, this thing again, what happened, what does it mean?
1287                                                                                         break;
1288                                                                         }
1289                                                                 }       //      end if (light_at_point...
1290                                                         }       // end if (light_dot >...
1291                                                 }       //      end for (vertnum=0...
1292                                         }       //      end if (rsegp...
1293                                 }       //      end for (sidenum=0...
1294                         }       //      end if (dist_to_rseg...
1295
1296                 }       //      end for (segnum=0...
1297
1298         }       //      end for (lightnum=0...
1299
1300 //mprintf((0, "\n"));
1301 }
1302
1303
1304 //      ------------------------------------------------------------------------------------------
1305 //      Zero all lighting values.
1306 void calim_zero_light_values(void)
1307 {
1308         int     segnum, sidenum, vertnum;
1309
1310         for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1311                 segment *segp = &Segments[segnum];
1312                 for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++) {
1313                         side    *sidep = &segp->sides[sidenum];
1314                         for (vertnum=0; vertnum<4; vertnum++)
1315                                 sidep->uvls[vertnum].l = F1_0/64;       // Put a tiny bit of light here.
1316                 }
1317                 Segment2s[segnum].static_light = F1_0 / 64;
1318         }
1319 }
1320
1321
1322 //      ------------------------------------------------------------------------------------------
1323 //      Used in setting average light value in a segment, cast light from a side to the center
1324 //      of all segments.
1325 void cast_light_from_side_to_center(segment *segp, int light_side, fix light_intensity, int quick_light)
1326 {
1327         vms_vector      segment_center;
1328         int                     segnum, lightnum;
1329
1330         compute_segment_center(&segment_center, segp);
1331
1332         //      Do for four lights, one just inside each corner of side containing light.
1333         for (lightnum=0; lightnum<4; lightnum++) {
1334                 int                     light_vertex_num;
1335                 vms_vector      vector_to_center;
1336                 vms_vector      light_location;
1337
1338                 light_vertex_num = segp->verts[Side_to_verts[light_side][lightnum]];
1339                 light_location = Vertices[light_vertex_num];
1340                 vm_vec_sub(&vector_to_center, &segment_center, &light_location);
1341                 vm_vec_scale_add(&light_location, &light_location, &vector_to_center, F1_0/64);
1342
1343                 for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1344                         segment         *rsegp = &Segments[segnum];
1345                         vms_vector      r_segment_center;
1346                         fix                     dist_to_rseg;
1347 //if ((segp == &Segments[Bugseg]) && (rsegp == &Segments[Bugseg]))
1348 //      Int3();
1349                         compute_segment_center(&r_segment_center, rsegp);
1350                         dist_to_rseg = vm_vec_dist_quick(&r_segment_center, &segment_center);
1351
1352                         if (dist_to_rseg <= LIGHT_DISTANCE_THRESHOLD) {
1353                                 fix     light_at_point;
1354                                 if (dist_to_rseg > F1_0)
1355                                         light_at_point = fixdiv(Magical_light_constant, dist_to_rseg);
1356                                 else
1357                                         light_at_point = Magical_light_constant;
1358
1359                                 if (light_at_point >= 0) {
1360                                         int             hit_type;
1361
1362                                         if (!quick_light) {
1363                                                 fvi_query fq;
1364                                                 fvi_info        hit_data;
1365
1366                                                 fq.p0                                           = &light_location;
1367                                                 fq.startseg         = SEGMENT_NUMBER(segp);
1368                                                 fq.p1                                           = &r_segment_center;
1369                                                 fq.rad                                  = 0;
1370                                                 fq.thisobjnum                   = -1;
1371                                                 fq.ignore_obj_list      = NULL;
1372                                                 fq.flags                                        = 0;
1373
1374                                                 hit_type = find_vector_intersection(&fq,&hit_data);
1375                                         }
1376                                         else
1377                                                 hit_type = HIT_NONE;
1378
1379                                         switch (hit_type) {
1380                                                 case HIT_NONE:
1381                                                         light_at_point = fixmul(light_at_point, light_intensity);
1382                                                         if (light_at_point >= F1_0)
1383                                                                 light_at_point = F1_0-1;
1384                                                         s2s2(rsegp)->static_light += light_at_point;
1385                                                         if (s2s2(segp)->static_light < 0)       // if it went negative, saturate
1386                                                                 s2s2(segp)->static_light = 0;
1387                                                         break;
1388                                                 case HIT_WALL:
1389                                                         break;
1390                                                 case HIT_OBJECT:
1391                                                         Int3(); // Hit object, should be ignoring objects!
1392                                                         break;
1393                                                 case HIT_BAD_P0:
1394                                                         Int3(); //      Ugh, this thing again, what happened, what does it mean?
1395                                                         break;
1396                                         }
1397                                 }       //      end if (light_at_point...
1398                         }       //      end if (dist_to_rseg...
1399
1400                 }       //      end for (segnum=0...
1401
1402         }       //      end for (lightnum=0...
1403
1404 }
1405
1406 //      ------------------------------------------------------------------------------------------
1407 //      Process all lights.
1408 void calim_process_all_lights(int quick_light)
1409 {
1410         int     segnum, sidenum;
1411
1412         for (segnum=0; segnum<=Highest_segment_index; segnum++) {
1413                 segment *segp = &Segments[segnum];
1414                 mprintf((0, "."));
1415                 for (sidenum=0; sidenum<MAX_SIDES_PER_SEGMENT; sidenum++) {
1416                         // if (!IS_CHILD(segp->children[sidenum])) {
1417                         if (WALL_IS_DOORWAY(segp, sidenum) != WID_NO_WALL) {
1418                                 side    *sidep = &segp->sides[sidenum];
1419                                 fix     light_intensity;
1420
1421                                 light_intensity = TmapInfo[sidep->tmap_num].lighting + TmapInfo[sidep->tmap_num2 & 0x3fff].lighting;
1422
1423 //                              if (segp->sides[sidenum].wall_num != -1) {
1424 //                                      int     wall_num, bitmap_num, effect_num;
1425 //                                      wall_num = segp->sides[sidenum].wall_num;
1426 //                                      effect_num = Walls[wall_num].type;
1427 //                                      bitmap_num = effects_bm_num[effect_num];
1428 //
1429 //                                      light_intensity += TmapInfo[bitmap_num].lighting;
1430 //                              }
1431
1432                                 if (light_intensity) {
1433                                         light_intensity /= 4;                   // casting light from four spots, so divide by 4.
1434                                         cast_light_from_side(segp, sidenum, light_intensity, quick_light);
1435                                         cast_light_from_side_to_center(segp, sidenum, light_intensity, quick_light);
1436                                 }
1437                         }
1438                 }
1439         }
1440 }
1441
1442 //      ------------------------------------------------------------------------------------------
1443 //      Apply static light in mine.
1444 //      First, zero all light values.
1445 //      Then, for all light sources, cast their light.
1446 void cast_all_light_in_mine(int quick_flag)
1447 {
1448
1449         validate_segment_all();
1450
1451         calim_zero_light_values();
1452
1453         calim_process_all_lights(quick_flag);
1454
1455 }
1456
1457 // int  Fvit_num = 1000;
1458 // 
1459 // fix find_vector_intersection_test(void)
1460 // {
1461 //      int             i;
1462 //      fvi_info        hit_data;
1463 //      int             p0_seg, p1_seg, this_objnum, ignore_obj, check_obj_flag;
1464 //      fix             rad;
1465 //      int             start_time = timer_get_milliseconds();;
1466 //      vms_vector      p0,p1;
1467 // 
1468 //      ignore_obj = 1;
1469 //      check_obj_flag = 0;
1470 //      this_objnum = -1;
1471 //      rad = F1_0/4;
1472 // 
1473 //      for (i=0; i<Fvit_num; i++) {
1474 //              p0_seg = d_rand()*(Highest_segment_index+1)/32768;
1475 //              compute_segment_center(&p0, &Segments[p0_seg]);
1476 // 
1477 //              p1_seg = d_rand()*(Highest_segment_index+1)/32768;
1478 //              compute_segment_center(&p1, &Segments[p1_seg]);
1479 // 
1480 //              find_vector_intersection(&hit_data, &p0, p0_seg, &p1, rad, this_objnum, ignore_obj, check_obj_flag);
1481 //      }
1482 // 
1483 //      return timer_get_milliseconds() - start_time;
1484 // }
1485
1486 vms_vector      Normals[MAX_SEGMENTS*12];
1487
1488 int     Normal_nearness = 4;
1489
1490 int normal_near(vms_vector *v1, vms_vector *v2)
1491 {
1492         if (abs(v1->x - v2->x) < Normal_nearness)
1493                 if (abs(v1->y - v2->y) < Normal_nearness)
1494                         if (abs(v1->z - v2->z) < Normal_nearness)
1495                                 return 1;
1496         return 0;
1497 }
1498
1499 int     Total_normals=0;
1500 int     Diff_normals=0;
1501
1502 void print_normals(void)
1503 {
1504         int                     i,j,s,n,nn;
1505         // vms_vector   *normal;
1506         int                     num_normals=0;
1507
1508         Total_normals = 0;
1509         Diff_normals = 0;
1510
1511         for (i=0; i<=Highest_segment_index; i++)
1512                 for (s=0; s<6; s++) {
1513                         if (Segments[i].sides[s].type == SIDE_IS_QUAD)
1514                                 nn=1;
1515                         else
1516                                 nn=2;
1517                         for (n=0; n<nn; n++) {
1518                                 for (j=0; j<num_normals; j++)
1519                                         if (normal_near(&Segments[i].sides[s].normals[n],&Normals[j]))
1520                                                 break;
1521                                 if (j == num_normals) {
1522                                         Normals[num_normals++] = Segments[i].sides[s].normals[n];
1523                                         Diff_normals++;
1524                                 }
1525                                 Total_normals++;
1526                         }
1527                 }
1528
1529 }
1530