summaryrefslogtreecommitdiffstats
path: root/progs/demos/isosurf.c
blob: 29550c465d292e7f434e502a5c480af0f322dc88 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
/* $Id: isosurf.c,v 1.3 1999/09/08 22:14:31 brianp Exp $ */

/*
 * Display an isosurface of 3-D wind speed volume.  
 *
 * Brian Paul  This file in public domain.
 */


/* Keys:
 * =====
 *
 *   - Arrow keys to rotate
 *   - 's' toggles smooth shading
 *   - 'l' toggles lighting
 *   - 'f' toggles fog
 *   - 'I' and 'i' zoom in and out
 *   - 'c' toggles a user clip plane
 *   - 'm' toggles colorful materials in GL_TRIANGLES modes.
 *   - '+' and '-' move the user clip plane
 *
 * Other options are available via the popup menu.
 */

/*
 * $Log: isosurf.c,v $
 * Revision 1.3  1999/09/08 22:14:31  brianp
 * minor changes. always call compactify_arrays()
 *
 * Revision 1.2  1999/09/03 14:56:40  keithw
 * Fog, displaylist and zoom operations
 *
 * Revision 3.4  1999/04/24 01:10:47  keithw
 * clip planes, materials
 *
 * Revision 3.3  1999/03/31 19:42:14  keithw
 * support for cva
 *
 * Revision 3.1  1998/11/01 20:30:20  brianp
 * added benchmark feature (b key)
 *
 * Revision 3.0  1998/02/14 18:42:29  brianp
 * initial rev
 *
 */



#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "GL/glut.h"

#include "../util/readtex.c"   /* I know, this is a hack.  KW: me too. */
#define TEXTURE_FILE "../images/reflect.rgb"

#define LIT                 0x1
#define UNLIT               0x2
#define TEXTURE             0x4
#define NO_TEXTURE          0x8
#define REFLECT             0x10
#define NO_REFLECT          0x20
#define POINT_FILTER        0x40
#define LINEAR_FILTER       0x80
#define GLVERTEX           0x100
#define DRAW_ARRAYS         0x200 /* or draw_elts, if compiled */
#define ARRAY_ELT           0x400
#define COMPILED            0x800
#define IMMEDIATE           0x1000
#define SHADE_SMOOTH        0x2000
#define SHADE_FLAT          0x4000
#define TRIANGLES           0x8000
#define STRIPS              0x10000
#define USER_CLIP           0x20000
#define NO_USER_CLIP        0x40000
#define MATERIALS           0x80000
#define NO_MATERIALS        0x100000
#define FOG                 0x200000
#define NO_FOG              0x400000
#define QUIT                0x800000
#define DISPLAYLIST         0x1000000

#define LIGHT_MASK  (LIT|UNLIT)
#define TEXTURE_MASK (TEXTURE|NO_TEXTURE)
#define REFLECT_MASK (REFLECT|NO_REFLECT)
#define FILTER_MASK (POINT_FILTER|LINEAR_FILTER)
#define RENDER_STYLE_MASK (GLVERTEX|DRAW_ARRAYS|ARRAY_ELT)
#define COMPILED_MASK (COMPILED|IMMEDIATE|DISPLAYLIST)
#define MATERIAL_MASK (MATERIALS|NO_MATERIALS)
#define PRIMITIVE_MASK (TRIANGLES|STRIPS)
#define CLIP_MASK (USER_CLIP|NO_USER_CLIP)
#define SHADE_MASK (SHADE_SMOOTH|SHADE_FLAT)
#define FOG_MASK (FOG|NO_FOG)

#define MAXVERTS 10000
static float data[MAXVERTS][6];
static float compressed_data[MAXVERTS][6];
static GLuint indices[MAXVERTS];
static GLuint tri_indices[MAXVERTS*3];
static GLfloat col[100][4];
static GLint numverts, num_tri_verts, numuniq;

static GLfloat xrot;
static GLfloat yrot;
static GLfloat dist = -6;
static GLint state, allowed = ~0;
static GLboolean doubleBuffer = GL_TRUE;
static GLdouble plane[4] = {1.0, 0.0, -1.0, 0.0};
static GLuint surf1;

