Debian Codegraph @

debian/external_deps/fetk/sg/src/ogl/oglps.c

raw
1 /*
2 * ***************************************************************************
3 * SG = < Socket Graphics >
4 * Copyright (C) 1994-- Michael Holst
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 *
20 * rcsid="$Id: oglps.c,v 1.10 2010/08/12 04:56:23 fetk Exp $"
21 * ***************************************************************************
22 */
23
24 /*
25 * ***************************************************************************
26 * File: oglps.c
27 *
28 * Purpose: High-quality OpenGL-to-Postscript rendering.
29 *
30 * Notes: The purpose of Oglps is to produce a very high-quality and
31 * realistic PostScript rendering of an OpenGL rendered scene, by
32 * using the feedback mechanism in OpenGL to fetch the set of
33 * polygons in the current scene, determine a logical painting order
34 * for the polygons in the scene using a constaint resolution-based
35 * ``feasible region'' approach, and then by drawing the scene in
36 * that order in PostScript, using the painter's algorithm. (While
37 * we usually have a Z-buffer when using OpenGL, we must resort to
38 * the painter's algorithm for rendering in postscript.)
39 *
40 * There are two main difficulties in implementing such a rendering:
41 *
42 * (1) The scene may not be orderable, e.g., if polygons overlap
43 * loops occur. This is actually quite common, especially for
44 * scenes with polygons that intersect or self-intersect, such
45 * as a scene containing a Klein bottle.
46 *
47 * (2) Even if the scene is orderable, determining an ordering may
48 * be difficult or extremely costly. In particular, the
49 * complexity of looking at all pair-wise interactions to
50 * determine constraints (which polygons must be drawn before
51 * other polygons) makes determining the rendering order quite
52 * expensive, and perhaps intractable for scenes with many
53 * polygons. (The complexity of the pairwise compare goes as
54 * N^2 for a scene with N polygons.)
55 *
56 * The first problem is solvable through subdivision; we ignore this
57 * problem here and assume we are dealing only with scenes
58 * renderable using the painter's algorithm.
59 *
60 * The second problem is addressed in a primative (but fast) way in
61 * several publically available GL-to-PS and OpenGL-to-PS
62 * generators. Unfortunately, these codes use a simple quicksort
63 * of the polygons by the z-coordinates of their centroids or
64 * baricenters, which works pretty well for very smooth triangular
65 * 2-manifolds, but fails badly for any seriously complex 3D scene.
66 * (Examples are 3D tetrhedral meshes, or even 2-manifold meshes
67 * which are not smooth.)
68 *
69 * In this code, we solve this second problem in the case of much
70 * more complex OpenGL scenes. We build a list of linear inequality
71 * constraints, and then locate a point in the feasible region
72 * defined by the constraints, producing a (possibly non-unique)
73 * rendering order that produces a correct (realistic) scene. We
74 * address the complexity problem by building a binary space
75 * partition tree in the Z (z-buffer) direction, and then adaptively
76 * bisect the polygons in each Z-slice to further reduce the number
77 * of polygons that must be pair-wise compared to produce the list
78 * of linear inequality constraints for that part of the scene.
79 *
80 * Once the list of linear inequality constraints has been created
81 * for the entire scene by moving through the Z-slices and through
82 * the X/Y partitions within each slice, we then use a "constraint
83 * walking" algorithm to locate a feasible rendering point in the
84 * feasible rendering region, beginning with a single unconstrained
85 * polygon in the rear of the scene.
86 *
87 * This "constraint walking" algorithm finds a feasible point in the
88 * feasible region defined by a set of (binary) linear inequality
89 * constraints in the sense of linear or nonlinear programming.
90 * However, the simple binary nature of each constraint allows us to
91 * find a feasible point without resorting to the use of something
92 * like phase one of the simplex method.
93 *
94 * Approach: The core rendering routines are based on the following approach.
95 *
96 * (1) We build a binary space partition tree, with cutting planes
97 * moved along the Z-axis from maximal Z (the first polygons to
98 * be drawn) to minimal Z (the last polygons to be drawn). This
99 * binary space partition tree is used primarily to try to
100 * reduce the complexity of collecting constraint information
101 * about the polygons. Note that polygons are cut exactly at
102 * the plane, resulting in fragments, so that the total number
103 * of polygons rendered actually increases with each partition
104 * that is used.
105 *
106 * (2) Within each Z partition (beginning with the maximal Z
107 * partition and working from back to front), we collect
108 * constraint information. We use adaptive orthogonal bisection
109 * (bisecting parallel to either the X axis or the Y axis,
110 * depending on which bisection results in the smallest total
111 * number of polygons appearing in the sum of both resulting
112 * polygon lists).
113 *
114 * The constraint information collected is as follows. If an
115 * polygon A is found to lie under B, then A must be drawn
116 * before B. We can view this as A "blocking" B from being
117 * drawn, or constraining B to be ordered after A in a sequential
118 * rendering order. We store this information by (1) placing B
119 * in a list maintained by A that keeps track of exactly which
120 * polygons A blocks from being drawn, and (2) incrementing a
121 * "blocked" counter in polygon B that counts how many polygons
122 * are blocking B from being drawn.
123 *
124 * The test of whether a polygon A lies above or below B is
125 * performed by forming the exact overlap polygon (if there is
126 * overlap), and then comparing the z-coordinates of the
127 * polygons A and B at the centroid of the overlap polygon.
128 * Comparing A and B by the z-coordinates of their separate
129 * baricenters can easily fail to order them correctly. However,
130 * using the z-coordinates at the centroid of their overlap
131 * polygon cannot fail, if the polygons are disjoint and
132 * non-intersecting.
133 *
134 * (3) Once the entire scene has been processed (hopefully in our
135 * lifetime, thanks to the complexity reductions in steps (1)
136 * and (2) above), we have a set of (binary) linear inequality
137 * constraints, defining a feasible rendering region. Every
138 * point in this feasible region represents a (possibly
139 * non-unique) rendering order that will produce a logically
140 * correct scene using the Painter's algorithm. We are not
141 * interested here in some optimal rendering order, but rather
142 * some ordering that produces a correct scene, so all we need
143 * to do is find a feasible point.
144 *
145 * At this point we must locate a single point in this feasible
146 * region. The standard approach for doing this is to build
147 * a "larger" linear programming problem for which we do have
148 * a starting point in the feasible region (of the larger
149 * problem), the solution of which is a feasible point in the
150 * original feasible region. Once we have this larger problem,
151 * we can use the simplex method to solve it to locate the
152 * point the feasible region that we were originally after.
153 *
154 * However, this is overkill here; our constraints are very
155 * special (binary), and a feasible point can be located much
156 * more efficiently by using the following "constraint walking"
157 * algorithm that has been suggested by Randy Bank. We begin by
158 * finding all polygons with no constraints (single traversal
159 * through the polygon list, looking for polygons with "blocked"
160 * counter set to zero). We place these unconstrained polygons
161 * in a final rendering order list, and then begin with the
162 * single unconstrained polygon in the first rendering list
163 * position.
164 *
165 * If the scene is renderable by the painter's algorithm, then
166 * this unconstrained list has atleast one polygon in it.
167 * We then "draw" it by "walking" the list that it maintains
168 * about polygons it was blocking. We then decrement the
169 * "blocked" counter in each of these polygons on the list.
170 * If any of the "blocked" counters reduce to zero, that polygon
171 * is placed on the final rendering list in the first empty
172 * slot. We now move to the second polygon in the unconstrained
173 * list, and "draw" it by walking its constraint list as for the
174 * first polygon. We continue in this manner until all polygons
175 * have been placed in a rendering order in the final rendering
176 * list.
177 *
178 * Note that if the scene is renderable (via painter's algorithm),
179 * then this algorithm cannot fail. Since we begin with all
180 * unconstrained polygons on the final rendering list, and since I
181 * immediately place any polygons with "blocked" count reduced to
182 * zero in the final rendering list, we always have access to all
183 * unconstrained polygons in the final rendering list. If we come
184 * to the end of the unconstrained polygons and we still have
185 * unrendered polygons, then we can conclude that the scene was not
186 * renderable by the painter's algorithm.
187 *
188 * Limits: To avoid floating point round-off problems that quickly kill
189 * the painter's algorithm, only TRIANGLES are rendered. All other
190 * OpenGL objects retrieved by the glFeedbackBuffer() call are
191 * ignored (including points, lines, polygons other than triangles,
192 * and all other OpenGL objects other than polygons). To make it
193 * possible to render the edges of e.g. a triangular or tetrahedral
194 * finite element mesh, an option is provided that will paint
195 * polygon outlines after the polygon itself is painted.
196 *
197 * Usage: This library is used as follows. You begin by making a call to
198 * "Oglps_begin()" with no argument. You follow this by rendering
199 * your scene as usual (e.g., "Reshape" and "Display"), and
200 * finally you call "Oglps_end(x,c,b)". You use first argment x=0
201 * for filled polygon rendering, or use x=1 for filled AND outlined
202 * polygon rendering. You use c=0 for black/white or c=1 for color
203 * as the second argument. Use the third argument b=0 for rendering
204 * of all polygons, or b=1 for removal of back-facing polygons
205 * before rendering (in a tetrahedral mesh, all back-facing triangles
206 * are in the interior of tets, and they can be safely removed before
207 * rendering, which will reduce the complexity costs of rendering
208 * the scene.)
209 *
210 * The calling sequence in your code will look something like this:
211 *
212 * Oglps_begin();
213 * reshape(w,h);
214 * display();
215 * Oglps_end( x, c, b );
216 *
217 * There is also a quick and dirty GLXpixmap-to-postscript generator
218 * that we more or less typed in from Kilgard's book; you call it
219 * as follows, where "x" and "c" are as above, and where w and h
220 * are the width and height (in pixels) of the pixmap:
221 *
222 * Oglps_gen( "glx.ps", x, c, w, h );
223 *
224 * (You must render into a GLXpixmap yourself, before calling
225 * Oglps_gen.)
226 *
227 * Comments: (1) The binary space paritioning scheme in the Z direction
228 * for reducing polygon comparision complexity is a well-known
229 * computational geometry algorithm in computer graphics, and
230 * can be found in most computational geometry books.
231 *
232 * (2) This OpenGL-2-Postscript rendering code came about by
233 * running into failure with the baricenter/quicksort ordering
234 * scheme used in Seth Teller's "PSGL" when trying to render
235 * complex OpenGL 3D finite element scenes into postscript.
236 * Peter Schroeder at Caltech suggested we try Gary Wu's
237 * "PSOGL", but it turns out that it shares the same simple
238 * baricenter/quicksort-based ordering scheme, so it fails to
239 * order these types of meshes correctly for the painter's
240 * algorithm in the same way as PSGL.
241 *
242 * We ended up writing an exact polygon intersection comparison
243 * code to exactly resolve front/behind compares for any
244 * polygon pair. Unfortunately, this creates a different "z"
245 * value for the same polygon, depending on who it is compared
246 * to (the overlap polygon changes). What this means is that
247 * normal sorting algorithms such as quicksort can no longer be
248 * used, since what we really have is a set of linear inequality
249 * constraints defining a feasible rendering region in the
250 * sense of linear or nonlinear programming. The solution was
251 * to use a completely constraint-oriented ordering approach,
252 * with binary space partitioning in Z, and then in X and Y as
253 * well, to keep the constraint construction complexity low,
254 * and then to resolve the constraints using something equivalent
255 * to phase one of the Simplex Method (which finds a feasible
256 * point in the feasible region from which to launch phase two).
257 *
258 * (3) While using phase one of the simplex method works here, in
259 * that it finds a feasible point in the feasible region defined
260 * by the set of constraints (i.e., a legal rendering order),
261 * Randy Bank had a nice insight that lets me avoid actually
262 * using the simplex method here. He had used a "constraint
263 * walking" algorithm like the one above for rendering scenes
264 * using the painter's algorithm in PLTMG, although he used
265 * mesh topology information to actually build the constraint
266 * information. While we have no topology to exploit here
267 * (all we get from OpenGL's feedback mechanism is a list of
268 * unrelated objects to render), we can actually use this
269 * constraint walking algorithm here, once we have built the
270 * constraints by other means. It is equivalent to phase one of
271 * the simplex method for finding a single point in the feasible
272 * region defined by a set of linear inequality constraints.
273 * The equivalence is due to the fact that the constraints in
274 * this situation are very special, namely binary linear
275 * inequality constraints.
276 *
277 * (4) We also added a completely separate quick and dirty postscript
278 * generator by condensing an example from Mark Kilgard's
279 * OpenGL/X programming book to a single routine. This single
280 * routine (Oglps_gen) is completely independent from the
281 * other rendering routines (shares no data, etc). It simply
282 * generates a postscript image from pixel data, so it achieves
283 * rendering quality on the order of a screen dump (pretty bad).
284 * But it is a quick was to get PS output without bringing up
285 * e.g. xv, if you don't want to wait for the painter's
286 * algorithm to correctly render your scene.
287 *
288 * Author: Michael Holst and Randy Bank
289 * ***************************************************************************
290 */
291
292 #include "oglps_p.h"
293
294 VEMBED(rcsid="$Id: oglps.c,v 1.10 2010/08/12 04:56:23 fetk Exp $")
295
296 #define VMAXPV 6 /* Max num of vertices allowed in a planar poly */
297 #define VBOX 10000.0 /* Virtual truncation box around the object */
298 #define VTINY 1.0e-6 /* The effective ZERO for all floating point */
299
300 /* PS generation parameters */
301 #define base 62
302 #define base3 ( base*base*base )
303 #define scale 5000
304 #define clipdist 0
305 #define PointsPerInch 72.0
306 #define PBox 0.02
307 #define PSize ( 8.0 * PointsPerInch )
308 #define PWidth ( 8.5 * PointsPerInch )
309 #define PHeight ( 8.5 * PointsPerInch )
310 #define PXmin ( (PWidth - PSize) / 2.0 )
311 #define PYmin ( (PHeight - PSize) / 2.0 )
312 #define PXmax ( PXmin + PSize )
313 #define PYmax ( PYmin + PSize )
314 #define PXmapPS(x) ( (((x) - Xmid)*XYscale + 0.5) * PSize + PXmin )
315 #define PYmapPS(y) ( (((y) - Ymid)*XYscale + 0.5) * PSize + PYmin )
316 #define PXmap01(x) (((x) - Xmid)*XYscale + 0.5)
317 #define PYmap01(y) (((y) - Ymid)*XYscale + 0.5)
318
319 typedef struct Color { /* RGBA-color object */
320 int i;
321 float r;
322 float g;
323 float b;
324 float a;
325 } Color;
326
327 typedef struct Vert { /* Vertex object */
328 double x;
329 double y;
330 double z;
331 } Vert;
332
333 typedef struct Bloc { /* Constraint matrix row entry */
334 struct Poly *guy;
335 struct Bloc *next;
336 } Bloc;
337
338 typedef struct Poly { /* Planar polygon datastructure */
339 int id; /* My global id */
340 int nv; /* My vertex count */
341 Color c; /* My color */
342 int bnum; /* Number of guys blocking me from being drawn */
343 Bloc *blist; /* The list of guys that I block from being drawn */
344 double xmin; /* Minimum x-value in me */
345 double xmax; /* Maximum x-value in me */
346 double ymin; /* Minimum y-value in me */
347 double ymax; /* Maximum y-value in me */
348 double zmin; /* Minimum z-value in me */
349 double zmax; /* Maximum z-value in me */
350 double bc[3]; /* Coordinates of my baricenter */
351 Vert v[VMAXPV]; /* My vertices */
352 } Poly;
353
354 VPRIVATE int floatBufferMax = 4*1024*1024; /* feedback buffer (fixed) */
355 VPRIVATE int floatBufferNum;
356 VPRIVATE float* floatBuffer;
357
358 VPRIVATE int triaBufferMax = 1024; /* start tria buffer small (dynamic) */
359 VPRIVATE int triaBufferNum;
360 VPRIVATE Poly* triaBuffer;
361
362 VPRIVATE int edgeBufferMax = 1024; /* start edge buffer small (dynamic) */
363 VPRIVATE int edgeBufferNum;
364 VPRIVATE Poly* edgeBuffer;
365
366 VPRIVATE int *xord; /* x/y/z-max orderings */
367 VPRIVATE int *yord;
368 VPRIVATE int *zord;
369
370 VPRIVATE int colorBufMax = base3; /* color index buffer (fixed) */
371 VPRIVATE int colorBufNum;
372 VPRIVATE int *colorBufI;
373 VPRIVATE float *colorBufR, *colorBufG, *colorBufB;
374 VPRIVATE int colorBufInit = 0;
375
376 VPRIVATE char psFileName[256]; /* PS filename, counter, and pointer */
377 VPRIVATE int psFileNumber = 0;
378 VPRIVATE FILE* psFilePtr;
379
380 VPRIVATE double Xmin; /* Smallest box containing the scene */
381 VPRIVATE double Xmax;
382 VPRIVATE double Ymin;
383 VPRIVATE double Ymax;
384 VPRIVATE double Zmin;
385 VPRIVATE double Zmax;
386
387 VPRIVATE double Xmid; /* Center of the containment Box */
388 VPRIVATE double Ymid;
389
390 VPRIVATE double XYscale; /* For PS generation page layout */
391
392 VPRIVATE char digits[62] = /* color encoding; makes small PS files */
393 "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
394
395 /*
396 * ***************************************************************************
397 * Private routine prototypes
398 * ***************************************************************************
399 */
400
401 /* interact with OpenGL feedback buffer */
402 VPRIVATE void yankPolys();
403
404 /* generic utilities */
405 VPRIVATE int roundX(float x);
406 VPRIVATE void sintc(char list[], int *length, int ival);
407 VPRIVATE void rgb2cindx(int *colorIndex, float red, float green, float blue);
408 #if 0
409 VPRIVATE void cindx2rgb(float *red, float *green, float *blue, int colorIndex);
410 #endif
411 VPRIVATE void xcrossy(double u[], double v[], double w[]);
412 VPRIVATE double norm2(double u[], int n);
413 VPRIVATE void normalize(double u[], int n);
414
415 /* polygon methods (simple) */
416 VPRIVATE void Poly_findCentroid(Poly *a);
417 VPRIVATE void Poly_swapVert0and1(Poly *a);
418 VPRIVATE void Poly_getMinMaxCentroid(Poly *a);
419 VPRIVATE void Poly_getIntercepts(Poly *a, Poly *b, int *no, Vert vo[]);
420 VPRIVATE void Poly_copy(Poly *a, Poly *b);
421 VPRIVATE void Poly_AblocksB(Poly *a, Poly *b);
422 VPRIVATE void Poly_matlabOut(
423 Poly *a, Poly *b, Poly *c, Poly *d,
424 int no, Vert vo[], double obc[], char *fname);
425
426 /* polygon methods (complex; intersection, area, etc) */
427 VPRIVATE int Poly_pointInTriangle(Poly *a, double x, double y, double TOL);
428 VPRIVATE void Poly_overlapTriangles(Poly *a, Poly *b, Poly *c);
429 VPRIVATE double Poly_evalTriangleZ(Poly *a, double x, double y);
430 VPRIVATE int Poly_compareTriangles(const void* A, const void* B);
431 VPRIVATE int Poly_compareMaxX(const void* A, const void* B);
432 VPRIVATE int Poly_compareMaxY(const void* A, const void* B);
433 VPRIVATE int Poly_compareMaxZ(const void* A, const void* B);
434 VPRIVATE int IntPoly_compareMaxX(const void* A, const void* B);
435 VPRIVATE int IntPoly_compareMaxY(const void* A, const void* B);
436 VPRIVATE int IntPoly_compareMaxZ(const void* A, const void* B);
437 VPRIVATE double Poly_areaTriangle(Poly *a);
438
439 /* polygon array methods (ordering, cutting, etc) */
440 VPRIVATE void Polys_paintOrdering(Poly tri[], int ntri,
441 int xo[], int yo[], int zo[]);
442 VPRIVATE void Polys_removeBackTriangles(Poly *tri[], int *ntri);
443 VPRIVATE void Polys_buildConstraints(
444 Poly tri[], int ntri, int xo[], int yo[], int zo[], int nord);
445 VPRIVATE void Polys_boxConstraints(
446 Poly tri[], int ntri, int guys[], int nguys);
447 VPRIVATE int Polys_testCut(Poly tri[], int ntri,
448 int xo[], int yo[], int zo[], int nord,
449 int *lsize, int *rsize);
450 VPRIVATE void Polys_makeCut(Poly tri[], int ntri,
451 int xo[], int yo[], int zo[], int nord,
452 int whichCut, int nleft, int nright,
453 int xleft[], int xright[],
454 int yleft[], int yright[],
455 int zleft[], int zright[]);
456
457 /* Better PS generation (borrowed from PLTMG with help from R. Bank) */
458 VPRIVATE void psgenHeader(void);
459 VPRIVATE void psgenTrailer(void);
460 VPRIVATE void psgenPaint(int outline);
461 VPRIVATE void psgenPaintPoly(Poly *p, int mode);
462 VPRIVATE void psgenUtl(int ncolor,
463 float red[], float green[], float blue[], int cidx[]);
464 VPRIVATE void psgenPath(float x[], float y[], int n, int icolor, int itype);
465
466 /*
467 * ***************************************************************************
468 * Public routines
469 * ***************************************************************************
470 */
471
472 /*
473 * ***************************************************************************
474 * Routine: Oglps_begin
475 *
476 * Purpose: Setup the feedback buffer for the OpenGL library to render into.
477 *
478 * Notes: We malloc the float, triangle, and edge buffer areas,
479 * set glRenderMode to GL_FEEDBACK, and finish by opening the
480 * output postscript file.
481 *
482 * The input parameters are interpretted as:
483 *
484 * filename ==> name of eventual output PostScript file
485 *
486 * Author: Michael Holst
487 * ***************************************************************************
488 */
489 VPUBLIC void Oglps_begin(void)
490 {
491 GLboolean zbufferPresent;
492 int rc, renderMode;
493
494 /* make sure we are not already in GL_FEEDBACK mode */
495 glGetIntegerv( GL_RENDER_MODE, &renderMode );
496 VJMPERR1( renderMode == GL_RENDER );
497
498 /* initialize the feedback float buffer */
499 if ( floatBuffer != VNULL ) free( floatBuffer );
500 floatBufferNum = 0;
501 floatBuffer = VNULL;
502 floatBuffer = (float*)calloc( floatBufferMax, sizeof(float) );
503 VJMPERR1( floatBuffer != VNULL );
504
505 /* initialize the triangle buffer */
506 if ( triaBuffer != VNULL ) free( triaBuffer );
507 triaBufferNum = 0;
508 triaBuffer = VNULL;
509 triaBuffer = (Poly*)calloc( triaBufferMax, sizeof(Poly) );
510 VJMPERR1( triaBuffer != VNULL );
511
512 /* initialize the edge buffer */
513 if ( edgeBuffer != VNULL ) free( edgeBuffer );
514 edgeBufferNum = 0;
515 edgeBuffer = VNULL;
516 edgeBuffer = (Poly*)calloc( edgeBufferMax, sizeof(Poly) );
517 VJMPERR1( edgeBuffer != VNULL );
518
519 /* make sure we have a z-buffer here to make everything possible */
520 glGetBooleanv( GL_DEPTH_TEST, &zbufferPresent );
521 VJMPERR1( zbufferPresent );
522
523 /* register feedback buffer (must happen BEFORE changing to GL_FEEDBACK) */
524 glFeedbackBuffer( floatBufferMax, GL_3D_COLOR, floatBuffer );
525
526 /* switch to GL_FEEDBACK mode (must happen AFTER registering the buffer) */
527 rc = glRenderMode( GL_FEEDBACK );
528 VJMPERR1( rc == 0 );
529
530 /* return without error */
531 return;
532
533 /* return with error */
534 VERROR1:
535 fprintf(stderr, "Oglps_begin: problem occurred (bailing out).\n");
536 }
537
538 /*
539 * ***************************************************************************
540 * Routine: Oglps_end
541 *
542 * Purpose: Feed triangles from the OpenGL library into our buffer
543 * and output to file.
544 *
545 * Notes: We flush the OpenGL rendering buffer, grab the triangles and
546 * edges from feedback buffer, construct a proper ordering for the
547 * painter's algorithm, and finally write the postscript output.
548 *
549 * The input parameters are interpretted as:
550 *
551 * outLine ==> 0=use filled triangles
552 * 1=use filled triangles and then outline them
553 *
554 * inColor ==> 0=grayscale
555 * 1=color
556 *
557 * doCulling ==> 0=don't cull (render everything)
558 * 1=cull (remove backface triangles before
559 * rendering)
560 *
561 * Author: Michael Holst
562 * ***************************************************************************
563 */
564 VPUBLIC void Oglps_end(int outLine, int inColor, int doCulling)
565 {
566 int i, renderMode, rc;
567
568 /* make sure we were in GL_FEEDBACK mode */
569 glGetIntegerv( GL_RENDER_MODE, &renderMode );
570 VJMPERR1( renderMode == GL_FEEDBACK );
571
572 /* flush the OpenGL pipeline */
573 glFinish();
574
575 /* retrieve triangles and edges from feedback buffer; check for error */
576 floatBufferNum = glRenderMode( GL_FEEDBACK );
577 VJMPERR2(floatBufferNum >= 0);
578
579 /* pull the triangles and edges out of the feedback float buffer */
580 yankPolys();
581
582 /* switch back to GL_RENDER mode */
583 rc = glRenderMode( GL_RENDER );
584 VJMPERR3( rc == 0 );
585
586 /* cull back-facing faces if requested (e.g. these are inside in tets) */
587 if (doCulling) Polys_removeBackTriangles( &triaBuffer, &triaBufferNum );
588
589 /* produce an initial ordering based on zmin values for each triangle */
590 if (triaBufferNum > 0) {
591 qsort( triaBuffer, triaBufferNum, sizeof(Poly), Poly_compareMaxZ );
592 xord = (int*)calloc( triaBufferNum, sizeof(int) );
593 yord = (int*)calloc( triaBufferNum, sizeof(int) );
594 zord = (int*)calloc( triaBufferNum, sizeof(int) );
595 for (i=0; i<triaBufferNum; i++) {
596 xord[i] = i;
597 yord[i] = i;
598 zord[i] = i;
599 }
600 qsort( xord, triaBufferNum, sizeof(int), IntPoly_compareMaxX );
601 qsort( yord, triaBufferNum, sizeof(int), IntPoly_compareMaxY );
602 qsort( zord, triaBufferNum, sizeof(int), IntPoly_compareMaxZ );
603 }
604
605 /* produce triangle ordering for drawing with the painter's algorithm */
606 Polys_paintOrdering( triaBuffer, triaBufferNum, xord, yord, zord);
607
608 /* output postscript header, all triangles, and a postscript trailer */
609 psgenHeader();
610 fprintf(stderr, "Oglps_end: opening <%s>\n", psFileName);
611 psgenPaint(outLine);
612 fprintf(stderr, "Oglps_end: closing <%s>\n", psFileName);
613 psgenTrailer();
614
615 /* memory usage statistics */
616 fprintf(stderr, "Oglps_end: fbuffer usage: <%d/%d> floats\n",
617 floatBufferNum, floatBufferMax);
618 fprintf(stderr, "Oglps_end: tbuffer usage: <%d/%d> triangles\n",
619 triaBufferNum, triaBufferMax);
620 fprintf(stderr, "Oglps_end: ebuffer usage: <%d/%d> edges\n",
621 edgeBufferNum, edgeBufferMax);
622
623 /* free everything */
624 if ( xord != VNULL ) free( xord ); xord = VNULL;
625 if ( yord != VNULL ) free( yord ); yord = VNULL;
626 if ( zord != VNULL ) free( zord ); zord = VNULL;
627
628 /* free everything */
629 if ( floatBuffer != VNULL ) free( floatBuffer );
630 floatBufferNum = 0;
631 floatBuffer = VNULL;
632 if ( triaBuffer != VNULL ) free( triaBuffer );
633 triaBufferNum = 0;
634 triaBuffer = VNULL;
635 if ( edgeBuffer != VNULL ) free( edgeBuffer );
636 edgeBufferNum = 0;
637 edgeBuffer = VNULL;
638
639 /* return without error */
640 return;
641
642 /* return with error */
643 VERROR1:
644 fprintf(stderr, "Oglps_end: PROBLEM: Not currently in FEEDBACK mode.\n");
645 fprintf(stderr, "Oglps_end: BAILING OUT.\n");
646 return;
647
648 VERROR2:
649 fprintf(stderr, "Oglps_end: PROBLEM: Feedback buffer not available.\n");
650 fprintf(stderr, "Oglps_end: BAILING OUT.\n");
651 return;
652
653 VERROR3:
654 fprintf(stderr, "Oglps_end: PROBLEM: Reset back to RENDER mode failed.\n");
655 fprintf(stderr, "Oglps_end: BAILING OUT.\n");
656 return;
657 }
658
659 /*
660 * ***************************************************************************
661 * Routine: Oglps_gen
662 *
663 * Purpose: Quick and dirty postscript generator (low-resolution only).
664 *
665 * Notes: This generator is a modified example from Mark Kilgard's book.
666 *
667 * The input parameters are interpretted as:
668 *
669 * filename ==> name of file containing PostScript output
670 *
671 * inColor ==> 0=grayscale
672 * 1=color
673 *
674 * width ==> width of input image in pixels
675 *
676 * height ==> height of input image in pixels
677 *
678 * Author: Michael Holst
679 * ***************************************************************************
680 */
681 VPUBLIC void Oglps_gen(char *filename, int inColor, int width, int height)
682 {
683 int swapbytes, lsbfirst, rowlength, skiprows, skippixels, alignment;
684 int i, pos, components;
685 int size;
686 unsigned char *curpix;
687 GLenum format;
688 void *pixels;
689 FILE *fp;
690
691 fprintf(stderr, "Oglps_gen: started generating PS from a pixmap..");
692
693 /* setup for pixel grab */
694 if (inColor) {
695 format = GL_RGB;
696 size = width * height * 3;
697 } else {
698 format = GL_LUMINANCE;
699 size = width * height * 1;
700 }
701 pixels = (void *)malloc(size);
702 VJMPERR1(pixels != VNULL);
703
704 /* store current GL_PACK settings */
705 glGetIntegerv(GL_PACK_SWAP_BYTES, &swapbytes);
706 glGetIntegerv(GL_PACK_LSB_FIRST, &lsbfirst);
707 glGetIntegerv(GL_PACK_ROW_LENGTH, &rowlength);
708 glGetIntegerv(GL_PACK_SKIP_ROWS, &skiprows);
709 glGetIntegerv(GL_PACK_SKIP_PIXELS, &skippixels);
710 glGetIntegerv(GL_PACK_ALIGNMENT, &alignment);
711 glPixelStorei(GL_PACK_SWAP_BYTES, GL_FALSE);
712 glPixelStorei(GL_PACK_LSB_FIRST, GL_FALSE);
713 glPixelStorei(GL_PACK_ROW_LENGTH, 0);
714 glPixelStorei(GL_PACK_SKIP_ROWS, 0);
715 glPixelStorei(GL_PACK_SKIP_PIXELS, 0);
716 glPixelStorei(GL_PACK_ALIGNMENT, 1);
717
718 /* actual pixel grab */
719 glReadPixels(0, 0, width, height, format,
720 GL_UNSIGNED_BYTE, (void *) pixels);
721
722 /* restore to original GL_PACK modes */
723 glPixelStorei(GL_PACK_SWAP_BYTES, swapbytes);
724 glPixelStorei(GL_PACK_LSB_FIRST, lsbfirst);
725 glPixelStorei(GL_PACK_ROW_LENGTH, rowlength);
726 glPixelStorei(GL_PACK_SKIP_ROWS, skiprows);
727 glPixelStorei(GL_PACK_SKIP_PIXELS, skippixels);
728 glPixelStorei(GL_PACK_ALIGNMENT, alignment);
729
730 /* okay generate a quick & dirty postscript file using the pixel data */
731 if (inColor) components = 3; /* Red, green, blue. */
732 else components = 1; /* Luminance. */
733 fp = fopen(filename, "w");
734 VJMPERR1(fp != VNULL);
735 fprintf(fp, "%%!PS-Adobe-2.0 EPSF-1.2\n");
736 fprintf(fp, "%%%%Creator: OpenGL pixmap render output\n");
737 fprintf(fp, "%%%%BoundingBox: 0 0 %d %d\n", width, height);
738 fprintf(fp, "%%%%EndComments\n");
739 fprintf(fp, "gsave\n");
740 fprintf(fp, "/bwproc {\n");
741 fprintf(fp, " rgbproc\n");
742 fprintf(fp, " dup length 3 idiv string 0 3 0\n");
743 fprintf(fp, " 5 -1 roll {\n");
744 fprintf(fp, " add 2 1 roll 1 sub dup 0 eq\n");
745 fprintf(fp, " { pop 3 idiv 3 -1 roll dup 4 -1 roll dup\n");
746 fprintf(fp, " 3 1 roll 5 -1 roll put 1 add 3 0 }\n");
747 fprintf(fp, " { 2 1 roll } ifelse\n");
748 fprintf(fp, " } forall\n");
749 fprintf(fp, " pop pop pop\n");
750 fprintf(fp, "} def\n");
751 fprintf(fp, "systemdict /colorimage known not {\n");
752 fprintf(fp, " /colorimage {\n");
753 fprintf(fp, " pop\n");
754 fprintf(fp, " pop\n");
755 fprintf(fp, " /rgbproc exch def\n");
756 fprintf(fp, " { bwproc } image\n");
757 fprintf(fp, " } def\n");
758 fprintf(fp, "} if\n");
759 fprintf(fp, "/picstr %d string def\n", width * components);
760 fprintf(fp, "%d %d scale\n", width, height);
761 fprintf(fp, "%d %d %d\n", width, height, 8);
762 fprintf(fp, "[%d 0 0 %d 0 0]\n", width, height);
763 fprintf(fp, "{currentfile picstr readhexstring pop}\n");
764 fprintf(fp, "false %d\n", components);
765 fprintf(fp, "colorimage\n");
766 curpix = (unsigned char *) pixels;
767 pos = 0;
768 for (i = width * height * components; i > 0; i--) {
769 fprintf(fp, "%02hx", *curpix++);
770 if (++pos >= 32) {
771 fprintf(fp, "\n");
772 pos = 0;
773 }
774 }
775 if (pos) fprintf(fp, "\n");
776 fprintf(fp, "grestore\n");
777 fprintf(fp, "showpage\n");
778 free(pixels);
779 fclose(fp);
780 fprintf(stderr, "..done.\n");
781
782 /* return without error */
783 return;
784
785 /* return with error */
786 VERROR1:
787 fprintf(stderr, "Oglps_gen: problem occurred (bailing out).\n");
788 }
789
790 /*
791 * ***************************************************************************
792 * Private routines
793 * ***************************************************************************
794 */
795
796 /*
797 * ***************************************************************************
798 * Routine: yankPolys
799 *
800 * Purpose: Yank out all triangles and edges from OpenGL feedback buffer.
801 *
802 * Author: Michael Holst
803 * ***************************************************************************
804 */
805 VPRIVATE void yankPolys(void)
806 {
807 int i, j, bufPtr;
808 float objectType;
809 Color vc;
810 Poly pp;
811
812 Xmin = VLARGE;
813 Xmax = -VLARGE;
814 Ymin = VLARGE;
815 Ymax = -VLARGE;
816
817 bufPtr=0;
818 while (bufPtr < floatBufferNum) {
819
820 /* "doubling malloc" approach to growing triangle array dynamically */
821 while ( triaBufferMax <= triaBufferNum ) {
822 triaBufferMax *= 2;
823 triaBuffer = (Poly*)realloc(triaBuffer,triaBufferMax*sizeof(Poly));
824 VJMPERR1( triaBuffer != VNULL );
825 }
826
827 /* "doubling malloc" approach to growing edge array dynamically */
828 while ( edgeBufferMax <= edgeBufferNum ) {
829 edgeBufferMax *= 2;
830 edgeBuffer = (Poly*)realloc(edgeBuffer,edgeBufferMax*sizeof(Poly));
831 VJMPERR1( edgeBuffer != VNULL );
832 }
833
834 /* grab the object type as the first field */
835 objectType = floatBuffer[bufPtr++];
836
837 /* pull out all necessary floats to characterize the object */
838 if ( objectType == GL_POINT_TOKEN ||
839 objectType == GL_LINE_TOKEN ||
840 objectType == GL_LINE_RESET_TOKEN ||
841 objectType == GL_POLYGON_TOKEN ) {
842 if ( objectType == GL_POINT_TOKEN ) {
843 pp.nv = 1;
844 } else if ( objectType == GL_LINE_TOKEN ||
845 objectType == GL_LINE_RESET_TOKEN ) {
846 pp.nv = 2;
847 } else if ( objectType == GL_POLYGON_TOKEN ) {
848 pp.nv = (int)floatBuffer[bufPtr++];
849 } else { VJMPERR1(0); }
850
851 VJMPERR1( (1<=pp.nv) && (pp.nv<=VMAXPV) );
852
853 /* grab all vertex locations and colors for this object */
854 pp.c.r = 0.;
855 pp.c.g = 0.;
856 pp.c.b = 0.;
857 pp.c.a = 0.;
858 for (i=0; i<pp.nv; i++) {
859
860 /* grab the vertex */
861 pp.v[i].x = floatBuffer[bufPtr++];
862 pp.v[i].y = floatBuffer[bufPtr++];
863 pp.v[i].z = floatBuffer[bufPtr++];
864
865 /* grab the vertex color */
866 vc.r = floatBuffer[bufPtr++];
867 vc.g = floatBuffer[bufPtr++];
868 vc.b = floatBuffer[bufPtr++];
869 vc.a = floatBuffer[bufPtr++];
870
871 /* check color for correct rgb range */
872 if (!( (0.0-VSMALL <= vc.r) && (vc.r <= 1.0+VSMALL) ) ) {
873 fprintf(stderr,"yankPolys: "
874 "MacOSX OpenGL BUG (& Workaround) Triggered: "
875 "vc.r=<%17.5le>\n",(double)vc.r);
876 vc.r = 1.0;
877 }
878 if (!( (0.0-VSMALL <= vc.g) && (vc.g <= 1.0+VSMALL) ) ) {
879 fprintf(stderr,"yankPolys: "
880 "MacOSX OpenGL BUG (& Workaround) Triggered: "
881 "vc.g=<%17.5le>\n",(double)vc.g);
882 vc.g = 1.0;
883 }
884 if (!( (0.0-VSMALL <= vc.b) && (vc.b <= 1.0+VSMALL) ) ) {
885 fprintf(stderr,"yankPolys: "
886 "MacOSX OpenGL BUG (& Workaround) Triggered: "
887 "vc.b=<%17.5le>\n",(double)vc.b);
888 vc.b = 1.0;
889 }
890 if (!( (0.0-VSMALL <= vc.a) && (vc.a <= 1.0+VSMALL) ) ) {
891 fprintf(stderr,"yankPolys: "
892 "MacOSX OpenGL BUG (& Workaround) Triggered: "
893 "vc.a=<%17.5le>\n",(double)vc.a);
894 vc.a = 1.0;
895 }
896
897 /* accumlate vertex color into the total color for object */
898 pp.c.r += vc.r;
899 pp.c.g += vc.g;
900 pp.c.b += vc.b;
901 pp.c.a += vc.a;
902 }
903
904 /* object color is "centroid" of vertex colors in color space */
905 pp.c.r /= pp.nv;
906 pp.c.g /= pp.nv;
907 pp.c.b /= pp.nv;
908 pp.c.a /= pp.nv;
909
910 /* discard points */
911 if ( pp.nv == 1 ) {
912
913 /* do nothing */
914
915 /* save edges */
916 } else if ( pp.nv == 2 ) {
917
918 /* get edge centroid, xmin/xmax, ymin/ymax, zmin/zmax */
919 Poly_getMinMaxCentroid( &pp );
920
921 /* check vertex locations for box containment */
922 for (j=0; j<pp.nv; j++)
923 if ((VABS(pp.v[j].x) > VBOX) || (VABS(pp.v[j].y) > VBOX))
924 fprintf(stderr,"yankPolys: PROBLEM: "
925 "pp.x[%d]=<%g> pp.y[%d]=<%g>\n",
926 j, pp.v[j].x, j, pp.v[j].y);
927
928 /* save data to new edge buffer location */
929 edgeBuffer[edgeBufferNum] = pp;
930 edgeBufferNum++;
931
932 /* save triangles */
933 } else if ( pp.nv == 3 ) {
934
935 /* get triangle centroid, xmin/xmax, ymin/ymax, zmin/zmax */
936 Poly_getMinMaxCentroid( &pp );
937
938 /* check vertex locations for box containment */
939 for (j=0; j<pp.nv; j++)
940 if ((VABS(pp.v[j].x) > VBOX) || (VABS(pp.v[j].y) > VBOX))
941 fprintf(stderr,"yankPolys: PROBLEM: "
942 "pp.x[%d]=<%g> pp.y[%d]=<%g>\n",
943 j, pp.v[j].x, j, pp.v[j].y);
944
945 /* save data to new triangle buffer location */
946 triaBuffer[triaBufferNum] = pp;
947 triaBufferNum++;
948
949 /* discard polygons which are higher order than triangles */
950 } else {
951
952 fprintf(stderr,"yankPolys: "
953 "Polygon discarded (more than three sides): "
954 "pp.nv=<%d>\n",pp.nv);
955
956 }
957
958 } else { VJMPERR1(0); }
959 }
960
961 /* return without error */
962 return;
963
964 /* return with error */
965 VERROR1:
966 fprintf(stderr, "yankPolys: problem occurred (bailing out).\n");
967 }
968
969 /*
970 * ***************************************************************************
971 * Routine: roundX
972 *
973 * Purpose: Round a float to nearlest int
974 * (yeah, this really is not in math.h...)
975 *
976 * Author: Michael Holst
977 * ***************************************************************************
978 */
979 int roundX(float x)
980 {
981 return (int)floor( x + 0.5 );
982 }
983
984 /*
985 * ***************************************************************************
986 * Routine: sintc
987 *
988 * Purpose: Convert integer to a character string.
989 *
990 * Author: Randy Bank
991 * ***************************************************************************
992 */
993 void sintc(char list[], int *length, int ival)
994 {
995 int i, j, n, temp[10];
996
997 if (ival == 0) {
998 *length = 1;
999 list[0] = '0';
1000 list[1] = '\0';
1001 } else {
1002 *length = 0;
1003 n = abs(ival);
1004 while (n > 0) {
1005 j = n / 10;
1006 i = n - j * 10;
1007 (*length)++;
1008 temp[*length-1] = i+1;
1009 n=j;
1010 }
1011 if (ival < 0) {
1012 list[0] = '-';
1013 for (i=0; i<(*length); i++) {
1014 list[i+1] = digits[ temp[*length-i-1] - 1];
1015 }
1016 ++(*length);
1017 } else {
1018 for (i=0; i<(*length); i++) {
1019 list[i] = digits[ temp[*length-i-1] - 1];
1020 }
1021 }
1022 list[(*length)] = '\0';
1023 }
1024 return;
1025 }
1026
1027 /*
1028 * ***************************************************************************
1029 * Routine: rgb2cindx
1030 *
1031 * Purpose: Convert rgb values on [0,1] to a color index on [0,base**3-1]
1032 *
1033 * Author: Randy Bank
1034 * ***************************************************************************
1035 */
1036 void rgb2cindx(int *colorIndex, float red, float green, float blue)
1037 {
1038 int ired, igreen, iblue;
1039
1040 ired = roundX(red * (base-1));
1041 igreen = roundX(green * (base-1));
1042 iblue = roundX(blue * (base-1));
1043 (*colorIndex) = (ired*base + igreen)*base +iblue;
1044 }
1045
1046 /*
1047 * ***************************************************************************
1048 * Routine: cindx2rgb
1049 *
1050 * Purpose: Convert color index on [0,base**3-1] to rgb values on [0,1]
1051 *
1052 * Author: Randy Bank
1053 * ***************************************************************************
1054 */
1055 #if 0
1056 void cindx2rgb(float *red, float *green, float *blue, int colorIndex)
1057 {
1058 int ired, igreen, iblue, ii;
1059
1060 ii = colorIndex / base;
1061 iblue = colorIndex - base*ii;
1062 ired = ii / base;
1063 igreen = ii - base*ired;
1064
1065 (*red) = (float)ired / (float)(base-1);
1066 (*green) = (float)igreen / (float)(base-1);
1067 (*blue) = (float)iblue / (float)(base-1);
1068 }
1069 #endif
1070
1071 /*
1072 * ***************************************************************************
1073 * Routine: xcrossy
1074 *
1075 * Purpose: Cross-product of two 3-vectors.
1076 *
1077 * Author: Michael Holst
1078 * ***************************************************************************
1079 */
1080 VPRIVATE void xcrossy(double u[], double v[], double w[])
1081 {
1082 u[0] = v[1]*w[2] - v[2]*w[1];
1083 u[1] = v[2]*w[0] - v[0]*w[2];
1084 u[2] = v[0]*w[1] - v[1]*w[0];
1085 }
1086
1087 /*
1088 * ***************************************************************************
1089 * Routine: norm2
1090 *
1091 * Purpose: Take the 2-norm of an n-vector.
1092 *
1093 * Author: Michael Holst
1094 * ***************************************************************************
1095 */
1096 VPRIVATE double norm2(double u[], int n)
1097 {
1098 int i;
1099 double result = 0.0;
1100 for (i=0; i<n; i++) result += u[i]*u[i];
1101 return VSQRT( result );
1102 }
1103
1104 /*
1105 * ***************************************************************************
1106 * Routine: normalize
1107 *
1108 * Purpose: Normalize an n-vector.
1109 *
1110 * Author: Michael Holst
1111 * ***************************************************************************
1112 */
1113 VPRIVATE void normalize(double u[], int n)
1114 {
1115 int i;
1116 double nscale = norm2(u,n);
1117 if (nscale <= 0.0) {
1118 nscale = 1.0;
1119 fprintf(stderr,"normalize: cannot normalize a zero vector.\n");
1120 }
1121 for (i=0; i<n; i++) u[i] /= nscale;
1122 }
1123
1124 /*
1125 * ***************************************************************************
1126 * Routine: Poly_areaTriangle
1127 *
1128 * Purpose: Compute the (2-measure) area of a triangle.
1129 *
1130 * Author: Michael Holst
1131 * ***************************************************************************
1132 */
1133 VPRIVATE double Poly_areaTriangle(Poly *a)
1134 {
1135 double value = 0.0;
1136
1137 VASSERT( a->nv == 3 );
1138
1139 value = (a->v[1].x-a->v[0].x)*(a->v[2].y-a->v[0].y)
1140 - (a->v[2].x-a->v[0].x)*(a->v[1].y-a->v[0].y);
1141 return value;
1142 }
1143
1144 /*
1145 * ***************************************************************************
1146 * Routine: Poly_pointInTriangle
1147 *
1148 * Purpose: Determine whether or not a point is inside a given triangle.
1149 *
1150 * Author: Michael Holst
1151 * ***************************************************************************
1152 */
1153 VPRIVATE int Poly_pointInTriangle(Poly *a, double x, double y, double TOL)
1154 {
1155 Poly aa, t0, t1, t2;
1156
1157 VASSERT( a->nv == 3 );
1158
1159 /* we need to work with a counter-clockwise ordering here */
1160 Poly_copy( &aa, a );
1161 if (Poly_areaTriangle(&aa) < 0.0) Poly_swapVert0and1(&aa);
1162
1163 t0.nv = 3;
1164 t0.v[0].x = x; t0.v[0].y = y;
1165 t0.v[1].x = aa.v[0].x; t0.v[1].y = aa.v[0].y;
1166 t0.v[2].x = aa.v[1].x; t0.v[2].y = aa.v[1].y;
1167
1168 t1.nv = 3;
1169 t1.v[0].x = x; t1.v[0].y = y;
1170 t1.v[1].x = aa.v[1].x; t1.v[1].y = aa.v[1].y;
1171 t1.v[2].x = aa.v[2].x; t1.v[2].y = aa.v[2].y;
1172
1173 t2.nv = 3;
1174 t2.v[0].x = x; t2.v[0].y = y;
1175 t2.v[1].x = aa.v[2].x; t2.v[1].y = aa.v[2].y;
1176 t2.v[2].x = aa.v[0].x; t2.v[2].y = aa.v[0].y;
1177
1178 if ( (Poly_areaTriangle(&t0) >= -TOL)
1179 && (Poly_areaTriangle(&t1) >= -TOL)
1180 && (Poly_areaTriangle(&t2) >= -TOL) ) {
1181 return 1;
1182 } else {
1183 return 0;
1184 }
1185 }
1186
1187 /*
1188 * ***************************************************************************
1189 * Routine: Poly_overlapTriangles
1190 *
1191 * Purpose: Compute the exact overlap polygon of two input triangles and
1192 * also compute its baricenter.
1193 *
1194 * Author: Michael Holst
1195 * ***************************************************************************
1196 */
1197 VPRIVATE void Poly_overlapTriangles(Poly *a, Poly *b, Poly *c)
1198 {
1199 int j, k, kk, nn, nn2, found;
1200 Vert vt[15];
1201
1202 VASSERT( a->nv == 3 );
1203 VASSERT( b->nv == 3 );
1204
1205 if ( (a->xmax < b->xmin)
1206 || (a->xmin > b->xmax)
1207 || (a->ymax < b->ymin)
1208 || (a->ymin > b->ymax) ) {
1209 c->nv = 0;
1210 } else {
1211
1212 /* calc (up to) 9 intercepts of 3 lines of 1st guy and 3 lines of 2nd */
1213 Poly_getIntercepts(a, b, &nn, vt);
1214 if ( ! ((0 <= nn) && (nn <= 9)) )
1215 fprintf(stderr,"Poly_overlapTriangles: intercepts = <%d>\n", nn);
1216 VASSERT( (0 <= nn) && (nn <= 15) );
1217
1218 /* add vertices of each triangle to the overlap polygon vertex list */
1219 kk = 0;
1220 for (k=0; k<a->nv; k++) {
1221 if (Poly_pointInTriangle(b,a->v[k].x,a->v[k].y,VTINY)) {
1222 vt[nn+kk].x = a->v[k].x;
1223 vt[nn+kk].y = a->v[k].y;
1224 kk++;
1225 }
1226 }
1227 for (k=0; k<b->nv; k++) {
1228 if (Poly_pointInTriangle(a,b->v[k].x,b->v[k].y,VTINY)) {
1229 vt[nn+kk].x = b->v[k].x;
1230 vt[nn+kk].y = b->v[k].y;
1231 kk++;
1232 }
1233 }
1234 nn += kk;
1235 if ( ! ((0 <= nn) && (nn <= 15)) )
1236 fprintf(stderr,"Poly_overlapTriangles: intercepts = <%d>\n", nn);
1237 VASSERT( (0 <= nn) && (nn <= 15) );
1238
1239 /* remove any duplicate vertices */
1240 nn2 = 0;
1241 for (k=0; k<nn; k++) {
1242 found = 0;
1243 for (j=0; j<nn2; j++) {
1244 if ( (VABS(vt[k].x-c->v[j].x)<VTINY)
1245 && (VABS(vt[k].y-c->v[j].y)<VTINY) )
1246 found = 1;
1247 }
1248 if (!found) {
1249 c->v[nn2].x = vt[k].x;
1250 c->v[nn2].y = vt[k].y;
1251 c->v[nn2].z = 0.0;
1252 nn2++;
1253 VASSERT( nn2 <= VMAXPV );
1254 }
1255 }
1256 c->nv = nn2;
1257 VASSERT( (0 <= c->nv) && (c->nv <= VMAXPV) );
1258
1259 /* compute centroid of common overlap polygon (1-6 sided possible) */
1260 Poly_getMinMaxCentroid(c);
1261
1262 /* geom (exact arithmetic), can never get more than 6 vertices */
1263 if (c->nv > 6) {
1264 fprintf(stderr,"Poly_overlapTriangles: c->nv=<%d>\n",c->nv);
1265 Poly_matlabOut(a, b, VNULL, VNULL, c->nv, c->v, c->bc, "go.m");
1266 }
1267 #if 0
1268 Poly_matlabOut(a, b, VNULL, VNULL, c->nv, c->v, c->bc, "go.m");
1269 #endif
1270 }
1271 }
1272
1273 /*
1274 * ***************************************************************************
1275 * Routine: Poly_evalTriangleZ
1276 *
1277 * Purpose: Evaluate the z-coordinate of an arbitrary (x,y) location
1278 * in a triangle that has an arbitrary orientation in R^3.
1279 *
1280 * Author: Michael Holst
1281 * ***************************************************************************
1282 */
1283 VPRIVATE double Poly_evalTriangleZ(Poly *a, double x, double y)
1284 {
1285 double aa, bb, cc, x0, y0, z0, x1, y1, z1, v0[3], v1[3], norm[3];
1286
1287 VASSERT( a->nv == 3 );
1288
1289 /* first verify that point is in the triangle */
1290 VASSERT( Poly_pointInTriangle(a,x,y,10.0*VTINY) );
1291
1292 /* okay get the z-value */
1293 z1 = 0.0;
1294 v0[0] = a->v[1].x - a->v[0].x;
1295 v0[1] = a->v[1].y - a->v[0].y;
1296 v0[2] = a->v[1].z - a->v[0].z;
1297 v1[0] = a->v[2].x - a->v[0].x;
1298 v1[1] = a->v[2].y - a->v[0].y;
1299 v1[2] = a->v[2].z - a->v[0].z;
1300 xcrossy(norm,v0,v1);
1301 normalize(norm,3);
1302 aa = norm[0];
1303 bb = norm[1];
1304 cc = norm[2];
1305 x0 = a->v[0].x;
1306 y0 = a->v[0].y;
1307 z0 = a->v[0].z;
1308 x1 = x;
1309 y1 = y;
1310 if (VABS(cc) < VTINY) {
1311 z1 = z0;
1312 } else {
1313 z1 = z0 - (aa*(x1-x0) + bb*(y1-y0)) / cc;
1314 }
1315 return z1;
1316 }
1317
1318 /*
1319 * ***************************************************************************
1320 * Routine: Poly_compareTriangles
1321 *
1322 * Purpose: Compare two triangles for z-buffer depth buy computing their
1323 * exact overlap polygon and using the centroid of that overlap
1324 * polygon for comparing their z-buffer depths.
1325 *
1326 * Notes: For sets of non-intersecting triangles, this comparison function
1327 * unambigously determines front-back relationships among triangles.
1328 *
1329 * Author: Michael Holst
1330 * ***************************************************************************
1331 */
1332 VPRIVATE int Poly_compareTriangles(const void* A, const void* B)
1333 {
1334 Poly *a = (Poly*)A;
1335 Poly *b = (Poly*)B;
1336
1337 double aDepth, bDepth;
1338 Poly c;
1339
1340 VASSERT( a->nv == 3 );
1341 VASSERT( b->nv == 3 );
1342
1343 /* ***************************** */
1344 /* return 0: draw either first */
1345 /* return -1: draw A first */
1346 /* return 1: draw B first */
1347 /* ***************************** */
1348
1349 /* compute common overlap polygon */
1350 Poly_overlapTriangles(a, b, &c);
1351 VASSERT( (0 <= c.nv) && (c.nv <= VMAXPV) );
1352
1353 /* no overlap: just return a zero to allow for arbitrary ordering */
1354 if (c.nv == 0) {
1355
1356 /* evaluate z-value of triangles at separate baricenters */
1357 aDepth = a->bc[2];
1358 bDepth = b->bc[2];
1359
1360 /* overlap: calc z-value for each triangle at baricenter of common poly */
1361 } else { /* (c.nv > 0) */
1362
1363 /* evaluate z-value of triangles at baricenter of common overlap */
1364 aDepth = Poly_evalTriangleZ(a, c.bc[0], c.bc[1]);
1365 bDepth = Poly_evalTriangleZ(b, c.bc[0], c.bc[1]);
1366 }
1367
1368 if ( VABS(aDepth-bDepth) < VTINY ) {
1369 /* DO NOT make constraint; either can be drawn first! */
1370 /* (we use a "nearly zero" test to deal with roundoff) */
1371 return 0;
1372 } else if ( aDepth > bDepth ) {
1373 return -1;
1374 } else if ( aDepth < bDepth ) {
1375 return 1;
1376 } else {
1377 /* we can only get here if some NANs are generated... */
1378 VASSERT(0);
1379 }
1380
1381 return 0;
1382 }
1383
1384 /*
1385 * ***************************************************************************
1386 * Routine: Poly_compareMaxX
1387 *
1388 * Purpose: Compare two triangles for X-buffer depth based simply on their
1389 * minimum X-buffer values throughout each entire triangle.
1390 *
1391 * Author: Michael Holst
1392 * ***************************************************************************
1393 */
1394 VPRIVATE int Poly_compareMaxX(const void* A, const void* B)
1395 {
1396 Poly *a = (Poly*)A;
1397 Poly *b = (Poly*)B;
1398
1399 double aDepth, bDepth;
1400
1401 VASSERT( a->nv == 3 );
1402 VASSERT( b->nv == 3 );
1403
1404 /* ***************************** */
1405 /* return 0: draw either first */
1406 /* return -1: draw A first */
1407 /* return 1: draw B first */
1408 /* ***************************** */
1409
1410 /* evaluate maxx for each triangle */
1411 aDepth = a->xmax;
1412 bDepth = b->xmax;
1413
1414 if ( VABS(aDepth-bDepth) < VTINY ) {
1415 /* DO NOT make constraint; either can be drawn first! */
1416 /* (we use a "nearly zero" test to deal with roundoff) */
1417 return 0;
1418 } else if ( aDepth > bDepth ) {
1419 return -1;
1420 } else if ( aDepth < bDepth ) {
1421 return 1;
1422 } else {
1423 /* we can only get here if some NANs are generated... */
1424 VASSERT(0);
1425 }
1426
1427 return 0;
1428 }
1429
1430 /*
1431 * ***************************************************************************
1432 * Routine: Poly_compareMaxY
1433 *
1434 * Purpose: Compare two triangles for Y-buffer depth based simply on their
1435 * minimum Y-buffer values throughout each entire triangle.
1436 *
1437 * Author: Michael Holst
1438 * ***************************************************************************
1439 */
1440 VPRIVATE int Poly_compareMaxY(const void* A, const void* B)
1441 {
1442 Poly *a = (Poly*)A;
1443 Poly *b = (Poly*)B;
1444
1445 double aDepth, bDepth;
1446
1447 VASSERT( a->nv == 3 );
1448 VASSERT( b->nv == 3 );
1449
1450 /* ***************************** */
1451 /* return 0: draw either first */
1452 /* return -1: draw A first */
1453 /* return 1: draw B first */
1454 /* ***************************** */
1455
1456 /* evaluate maxy for each triangle */
1457 aDepth = a->ymax;
1458 bDepth = b->ymax;
1459
1460 if ( VABS(aDepth-bDepth) < VTINY ) {
1461 /* DO NOT make constraint; either can be drawn first! */
1462 /* (we use a "nearly zero" test to deal with roundoff) */
1463 return 0;
1464 } else if ( aDepth > bDepth ) {
1465 return -1;
1466 } else if ( aDepth < bDepth ) {
1467 return 1;
1468 } else {
1469 /* we can only get here if some NANs are generated... */
1470 VASSERT(0);
1471 }
1472
1473 return 0;
1474 }
1475
1476 /*
1477 * ***************************************************************************
1478 * Routine: Poly_compareMaxZ
1479 *
1480 * Purpose: Compare two triangles for z-buffer depth based simply on their
1481 * minimum Z-buffer values throughout each entire triangle.
1482 *
1483 * Author: Michael Holst
1484 * ***************************************************************************
1485 */
1486 VPRIVATE int Poly_compareMaxZ(const void* A, const void* B)
1487 {
1488 Poly *a = (Poly*)A;
1489 Poly *b = (Poly*)B;
1490
1491 double aDepth, bDepth;
1492
1493 VASSERT( a->nv == 3 );
1494 VASSERT( b->nv == 3 );
1495
1496 /* ***************************** */
1497 /* return 0: draw either first */
1498 /* return -1: draw A first */
1499 /* return 1: draw B first */
1500 /* ***************************** */
1501
1502 /* evaluate maxz for each triangle */
1503 aDepth = a->zmax;
1504 bDepth = b->zmax;
1505
1506 if ( VABS(aDepth-bDepth) < VTINY ) {
1507 /* DO NOT make constraint; either can be drawn first! */
1508 /* (we use a "nearly zero" test to deal with roundoff) */
1509 return 0;
1510 } else if ( aDepth > bDepth ) {
1511 return -1;
1512 } else if ( aDepth < bDepth ) {
1513 return 1;
1514 } else {
1515 /* we can only get here if some NANs are generated... */
1516 VASSERT(0);
1517 }
1518
1519 return 0;
1520 }
1521
1522 /*
1523 * ***************************************************************************
1524 * Routine: IntPoly_compareMaxX
1525 *
1526 * Purpose: Front-end to Poly_compareMaxX() for sorting integer arrays
1527 * of triangle numbers based on minimum X-buffer values.
1528 *
1529 * Author: Michael Holst
1530 * ***************************************************************************
1531 */
1532 VPRIVATE int IntPoly_compareMaxX(const void* A, const void* B)
1533 {
1534 Poly *a, *b;
1535 int AA = *((int*)A);
1536 int BB = *((int*)B);
1537 a = triaBuffer+xord[AA];
1538 b = triaBuffer+xord[BB];
1539 return Poly_compareMaxX(a, b);
1540 }
1541
1542 /*
1543 * ***************************************************************************
1544 * Routine: IntPoly_compareMaxY
1545 *
1546 * Purpose: Front-end to Poly_compareMaxY() for sorting integer arrays
1547 * of triangle numbers based on minimum Y-buffer values.
1548 *
1549 * Author: Michael Holst
1550 * ***************************************************************************
1551 */
1552 VPRIVATE int IntPoly_compareMaxY(const void* A, const void* B)
1553 {
1554 Poly *a, *b;
1555 int AA = *((int*)A);
1556 int BB = *((int*)B);
1557 a = triaBuffer+yord[AA];
1558 b = triaBuffer+yord[BB];
1559 return Poly_compareMaxY(a, b);
1560 }
1561
1562 /*
1563 * ***************************************************************************
1564 * Routine: IntPoly_compareMaxZ
1565 *
1566 * Purpose: Front-end to Poly_compareMaxZ() for sorting integer arrays
1567 * of triangle numbers based on minimum Z-buffer values.
1568 *
1569 * Author: Michael Holst
1570 * ***************************************************************************
1571 */
1572 VPRIVATE int IntPoly_compareMaxZ(const void* A, const void* B)
1573 {
1574 Poly *a, *b;
1575 int AA = *((int*)A);
1576 int BB = *((int*)B);
1577 a = triaBuffer+zord[AA];
1578 b = triaBuffer+zord[BB];
1579 return Poly_compareMaxZ(a, b);
1580 }
1581
1582 /*
1583 * ***************************************************************************
1584 * Routine: Poly_getIntercepts
1585 *
1586 * Purpose: Compute all overlap intercepts of the edges of two polygons.
1587 *
1588 * Author: Michael Holst
1589 * ***************************************************************************
1590 */
1591 VPRIVATE void Poly_getIntercepts(Poly *a, Poly *b, int *no, Vert vo[])
1592 {
1593 int i, j;
1594 double det, idet, t, s, x, y, x2, y2;
1595 double v0[2], v1[2], v2[2], v3[2], f[2], m[2][2], mi[2][2];
1596
1597 VASSERT( (0 <= a->nv) && (a->nv <= VMAXPV) );
1598 VASSERT( (0 <= b->nv) && (b->nv <= VMAXPV) );
1599
1600 *no = 0;
1601 for (i=0; i<a->nv; i++) {
1602 v0[0] = a->v[i].x;
1603 v0[1] = a->v[i].y;
1604 v1[0] = a->v[(i+1)%3].x;
1605 v1[1] = a->v[(i+1)%3].y;
1606
1607 for (j=0; j<b->nv; j++) {
1608 v2[0] = b->v[j].x;
1609 v2[1] = b->v[j].y;
1610 v3[0] = b->v[(j+1)%3].x;
1611 v3[1] = b->v[(j+1)%3].y;
1612
1613 f[0] = v2[0] - v0[0];
1614 f[1] = v2[1] - v0[1];
1615 m[0][0] = v1[0] - v0[0];
1616 m[1][0] = v1[1] - v0[1];
1617 m[0][1] = v2[0] - v3[0];
1618 m[1][1] = v2[1] - v3[1];
1619 det = m[0][0]*m[1][1] - m[0][1]*m[1][0];
1620
1621 /* if the two lines are not parallel */
1622 if (VABS(det) > VTINY) {
1623 idet = 1.0 / det;
1624 mi[0][0] = idet * m[1][1];
1625 mi[1][1] = idet * m[0][0];
1626 mi[0][1] = - idet * m[0][1];
1627 mi[1][0] = - idet * m[1][0];
1628 t = mi[0][0]*f[0] + mi[0][1]*f[1];
1629 s = mi[1][0]*f[0] + mi[1][1]*f[1];
1630
1631 /* if common intersection is contained in edges themselves */
1632 if ( (0.0 <= t) && (t <= 1.0) && (0.0 <= s) && (s <= 1.0) ) {
1633 x = v0[0] + t * (v1[0] - v0[0]);
1634 y = v0[1] + t * (v1[1] - v0[1]);
1635 x2 = v2[0] + s * (v3[0] - v2[0]);
1636 y2 = v2[1] + s * (v3[1] - v2[1]);
1637 if ( ! ((VABS(x-x2) < VTINY) && (VABS(y-y2) < VTINY)) )
1638 fprintf(stderr,"Poly_getIntercepts: variation: "
1639 "(x-x2,y-y2)=(%15.8e,%15.8e)\n",
1640 VABS(x-x2),VABS(y-y2));
1641
1642 /* paranoia; should be in triangle since s,t in [0,1] */
1643 #if 1
1644 vo[*no].x = x;
1645 vo[*no].y = y;
1646 (*no)++;
1647 #endif
1648 #if 0
1649 if ( Poly_pointInTriangle(a,x,y,VTINY)
1650 && Poly_pointInTriangle(b,x,y,VTINY) ) {
1651 vo[*no].x = x;
1652 vo[*no].y = y;
1653 (*no)++;
1654 }
1655 #endif
1656 }
1657 }
1658 }
1659 }
1660 }
1661
1662 /*
1663 * ***************************************************************************
1664 * Routine: Poly_findCentroid
1665 *
1666 * Purpose: Compute the centroid of a set of vertices.
1667 *
1668 * Author: Michael Holst
1669 * ***************************************************************************
1670 */
1671 VPRIVATE void Poly_findCentroid(Poly *a)
1672 {
1673 int k;
1674
1675 VASSERT( (0 <= a->nv) && (a->nv <= VMAXPV) );
1676
1677 for (k=0; k<3; k++) a->bc[k] = 0.0;
1678 for (k=0; k<a->nv; k++) {
1679 a->bc[0] += a->v[k].x;
1680 a->bc[1] += a->v[k].y;
1681 a->bc[2] += a->v[k].z;
1682 }
1683 for (k=0; k<3; k++) a->bc[k] /= a->nv;
1684 }
1685
1686 /*
1687 * ***************************************************************************
1688 * Routine: Poly_matlabOut
1689 *
1690 * Purpose: Output some polygons in a MATLAB-compatible form.
1691 *
1692 * Author: Michael Holst
1693 * ***************************************************************************
1694 */
1695 VPRIVATE void Poly_matlabOut(
1696 Poly *a, Poly *b, Poly *c, Poly *d,
1697 int no, Vert vo[], double obc[],
1698 char *fname)
1699 {
1700 int k;
1701 FILE *fp;
1702
1703 fp = fopen(fname, "a");
1704 fprintf(fp,"clf\n");
1705 fprintf(fp,"axis('equal');\n");
1706 fprintf(fp,"hold on\n");
1707 if (a != VNULL) {
1708 fprintf(fp,"%% Poly A\n");
1709 fprintf(fp,"A=[\n");
1710 for (k=0; k<a->nv; k++)
1711 fprintf(fp,"%15.8e %15.8e\n", a->v[k].x, a->v[k].y);
1712 fprintf(fp,"];\n");
1713 fprintf(fp,"xA = [ A(:,1) ; A(1,1) ];\n");
1714 fprintf(fp,"yA = [ A(:,2) ; A(1,2) ];\n");
1715 fprintf(fp,"plot(xA,yA,'g');\n");
1716 fprintf(fp,"plot(xA,yA,'og');\n");
1717 }
1718 if (b != VNULL) {
1719 fprintf(fp,"%% Poly B\n");
1720 fprintf(fp,"B=[\n");
1721 for (k=0; k<b->nv; k++)
1722 fprintf(fp,"%15.8e %15.8e\n", b->v[k].x, b->v[k].y);
1723 fprintf(fp,"];\n");
1724 fprintf(fp,"xB = [ B(:,1) ; B(1,1) ];\n");
1725 fprintf(fp,"yB = [ B(:,2) ; B(1,2) ];\n");
1726 fprintf(fp,"plot(xB,yB,'--r');\n");
1727 fprintf(fp,"plot(xB,yB,'or');\n");
1728 }
1729 if (c != VNULL) {
1730 fprintf(fp,"%% Poly C\n");
1731 fprintf(fp,"C=[\n");
1732 for (k=0; k<c->nv; k++)
1733 fprintf(fp,"%15.8e %15.8e\n", c->v[k].x, c->v[k].y);
1734 fprintf(fp,"];\n");
1735 fprintf(fp,"xC = [ C(:,1) ; C(1,1) ];\n");
1736 fprintf(fp,"yC = [ C(:,2) ; C(1,2) ];\n");
1737 fprintf(fp,"plot(xC,yC,'--b');\n");
1738 fprintf(fp,"plot(xC,yC,'ob');\n");
1739 }
1740 if (d != VNULL) {
1741 fprintf(fp,"%% Poly D\n");
1742 fprintf(fp,"D=[\n");
1743 for (k=0; k<d->nv; k++)
1744 fprintf(fp,"%15.8e %15.8e\n", d->v[k].x, d->v[k].y);
1745 fprintf(fp,"];\n");
1746 fprintf(fp,"xD = [ D(:,1) ; D(1,1) ];\n");
1747 fprintf(fp,"yD = [ D(:,2) ; D(1,2) ];\n");
1748 fprintf(fp,"plot(xD,yD,'--y');\n");
1749 fprintf(fp,"plot(xD,yD,'oy');\n");
1750 }
1751 if (no > 0) {
1752 fprintf(fp,"%% Overlap Polygon\n");
1753 fprintf(fp,"Q=[\n");
1754 for (k=0; k<no; k++)
1755 fprintf(fp,"%15.8e %15.8e\n", vo[k].x, vo[k].y);
1756 fprintf(fp,"];\n");
1757 fprintf(fp,"xQ = Q(:,1);\n");
1758 fprintf(fp,"yQ = Q(:,2);\n");
1759 fprintf(fp,"plot(xQ,yQ,'o');\n");
1760 }
1761 if (no > 0) {
1762 fprintf(fp,"%% Overlap Polygon Centroid\n");
1763 fprintf(fp,"P=[\n");
1764 fprintf(fp,"%15.8e %15.8e\n", obc[0], obc[1]);
1765 fprintf(fp,"];\n");
1766 fprintf(fp,"xP = P(1);\n");
1767 fprintf(fp,"yP = P(2);\n");
1768 fprintf(fp,"plot(xP,yP,'xr');\n");
1769 }
1770 fprintf(fp,"fprintf('..');\n");
1771 fprintf(fp,"pause\n");
1772 fclose(fp);
1773 }
1774
1775 /*
1776 * ***************************************************************************
1777 * Routine: Poly_swapVert0and1
1778 *
1779 * Purpose: Swap the first two vertices in a set of vertices.
1780 *
1781 * Author: Michael Holst
1782 * ***************************************************************************
1783 */
1784 VPRIVATE void Poly_swapVert0and1(Poly *a)
1785 {
1786 double tmp;
1787
1788 VASSERT( (0 <= a->nv) && (a->nv <= VMAXPV) );
1789
1790 tmp = a->v[0].x; a->v[0].x = a->v[1].x; a->v[1].x = tmp;
1791 tmp = a->v[0].y; a->v[0].y = a->v[1].y; a->v[1].y = tmp;
1792 tmp = a->v[0].z; a->v[0].z = a->v[1].z; a->v[1].z = tmp;
1793 }
1794
1795 /*
1796 * ***************************************************************************
1797 * Routine: Poly_getMinMaxCentroid
1798 *
1799 * Purpose: Calculate the min/max x/y/z coordinates of a polygon, and also
1800 * compute the centroid (baricenter) of the polygon.
1801 *
1802 * Author: Michael Holst
1803 * ***************************************************************************
1804 */
1805 VPRIVATE void Poly_getMinMaxCentroid(Poly *a)
1806 {
1807 int k;
1808
1809 VASSERT( (0 <= a->nv) && (a->nv <= VMAXPV) );
1810
1811 a->xmin = VLARGE;
1812 a->xmax = -VLARGE;
1813 a->ymin = VLARGE;
1814 a->ymax = -VLARGE;
1815 a->zmin = VLARGE;
1816 a->zmax = -VLARGE;
1817 for (k=0; k<a->nv; k++) {
1818 if (a->v[k].x < a->xmin) a->xmin = a->v[k].x;
1819 if (a->v[k].x > a->xmax) a->xmax = a->v[k].x;
1820 if (a->v[k].y < a->ymin) a->ymin = a->v[k].y;
1821 if (a->v[k].y > a->ymax) a->ymax = a->v[k].y;
1822 if (a->v[k].z < a->zmin) a->zmin = a->v[k].z;
1823 if (a->v[k].z > a->zmax) a->zmax = a->v[k].z;
1824 }
1825 if (a->xmin < Xmin) Xmin = a->xmin;
1826 if (a->xmax > Xmax) Xmax = a->xmax;
1827 if (a->ymin < Ymin) Ymin = a->ymin;
1828 if (a->ymax > Ymax) Ymax = a->ymax;
1829 if (a->zmin < Zmin) Zmin = a->zmin;
1830 if (a->zmax > Zmax) Zmax = a->zmax;
1831 Xmid = ( Xmax + Xmin ) / 2.;
1832 Ymid = ( Ymax + Ymin ) / 2.;
1833 XYscale = 1. / VMAX2( Xmax-Xmin, Ymax-Ymin );
1834
1835 Poly_findCentroid(a);
1836 }
1837
1838 /*
1839 * ***************************************************************************
1840 * Routine: Poly_copy
1841 *
1842 * Purpose: Copy the contents of one polygon into another polygon.
1843 *
1844 * Author: Michael Holst
1845 * ***************************************************************************
1846 */
1847 VPRIVATE void Poly_copy(Poly *a, Poly *b)
1848 {
1849 VASSERT( (0 <= b->nv) && (b->nv <= VMAXPV) );
1850 *a = *b;
1851 }
1852
1853 /*
1854 * ***************************************************************************
1855 * Routine: Poly_AblocksB
1856 *
1857 * Purpose: Record the fact that polygon A blocks polygon B.
1858 *
1859 * Notes: We place "B" on a list that "A" maintains of all guys that he is
1860 * blocking from being drawn as long as he is not drawn. We then
1861 * also increment a counter in B that keeps track of how many
1862 * guys are blocking it from being drawn.
1863 *
1864 * Author: Michael Holst
1865 * ***************************************************************************
1866 */
1867 VPRIVATE void Poly_AblocksB(Poly *a, Poly *b)
1868 {
1869 Bloc *curr, *mnew;
1870
1871 VASSERT( (0 <= a->nv) && (a->nv <= VMAXPV) );
1872 VASSERT( (0 <= b->nv) && (b->nv <= VMAXPV) );
1873
1874 mnew=VNULL;
1875 curr=a->blist;
1876
1877 if (curr == VNULL) {
1878 (b->bnum)++;
1879 curr = (Bloc*)calloc( 1, sizeof(Bloc) );
1880 curr->guy = b;
1881 curr->next = VNULL;
1882 a->blist = curr;
1883 return;
1884 } else {
1885 if ( curr->guy == b ) return;
1886 while (1) {
1887 if (curr->next == VNULL) {
1888 (b->bnum)++;
1889 mnew = (Bloc*)calloc( 1, sizeof(Bloc) );
1890 mnew->guy = b;
1891 mnew->next = VNULL;
1892 curr->next = mnew;
1893 return;
1894 } else {
1895 if ( curr->guy == b ) return;
1896 curr = curr->next;
1897 }
1898 }
1899 }
1900 }
1901
1902 /*
1903 * ***************************************************************************
1904 * Routine: Polys_removeBackTriangles
1905 *
1906 * Purpose: Remove all backfacing triangles from the set of triangles.
1907 *
1908 * Notes: This is useful for rendering tetrahedral meshes in which
1909 * all backfacing triangles are guaranteed to be buried by
1910 * front-facing triangles, and so can be safely culled.
1911 *
1912 * Author: Michael Holst
1913 * ***************************************************************************
1914 */
1915 VPRIVATE void Polys_removeBackTriangles(Poly *tri[], int *ntri)
1916 {
1917 int i, ii;
1918 Poly *pp;
1919
1920 /* input check */
1921 if (*ntri == 0) return;
1922 VASSERT( *ntri > 0 );
1923
1924 /* remove back-facing triangles */
1925 pp = (Poly*)calloc( (*ntri), sizeof(Poly) );
1926 ii = 0;
1927 for (i=0; i<(*ntri); i++) {
1928 if (Poly_areaTriangle( (*tri)+i ) > 0.0) {
1929 Poly_copy( pp+ii, (*tri)+i );
1930 ii++;
1931 }
1932 }
1933
1934 fprintf(stderr,
1935 "Polys_removeBackTriangles: removed <%d> of <%d> triangles,"
1936 " leaving <%d> triangles\n", ((*ntri)-ii), (*ntri), ii );
1937
1938 free(*tri);
1939 (*ntri) = ii;
1940 (*tri) = pp;
1941 }
1942
1943 /*
1944 * ***************************************************************************
1945 * Routine: Polys_buildConstraints
1946 *
1947 * Purpose: MODE1: Build all front-back constraints between all pairs of
1948 * polygons in set of polygons using exact polygon overlaps.
1949 *
1950 * MODE2: Build SOME front-back constraints between pairs of polygons
1951 * in a set of polygons using exact polygon overlaps.
1952 * We only build constraints for polygons which overlap in
1953 * their respective [zmin,zmax] windows.
1954 *
1955 * Notes: To keep the complexity costs down, we bisect the polygons
1956 * along an X- or Y- cutting plane and call ourselves recursively
1957 * on the bisection children. Once the polygon set is small
1958 * enough, we pair-wise compare all polygons in the set using
1959 * the centroid of their exact overlap polygon. This compare
1960 * cannot fail to build the constraints correctly if the polygons
1961 * are non-intersecting.
1962 *
1963 * Author: Michael Holst
1964 * ***************************************************************************
1965 */
1966 VPRIVATE void Polys_buildConstraints(
1967 Poly tri[], int ntri, int xo[], int yo[], int zo[], int nord)
1968 {
1969 int whichCut, lsize, rsize;
1970 int *xleft, *xright, *yleft, *yright, *zleft, *zright;
1971
1972 whichCut = Polys_testCut(tri, ntri, xo, yo, zo, nord, &lsize, &rsize);
1973 if ( (lsize*lsize + rsize*rsize) < nord*nord ) {
1974 xleft = (int*)calloc( lsize, sizeof(int) );
1975 xright = (int*)calloc( rsize, sizeof(int) );
1976 yleft = (int*)calloc( lsize, sizeof(int) );
1977 yright = (int*)calloc( rsize, sizeof(int) );
1978 zleft = (int*)calloc( lsize, sizeof(int) );
1979 zright = (int*)calloc( rsize, sizeof(int) );
1980 Polys_makeCut(tri, ntri, xo, yo, zo, nord, whichCut,
1981 lsize, rsize, xleft, xright, yleft, yright, zleft, zright);
1982 Polys_buildConstraints(tri, ntri, xleft, yleft, zleft, lsize);
1983 free(xleft);
1984 free(yleft);
1985 free(zleft);
1986 Polys_buildConstraints(tri, ntri, xright, yright, zright, rsize);
1987 free(xright);
1988 free(yright);
1989 free(zright);
1990 } else {
1991 Polys_boxConstraints(tri, ntri, zo, nord);
1992 }
1993 }
1994
1995 /*
1996 * ***************************************************************************
1997 * Routine: Polys_boxConstraints
1998 *
1999 * Purpose: MODE1: Build all front-back constraints between all pairs of
2000 * polygons in set of polygons using exact polygon overlaps.
2001 *
2002 * MODE2: Build SOME front-back constraints between pairs of polygons
2003 * in a set of polygons using exact polygon overlaps.
2004 * We only build constraints for polygons which overlap in
2005 * their respective [zmin,zmax] windows.
2006 *
2007 * Notes: To keep the complexity costs down, we bisect the polygons
2008 * along an X- or Y- cutting plane and call ourselves recursively
2009 * on the bisection children. Once the polygon set is small
2010 * enough, we pair-wise compare all polygons in the set using
2011 * the centroid of their exact overlap polygon. This compare
2012 * cannot fail to build the constraints correctly if the polygons
2013 * are non-intersecting.
2014 *
2015 * Author: Michael Holst
2016 * ***************************************************************************
2017 */
2018 VPRIVATE void Polys_boxConstraints(
2019 Poly tri[], int ntri, int guys[], int nguys)
2020 {
2021 int i, j;
2022 Poly *a, *b, c;
2023 double aDepth, bDepth;
2024
2025 fprintf(stderr,"Polys_boxConstraints: "
2026 "building constraints for <%d> polygons.\n", nguys);
2027
2028 /* build the constraints as efficiently as possible */
2029 for (i=0; i<nguys; i++) {
2030 a = tri+guys[i];
2031 if ( ! ((i+1)%1000) )
2032 fprintf(stderr,"Polys_boxConstraints: "
2033 "building constraint <%d>\n", i);
2034
2035 /* okay, do the pair-wise compares */
2036 for (j=i+1; j<nguys; j++) {
2037 b = tri+guys[j];
2038 Poly_overlapTriangles(a, b, &c);
2039 if (c.nv > 0) {
2040 /* evaluate z-value of triangles at the common point */
2041 aDepth = Poly_evalTriangleZ(a, c.bc[0], c.bc[1]);
2042 bDepth = Poly_evalTriangleZ(b, c.bc[0], c.bc[1]);
2043 if ( VABS(aDepth-bDepth) < VTINY ) {
2044 /* DO NOT make constraint; either can be drawn first! */
2045 /* (we use a "nearly zero" test to deal with roundoff) */
2046 } else if ( aDepth > bDepth ) {
2047 Poly_AblocksB(a,b);
2048 } else if ( aDepth < bDepth ) {
2049 Poly_AblocksB(b,a);
2050 } else {
2051 /* we can only get here if some NANs are generated... */
2052 VASSERT(0);
2053 }
2054 }
2055 }
2056 }
2057 }
2058
2059 /*
2060 * ***************************************************************************
2061 * Routine: Polys_paintOrdering
2062 *
2063 * Purpose: Find a feasible point in the feasible rendering region.
2064 *
2065 * Notes: We do this VERY quickly; see our paper...
2066 *
2067 * Authors: Michael Holst and Randy Bank
2068 * ***************************************************************************
2069 */
2070 VPRIVATE void Polys_paintOrdering(Poly tri[], int ntri,
2071 int xo[], int yo[], int zo[])
2072 {
2073 int i, j, ppPtr, curPtr, done;
2074 Poly *pp, *qq;
2075 Bloc *curr, *last;
2076
2077 fprintf(stderr,
2078 "Polys_paintOrdering: defining feasible region for <%d> polygons.\n",
2079 ntri);
2080
2081 /* input check */
2082 if (ntri == 0) return;
2083 VASSERT( ntri > 0 );
2084
2085 /* initialize the constraint count and list */
2086 /* tri->bnum == number of guys that must be ordered before polygon */
2087 /* tri->blist == list of guys that triangle blocks from being drawn */
2088 for (i=0; i<ntri; i++) {
2089 tri[i].bnum = 0;
2090 tri[i].blist = VNULL;
2091 tri[i].id = i;
2092 }
2093
2094 /* first build the constraint list */
2095 Polys_buildConstraints(tri, ntri, xo, yo, zo, ntri);
2096
2097 /* start traversing final list and resolv constraints */
2098 pp = (Poly*)calloc( ntri, sizeof(Poly) );
2099 ppPtr = 0;
2100 curPtr = 0;
2101 for (i=0; i<ntri; i++) {
2102 if ( ! (i%1000) )
2103 fprintf(stderr,"Polys_paintOrdering: resolving constraint <%d>\n",i);
2104
2105 if ( i >= ppPtr ) {
2106 j=curPtr;
2107 done=0;
2108 while (!done) {
2109 if (tri[j].bnum == 0) {
2110 tri[j].bnum = -1;
2111 Poly_copy( pp+ppPtr, tri+j );
2112 ppPtr++;
2113 curPtr = j+1;
2114 done=1;
2115 } else if (j==ntri-1) {
2116 fprintf(stderr,"Polys_paintOrdering: "
2117 "constraint resolution failed.\n");
2118 fprintf(stderr,"Polys_paintOrdering: the "
2119 "painter's algorithm WILL NOT work for this scene.\n");
2120 fprintf(stderr,"Polys_paintOrdering: "
2121 "reverting to quicksort.\n");
2122 qsort( triaBuffer, triaBufferNum, sizeof(Poly),
2123 Poly_compareTriangles );
2124 return;
2125 } else {
2126 j++;
2127 }
2128 }
2129 }
2130 VASSERT( ppPtr > i );
2131
2132 curr = pp[i].blist;
2133 while (curr != VNULL) {
2134 qq = curr->guy;
2135 VASSERT( qq != VNULL );
2136 VASSERT( qq->bnum > 0 );
2137 (qq->bnum)--;
2138 if ( ((qq->bnum) == 0) && (qq->id < curPtr)) {
2139 qq->bnum = -1;
2140 Poly_copy( pp+ppPtr, qq );
2141 ppPtr++;
2142 }
2143 last = curr;
2144 curr = curr->next;
2145 free(last);
2146 }
2147 }
2148
2149 /* copy the list back in the correct order */
2150 for (i=0; i<ntri; i++)
2151 Poly_copy( tri+i, pp+i );
2152 free(pp);
2153
2154 fprintf(stderr,"Polys_paintOrdering: "
2155 "constraint resolution succeeded.\n");
2156 fprintf(stderr,"Polys_paintOrdering: "
2157 "the painter's algorithm WILL work for this scene.\n");
2158 }
2159
2160 /*
2161 * ***************************************************************************
2162 * Routine: psgenHeader
2163 *
2164 * Purpose: Generate index of colors and a corresponding postscript header,
2165 * using psgenUtl.
2166 *
2167 * Author: Michael Holst
2168 * ***************************************************************************
2169 */
2170 void psgenHeader(void)
2171 {
2172 int i, blackIndex;
2173 Color col;
2174
2175 /* malloc the color space (only once!) */
2176 if ( !colorBufInit ) {
2177 colorBufInit = 1;
2178 colorBufI = (int*)calloc( colorBufMax, sizeof(int) );
2179 colorBufR = (float*)calloc( colorBufMax, sizeof(float) );
2180 colorBufG = (float*)calloc( colorBufMax, sizeof(float) );
2181 colorBufB = (float*)calloc( colorBufMax, sizeof(float) );
2182 }
2183 colorBufNum = colorBufMax;
2184 for (i=0; i<colorBufNum; i++) {
2185 colorBufI[i] = 0;
2186 colorBufR[i] = 0.;
2187 colorBufG[i] = 0.;
2188 colorBufB[i] = 0.;
2189 }
2190
2191 /* ALWAYS pub black on the index list of colors */
2192 rgb2cindx( &blackIndex, 0., 0., 0. );
2193 colorBufI[ blackIndex ] = 1;
2194 colorBufR[ blackIndex ] = 0.;
2195 colorBufG[ blackIndex ] = 0.;
2196 colorBufB[ blackIndex ] = 0.;
2197
2198 /* do the mapping to fill the color mapping arrays */
2199 for (i=0; i<triaBufferNum; i++) {
2200 if (triaBuffer[i].nv != 3) {
2201 fprintf(stderr, "psgenHeader: triaBuffer[%d].nv = <%d>\n",
2202 i, triaBuffer[i].nv);
2203 } else {
2204 col = triaBuffer[i].c;
2205 rgb2cindx( &(col.i), col.r, col.g, col.b );
2206 triaBuffer[i].c.i = col.i;
2207 colorBufI[ col.i ] = 1;
2208 colorBufR[ col.i ] = col.r;
2209 colorBufG[ col.i ] = col.g;
2210 colorBufB[ col.i ] = col.b;
2211 }
2212 }
2213
2214 psgenUtl(colorBufNum, colorBufR, colorBufG, colorBufB, colorBufI);
2215 }
2216
2217 /*
2218 * ***************************************************************************
2219 * Routine: psgenTrailer
2220 *
2221 * Purpose: Finish the postscript file with a showpage using psgenUtl.
2222 *
2223 * Author: Michael Holst
2224 * ***************************************************************************
2225 */
2226 void psgenTrailer(void)
2227 {
2228 psgenUtl(-1, colorBufR, colorBufG, colorBufB, colorBufI);
2229 }
2230
2231 /*
2232 * ***************************************************************************
2233 * Routine: psgenPaint
2234 *
2235 * Purpose: Write out each triangle in postscript.
2236 *
2237 * Author: Michael Holst
2238 * ***************************************************************************
2239 */
2240 VPRIVATE void psgenPaint(int outline)
2241 {
2242 int i;
2243 for (i=0; i<triaBufferNum; i++) {
2244 VJMPERR1( triaBuffer[i].nv == 3 );
2245 psgenPaintPoly( triaBuffer+i, outline );
2246 }
2247
2248 /* return without error */
2249 return;
2250
2251 /* return with error */
2252 VERROR1:
2253 fprintf(stderr, "psgenPaint: problem occurred (bailing out).\n");
2254 }
2255
2256 /*
2257 * ***************************************************************************
2258 * Routine: psgenPaintPoly
2259 *
2260 * Purpose: Write out a single triangle in postscript using psgenPath.
2261 *
2262 * Author: Michael Holst
2263 * ***************************************************************************
2264 */
2265 void psgenPaintPoly(Poly *p, int mode)
2266 {
2267 int i;
2268 float x[100], y[100];
2269
2270 /* put the polygon vertices in the arrays */
2271 for (i=0; i<p->nv; i++) {
2272 x[i] = (float)PXmap01( p->v[i].x );
2273 y[i] = (float)PYmap01( p->v[i].y );
2274 }
2275
2276 /* loop the first guy in again as the last guy to form a loop */
2277 i=p->nv;
2278 x[i] = (float)PXmap01( p->v[0].x );
2279 y[i] = (float)PYmap01( p->v[0].y );
2280
2281 /*
2282 * mode = [ 0 | 1 ] ==> fill
2283 * mode = [ 1 | 2 ] ==> outline
2284 * mode = 1 ==> both fill and outline
2285 */
2286 if ((mode==0) || (mode==1)) psgenPath(x, y, p->nv, p->c.i, 1);
2287 if ((mode==1) || (mode==2)) psgenPath(x, y, p->nv+1, 0, 0);
2288 }
2289
2290 /*
2291 * ***************************************************************************
2292 * Routine: psgenUtl
2293 *
2294 * Purpose: Generate PS file header for ncolors given as RGB floats in [0,1]
2295 *
2296 * Author: Converted from R. Bank's PLTMG by Michael Holst and Randy Bank
2297 * ***************************************************************************
2298 */
2299 void psgenUtl(int ncolor,
2300 float red[], float green[], float blue[], int cidx[])
2301 {
2302 int i, i0, i1, i2, ii, xmin, ymin, xmax, ymax, uniq;
2303 float si, width, sca;
2304
2305 /* pop out a showpage and return */
2306 if (ncolor <= 0) {
2307 fprintf(psFilePtr, "showpage\n");
2308 fclose(psFilePtr);
2309 psFilePtr = VNULL;
2310 return;
2311 }
2312
2313 /* the PS filename */
2314 ii = psFileNumber / 10;
2315 i0 = psFileNumber - ii * 10;
2316 i1 = ii - ii / 10 * 10;
2317 strcpy(psFileName, "fig00.ps");
2318 psFileName[3] = digits[i1];
2319 psFileName[4] = digits[i0];
2320 psFileNumber++;
2321
2322 /* header and macros to reduce PS file size */
2323 sca = (float)VMAX2(Xmax-Xmin,Ymax-Ymin);
2324 psFilePtr = fopen(psFileName,"w");
2325 fprintf(psFilePtr, "%%!PS-Adobe-3.0 EPSF-3.0\n");
2326 fprintf(psFilePtr, "%%%%Title: <%s>\n", psFileName);
2327 fprintf(psFilePtr, "%%%%Creator: Oglps"
2328 " (Rendering of an OpenGL Scene into PostScript)\n");
2329 fprintf(psFilePtr, "%%%%BoundingBox: %d %d %d %d\n",
2330 (int)PXmapPS(Xmin-PBox*sca),(int)PYmapPS(Ymin-PBox*sca),
2331 (int)PXmapPS(Xmax+PBox*sca),(int)PYmapPS(Ymax+PBox*sca));
2332 fprintf(psFilePtr, "[%d %d %d %d %d %d] concat\n",
2333 (int)(PSize), 0, 0, (int)(PSize), (int)(PXmin), (int)(PYmin));
2334 si = 1.f / scale;
2335 width = .01f / scale;
2336 fprintf(psFilePtr, "%8.6f %8.6f scale\n", si, si);
2337 fprintf(psFilePtr, "%10.8f setlinewidth\n", width);
2338 fprintf(psFilePtr, "2 setlinejoin\n");
2339 fprintf(psFilePtr, "/s {setrgbcolor newpath moveto} def\n");
2340 fprintf(psFilePtr, "/r {count 2 idiv {rlineto} repeat} def\n");
2341 fprintf(psFilePtr, "/f {s r closepath fill} def\n");
2342 fprintf(psFilePtr, "/g {s r stroke} def\n");
2343
2344 /* clipping hack: clips scene to a smaller box; fixes an OpenGL bug */
2345 xmin = (int)(PXmap01(Xmin) * scale);
2346 xmax = (int)(PXmap01(Xmax) * scale);
2347 ymin = (int)(PYmap01(Ymin) * scale);
2348 ymax = (int)(PYmap01(Ymax) * scale);
2349 fprintf(psFilePtr, "newpath\n");
2350 fprintf(psFilePtr, "%d %d moveto ", xmin+clipdist, ymin+clipdist);
2351 fprintf(psFilePtr, "%d %d lineto ", xmax-clipdist, ymin+clipdist);
2352 fprintf(psFilePtr, "%d %d lineto ", xmax-clipdist, ymax-clipdist);
2353 fprintf(psFilePtr, "%d %d lineto\n", xmin+clipdist, ymax-clipdist);
2354 fprintf(psFilePtr, "closepath clip\n");
2355
2356 /* color definitions */
2357 uniq = 0;
2358 for (i=0; i<ncolor; i++) {
2359 if (cidx[i] == 1) {
2360 uniq++;
2361 i2 = i / (base*base);
2362 i1 = (i-i2*base*base) / base;
2363 i0 = i - i1*base - i2*base*base;
2364 fprintf(psFilePtr, "/b%c%c%c {%4.2f %4.2f %4.2f g} def\n",
2365 digits[i2],digits[i1],digits[i0],red[i],green[i],blue[i]);
2366 fprintf(psFilePtr, "/c%c%c%c {%4.2f %4.2f %4.2f f} def\n",
2367 digits[i2],digits[i1],digits[i0],red[i],green[i],blue[i]);
2368 }
2369 }
2370 fprintf(stderr, "psgenUtl: found <%d> unique colors.\n", uniq);
2371 }
2372
2373 /*
2374 * ***************************************************************************
2375 * Routine: psgenPath
2376 *
2377 * Purpose: Render a single polygon into one line of the PS file.
2378 *
2379 * Author: Converted from R. Bank's PLTMG by Michael Holst and Randy Bank
2380 * ***************************************************************************
2381 */
2382 void psgenPath(float x[], float y[], int n, int icolor, int itype)
2383 {
2384 int lenx, leny, i, k, i0, i1, i2, ix, iy, length, npts;
2385 char buf[100];
2386
2387 /* print a path in compact int form; look for first nontrivial entry */
2388 length = 0;
2389 npts = 0;
2390 for (i=n-1; i>0; i--) {
2391 ix = roundX( (x[i]-x[i-1]) * scale );
2392 iy = roundX( (y[i]-y[i-1]) * scale );
2393 if ( (ix != 0) || (iy != 0) ) {
2394 sintc(buf+length, &lenx, ix);
2395 length += (lenx+1);
2396 buf[length-1] = ' ';
2397 sintc(buf+length, &leny, iy);
2398 length += (leny+1);
2399 npts = npts+1;
2400 buf[length-1] = ' ';
2401
2402 /* purge the buffer when we exceed bufferlength */
2403 if (length > 60) {
2404 for (k=0; k<length; k++)
2405 fprintf(psFilePtr,"%c",buf[k]);
2406 fprintf(psFilePtr,"\n");
2407 length = 0;
2408 }
2409 }
2410 }
2411 if (npts == 0) return;
2412
2413 /* the last entry */
2414 ix = roundX( x[0] * scale );
2415 iy = roundX( y[0] * scale );
2416 sintc(buf+length, &lenx, ix);
2417 length += (lenx+1);
2418 buf[length-1] = ' ';
2419 sintc(buf+length, &leny, iy);
2420 length += (leny+1);
2421 buf[length-1] = ' ';
2422
2423 /* set color, and line/fill */
2424 if (itype == 1) {
2425 buf[length] = 'c';
2426 } else {
2427 buf[length] = 'b';
2428 }
2429 i2 = icolor / (base*base);
2430 i1 = (icolor-i2*base*base) / base;
2431 i0 = icolor - i1*base - i2*base*base;
2432 buf[length+1] = digits[i2];
2433 buf[length+2] = digits[i1];
2434 buf[length+3] = digits[i0];
2435 length += 4;
2436
2437 /* finally, purge the buffer */
2438 for (k=0; k<length; k++)
2439 fprintf(psFilePtr,"%c",buf[k]);
2440 fprintf(psFilePtr,"\n");
2441 }
2442
2443 /*
2444 * ***************************************************************************
2445 * Routine: Polys_testCut
2446 *
2447 * Purpose: Find an orthogonal plane along which a bisection will split
2448 * a set of polygons nearly in half.
2449 *
2450 * Author: Michael Holst and Randy Bank
2451 * ***************************************************************************
2452 */
2453 VPRIVATE int Polys_testCut(Poly tri[], int ntri,
2454 int xo[], int yo[], int zo[], int nord,
2455 int *lsize, int *rsize)
2456 {
2457 int i, nhf, xlsize, xrsize, ylsize, yrsize, zlsize, zrsize;
2458 int xsize, ysize, zsize;
2459 double xcut, ycut, zcut;
2460 Poly *xp, *yp, *zp;
2461
2462 nhf = (int)(nord/2);
2463 xcut = tri[ xo[nhf] ].xmax;
2464 ycut = tri[ yo[nhf] ].ymax;
2465 zcut = tri[ zo[nhf] ].zmax;
2466
2467 xlsize = 0;
2468 ylsize = 0;
2469 zlsize = 0;
2470 xrsize = 0;
2471 yrsize = 0;
2472 zrsize = 0;
2473 for (i=0; i<nord; i++) {
2474 xp = tri+xo[i];
2475 yp = tri+yo[i];
2476 zp = tri+zo[i];
2477
2478 if (xp->xmax < xcut) {
2479 xlsize++;
2480 } else if (xp->xmin > xcut) {
2481 xrsize++;
2482 } else {
2483 xlsize++;
2484 xrsize++;
2485 }
2486 if (yp->ymax < ycut) {
2487 ylsize++;
2488 } else if (yp->ymin > ycut) {
2489 yrsize++;
2490 } else {
2491 ylsize++;
2492 yrsize++;
2493 }
2494 if (zp->zmax < zcut) {
2495 zlsize++;
2496 } else if (zp->zmin > zcut) {
2497 zrsize++;
2498 } else {
2499 zlsize++;
2500 zrsize++;
2501 }
2502 }
2503 xsize = VMAX2( VABS(xlsize-nhf), VABS(xrsize-nhf) );
2504 ysize = VMAX2( VABS(ylsize-nhf), VABS(yrsize-nhf) );
2505 zsize = VMAX2( VABS(zlsize-nhf), VABS(zrsize-nhf) );
2506
2507 if ( xsize < VMIN2(ysize,zsize) ) {
2508 *lsize = xlsize;
2509 *rsize = xrsize;
2510 return 0;
2511 } else if ( ysize < VMIN2(xsize,zsize) ) {
2512 *lsize = ylsize;
2513 *rsize = yrsize;
2514 return 1;
2515 } else {
2516 *lsize = zlsize;
2517 *rsize = zrsize;
2518 return 2;
2519 }
2520 }
2521
2522 /*
2523 * ***************************************************************************
2524 * Routine: Polys_makeCut
2525 *
2526 * Purpose: Make the orthogonal plane cuts.
2527 *
2528 * Author: Michael Holst and Randy Bank
2529 * ***************************************************************************
2530 */
2531 VPRIVATE void Polys_makeCut(Poly tri[], int ntri,
2532 int xo[], int yo[], int zo[], int nord,
2533 int whichCut, int nleft, int nright,
2534 int xleft[], int xright[],
2535 int yleft[], int yright[],
2536 int zleft[], int zright[])
2537 {
2538 int i, nhf, xlsize, xrsize, ylsize, yrsize, zlsize, zrsize;
2539 double cut, xpmax, xpmin, ypmax, ypmin, zpmax, zpmin;
2540 Poly *xp, *yp, *zp;
2541
2542 nhf = (int)(nord/2);
2543 if (whichCut == 0) {
2544 cut = tri[ xo[nhf] ].xmax;
2545 } else if (whichCut == 1) {
2546 cut = tri[ yo[nhf] ].ymax;
2547 } else if (whichCut == 2) {
2548 cut = tri[ zo[nhf] ].zmax;
2549 } else {
2550 cut = 0.0;
2551 VASSERT(0);
2552 }
2553
2554 xlsize = 0;
2555 ylsize = 0;
2556 zlsize = 0;
2557 xrsize = 0;
2558 yrsize = 0;
2559 zrsize = 0;
2560 for (i=0; i<nord; i++) {
2561 xp = tri+xo[i];
2562 yp = tri+yo[i];
2563 zp = tri+zo[i];
2564 if ( whichCut == 0 ) {
2565 xpmax = xp->xmax;
2566 xpmin = xp->xmin;
2567 ypmax = yp->xmax;
2568 ypmin = yp->xmin;
2569 zpmax = zp->xmax;
2570 zpmin = zp->xmin;
2571 } else if ( whichCut == 1 ) {
2572 xpmax = xp->ymax;
2573 xpmin = xp->ymin;
2574 ypmax = yp->ymax;
2575 ypmin = yp->ymin;
2576 zpmax = zp->ymax;
2577 zpmin = zp->ymin;
2578 } else {
2579 xpmax = xp->zmax;
2580 xpmin = xp->zmin;
2581 ypmax = yp->zmax;
2582 ypmin = yp->zmin;
2583 zpmax = zp->zmax;
2584 zpmin = zp->zmin;
2585 }
2586
2587 if (xpmax < cut) {
2588 xleft[xlsize] = xo[i];
2589 xlsize++;
2590 } else if (xpmin > cut) {
2591 xright[xrsize] = xo[i];
2592 xrsize++;
2593 } else {
2594 xleft[xlsize] = xo[i];
2595 xright[xrsize] = xo[i];
2596 xlsize++;
2597 xrsize++;
2598 }
2599
2600 if (ypmax < cut) {
2601 yleft[ylsize] = yo[i];
2602 ylsize++;
2603 } else if (ypmin > cut) {
2604 yright[yrsize] = yo[i];
2605 yrsize++;
2606 } else {
2607 yleft[ylsize] = yo[i];
2608 yright[yrsize] = yo[i];
2609 ylsize++;
2610 yrsize++;
2611 }
2612 if (zpmax < cut) {
2613 zleft[zlsize] = zo[i];
2614 zlsize++;
2615 } else if (zpmin > cut) {
2616 zright[zrsize] = zo[i];
2617 zrsize++;
2618 } else {
2619 zleft[zlsize] = zo[i];
2620 zright[zrsize] = zo[i];
2621 zlsize++;
2622 zrsize++;
2623 }
2624 }
2625
2626 VASSERT( (xlsize == nleft) && (xrsize == nright) );
2627 }
2628