2e2b5f66e55673e5b0f68e7f96c5a1ad9102e15a
[occt.git] / src / OpenGl / OpenGl_View_2.cxx
1 // Created on: 2011-09-20
2 // Created by: Sergey ZERCHANINOV
3 // Copyright (c) 2011-2012 OPEN CASCADE SAS
4 //
5 // The content of this file is subject to the Open CASCADE Technology Public
6 // License Version 6.5 (the "License"). You may not use the content of this file
7 // except in compliance with the License. Please obtain a copy of the License
8 // at http://www.opencascade.org and read it completely before using this file.
9 //
10 // The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
11 // main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
12 //
13 // The Original Code and all software distributed under the License is
14 // distributed on an "AS IS" basis, without warranty of any kind, and the
15 // Initial Developer hereby disclaims all such warranties, including without
16 // limitation, any warranties of merchantability, fitness for a particular
17 // purpose or non-infringement. Please see the License for the specific terms
18 // and conditions governing the rights and limitations under the License.
19
20 #include <stdio.h>
21 #include <stdlib.h>
22
23 #include <OpenGl_GlCore11.hxx>
24 #include <OpenGl_tgl_funcs.hxx>
25
26 #include <Image_AlienPixMap.hxx>
27 #include <Visual3d_Layer.hxx>
28
29 #include <OpenGl_AspectLine.hxx>
30 #include <OpenGl_Display.hxx>
31 #include <OpenGl_Workspace.hxx>
32 #include <OpenGl_View.hxx>
33 #include <OpenGl_Trihedron.hxx>
34 #include <OpenGl_GraduatedTrihedron.hxx>
35 #include <OpenGl_PrinterContext.hxx>
36 #include <OpenGl_Structure.hxx>
37
38 #define EPSI 0.0001
39
40 static const GLfloat default_amb[4] = { 0.F, 0.F, 0.F, 1.F };
41 static const GLfloat default_sptdir[3] = { 0.F, 0.F, -1.F };
42 static const GLfloat default_sptexpo = 0.F;
43 static const GLfloat default_sptcutoff = 180.F;
44
45 extern void InitLayerProp (const int AListId); //szvgl: defined in OpenGl_GraphicDriver_Layer.cxx
46
47 /*----------------------------------------------------------------------*/
48
49 struct OPENGL_CLIP_PLANE
50 {
51   GLboolean isEnabled;
52   GLdouble Equation[4];
53   DEFINE_STANDARD_ALLOC
54 };
55
56 /*----------------------------------------------------------------------*/
57 /*
58 * Fonctions privees
59 */
60
61 /*-----------------------------------------------------------------*/
62 /*
63 *  Set des lumieres
64 */
65 static void bind_light(const OpenGl_Light *lptr, int *gl_lid)
66 {
67   // Only 8 lights in OpenGL...
68   if (*gl_lid > GL_LIGHT7) return;
69
70   // the light is a headlight ?
71   GLint cur_matrix;
72   if (lptr->HeadLight)
73   {
74     glGetIntegerv(GL_MATRIX_MODE, &cur_matrix);
75     glMatrixMode(GL_MODELVIEW);
76     glPushMatrix();
77     glLoadIdentity();
78   }
79
80   GLfloat data_amb[4];
81   GLfloat data_diffu[4];
82   GLfloat data_pos[4];
83   GLfloat data_sptdir[3];
84   GLfloat data_sptexpo;
85   GLfloat data_sptcutoff;
86   GLfloat data_constantattenuation;
87   GLfloat data_linearattenuation;
88
89   /* set la light en fonction de son type */
90   switch (lptr->type)
91   {
92   case TLightAmbient:
93     data_amb[0] = lptr->col.rgb[0];
94     data_amb[1] = lptr->col.rgb[1];
95     data_amb[2] = lptr->col.rgb[2];
96     data_amb[3] = 1.0;
97
98     /*------------------------- Ambient ---------------------------*/
99     /*
100     * The GL_AMBIENT parameter refers to RGBA intensity of the ambient
101     * light.
102     */
103     glLightModelfv(GL_LIGHT_MODEL_AMBIENT, data_amb);
104     break;
105
106
107   case TLightDirectional:
108     data_diffu[0] = lptr->col.rgb[0];
109     data_diffu[1] = lptr->col.rgb[1];
110     data_diffu[2] = lptr->col.rgb[2];
111     data_diffu[3] = 1.0;
112
113     /*------------------------- Direction ---------------------------*/
114     /* From Open GL Programming Rev 1 Guide Chapt 6 :
115     Lighting The Mathematics of Lighting ( p 168 )
116
117     Directional Light Source ( Infinite ) :
118     if the last parameter of GL_POSITION , w , is zero, the
119     corresponding light source is a Directional one.
120
121     GL_SPOT_CUTOFF a 180 signifie que ce n'est pas un spot.
122     To create a realistic effect,  set the GL_SPECULAR parameter
123     to the same value as the GL_DIFFUSE.
124     */
125
126     data_pos[0] = -lptr->dir[0];
127     data_pos[1] = -lptr->dir[1];
128     data_pos[2] = -lptr->dir[2];
129     data_pos[3] = 0.0;
130
131     glLightfv(*gl_lid, GL_AMBIENT, default_amb);
132     glLightfv(*gl_lid, GL_DIFFUSE, data_diffu);
133     glLightfv(*gl_lid, GL_SPECULAR, data_diffu);
134
135     glLightfv(*gl_lid, GL_POSITION, data_pos);
136     glLightfv(*gl_lid, GL_SPOT_DIRECTION, default_sptdir);
137     glLightf(*gl_lid, GL_SPOT_EXPONENT, default_sptexpo);
138     glLightf(*gl_lid, GL_SPOT_CUTOFF, default_sptcutoff);
139     break;
140
141
142   case TLightPositional:
143     data_diffu[0] = lptr->col.rgb[0];
144     data_diffu[1] = lptr->col.rgb[1];
145     data_diffu[2] = lptr->col.rgb[2];
146     data_diffu[3] = 1.0;
147
148     /*------------------------- Position -----------------------------*/
149     /* From Open GL Programming Rev 1 Guide Chapt 6 :
150     Lighting The Mathematics of Lighting ( p 168 )
151     Positional Light Source :
152     if the last parameter of GL_POSITION , w , is nonzero,
153     the corresponding light source is a Positional one.
154
155     GL_SPOT_CUTOFF a 180 signifie que ce n'est pas un spot.
156
157     To create a realistic effect,  set the GL_SPECULAR parameter
158     to the same value as the GL_DIFFUSE.
159     */
160
161     data_pos[0] = lptr->pos[0];
162     data_pos[1] = lptr->pos[1];
163     data_pos[2] = lptr->pos[2];
164     data_pos[3] = 1.0;
165
166     data_constantattenuation = lptr->atten[0];
167     data_linearattenuation = lptr->atten[1];
168
169     glLightfv(*gl_lid, GL_AMBIENT, default_amb);
170     glLightfv(*gl_lid, GL_DIFFUSE, data_diffu);
171     glLightfv(*gl_lid, GL_SPECULAR, data_diffu);
172
173     glLightfv(*gl_lid, GL_POSITION, data_pos);
174     glLightfv(*gl_lid, GL_SPOT_DIRECTION, default_sptdir);
175     glLightf(*gl_lid, GL_SPOT_EXPONENT, default_sptexpo);
176     glLightf(*gl_lid, GL_SPOT_CUTOFF, default_sptcutoff);
177     glLightf(*gl_lid, GL_CONSTANT_ATTENUATION, data_constantattenuation);
178     glLightf(*gl_lid, GL_LINEAR_ATTENUATION, data_linearattenuation);
179     glLightf(*gl_lid, GL_QUADRATIC_ATTENUATION, 0.0);
180     break;
181
182
183   case TLightSpot:
184     data_diffu[0] = lptr->col.rgb[0];
185     data_diffu[1] = lptr->col.rgb[1];
186     data_diffu[2] = lptr->col.rgb[2];
187     data_diffu[3] = 1.0;
188
189     data_pos[0] = lptr->pos[0];
190     data_pos[1] = lptr->pos[1];
191     data_pos[2] = lptr->pos[2];
192     data_pos[3] = 1.0;
193
194     data_sptdir[0] = lptr->dir[0];
195     data_sptdir[1] = lptr->dir[1];
196     data_sptdir[2] = lptr->dir[2];
197
198     data_sptexpo = ( float )lptr->shine * 128.0F;
199     data_sptcutoff = ( float )(lptr->angle * 180.0F)/( float )M_PI;
200
201     data_constantattenuation = lptr->atten[0];
202     data_linearattenuation = lptr->atten[1];
203
204     glLightfv(*gl_lid, GL_AMBIENT, default_amb);
205     glLightfv(*gl_lid, GL_DIFFUSE, data_diffu);
206     glLightfv(*gl_lid, GL_SPECULAR, data_diffu);
207
208     glLightfv(*gl_lid, GL_POSITION, data_pos);
209     glLightfv(*gl_lid, GL_SPOT_DIRECTION, data_sptdir);
210     glLightf(*gl_lid, GL_SPOT_EXPONENT, data_sptexpo);
211     glLightf(*gl_lid, GL_SPOT_CUTOFF, data_sptcutoff);
212     glLightf(*gl_lid, GL_CONSTANT_ATTENUATION, data_constantattenuation);
213     glLightf(*gl_lid, GL_LINEAR_ATTENUATION, data_linearattenuation);
214     glLightf(*gl_lid, GL_QUADRATIC_ATTENUATION, 0.0);
215     break;
216   }
217
218   if (lptr->type != TLightAmbient)
219   {
220     glEnable(*gl_lid);
221     (*gl_lid)++;
222   }
223
224   /* si la light etait une headlight alors restaure la matrice precedente */
225   if (lptr->HeadLight)
226   {
227     glPopMatrix();
228     glMatrixMode(cur_matrix);
229   }
230 }
231
232 /*----------------------------------------------------------------------*/
233 /*
234 * Prototypes
235 */
236
237 static void call_util_apply_trans2( float ix, float iy, float iz, matrix3 mat,
238                                    float *ox, float *oy, float *oz );
239 static void call_util_mat_mul( matrix3 mat_a, matrix3 mat_b, matrix3 mat_c);
240
241 /*----------------------------------------------------------------------*/
242 /*
243 * Fonctions externes
244 */
245
246 /*
247 *  Evaluates orientation matrix.
248 */
249 /* OCC18942: obsolete in OCCT6.3, might be removed in further versions! */
250 void call_func_eval_ori_matrix3 (const point3* vrp,        // view reference point
251                                  const vec3*   vpn,        // view plane normal
252                                  const vec3*   vup,        // view up vector
253                                  int*          err_ind,
254                                  float         mout[4][4]) // OUT view orientation matrix
255 {
256
257   /* Translate to VRP then change the basis.
258   * The old basis is: e1 = < 1, 0, 0>, e2 = < 0, 1, 0>, e3 = < 0, 0, 1>.
259   * The new basis is: ("x" means cross product)
260   *  e3' = VPN / |VPN|
261   *  e1' = VUP x VPN / |VUP x VPN|
262   *  e2' = e3' x e1'
263   * Therefore the transform from old to new is x' = TAx, where:
264   *
265   *       | e1'x e2'x e3'x 0 |         |   1      0      0      0 |
266   *   A = | e1'y e2'y e3'y 0 |,    T = |   0      1      0      0 |
267   *       | e1'z e2'z e3'z 0 |         |   0      0      1      0 |
268   *       |  0    0    0   1 |         | -vrp.x -vrp.y -vrp.z   1 |
269   *
270   */
271
272   /*
273   * These ei's are really ei primes.
274   */
275   register float      (*m)[4][4];
276   point3      e1, e2, e3, e4;
277   double      s, v;
278
279   /*
280   * e1' = VUP x VPN / |VUP x VPN|, but do the division later.
281   */
282   e1.x = vup->delta_y * vpn->delta_z - vup->delta_z * vpn->delta_y;
283   e1.y = vup->delta_z * vpn->delta_x - vup->delta_x * vpn->delta_z;
284   e1.z = vup->delta_x * vpn->delta_y - vup->delta_y * vpn->delta_x;
285   s = sqrt( e1.x * e1.x + e1.y * e1.y + e1.z * e1.z);
286   e3.x = vpn->delta_x;
287   e3.y = vpn->delta_y;
288   e3.z = vpn->delta_z;
289   v = sqrt( e3.x * e3.x + e3.y * e3.y + e3.z * e3.z);
290   /*
291   * Check for vup and vpn colinear (zero dot product).
292   */
293   if ((s > -EPSI) && (s < EPSI))
294     *err_ind = 2;
295   else
296     /*
297     * Check for a normal vector not null.
298     */
299     if ((v > -EPSI) && (v < EPSI))
300       *err_ind = 3;
301     else {
302       /*
303       * Normalize e1
304       */
305       e1.x /= ( float )s;
306       e1.y /= ( float )s;
307       e1.z /= ( float )s;
308       /*
309       * e3 = VPN / |VPN|
310       */
311       e3.x /= ( float )v;
312       e3.y /= ( float )v;
313       e3.z /= ( float )v;
314       /*
315       * e2 = e3 x e1
316       */
317       e2.x = e3.y * e1.z - e3.z * e1.y;
318       e2.y = e3.z * e1.x - e3.x * e1.z;
319       e2.z = e3.x * e1.y - e3.y * e1.x;
320       /*
321       * Add the translation
322       */
323       e4.x = -( e1.x * vrp->x + e1.y * vrp->y + e1.z * vrp->z);
324       e4.y = -( e2.x * vrp->x + e2.y * vrp->y + e2.z * vrp->z);
325       e4.z = -( e3.x * vrp->x + e3.y * vrp->y + e3.z * vrp->z);
326       /*
327       * Homogeneous entries
328       *
329       *  | e1.x  e2.x  e3.x  0.0 |   | 1  0  0  0 |
330       *  | e1.y  e2.y  e3.y  0.0 | * | 0  1  0  0 |
331       *  | e1.z  e2.z  e3.z  0.0 |   | a  b  1  c |
332       *  | e4.x  e4.y  e4.z  1.0 |   | 0  0  0  1 |
333       */
334
335       m = (float (*)[4][4])mout;
336
337       (*m)[0][0] = e1.x;
338       (*m)[0][1] = e2.x;
339       (*m)[0][2] = e3.x;
340       (*m)[0][3] = ( float )0.0;
341
342       (*m)[1][0] = e1.y;
343       (*m)[1][1] = e2.y;
344       (*m)[1][2] = e3.y;
345       (*m)[1][3] = ( float )0.0;
346
347       (*m)[2][0] = e1.z;
348       (*m)[2][1] = e2.z;
349       (*m)[2][2] = e3.z;
350       (*m)[2][3] = ( float )0.0;
351
352       (*m)[3][0] = e4.x;
353       (*m)[3][1] = e4.y;
354       (*m)[3][2] = e4.z;
355       (*m)[3][3] = ( float )1.0;
356
357       *err_ind = 0;
358     }
359 }
360
361 /*----------------------------------------------------------------------*/
362 /*
363 *  Evaluates mapping matrix.
364 */
365 /* OCC18942: obsolete in OCCT6.3, might be removed in further versions! */
366 void call_func_eval_map_matrix3(
367                                 view_map3 *Map,
368                                 int *err_ind,
369                                 matrix3 mat)
370 {
371   int i, j;
372   matrix3 Tpar, Spar;
373   matrix3 Tper, Sper;
374   matrix3 Shear;
375   matrix3 Scale;
376   matrix3 Tprp;
377   matrix3 aux_mat1, aux_mat2, aux_mat3;
378   point3 Prp;
379
380   *err_ind = 0;
381   for (i=0; i<4; i++)
382     for (j=0; j<4; j++)
383       Spar[i][j] = Sper[i][j] = aux_mat1[i][j] = aux_mat2[i][j] =
384       aux_mat3[i][j] = Tper[i][j] = Tpar[i][j] = Tprp[i][j] =
385       Shear[i][j] = Scale[i][j] = ( float )(i == j);
386
387   Prp.x = Map->proj_ref_point.x;
388   Prp.y = Map->proj_ref_point.y;
389   Prp.z = Map->proj_ref_point.z;
390
391   /*
392   * Type Parallele
393   */
394   if (Map->proj_type == TYPE_PARAL)
395   {
396     float umid, vmid;
397     point3 temp;
398
399 #ifdef FMN
400     float    cx, cy, gx, gy, xsf, ysf, zsf;
401     float    fpd, bpd;
402     float    dopx, dopy, dopz;
403     matrix3  tmat = { { ( float )1.0, ( float )0.0, ( float )0.0, ( float )0.0 },
404     { ( float )0.0, ( float )1.0, ( float )0.0, ( float )0.0 },
405     { ( float )0.0, ( float )0.0, ( float )1.0, ( float )0.0 },
406     { ( float )0.0, ( float )0.0, ( float )0.0, ( float )1.0 } };
407     matrix3  smat = { { ( float )1.0, ( float )0.0, ( float )0.0, ( float )0.0 },
408     { ( float )0.0, ( float )1.0, ( float )0.0, ( float )0.0 },
409     { ( float )0.0, ( float )0.0, ( float )1.0, ( float )0.0 },
410     { ( float )0.0, ( float )0.0, ( float )0.0, ( float )1.0 } };
411     matrix3 shmat = { { ( float )1.0, ( float )0.0, ( float )0.0, ( float )0.0 },
412     { ( float )0.0, ( float )1.0, ( float )0.0, ( float )0.0 },
413     { ( float )0.0, ( float )0.0, ( float )1.0, ( float )0.0 },
414     { ( float )0.0, ( float )0.0, ( float )0.0, ( float )1.0 } };
415     matrix3 tshmat = { { ( float )1.0, ( float )0.0, ( float )0.0, ( float )0.0 },
416     { ( float )0.0, ( float )1.0, ( float )0.0, ( float )0.0 },
417     { ( float )0.0, ( float )0.0, ( float )1.0, ( float )0.0 },
418     { ( float )0.0, ( float )0.0, ( float )0.0, ( float )1.0 } };
419
420     /* centers */
421     cx = Map->win.x_min + Map->win.x_max, cx /= ( float )2.0;
422     cy = Map->win.y_min + Map->win.y_max, cy /= ( float )2.0;
423
424     gx = 2.0/ (Map->win.x_max - Map->win.x_min);
425     gy = 2.0/ (Map->win.y_max - Map->win.y_min);
426
427     tmat[0][3] = -cx;
428     tmat[1][3] = -cy;
429     tmat[2][3] = (Map->front_plane + Map->back_plane)/(Map->front_plane - Map->back_plane);
430
431     smat[0][0] = gx;
432     smat[1][1] = gy;
433     smat[2][2] = -2./(Map->front_plane - Map->back_plane);
434
435     /* scale factors */
436     dopx = cx - Prp.x;
437     dopy = cy - Prp.y;
438     dopz = - Prp.z;
439
440     /* map matrix */
441     shmat[0][2] = -(dopx/dopz);
442     shmat[1][2] = -(dopy/dopz);
443
444     /* multiply to obtain mapping matrix */
445     call_util_mat_mul( tmat, shmat, tshmat );
446     call_util_mat_mul( smat, tshmat, mat );
447
448     return;
449 #endif
450
451     /* CAL */
452     Map->proj_vp.z_min = ( float )0.0;
453     Map->proj_vp.z_max = ( float )1.0;
454     /* CAL */
455
456     /* Shear matrix calculation */
457     umid = ( float )(Map->win.x_min+Map->win.x_max)/( float )2.0;
458     vmid = ( float )(Map->win.y_min+Map->win.y_max)/( float )2.0;
459     if(Prp.z == Map->view_plane){
460       /* Projection reference point is on the view plane */
461       *err_ind = 1;
462       return;
463     }
464     Shear[2][0] = ( float )(-1.0) * ((Prp.x-umid)/(Prp.z-Map->view_plane));
465     Shear[2][1] = ( float )(-1.0) * ((Prp.y-vmid)/(Prp.z-Map->view_plane));
466
467     /*
468     * Calculate the lower left coordinate of the view plane
469     * after the Shearing Transformation.
470     */
471     call_util_apply_trans2(Map->win.x_min, Map->win.y_min,
472       Map->view_plane, Shear, &(temp.x), &(temp.y), &(temp.z));
473
474     /* Translate the back plane to the origin */
475     Tpar[3][0] = ( float )(-1.0) * temp.x;
476     Tpar[3][1] = ( float )(-1.0) * temp.y;
477     Tpar[3][2] = ( float )(-1.0) * Map->back_plane;
478
479     call_util_mat_mul(Shear, Tpar, aux_mat1);
480
481     /* Calculation of Scaling transformation */
482     Spar[0][0] = ( float )1.0 / (Map->win.x_max - Map->win.x_min);
483     Spar[1][1] = ( float )1.0 / (Map->win.y_max - Map->win.y_min);
484     Spar[2][2] = ( float )1.0 / (Map->front_plane - Map->back_plane );
485     call_util_mat_mul (aux_mat1, Spar, aux_mat2);
486     /* Atlast we transformed view volume to NPC */
487
488     /* Translate and scale the view plane to projection view port */
489     if(Map->proj_vp.x_min < 0.0 || Map->proj_vp.y_min < 0.0 ||
490       Map->proj_vp.z_min < 0.0 || Map->proj_vp.x_max > 1.0 ||
491       Map->proj_vp.y_max > 1.0 || Map->proj_vp.z_max > 1.0 ||
492       Map->proj_vp.x_min > Map->proj_vp.x_max ||
493       Map->proj_vp.y_min > Map->proj_vp.y_max ||
494       Map->proj_vp.z_min > Map->proj_vp.z_max){
495         *err_ind = 1;
496         return;
497       }
498       for(i=0; i<4; i++)
499         for(j=0; j<4; j++)
500           aux_mat1[i][j] = (float)(i==j);
501       aux_mat1[0][0] = Map->proj_vp.x_max-Map->proj_vp.x_min;
502       aux_mat1[1][1] = Map->proj_vp.y_max-Map->proj_vp.y_min;
503       aux_mat1[2][2] = Map->proj_vp.z_max-Map->proj_vp.z_min;
504       aux_mat1[3][0] = Map->proj_vp.x_min;
505       aux_mat1[3][1] = Map->proj_vp.y_min;
506       aux_mat1[3][2] = Map->proj_vp.z_min;
507       call_util_mat_mul (aux_mat2, aux_mat1, mat);
508
509       return;
510   }
511
512   /*
513   * Type Perspective
514   */
515   else if (Map->proj_type == TYPE_PERSPECT)
516   {
517     float umid, vmid;
518     float B, F, V;
519     float Zvmin;
520
521     /* CAL */
522     Map->proj_vp.z_min = ( float )0.0;
523     Map->proj_vp.z_max = ( float )1.0;
524     /* CAL */
525
526     B = Map->back_plane;
527     F = Map->front_plane;
528     V = Map->view_plane;
529
530     if(Prp.z == Map->view_plane){
531       /* Centre of Projection is on the view plane */
532       *err_ind = 1;
533       return;
534     }
535     if(Map->proj_vp.x_min < 0.0 || Map->proj_vp.y_min < 0.0 ||
536       Map->proj_vp.z_min < 0.0 || Map->proj_vp.x_max > 1.0 ||
537       Map->proj_vp.y_max > 1.0 || Map->proj_vp.z_max > 1.0 ||
538       Map->proj_vp.x_min > Map->proj_vp.x_max ||
539       Map->proj_vp.y_min > Map->proj_vp.y_max ||
540       Map->proj_vp.z_min > Map->proj_vp.z_max ||
541       F < B){
542         *err_ind = 1;
543         return;
544       }
545
546       /* This is the transformation to move VRC to Center Of Projection */
547       Tprp[3][0] = ( float )(-1.0)*Prp.x;
548       Tprp[3][1] = ( float )(-1.0)*Prp.y;
549       Tprp[3][2] = ( float )(-1.0)*Prp.z;
550
551       /* Calculation of Shear matrix */
552       umid = ( float )(Map->win.x_min+Map->win.x_max)/( float )2.0-Prp.x;
553       vmid = ( float )(Map->win.y_min+Map->win.y_max)/( float )2.0-Prp.y;
554       Shear[2][0] = ( float )(-1.0)*umid/(Map->view_plane-Prp.z);
555       Shear[2][1] = ( float )(-1.0)*vmid/(Map->view_plane-Prp.z);
556       call_util_mat_mul(Tprp, Shear, aux_mat3);
557
558       /* Scale the view volume to canonical view volume
559       * Centre of projection at origin.
560       * 0 <= N <= -1, -0.5 <= U <= 0.5, -0.5 <= V <= 0.5
561       */
562       Scale[0][0] =  (( float )(-1.0)*Prp.z+V)/
563         ((Map->win.x_max-Map->win.x_min)*(( float )(-1.0)*Prp.z+B));
564       Scale[1][1] =  (( float )(-1.0)*Prp.z+V)/
565         ((Map->win.y_max-Map->win.y_min)*(( float )(-1.0)*Prp.z+B));
566       Scale[2][2] =  ( float )(-1.0) / (( float )(-1.0)*Prp.z+B);
567
568       call_util_mat_mul(aux_mat3, Scale, aux_mat1);
569
570       /*
571       * Transform the Perspective view volume into
572       * Parallel view volume.
573       * Lower left coordinate: (-0.5,-0.5, -1)
574       * Upper right coordinate: (0.5, 0.5, 1.0)
575       */
576       Zvmin = ( float )(-1.0*(-1.0*Prp.z+F)/(-1.0*Prp.z+B));
577       aux_mat2[2][2] = ( float )1.0/(( float )1.0+Zvmin);
578       aux_mat2[2][3] = ( float )(-1.0);
579       aux_mat2[3][2] = ( float )(-1.0)*Zvmin*aux_mat2[2][2];
580       aux_mat2[3][3] = ( float )0.0;
581       call_util_mat_mul(aux_mat1, aux_mat2, Shear);
582
583       for(i=0; i<4; i++)
584         for(j=0; j<4; j++)
585           aux_mat1[i][j] = aux_mat2[i][j] = (float)(i==j);
586
587       /* Translate and scale the view plane to projection view port */
588       aux_mat2[0][0] = (Map->proj_vp.x_max-Map->proj_vp.x_min);
589       aux_mat2[1][1] = (Map->proj_vp.y_max-Map->proj_vp.y_min);
590       aux_mat2[2][2] = (Map->proj_vp.z_max-Map->proj_vp.z_min);
591       aux_mat2[3][0] = aux_mat2[0][0]/( float )2.0+Map->proj_vp.x_min;
592       aux_mat2[3][1] = aux_mat2[1][1]/( float )2.0+Map->proj_vp.y_min;
593       aux_mat2[3][2] = aux_mat2[2][2]+Map->proj_vp.z_min;
594       call_util_mat_mul (Shear, aux_mat2, mat);
595
596       return;
597   }
598   else
599     *err_ind = 1;
600 }
601
602 /*----------------------------------------------------------------------*/
603
604 static void
605 call_util_apply_trans2( float ix, float iy, float iz, matrix3 mat,
606                        float *ox, float *oy, float *oz )
607 {
608   float temp;
609   *ox = ix*mat[0][0]+iy*mat[1][0]+iz*mat[2][0]+mat[3][0];
610   *oy = ix*mat[0][1]+iy*mat[1][1]+iz*mat[2][1]+mat[3][1];
611   *oz = ix*mat[0][2]+iy*mat[1][2]+iz*mat[2][2]+mat[3][2];
612   temp = ix * mat[0][3]+iy * mat[1][3]+iz * mat[2][3]+mat[3][3];
613   *ox /= temp;
614   *oy /= temp;
615   *oz /= temp;
616 }
617
618 /*----------------------------------------------------------------------*/
619
620 static void
621 call_util_mat_mul( matrix3 mat_a, matrix3 mat_b, matrix3 mat_c)
622 {
623   int i, j, k;
624
625   for (i=0; i<4; i++)
626     for (j=0; j<4; j++)
627       for (mat_c[i][j] = ( float )0.0,k=0; k<4; k++)
628         mat_c[i][j] += mat_a[i][k] * mat_b[k][j];
629 }
630
631 /*----------------------------------------------------------------------*/
632
633 //call_func_redraw_all_structs_proc
634 void OpenGl_View::Render (const Handle(OpenGl_PrinterContext)& thePrintContext,
635                           const Handle(OpenGl_Workspace) &AWorkspace,
636                           const Graphic3d_CView& ACView,
637                           const Aspect_CLayer2d& ACUnderLayer,
638                           const Aspect_CLayer2d& ACOverLayer)
639 {
640   // Store and disable current clipping planes
641   GLint maxplanes;
642   glGetIntegerv(GL_MAX_CLIP_PLANES, &maxplanes);
643   const GLenum lastid = GL_CLIP_PLANE0 + maxplanes;
644   OPENGL_CLIP_PLANE *oldPlanes = new OPENGL_CLIP_PLANE[maxplanes];
645   OPENGL_CLIP_PLANE *ptrPlane = oldPlanes;
646   GLenum planeid = GL_CLIP_PLANE0;
647   for ( ; planeid < lastid; planeid++, ptrPlane++ )
648   {
649     glGetClipPlane( planeid, ptrPlane->Equation );
650     if ( ptrPlane->isEnabled )
651     {
652       glDisable( planeid );
653       ptrPlane->isEnabled = GL_TRUE;
654     }
655         else
656       ptrPlane->isEnabled = GL_FALSE;
657   }
658
659   /////////////////////////////////////////////////////////////////////////////
660   // Step 1: Prepare for redraw
661
662   // Render background
663   if ( (AWorkspace->NamedStatus & OPENGL_NS_WHITEBACK) == 0 &&
664            ( myBgTexture.TexId != 0 || myBgGradient.type != Aspect_GFM_NONE ) )
665   {
666     const Standard_Integer aViewWidth = AWorkspace->Width();
667     const Standard_Integer aViewHeight = AWorkspace->Height();
668
669     glPushAttrib( GL_ENABLE_BIT | GL_TEXTURE_BIT );
670
671     glMatrixMode( GL_PROJECTION );
672     glPushMatrix();
673     glLoadIdentity();
674     glMatrixMode( GL_MODELVIEW );
675     glPushMatrix();
676     glLoadIdentity();
677
678     if ( glIsEnabled( GL_DEPTH_TEST ) )
679       glDisable( GL_DEPTH_TEST ); //push GL_ENABLE_BIT
680
681     // drawing bg gradient if:
682     // - gradient fill type is not Aspect_GFM_NONE and
683     // - either background texture is no specified or it is drawn in Aspect_FM_CENTERED mode
684     if ( ( myBgGradient.type != Aspect_GFM_NONE ) &&
685          ( myBgTexture.TexId == 0 || myBgTexture.Style == Aspect_FM_CENTERED ||
686            myBgTexture.Style == Aspect_FM_NONE ) )
687     {
688       Tfloat* corner1 = 0;/* -1,-1*/
689       Tfloat* corner2 = 0;/*  1,-1*/
690       Tfloat* corner3 = 0;/*  1, 1*/
691       Tfloat* corner4 = 0;/* -1, 1*/
692       Tfloat dcorner1[3];
693       Tfloat dcorner2[3];
694
695       switch( myBgGradient.type )
696       {
697         case Aspect_GFM_HOR:
698           corner1 = myBgGradient.color1.rgb;
699           corner2 = myBgGradient.color2.rgb;
700           corner3 = myBgGradient.color2.rgb;
701           corner4 = myBgGradient.color1.rgb;
702           break;
703         case Aspect_GFM_VER:
704           corner1 = myBgGradient.color2.rgb;
705           corner2 = myBgGradient.color2.rgb;
706           corner3 = myBgGradient.color1.rgb;
707           corner4 = myBgGradient.color1.rgb;
708           break;
709         case Aspect_GFM_DIAG1:
710           corner2 = myBgGradient.color2.rgb;
711           corner4 = myBgGradient.color1.rgb;
712           dcorner1 [0] = dcorner2[0] = 0.5F * (corner2[0] + corner4[0]);
713           dcorner1 [1] = dcorner2[1] = 0.5F * (corner2[1] + corner4[1]);
714           dcorner1 [2] = dcorner2[2] = 0.5F * (corner2[2] + corner4[2]);
715           corner1 = dcorner1;
716           corner3 = dcorner2;
717           break;
718         case Aspect_GFM_DIAG2:
719           corner1 = myBgGradient.color2.rgb;
720           corner3 = myBgGradient.color1.rgb;
721           dcorner1 [0] = dcorner2[0] = 0.5F * (corner1[0] + corner3[0]);
722           dcorner1 [1] = dcorner2[1] = 0.5F * (corner1[1] + corner3[1]);
723           dcorner1 [2] = dcorner2[2] = 0.5F * (corner1[2] + corner3[2]);
724           corner2 = dcorner1;
725           corner4 = dcorner2;
726           break;
727         case Aspect_GFM_CORNER1:
728           corner1 = myBgGradient.color2.rgb;
729           corner2 = myBgGradient.color2.rgb;
730           corner3 = myBgGradient.color2.rgb;
731           corner4 = myBgGradient.color1.rgb;
732           break;
733         case Aspect_GFM_CORNER2:
734           corner1 = myBgGradient.color2.rgb;
735           corner2 = myBgGradient.color2.rgb;
736           corner3 = myBgGradient.color1.rgb;
737           corner4 = myBgGradient.color2.rgb;
738           break;
739         case Aspect_GFM_CORNER3:
740           corner1 = myBgGradient.color2.rgb;
741           corner2 = myBgGradient.color1.rgb;
742           corner3 = myBgGradient.color2.rgb;
743           corner4 = myBgGradient.color2.rgb;
744           break;
745         case Aspect_GFM_CORNER4:
746           corner1 = myBgGradient.color1.rgb;
747           corner2 = myBgGradient.color2.rgb;
748           corner3 = myBgGradient.color2.rgb;
749           corner4 = myBgGradient.color2.rgb;
750           break;
751         default:
752           //printf("gradient background type not right\n");
753          break;
754       }
755
756       // Save GL parameters
757       glDisable( GL_LIGHTING ); //push GL_ENABLE_BIT
758
759       GLint curSM;
760       glGetIntegerv( GL_SHADE_MODEL, &curSM );
761       if ( curSM != GL_SMOOTH )
762         glShadeModel( GL_SMOOTH ); //push GL_LIGHTING_BIT
763
764       glBegin(GL_TRIANGLE_FAN);
765       if( myBgGradient.type != Aspect_GFM_CORNER1 && myBgGradient.type != Aspect_GFM_CORNER3 )
766       {
767         glColor3f(corner1[0],corner1[1],corner1[2]); glVertex2f(-1.,-1.);
768         glColor3f(corner2[0],corner2[1],corner2[2]); glVertex2f( 1.,-1.);
769         glColor3f(corner3[0],corner3[1],corner3[2]); glVertex2f( 1., 1.);
770         glColor3f(corner4[0],corner4[1],corner4[2]); glVertex2f(-1., 1.);
771       }
772       else //if ( myBgGradient.type == Aspect_GFM_CORNER1 || myBgGradient.type == Aspect_GFM_CORNER3 )
773       {
774         glColor3f(corner2[0],corner2[1],corner2[2]); glVertex2f( 1.,-1.);
775         glColor3f(corner3[0],corner3[1],corner3[2]); glVertex2f( 1., 1.);
776         glColor3f(corner4[0],corner4[1],corner4[2]); glVertex2f(-1., 1.);
777         glColor3f(corner1[0],corner1[1],corner1[2]); glVertex2f(-1.,-1.);
778       }
779       glEnd();
780
781       // Restore GL parameters
782       if ( curSM != GL_SMOOTH )
783         glShadeModel( curSM );
784     }
785     // drawing bg image if:
786     // - it is defined and
787     // - fill type is not Aspect_FM_NONE
788     if ( myBgTexture.TexId != 0 && myBgTexture.Style != Aspect_FM_NONE )
789     {
790       GLfloat texX_range = 1.F; // texture <s> coordinate
791       GLfloat texY_range = 1.F; // texture <t> coordinate
792
793           // Set up for stretching or tiling
794       GLfloat x_offset, y_offset;
795       if ( myBgTexture.Style == Aspect_FM_CENTERED )
796       {
797         x_offset = (GLfloat)myBgTexture.Width / (GLfloat)aViewWidth;
798         y_offset = (GLfloat)myBgTexture.Height / (GLfloat)aViewHeight;
799       }
800       else
801       {
802         x_offset = 1.F;
803         y_offset = 1.F;
804         if ( myBgTexture.Style == Aspect_FM_TILED )
805         {
806           texX_range = (GLfloat)aViewWidth / (GLfloat)myBgTexture.Width;
807           texY_range = (GLfloat)aViewHeight / (GLfloat)myBgTexture.Height;
808         }
809       }
810
811       // OCCT issue 0023000: Improve the way the gradient and textured
812       // background is managed in 3d viewer (note 0020339)
813       // Setting this coefficient to -1.F allows to tile textures relatively
814       // to the top-left corner of the view (value 1.F corresponds to the
815       // initial behaviour - tiling from the bottom-left corner)
816       GLfloat aCoef = -1.F;
817
818       glEnable( GL_TEXTURE_2D ); //push GL_ENABLE_BIT
819       glBindTexture( GL_TEXTURE_2D, myBgTexture.TexId ); //push GL_TEXTURE_BIT
820
821       glDisable( GL_BLEND ); //push GL_ENABLE_BIT
822
823       glColor3fv( AWorkspace->BackgroundColor().rgb );
824       glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL); //push GL_TEXTURE_BIT
825
826       // Note that texture is mapped using GL_REPEAT wrapping mode so integer part
827       // is simply ignored, and negative multiplier is here for convenience only
828       // and does not result e.g. in texture mirroring
829       glBegin( GL_QUADS );
830       glTexCoord2f(0.F, 0.F); glVertex2f( -x_offset, -aCoef * y_offset );
831       glTexCoord2f(texX_range, 0.F); glVertex2f( x_offset, -aCoef * y_offset );
832       glTexCoord2f(texX_range, aCoef * texY_range); glVertex2f( x_offset, aCoef * y_offset );
833       glTexCoord2f(0.F, aCoef * texY_range); glVertex2f( -x_offset, aCoef * y_offset );
834       glEnd();
835     }
836
837     glPopMatrix();
838     glMatrixMode( GL_PROJECTION );
839     glPopMatrix();
840     glMatrixMode( GL_MODELVIEW );
841
842     glPopAttrib(); //GL_ENABLE_BIT | GL_TEXTURE_BIT
843
844     if ( AWorkspace->UseZBuffer() )
845       glEnable( GL_DEPTH_TEST );
846
847     /* GL_DITHER on/off pour le trace */
848     if (AWorkspace->Dither())
849       glEnable (GL_DITHER);
850     else
851       glDisable (GL_DITHER);
852   }
853
854   // Switch off lighting by default
855   glDisable(GL_LIGHTING);
856
857   /////////////////////////////////////////////////////////////////////////////
858   // Step 2: Draw underlayer
859   RedrawLayer2d (thePrintContext, AWorkspace, ACView, ACUnderLayer);
860
861   /////////////////////////////////////////////////////////////////////////////
862   // Step 3: Redraw main plane
863
864   // Setup face culling
865   GLboolean isCullFace = GL_FALSE;
866   if ( myBackfacing )
867   {
868     isCullFace = glIsEnabled( GL_CULL_FACE );
869     if ( myBackfacing < 0 )
870     {
871       glEnable( GL_CULL_FACE );
872       glCullFace( GL_BACK );
873     }
874         else
875       glDisable( GL_CULL_FACE );
876   }
877
878   //TsmPushAttri(); /* save previous graphics context */
879
880   // if the view is scaled normal vectors are scaled to unit length for correct displaying of shaded objects
881   if(myExtra.scaleFactors[0] != 1.F ||
882      myExtra.scaleFactors[1] != 1.F ||
883      myExtra.scaleFactors[2] != 1.F)
884     glEnable(GL_NORMALIZE);
885   else if(glIsEnabled(GL_NORMALIZE))
886     glDisable(GL_NORMALIZE);
887
888   // Apply View Projection
889   // This routine activates the Projection matrix for a view.
890
891   glMatrixMode( GL_PROJECTION );
892
893 #ifdef _WIN32
894   // add printing scale/tiling transformation
895   if (!thePrintContext.IsNull())
896   {
897     thePrintContext->LoadProjTransformation();
898   }
899   else
900 #endif
901     glLoadIdentity();
902
903   glMultMatrixf( (const GLfloat *) myMappingMatrix );
904
905   // Add translation necessary for the environnement mapping
906   if (mySurfaceDetail != Visual3d_TOD_NONE)
907   {
908     // OCC280: FitAll work incorrect for perspective view if the SurfaceDetail mode is V3d_TEX_ENVIRONMENT or V3d_TEX_ALL
909     // const GLfloat dep = vptr->vrep.extra.map.fpd * 0.5F;
910     const GLfloat dep = (myExtra.map.fpd + myExtra.map.bpd) * 0.5F;
911     glTranslatef(-dep*myExtra.vpn[0],-dep*myExtra.vpn[1],-dep*myExtra.vpn[2]);
912   }
913
914   // Apply matrix
915   AWorkspace->SetViewMatrix((const OpenGl_Matrix *)myOrientationMatrix);
916
917 /*
918 While drawing after a clipplane has been defined and enabled, each vertex
919 is transformed to eye-coordinates, where it is dotted with the transformed
920 clipping plane equation.  Eye-coordinate vertexes whose dot product with
921 the transformed clipping plane equation is positive or zero are in, and
922 require no clipping.  Those eye-coordinate vertexes whose dot product is
923 negative are clipped.  Because clipplane clipping is done in eye-
924 coordinates, changes to the projection matrix have no effect on its
925 operation.
926
927 A point and a normal are converted to a plane equation in the following manner:
928
929 point = [Px,Py,Pz]
930
931 normal = |Nx|
932 |Ny|
933 |Nz|
934
935 plane equation = |A|
936 |B|
937 |C|
938 |D|
939 A = Nx
940 B = Ny
941 C = Nz
942 D = -[Px,Py,Pz] dot |Nx|
943 |Ny|
944 |Nz|
945
946 */
947
948   // Apply Fog
949   if ( myFog.IsOn )
950   {
951     const GLfloat ramp = myExtra.map.fpd - myExtra.map.bpd;
952     const GLfloat fog_start = myFog.Front * ramp - myExtra.map.fpd;
953     const GLfloat fog_end   = myFog.Back  * ramp - myExtra.map.fpd;
954
955     glFogi(GL_FOG_MODE, GL_LINEAR);
956     glFogf(GL_FOG_START, fog_start);
957     glFogf(GL_FOG_END, fog_end);
958     glFogfv(GL_FOG_COLOR, myFog.Color.rgb);
959     glEnable(GL_FOG);
960   }
961   else
962     glDisable(GL_FOG);
963
964   // Apply Lights
965   {
966     int i;
967
968     // Switch off all lights
969     for (i = GL_LIGHT0; i <= GL_LIGHT7; i++)
970       glDisable(i);
971     glLightModelfv(GL_LIGHT_MODEL_AMBIENT, default_amb);
972
973     /* set les lights */
974     int gl_lid = GL_LIGHT0;
975     OpenGl_ListOfLight::Iterator itl(myLights);
976     for (; itl.More(); itl.Next())
977     {
978       const OpenGl_Light &alight = itl.Value();
979       bind_light(&alight, &gl_lid);
980     }
981
982     if (gl_lid != GL_LIGHT0) glEnable(GL_LIGHTING);
983   }
984
985   // Apply InteriorShadingMethod
986   glShadeModel( myIntShadingMethod == TEL_SM_FLAT ? GL_FLAT : GL_SMOOTH );
987
988   // Apply clipping planes
989   {
990     // Define starting plane id
991     planeid = GL_CLIP_PLANE0;
992
993     GLdouble equation[4];
994
995     if ( myZClip.Back.IsOn || myZClip.Front.IsOn )
996     {
997       // Apply front and back clipping planes
998       GLfloat mat[4][4];
999       glMatrixMode( GL_MODELVIEW );
1000       glGetFloatv( GL_MODELVIEW_MATRIX,(GLfloat *) mat );
1001       glLoadIdentity();
1002
1003       const GLdouble ramp = myExtra.map.fpd - myExtra.map.bpd;
1004
1005       if ( myZClip.Back.IsOn )
1006       {
1007         const GLdouble back = ramp * myZClip.Back.Limit + myExtra.map.bpd;
1008         equation[0] = 0.0;  /* Nx */
1009         equation[1] = 0.0;  /* Ny */
1010         equation[2] = 1.0;  /* Nz */
1011         equation[3] = -back; /* P dot N */
1012         glClipPlane( planeid, equation );
1013         glEnable( planeid );
1014         planeid++;
1015       }
1016
1017       if ( myZClip.Front.IsOn )
1018       {
1019         const GLdouble front = ramp * myZClip.Front.Limit + myExtra.map.bpd;
1020         equation[0] = 0.0;  /* Nx */
1021         equation[1] = 0.0;  /* Ny */
1022         equation[2] = -1.0; /* Nz */
1023         equation[3] = front; /* P dot N */
1024         glClipPlane( planeid, equation );
1025         glEnable( planeid );
1026         planeid++;
1027       }
1028
1029       glLoadMatrixf( (GLfloat *) mat );
1030     }
1031
1032     // Apply user clipping planes
1033     NCollection_List<OPENGL_CLIP_REP>::Iterator planeIter(myClippingPlanes);
1034     for ( ; planeIter.More(); planeIter.Next() )
1035     {
1036       glClipPlane( planeid, planeIter.Value().equation );
1037       glEnable( planeid );
1038       planeid++;
1039     }
1040   }
1041
1042   // Apply AntiAliasing
1043   {
1044     if (myAntiAliasing)
1045       AWorkspace->NamedStatus |= OPENGL_NS_ANTIALIASING;
1046         else
1047       AWorkspace->NamedStatus &= ~OPENGL_NS_ANTIALIASING;
1048   }
1049
1050   // Clear status bitfields
1051   AWorkspace->NamedStatus &= ~(OPENGL_NS_2NDPASSNEED | OPENGL_NS_2NDPASSDO);
1052
1053   // Added PCT for handling of textures
1054   switch (mySurfaceDetail)
1055   {
1056     case Visual3d_TOD_NONE:
1057       AWorkspace->NamedStatus |= OPENGL_NS_FORBIDSETTEX;
1058       AWorkspace->DisableTexture();
1059       // Render the view
1060       RenderStructs(AWorkspace);
1061       break;
1062
1063     case Visual3d_TOD_ENVIRONMENT:
1064       AWorkspace->NamedStatus |= OPENGL_NS_FORBIDSETTEX;
1065       AWorkspace->EnableTexture (myTextureEnv);
1066       // Render the view
1067       RenderStructs(AWorkspace);
1068       AWorkspace->DisableTexture();
1069       break;
1070
1071     case Visual3d_TOD_ALL:
1072       // First pass
1073       AWorkspace->NamedStatus &= ~OPENGL_NS_FORBIDSETTEX;
1074       // Render the view
1075       RenderStructs(AWorkspace);
1076       AWorkspace->DisableTexture();
1077
1078       // Second pass
1079       if (AWorkspace->NamedStatus & OPENGL_NS_2NDPASSNEED)
1080       {
1081         AWorkspace->NamedStatus |= OPENGL_NS_2NDPASSDO;
1082         AWorkspace->EnableTexture (myTextureEnv);
1083
1084         /* sauvegarde de quelques parametres OpenGL */
1085         GLint blend_dst, blend_src;
1086         GLint zbuff_f;
1087         GLboolean zbuff_w;
1088         glGetBooleanv(GL_DEPTH_WRITEMASK, &zbuff_w);
1089         glGetIntegerv(GL_DEPTH_FUNC, &zbuff_f);
1090         glGetIntegerv(GL_BLEND_DST, &blend_dst);
1091         glGetIntegerv(GL_BLEND_SRC, &blend_src);
1092         GLboolean zbuff_state = glIsEnabled(GL_DEPTH_TEST);
1093         GLboolean blend_state = glIsEnabled(GL_BLEND);
1094
1095         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1096         glEnable(GL_BLEND);
1097
1098         glDepthFunc(GL_EQUAL);
1099         glDepthMask(GL_FALSE);
1100         glEnable(GL_DEPTH_TEST);
1101
1102         AWorkspace->NamedStatus |= OPENGL_NS_FORBIDSETTEX;
1103
1104         // Render the view
1105         RenderStructs(AWorkspace);
1106         AWorkspace->DisableTexture();
1107
1108         /* restauration des parametres OpenGL */
1109         glBlendFunc(blend_src, blend_dst);
1110         if (!blend_state) glDisable(GL_BLEND);
1111
1112         glDepthFunc(zbuff_f);
1113         glDepthMask(zbuff_w);
1114         if (!zbuff_state) glDisable(GL_DEPTH_FUNC);
1115       }
1116       break;
1117   }
1118
1119   // Resetting GL parameters according to the default aspects
1120   // in order to synchronize GL state with the graphic driver state
1121   // before drawing auxiliary stuff (trihedrons, overlayer)
1122   // and invoking optional callbacks
1123   AWorkspace->ResetAppliedAspect();
1124
1125   // Disable current clipping planes
1126   for ( planeid = GL_CLIP_PLANE0; planeid < lastid; planeid++ )
1127     glDisable( planeid );
1128
1129   // display global trihedron
1130   if (myTrihedron != NULL)
1131   {
1132     myTrihedron->Render (AWorkspace);
1133   }
1134   if (myGraduatedTrihedron != NULL)
1135   {
1136     myGraduatedTrihedron->Render (AWorkspace);
1137   }
1138
1139   // Restore face culling
1140   if ( myBackfacing )
1141   {
1142     if ( isCullFace )
1143     {
1144       glEnable   ( GL_CULL_FACE );
1145       glCullFace ( GL_BACK      );
1146     }
1147     else
1148       glDisable ( GL_CULL_FACE );
1149   }
1150
1151   /////////////////////////////////////////////////////////////////////////////
1152   // Step 6: Draw overlayer
1153   const int aMode = 0;
1154   AWorkspace->DisplayCallback (ACView, (aMode | OCC_PRE_OVERLAY));
1155
1156   RedrawLayer2d (thePrintContext, AWorkspace, ACView, ACOverLayer);
1157
1158   AWorkspace->DisplayCallback (ACView, aMode);
1159
1160   // Restore clipping planes
1161   for ( ptrPlane = oldPlanes, planeid = GL_CLIP_PLANE0; planeid < lastid; planeid++, ptrPlane++ )
1162   {
1163     glClipPlane( planeid, ptrPlane->Equation );
1164     if ( ptrPlane->isEnabled )
1165       glEnable( planeid );
1166     else
1167       glDisable( planeid );
1168   }
1169   delete[] oldPlanes;
1170 }
1171
1172 /*----------------------------------------------------------------------*/
1173
1174 //ExecuteViewDisplay
1175 void OpenGl_View::RenderStructs (const Handle(OpenGl_Workspace) &AWorkspace)
1176 {
1177   if ( myZLayers.NbStructures() <= 0 )
1178     return;
1179
1180   glPushAttrib ( GL_DEPTH_BUFFER_BIT );
1181
1182   //TsmPushAttri(); /* save previous graphics context */
1183
1184   if ( (AWorkspace->NamedStatus & OPENGL_NS_2NDPASSNEED) == 0 )
1185   {
1186     const int antiAliasingMode = AWorkspace->GetDisplay()->AntiAliasingMode();
1187
1188     if ( !myAntiAliasing )
1189     {
1190       glDisable(GL_POINT_SMOOTH);
1191       glDisable(GL_LINE_SMOOTH);
1192       if( antiAliasingMode & 2 ) glDisable(GL_POLYGON_SMOOTH);
1193       glBlendFunc (GL_ONE, GL_ZERO);
1194       glDisable (GL_BLEND);
1195     }
1196     else
1197     {
1198       glEnable(GL_POINT_SMOOTH);
1199       glEnable(GL_LINE_SMOOTH);
1200       if( antiAliasingMode & 2 ) glEnable(GL_POLYGON_SMOOTH);
1201       glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1202       glEnable (GL_BLEND);
1203     }
1204   }
1205
1206   myZLayers.Render (AWorkspace);
1207
1208   //TsmPopAttri(); /* restore previous graphics context; before update lights */
1209   glPopAttrib();
1210 }
1211
1212 /*----------------------------------------------------------------------*/
1213
1214 //call_togl_redraw_layer2d
1215 void OpenGl_View::RedrawLayer2d (const Handle(OpenGl_PrinterContext)& thePrintContext,
1216                                  const Handle(OpenGl_Workspace)&      /*AWorkspace*/,
1217                                  const Graphic3d_CView&               ACView,
1218                                  const Aspect_CLayer2d&               ACLayer)
1219 {
1220   if (&ACLayer == NULL
1221    || ACLayer.ptrLayer == NULL
1222    || ACLayer.ptrLayer->listIndex == 0) return;
1223
1224   GLsizei dispWidth  = (GLsizei )ACLayer.viewport[0];
1225   GLsizei dispHeight = (GLsizei )ACLayer.viewport[1];
1226
1227   glMatrixMode( GL_MODELVIEW );
1228   glPushMatrix ();
1229   glLoadIdentity ();
1230
1231   glMatrixMode (GL_PROJECTION);
1232   glPushMatrix ();
1233   glLoadIdentity ();
1234
1235   if (!ACLayer.sizeDependent)
1236     glViewport (0, 0, dispWidth, dispHeight);
1237
1238   float left = ACLayer.ortho[0];
1239   float right = ACLayer.ortho[1];
1240   float bottom = ACLayer.ortho[2];
1241   float top = ACLayer.ortho[3];
1242
1243   int attach = ACLayer.attach;
1244
1245   float ratio;
1246   if (!ACLayer.sizeDependent)
1247     ratio = (float) dispWidth/dispHeight;
1248   else
1249     ratio = ACView.DefWindow.dx/ACView.DefWindow.dy;
1250
1251   float delta;
1252   if (ratio >= 1.0) {
1253     delta = (float )((top - bottom)/2.0);
1254     switch (attach) {
1255       case 0: /* Aspect_TOC_BOTTOM_LEFT */
1256         top = bottom + 2*delta/ratio;
1257         break;
1258       case 1: /* Aspect_TOC_BOTTOM_RIGHT */
1259         top = bottom + 2*delta/ratio;
1260         break;
1261       case 2: /* Aspect_TOC_TOP_LEFT */
1262         bottom = top - 2*delta/ratio;
1263         break;
1264       case 3: /* Aspect_TOC_TOP_RIGHT */
1265         bottom = top - 2*delta/ratio;
1266         break;
1267     }
1268   }
1269   else {
1270     delta = (float )((right - left)/2.0);
1271     switch (attach) {
1272       case 0: /* Aspect_TOC_BOTTOM_LEFT */
1273         right = left + 2*delta*ratio;
1274         break;
1275       case 1: /* Aspect_TOC_BOTTOM_RIGHT */
1276         left = right - 2*delta*ratio;
1277         break;
1278       case 2: /* Aspect_TOC_TOP_LEFT */
1279         right = left + 2*delta*ratio;
1280         break;
1281       case 3: /* Aspect_TOC_TOP_RIGHT */
1282         left = right - 2*delta*ratio;
1283         break;
1284     }
1285   }
1286
1287 #ifdef _WIN32
1288   // Check printer context that exists only for print operation
1289   if (!thePrintContext.IsNull())
1290   {
1291     // additional transformation matrix could be applied to
1292     // render only those parts of viewport that will be
1293     // passed to a printer as a current "frame" to provide
1294     // tiling; scaling of graphics by matrix helps render a
1295     // part of a view (frame) in same viewport, but with higher
1296     // resolution
1297     thePrintContext->LoadProjTransformation();
1298
1299     // printing operation also assumes other viewport dimension
1300     // to comply with transformation matrix or graphics scaling
1301     // factors for tiling for layer redraw
1302     GLsizei anViewportX = 0;
1303     GLsizei anViewportY = 0;
1304     thePrintContext->GetLayerViewport (anViewportX, anViewportY);
1305     if (anViewportX != 0 && anViewportY != 0)
1306       glViewport (0, 0, anViewportX, anViewportY);
1307   }
1308 #endif
1309
1310   glOrtho (left, right, bottom, top, -1.0, 1.0);
1311
1312   glPushAttrib (
1313     GL_LIGHTING_BIT | GL_LINE_BIT | GL_POLYGON_BIT |
1314     GL_DEPTH_BUFFER_BIT | GL_CURRENT_BIT | GL_TEXTURE_BIT );
1315
1316   glDisable (GL_DEPTH_TEST);
1317   glDisable (GL_TEXTURE_1D);
1318   glDisable (GL_TEXTURE_2D);
1319   glDisable (GL_LIGHTING);
1320
1321   // TODO: Obsolete code, the display list is always empty now, to be removed
1322   glCallList (ACLayer.ptrLayer->listIndex);
1323
1324   //calling dynamic render of LayerItems
1325   if ( ACLayer.ptrLayer->layerData )
1326   {
1327     InitLayerProp(ACLayer.ptrLayer->listIndex);
1328     ((Visual3d_Layer*)ACLayer.ptrLayer->layerData)->RenderLayerItems();
1329     InitLayerProp(0);
1330   }
1331
1332   glPopAttrib ();
1333
1334   glMatrixMode (GL_PROJECTION);
1335   glPopMatrix ();
1336
1337   glMatrixMode( GL_MODELVIEW );
1338   glPopMatrix ();
1339
1340   if (!ACLayer.sizeDependent)
1341     glViewport (0, 0, (GLsizei) ACView.DefWindow.dx, (GLsizei) ACView.DefWindow.dy);
1342
1343   glFlush ();
1344 }
1345
1346 /*----------------------------------------------------------------------*/
1347
1348 //call_togl_create_bg_texture
1349 void OpenGl_View::CreateBackgroundTexture (const Standard_CString  theFilePath,
1350                                            const Aspect_FillMethod theFillStyle)
1351 {
1352   if (myBgTexture.TexId != 0)
1353   {
1354     // delete existing texture
1355     glDeleteTextures (1, (GLuint* )&(myBgTexture.TexId));
1356     myBgTexture.TexId = 0;
1357   }
1358
1359   // load image from file
1360   Image_AlienPixMap anImageLoaded;
1361   if (!anImageLoaded.Load (theFilePath))
1362   {
1363     return;
1364   }
1365
1366   Image_PixMap anImage;
1367   if (anImageLoaded.RowExtraBytes() == 0 &&
1368       (anImageLoaded.Format() == Image_PixMap::ImgRGB
1369     || anImageLoaded.Format() == Image_PixMap::ImgRGB32
1370     || anImageLoaded.Format() == Image_PixMap::ImgRGBA))
1371   {
1372     anImage.InitWrapper (anImageLoaded.Format(), anImageLoaded.ChangeData(),
1373                          anImageLoaded.SizeX(), anImageLoaded.SizeY(), anImageLoaded.SizeRowBytes());
1374   }
1375   else
1376   {
1377     // convert image to RGB format
1378     if (!anImage.InitTrash (Image_PixMap::ImgRGB, anImageLoaded.SizeX(), anImageLoaded.SizeY()))
1379     {
1380       return;
1381     }
1382
1383     anImage.SetTopDown (false);
1384     Image_PixMapData<Image_ColorRGB>& aDataNew = anImage.EditData<Image_ColorRGB>();
1385     Quantity_Color aSrcColor;
1386     for (Standard_Size aRow = 0; aRow < anImage.SizeY(); ++aRow)
1387     {
1388       for (Standard_Size aCol = 0; aCol < anImage.SizeX(); ++aCol)
1389       {
1390         aSrcColor = anImageLoaded.PixelColor ((Standard_Integer )aCol, (Standard_Integer )aRow);
1391         Image_ColorRGB& aColor = aDataNew.ChangeValue (aRow, aCol);
1392         aColor.r() = Standard_Byte(255.0 * aSrcColor.Red());
1393         aColor.g() = Standard_Byte(255.0 * aSrcColor.Green());
1394         aColor.b() = Standard_Byte(255.0 * aSrcColor.Blue());
1395       }
1396     }
1397     anImageLoaded.Clear();
1398   }
1399
1400   // create MipMapped texture
1401   glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
1402
1403   GLuint aTextureId = 0;
1404   glGenTextures (1, &aTextureId);
1405   glBindTexture (GL_TEXTURE_2D, aTextureId);
1406
1407   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,     GL_REPEAT);
1408   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,     GL_REPEAT);
1409   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
1410   glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
1411
1412   const GLenum aDataFormat = (anImage.Format() == Image_PixMap::ImgRGB) ? GL_RGB : GL_RGBA;
1413   gluBuild2DMipmaps (GL_TEXTURE_2D, 3/*4*/,
1414                      GLint(anImage.SizeX()), GLint(anImage.SizeY()),
1415                      aDataFormat, GL_UNSIGNED_BYTE, anImage.Data());
1416
1417   myBgTexture.TexId  = aTextureId;
1418   myBgTexture.Width  = (Standard_Integer )anImage.SizeX();
1419   myBgTexture.Height = (Standard_Integer )anImage.SizeY();
1420   myBgTexture.Style  = theFillStyle;
1421 }
1422
1423 /*----------------------------------------------------------------------*/
1424
1425 //call_togl_set_bg_texture_style
1426 void OpenGl_View::SetBackgroundTextureStyle (const Aspect_FillMethod AFillStyle)
1427 {
1428   myBgTexture.Style = AFillStyle;
1429 }
1430
1431 /*----------------------------------------------------------------------*/
1432
1433 //call_togl_gradient_background
1434 void OpenGl_View::SetBackgroundGradient (const Quantity_Color& AColor1,
1435                                         const Quantity_Color& AColor2,
1436                                         const Aspect_GradientFillMethod AType)
1437 {
1438   Standard_Real R,G,B;
1439   AColor1.Values( R, G, B, Quantity_TOC_RGB );
1440   myBgGradient.color1.rgb[0] = ( Tfloat )R;
1441   myBgGradient.color1.rgb[1] = ( Tfloat )G;
1442   myBgGradient.color1.rgb[2] = ( Tfloat )B;
1443   myBgGradient.color1.rgb[3] = 0.F;
1444
1445   AColor2.Values( R, G, B, Quantity_TOC_RGB );
1446   myBgGradient.color2.rgb[0] = ( Tfloat )R;
1447   myBgGradient.color2.rgb[1] = ( Tfloat )G;
1448   myBgGradient.color2.rgb[2] = ( Tfloat )B;
1449   myBgGradient.color2.rgb[3] = 0.F;
1450
1451   myBgGradient.type = AType;
1452 }
1453
1454 /*----------------------------------------------------------------------*/
1455
1456 //call_togl_set_gradient_type
1457 void OpenGl_View::SetBackgroundGradientType (const Aspect_GradientFillMethod AType)
1458 {
1459   myBgGradient.type = AType;
1460 }
1461
1462 //=======================================================================
1463 //function : AddZLayer
1464 //purpose  :
1465 //=======================================================================
1466
1467 void OpenGl_View::AddZLayer (const Standard_Integer theLayerId)
1468 {
1469   myZLayers.AddLayer (theLayerId);
1470 }
1471
1472 //=======================================================================
1473 //function : RemoveZLayer
1474 //purpose  :
1475 //=======================================================================
1476
1477 void OpenGl_View::RemoveZLayer (const Standard_Integer theLayerId)
1478 {
1479   myZLayers.RemoveLayer (theLayerId);
1480 }
1481
1482 //=======================================================================
1483 //function : DisplayStructure
1484 //purpose  :
1485 //=======================================================================
1486
1487 void OpenGl_View::DisplayStructure (const OpenGl_Structure *theStructure,
1488                                     const Standard_Integer  thePriority)
1489 {
1490   Standard_Integer aZLayer = theStructure->GetZLayer ();
1491   myZLayers.AddStructure (theStructure, aZLayer, thePriority);
1492 }
1493
1494 //=======================================================================
1495 //function : EraseStructure
1496 //purpose  :
1497 //=======================================================================
1498
1499 void OpenGl_View::EraseStructure (const OpenGl_Structure *theStructure)
1500 {
1501   Standard_Integer aZLayer = theStructure->GetZLayer ();
1502   myZLayers.RemoveStructure (theStructure, aZLayer);
1503 }
1504
1505 //=======================================================================
1506 //function : ChangeZLayer
1507 //purpose  :
1508 //=======================================================================
1509
1510 void OpenGl_View::ChangeZLayer (const OpenGl_Structure *theStructure,
1511                                 const Standard_Integer  theNewLayerId)
1512 {
1513   Standard_Integer anOldLayer = theStructure->GetZLayer ();
1514   myZLayers.ChangeLayer (theStructure, anOldLayer, theNewLayerId);
1515 }