/* forward decl */
int BuildList( int mode );


static void read_surface( char *filename )
{
   FILE *f;

   f = fopen(filename,"r");
   if (!f) {
      printf("couldn't read %s\n", filename);
      exit(1);
   }

   numverts = 0;
   while (!feof(f) && numverts<MAXVERTS) {
      fscanf( f, "%f %f %f  %f %f %f",
	      &data[numverts][0], &data[numverts][1], &data[numverts][2],
	      &data[numverts][3], &data[numverts][4], &data[numverts][5] );
      numverts++;
   }
   numverts--;

   printf("%d vertices, %d triangles\n", numverts, numverts-2);
   fclose(f);
}




struct data_idx {
   float *data;
   int idx;
   int uniq_idx;
};


#define COMPARE_FUNC( AXIS )                            \
int compare_axis_##AXIS( const void *a, const void *b )	\
{							\
   float t = ( (*(struct data_idx *)a).data[AXIS] -	\
	       (*(struct data_idx *)b).data[AXIS] );	\
   							\
   if (t < 0) return -1;				\
   if (t > 0) return 1;					\
   return 0;						\
}

COMPARE_FUNC(0)
COMPARE_FUNC(1)
COMPARE_FUNC(2)
COMPARE_FUNC(3)
COMPARE_FUNC(4)
COMPARE_FUNC(5)
COMPARE_FUNC(6)

int (*(compare[7]))( const void *a, const void *b ) =
{
   compare_axis_0,
   compare_axis_1,
   compare_axis_2,
   compare_axis_3,
   compare_axis_4,
   compare_axis_5,
   compare_axis_6,
};


#define VEC_ELT(f, s, i)  (float *)(((char *)f) + s * i)

static int sort_axis( int axis, 
		      int vec_size,
		      int vec_stride,
		      struct data_idx *indices,
		      int start,
		      int finish,
		      float *out,
		      int uniq,
		      const float fudge )
{
   int i;

   if (finish-start > 2) 
   {
      qsort( indices+start, finish-start, sizeof(*indices), compare[axis] );
   } 
   else if (indices[start].data[axis] > indices[start+1].data[axis]) 
   {
      struct data_idx tmp = indices[start];
      indices[start] = indices[start+1];
      indices[start+1] = tmp;
   }
	 
   if (axis == vec_size-1) {
      for (i = start ; i < finish ; ) {
	 float max = indices[i].data[axis] + fudge;
	 float *dest = VEC_ELT(out, vec_stride, uniq);
	 int j;
	
	 for (j = 0 ; j < vec_size ; j++)
	    dest[j] = indices[i].data[j];

	 for ( ; i < finish && max >= indices[i].data[axis]; i++) 
	    indices[i].uniq_idx = uniq;

	 uniq++;
      }
   } else {
      for (i = start ; i < finish ; ) {
	 int j = i + 1;
	 float max = indices[i].data[axis] + fudge;
	 while (j < finish && max >= indices[j].data[axis]) j++;
	 if (j == i+1) {
	    float *dest = VEC_ELT(out, vec_stride, uniq);
	    int k;

	    indices[i].uniq_idx = uniq;
	
	    for (k = 0 ; k < vec_size ; k++)
	       dest[k] = indices[i].data[k];

	    uniq++;
	 } else {
	    uniq = sort_axis( axis+1, vec_size, vec_stride,
			      indices, i, j, out, uniq, fudge );
	 }
	 i = j;
      }
   }

   return uniq;
}


static void extract_indices1( const struct data_idx *in, unsigned int *out, 
			      int n )
{
   int i;
   for ( i = 0 ; i < n ; i++ ) {
      out[in[i].idx] = in[i].uniq_idx;
   }
}


static void compactify_arrays(void)
{
   int i;
   struct data_idx *ind;

   ind = (struct data_idx *) malloc( sizeof(struct data_idx) * numverts );

   for (i = 0 ; i < numverts ; i++) {
      ind[i].idx = i;
      ind[i].data = data[i];
   }

   numuniq = sort_axis(0, 
		       sizeof(compressed_data[0])/sizeof(float), 
		       sizeof(compressed_data[0]),
		       ind, 
		       0, 
		       numverts, 
		       (float *)compressed_data, 
		       0,
		       1e-6);

   printf("Nr unique vertex/normal pairs: %d\n", numuniq);

   extract_indices1( ind, indices, numverts );
   free( ind );
}

static float myrand( float max )
{
   return max*rand()/(RAND_MAX+1.0);
}


static void make_tri_indices( void )
{
   unsigned int *v = tri_indices;
   unsigned int parity = 0;
   unsigned int i, j;

   for (j=2;j<numverts;j++,parity^=1) {
      if (parity) {
	 *v++ = indices[j-1];
	 *v++ = indices[j-2]; 
	 *v++ = indices[j];
      } else {
	 *v++ = indices[j-2];
	 *v++ = indices[j-1];
	 *v++ = indices[j];
      }
   }
   
   num_tri_verts = v - tri_indices;
   printf("num_tri_verts: %d\n", num_tri_verts);

   for (i = j = 0 ; i < num_tri_verts ; i += 600, j++) {
      col[j][3] = 1;
      col[j][2] = myrand(1);
      col[j][1] = myrand(1);
      col[j][0] = myrand(1);
   }
}

#define MIN(x,y) (x < y) ? x : y

static void draw_surface( int with_state )
{
   GLuint i, j;

   switch (with_state & (COMPILED_MASK|RENDER_STYLE_MASK|PRIMITIVE_MASK)) {
#ifdef GL_EXT_vertex_array

   case (COMPILED|DRAW_ARRAYS|STRIPS):
      glDrawElements( GL_TRIANGLE_STRIP, numverts, GL_UNSIGNED_INT, indices );
      break;


   case (COMPILED|ARRAY_ELT|STRIPS):
      glBegin( GL_TRIANGLE_STRIP );
      for (i = 0 ; i < numverts ; i++) 
	 glArrayElement( indices[i] );      
      glEnd();
      break;

   case (COMPILED|DRAW_ARRAYS|TRIANGLES):
   case (IMMEDIATE|DRAW_ARRAYS|TRIANGLES):
      if (with_state & MATERIALS) {
	 for (j = i = 0 ; i < num_tri_verts ; i += 600, j++) {
	    GLuint nr = MIN(num_tri_verts-i, 600);
	    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, col[j]);
	    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, col[j]);
	    glDrawElements( GL_TRIANGLES, nr, GL_UNSIGNED_INT, tri_indices+i );
	 }
      } else {
	 glDrawElements( GL_TRIANGLES, num_tri_verts, GL_UNSIGNED_INT, 
			 tri_indices );
      }

      break;

      /* Uses the original arrays (including duplicate elements):
       */
   case (IMMEDIATE|DRAW_ARRAYS|STRIPS):
      glDrawArraysEXT( GL_TRIANGLE_STRIP, 0, numverts );
      break;

      /* Uses the original arrays (including duplicate elements):
       */
   case (IMMEDIATE|ARRAY_ELT|STRIPS):
      glBegin( GL_TRIANGLE_STRIP );
      for (i = 0 ; i < numverts ; i++)
	 glArrayElement( i );
      glEnd();
      break;

   case (IMMEDIATE|ARRAY_ELT|TRIANGLES):
   case (COMPILED|ARRAY_ELT|TRIANGLES):
      if (with_state & MATERIALS) {
	 for (j = i = 0 ; i < num_tri_verts ; i += 600, j++) {
	    GLuint nr = MIN(num_tri_verts-i, 600);
	    GLuint k;
	    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, col[j]);
	    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, col[j]);
	    glBegin( GL_TRIANGLES );
	    for (k = 0 ; k < nr ; k++)
	       glArrayElement( tri_indices[i+k] );
	    glEnd();
	 }
      } else {
	 glBegin( GL_TRIANGLES );
	 for (i = 0 ; i < num_tri_verts ; i++)
	    glArrayElement( tri_indices[i] );
	       
	 glEnd();
      }	 
      break;

   case (IMMEDIATE|GLVERTEX|TRIANGLES):
      if (with_state & MATERIALS) {
	 for (j = i = 0 ; i < num_tri_verts ; i += 600, j++) {
	    GLuint nr = MIN(num_tri_verts-i, 600);
	    GLuint k;
	    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, col[j]);
	    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, col[j]);
	    glBegin( GL_TRIANGLES );
	    for (k = 0 ; k < nr ; k++) {
	       glNormal3fv( &compressed_data[tri_indices[i+k]][3] );
	       glVertex3fv( &compressed_data[tri_indices[i+k]][0] );
	    }
	    glEnd();
	 }
      } else {
	 glBegin( GL_TRIANGLES );
	 for (i = 0 ; i < num_tri_verts ; i++) {
	    glNormal3fv( &compressed_data[tri_indices[i]][3] );
	    glVertex3fv( &compressed_data[tri_indices[i]][0] );
	 }
	 glEnd();
      }	 
      break;

   case (DISPLAYLIST|GLVERTEX|STRIPS):
      if (!surf1)
	 surf1 = BuildList( GL_COMPILE_AND_EXECUTE );
      else
	 glCallList(surf1);
      break;

#endif

      /* Uses the original arrays (including duplicate elements):
       */
   default:
      glBegin( GL_TRIANGLE_STRIP );
      for (i=0;i<numverts;i++) {
         glNormal3fv( &data[i][3] );
         glVertex3fv( &data[i][0] );
      }
      glEnd();
   }
}



static void Display(void)
{
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
    draw_surface( state );
    glFlush();
    if (doubleBuffer) glutSwapBuffers();    
}

int BuildList( int mode )
{
   int rv = glGenLists(1);
   glNewList(rv, mode );
   draw_surface( IMMEDIATE|GLVERTEX|STRIPS );
   glEndList();
   return rv;
}

/* KW: only do this when necessary, so CVA can re-use results.
 */
static void set_matrix( void )
{
   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glTranslatef( 0.0, 0.0, dist );
   glRotatef( yrot, 0.0, 1.0, 0.0 );
   glRotatef( xrot, 1.0, 0.0, 0.0 );
}

static void Benchmark( float xdiff, float ydiff )
{
   int startTime, endTime;
   int draws;
   double seconds, fps, triPerSecond;

   printf("Benchmarking...\n");

   draws = 0;
   startTime = glutGet(GLUT_ELAPSED_TIME);
   xrot = 0.0;
   do {
      xrot += xdiff;
      yrot += ydiff;
      set_matrix();
      Display();
      draws++;
      endTime = glutGet(GLUT_ELAPSED_TIME);
   } while (endTime - startTime < 5000);   /* 5 seconds */

   /* Results */
   seconds = (double) (endTime - startTime) / 1000.0;
   triPerSecond = (numverts - 2) * draws / seconds;
   fps = draws / seconds;
   printf("Result:  triangles/sec: %g  fps: %g\n", triPerSecond, fps);
}


static void InitMaterials(void)
{
    static float ambient[] = {0.1, 0.1, 0.1, 1.0};
    static float diffuse[] = {0.5, 1.0, 1.0, 1.0};
    static float position0[] = {0.0, 0.0, 20.0, 0.0};
    static float position1[] = {0.0, 0.0, -20.0, 0.0};
    static float front_mat_shininess[] = {60.0};
    static float front_mat_specular[] = {0.2, 0.2, 0.2, 1.0};
    static float front_mat_diffuse[] = {0.5, 0.28, 0.38, 1.0};
    /*
    static float back_mat_shininess[] = {60.0};
    static float back_mat_specular[] = {0.5, 0.5, 0.2, 1.0};
    static float back_mat_diffuse[] = {1.0, 1.0, 0.2, 1.0};
    */
    static float lmodel_ambient[] = {1.0, 1.0, 1.0, 1.0};
    static float lmodel_twoside[] = {GL_FALSE};

    glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
    glLightfv(GL_LIGHT0, GL_POSITION, position0);
    glEnable(GL_LIGHT0);
    
    glLightfv(GL_LIGHT1, GL_AMBIENT, ambient);
    glLightfv(GL_LIGHT1, GL_DIFFUSE, diffuse);
    glLightfv(GL_LIGHT1, GL_POSITION, position1);
    glEnable(GL_LIGHT1);
    
    glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient);
    glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside);

    glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, front_mat_shininess);
    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, front_mat_specular);
    glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, front_mat_diffuse);
}



#define UPDATE(o,n,mask) (o&=~mask, o|=n&mask)
#define CHANGED(o,n,mask) ((n&mask) && \
                           (n&mask) != (o&mask) ? UPDATE(o,n,mask) : 0)

static void ModeMenu(int m)
{
   m &= allowed;

   if (!m) return;

   if (m==QUIT) 
      exit(0);

   if (CHANGED(state, m, FILTER_MASK)) {
      if (m & LINEAR_FILTER) {
	 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      } else {
	 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
	 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
      }
   }

   if (CHANGED(state, m, LIGHT_MASK)) {
      if (m & LIT)
	 glEnable(GL_LIGHTING);
      else
	 glDisable(GL_LIGHTING);
   }

   if (CHANGED(state, m, SHADE_MASK)) {
      if (m & SHADE_SMOOTH)
	 glShadeModel(GL_SMOOTH);
      else
	 glShadeModel(GL_FLAT);
   }


   if (CHANGED(state, m, TEXTURE_MASK)) {
      if (m & TEXTURE) 
	 glEnable(GL_TEXTURE_2D);
      else
	 glDisable(GL_TEXTURE_2D);
   }

   if (CHANGED(state, m, REFLECT_MASK)) {
      if (m & REFLECT) {
	 glEnable(GL_TEXTURE_GEN_S);
	 glEnable(GL_TEXTURE_GEN_T);
      } else {
	 glDisable(GL_TEXTURE_GEN_S);
	 glDisable(GL_TEXTURE_GEN_T);
      }
   }

   if (CHANGED(state, m, CLIP_MASK)) {
      if (m & USER_CLIP) {
	 glEnable(GL_CLIP_PLANE0);
      } else {
	 glDisable(GL_CLIP_PLANE0);
      }
   }

   if (CHANGED(state, m, FOG_MASK)) {
      if (m & FOG) 
      {
	 glEnable(GL_FOG);
	 printf("FOG enable\n");
      } 
      else 
      {
	 glDisable(GL_FOG);
	 printf("FOG disable\n");
      }
   }

#ifdef GL_EXT_vertex_array
   if (CHANGED(state, m, (COMPILED_MASK|RENDER_STYLE_MASK|PRIMITIVE_MASK))) 
   {
      if ((m & (COMPILED_MASK|PRIMITIVE_MASK)) == (IMMEDIATE|STRIPS))
      {
	 glVertexPointerEXT( 3, GL_FLOAT, sizeof(data[0]), numverts, data );
	 glNormalPointerEXT( GL_FLOAT, sizeof(data[0]), numverts, &data[0][3]);
      }
      else 
      {
	 glVertexPointerEXT( 3, GL_FLOAT, sizeof(data[0]), numuniq, 
			     compressed_data );
	 glNormalPointerEXT( GL_FLOAT, sizeof(data[0]), numuniq, 
			     &compressed_data[0][3]);
      }
#ifdef GL_EXT_compiled_vertex_array
      if (m & COMPILED) {
	 glLockArraysEXT( 0, numuniq );
      } else {
	 glUnlockArraysEXT();
      }
#endif
   }
#endif

   if (m & (RENDER_STYLE_MASK|PRIMITIVE_MASK)) {
      UPDATE(state, m, (RENDER_STYLE_MASK|PRIMITIVE_MASK));
   }
   
   if (m & MATERIAL_MASK) {
      UPDATE(state, m, MATERIAL_MASK);
   }

   glutPostRedisplay();
}



static void Init(void)
{
   GLfloat fogColor[4] = {0.5,1.0,0.5,1.0};

   glClearColor(0.0, 0.0, 0.0, 0.0);
   glEnable( GL_DEPTH_TEST );
   glEnable( GL_VERTEX_ARRAY_EXT );
   glEnable( GL_NORMAL_ARRAY_EXT );

   InitMaterials();

   glMatrixMode(GL_PROJECTION);
   glLoadIdentity();
   glFrustum( -1.0, 1.0, -1.0, 1.0, 5, 25 );

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();
   glClipPlane(GL_CLIP_PLANE0, plane); 

   set_matrix();

   glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
   glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);

   glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
   glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);

   if (!LoadRGBMipmaps(TEXTURE_FILE, GL_RGB)) {
      printf("Error: couldn't load texture image\n");
      exit(1);
   }

   /* Green fog is easy to see */
   glFogi(GL_FOG_MODE,GL_EXP2);
   glFogfv(GL_FOG_COLOR,fogColor);
   glFogf(GL_FOG_DENSITY,0.15);
   glHint(GL_FOG_HINT,GL_DONT_CARE);


   compactify_arrays();
   make_tri_indices();

   surf1 = BuildList( GL_COMPILE );

   ModeMenu(SHADE_SMOOTH|
	    LIT|
	    NO_TEXTURE|
	    NO_REFLECT|
	    POINT_FILTER|
	    IMMEDIATE|
	    NO_USER_CLIP|
	    NO_MATERIALS|
	    NO_FOG|
	    GLVERTEX);
}



static void Reshape(int width, int height)
{
    glViewport(0, 0, (GLint)width, (GLint)height);
}



static void Key( unsigned char key, int x, int y )
{
   (void) x;
   (void) y;
   switch (key) {
   case 27:
      exit(0);
   case 'f':
      ModeMenu((state ^ FOG_MASK) & FOG_MASK);
      break;
   case 's':
      ModeMenu((state ^ SHADE_MASK) & SHADE_MASK);
      break;
   case 'l':
      ModeMenu((state ^ LIGHT_MASK) & LIGHT_MASK);
      break;
   case 'm':
      ModeMenu((state ^ MATERIAL_MASK) & MATERIAL_MASK);
      break;
   case 'c':
      ModeMenu((state ^ CLIP_MASK) & CLIP_MASK);
      break;
   case 'b':
      Benchmark(5.0, 0);
      break;
   case 'B':
      Benchmark(0, 5.0);
      break;
   case 'i':
      dist += .25;
      set_matrix();
      glutPostRedisplay();
      break;
   case 'I':
      dist -= .25;
      set_matrix();
      glutPostRedisplay();
      break;
   case '-':
   case '_':
      plane[3] += 2.0;
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
      glClipPlane(GL_CLIP_PLANE0, plane);
      set_matrix();
      glutPostRedisplay();
      break;
   case '+':
   case '=':
      plane[3] -= 2.0;
      glMatrixMode(GL_MODELVIEW);
      glLoadIdentity();
      glClipPlane(GL_CLIP_PLANE0, plane);
      set_matrix();
      glutPostRedisplay();
      break;

   }
}


static void SpecialKey( int key, int x, int y )
{
   (void) x;
   (void) y;
   switch (key) {
   case GLUT_KEY_LEFT:
      yrot -= 15.0;
      break;
   case GLUT_KEY_RIGHT:
      yrot += 15.0;
      break;
   case GLUT_KEY_UP:
      xrot += 15.0;
      break;
   case GLUT_KEY_DOWN:
      xrot -= 15.0;
      break;
   default:
      return;
   }
   set_matrix();
   glutPostRedisplay();
}



static GLint Args(int argc, char **argv)
{
   GLint i;
   GLint mode = 0;

   for (i = 1; i < argc; i++) {
      if (strcmp(argv[i], "-sb") == 0) {
         doubleBuffer = GL_FALSE;
      }
      else if (strcmp(argv[i], "-db") == 0) {
         doubleBuffer = GL_TRUE;
      }
      else {
         printf("%s (Bad option).\n", argv[i]);
	 return QUIT;
      }
   }

   return mode;
}

int main(int argc, char **argv)
{
   GLenum type;
   char *extensions;

   GLuint arg_mode = Args(argc, argv);

   if (arg_mode & QUIT)
      exit(0);

   read_surface( "isosurf.dat" );

   glutInitWindowPosition(0, 0);
   glutInitWindowSize(400, 400);
   
   type = GLUT_DEPTH;
   type |= GLUT_RGB;
   type |= (doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE;
   glutInitDisplayMode(type);

   if (glutCreateWindow("Isosurface") <= 0) {
      exit(0);
   }

   /* Make sure server supports the vertex array extension */
   extensions = (char *) glGetString( GL_EXTENSIONS );

   if (!strstr( extensions, "GL_EXT_vertex_array" )) 
   {
      printf("Vertex arrays not supported by this renderer\n");
      allowed &= ~(COMPILED|DRAW_ARRAYS|ARRAY_ELT);
   }
   else if (!strstr( extensions, "GL_EXT_compiled_vertex_array" )) 
   {
      printf("Compiled vertex arrays not supported by this renderer\n");
      allowed &= ~COMPILED;
   }

   Init();
   ModeMenu(arg_mode);
   
   glutCreateMenu(ModeMenu);
   glutAddMenuEntry("Lit",                   LIT|NO_TEXTURE|NO_REFLECT);
   glutAddMenuEntry("Unlit",                 UNLIT|NO_TEXTURE|NO_REFLECT);
/*    glutAddMenuEntry("Textured", TEXTURE); */
   glutAddMenuEntry("Reflect",               TEXTURE|REFLECT);
   glutAddMenuEntry("", 0);   
   glutAddMenuEntry("Smooth",                SHADE_SMOOTH);
   glutAddMenuEntry("Flat",                  SHADE_FLAT);
   glutAddMenuEntry("", 0);   
   glutAddMenuEntry("Fog",                   FOG);
   glutAddMenuEntry("No Fog",                NO_FOG);
   glutAddMenuEntry("", 0);   
   glutAddMenuEntry("Point Filtered",        POINT_FILTER);
   glutAddMenuEntry("Linear Filtered",       LINEAR_FILTER);
   glutAddMenuEntry("", 0);   
   glutAddMenuEntry("glVertex (STRIPS)",    IMMEDIATE|GLVERTEX|STRIPS);
   glutAddMenuEntry("glVertex (TRIANGLES)", IMMEDIATE|GLVERTEX|TRIANGLES);
   glutAddMenuEntry("", 0);   
   glutAddMenuEntry("glVertex display list (STRIPS)", 
		    DISPLAYLIST|GLVERTEX|STRIPS);
   glutAddMenuEntry("", 0);   
   if (allowed & DRAW_ARRAYS) {
      glutAddMenuEntry("DrawArrays (STRIPS)",
		       IMMEDIATE|DRAW_ARRAYS|STRIPS);
      glutAddMenuEntry("ArrayElement (STRIPS)",  
		       IMMEDIATE|ARRAY_ELT|STRIPS);
      glutAddMenuEntry("DrawElements (TRIANGLES)", 
		       IMMEDIATE|DRAW_ARRAYS|TRIANGLES);
      glutAddMenuEntry("ArrayElement (TRIANGLES)", 
		       IMMEDIATE|ARRAY_ELT|TRIANGLES);
      glutAddMenuEntry("", 0);   

   }
   if (allowed & COMPILED) {
      glutAddMenuEntry("Compiled DrawElements (TRIANGLES)", 
		       COMPILED|DRAW_ARRAYS|TRIANGLES);
      glutAddMenuEntry("Compiled DrawElements (STRIPS)", 
		       COMPILED|DRAW_ARRAYS|STRIPS);
      glutAddMenuEntry("Compiled ArrayElement (TRIANGLES)", 
		       COMPILED|ARRAY_ELT|TRIANGLES);   
      glutAddMenuEntry("Compiled ArrayElement (STRIPS)", 
		       COMPILED|ARRAY_ELT|STRIPS);   
      glutAddMenuEntry("", 0);   
   }
   glutAddMenuEntry("Quit",                  QUIT);
   glutAttachMenu(GLUT_RIGHT_BUTTON);

   glutReshapeFunc(Reshape);
   glutKeyboardFunc(Key);
   glutSpecialFunc(SpecialKey);
   glutDisplayFunc(Display);
   glutMainLoop();
   return 0;
}