1/*
2 * Mesa 3-D graphics library
3 *
4 * Copyright (C) 1999-2005  Brian Paul   All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included
14 * in all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22 * OTHER DEALINGS IN THE SOFTWARE.
23 */
24
25
26/**
27 * \file m_matrix.c
28 * Matrix operations.
29 *
30 * \note
31 * -# 4x4 transformation matrices are stored in memory in column major order.
32 * -# Points/vertices are to be thought of as column vectors.
33 * -# Transformation of a point p by a matrix M is: p' = M * p
34 */
35
36
37#include "c99_math.h"
38#include "main/errors.h"
39#include "main/glheader.h"
40#include "main/imports.h"
41#include "main/macros.h"
42
43#include "m_matrix.h"
44
45
46/**
47 * \defgroup MatFlags MAT_FLAG_XXX-flags
48 *
49 * Bitmasks to indicate different kinds of 4x4 matrices in GLmatrix::flags
50 */
51/*@{*/
52#define MAT_FLAG_IDENTITY       0     /**< is an identity matrix flag.
53                                       *   (Not actually used - the identity
54                                       *   matrix is identified by the absence
55                                       *   of all other flags.)
56                                       */
57#define MAT_FLAG_GENERAL        0x1   /**< is a general matrix flag */
58#define MAT_FLAG_ROTATION       0x2   /**< is a rotation matrix flag */
59#define MAT_FLAG_TRANSLATION    0x4   /**< is a translation matrix flag */
60#define MAT_FLAG_UNIFORM_SCALE  0x8   /**< is an uniform scaling matrix flag */
61#define MAT_FLAG_GENERAL_SCALE  0x10  /**< is a general scaling matrix flag */
62#define MAT_FLAG_GENERAL_3D     0x20  /**< general 3D matrix flag */
63#define MAT_FLAG_PERSPECTIVE    0x40  /**< is a perspective proj matrix flag */
64#define MAT_FLAG_SINGULAR       0x80  /**< is a singular matrix flag */
65#define MAT_DIRTY_TYPE          0x100  /**< matrix type is dirty */
66#define MAT_DIRTY_FLAGS         0x200  /**< matrix flags are dirty */
67#define MAT_DIRTY_INVERSE       0x400  /**< matrix inverse is dirty */
68
69/** angle preserving matrix flags mask */
70#define MAT_FLAGS_ANGLE_PRESERVING (MAT_FLAG_ROTATION | \
71				    MAT_FLAG_TRANSLATION | \
72				    MAT_FLAG_UNIFORM_SCALE)
73
74/** geometry related matrix flags mask */
75#define MAT_FLAGS_GEOMETRY (MAT_FLAG_GENERAL | \
76			    MAT_FLAG_ROTATION | \
77			    MAT_FLAG_TRANSLATION | \
78			    MAT_FLAG_UNIFORM_SCALE | \
79			    MAT_FLAG_GENERAL_SCALE | \
80			    MAT_FLAG_GENERAL_3D | \
81			    MAT_FLAG_PERSPECTIVE | \
82	                    MAT_FLAG_SINGULAR)
83
84/** length preserving matrix flags mask */
85#define MAT_FLAGS_LENGTH_PRESERVING (MAT_FLAG_ROTATION | \
86				     MAT_FLAG_TRANSLATION)
87
88
89/** 3D (non-perspective) matrix flags mask */
90#define MAT_FLAGS_3D (MAT_FLAG_ROTATION | \
91		      MAT_FLAG_TRANSLATION | \
92		      MAT_FLAG_UNIFORM_SCALE | \
93		      MAT_FLAG_GENERAL_SCALE | \
94		      MAT_FLAG_GENERAL_3D)
95
96/** dirty matrix flags mask */
97#define MAT_DIRTY          (MAT_DIRTY_TYPE | \
98			    MAT_DIRTY_FLAGS | \
99			    MAT_DIRTY_INVERSE)
100
101/*@}*/
102
103
104/**
105 * Test geometry related matrix flags.
106 *
107 * \param mat a pointer to a GLmatrix structure.
108 * \param a flags mask.
109 *
110 * \returns non-zero if all geometry related matrix flags are contained within
111 * the mask, or zero otherwise.
112 */
113#define TEST_MAT_FLAGS(mat, a)  \
114    ((MAT_FLAGS_GEOMETRY & (~(a)) & ((mat)->flags) ) == 0)
115
116
117
118/**
119 * Names of the corresponding GLmatrixtype values.
120 */
121static const char *types[] = {
122   "MATRIX_GENERAL",
123   "MATRIX_IDENTITY",
124   "MATRIX_3D_NO_ROT",
125   "MATRIX_PERSPECTIVE",
126   "MATRIX_2D",
127   "MATRIX_2D_NO_ROT",
128   "MATRIX_3D"
129};
130
131
132/**
133 * Identity matrix.
134 */
135static const GLfloat Identity[16] = {
136   1.0, 0.0, 0.0, 0.0,
137   0.0, 1.0, 0.0, 0.0,
138   0.0, 0.0, 1.0, 0.0,
139   0.0, 0.0, 0.0, 1.0
140};
141
142
143
144/**********************************************************************/
145/** \name Matrix multiplication */
146/*@{*/
147
148#define A(row,col)  a[(col<<2)+row]
149#define B(row,col)  b[(col<<2)+row]
150#define P(row,col)  product[(col<<2)+row]
151
152/**
153 * Perform a full 4x4 matrix multiplication.
154 *
155 * \param a matrix.
156 * \param b matrix.
157 * \param product will receive the product of \p a and \p b.
158 *
159 * \warning Is assumed that \p product != \p b. \p product == \p a is allowed.
160 *
161 * \note KW: 4*16 = 64 multiplications
162 *
163 * \author This \c matmul was contributed by Thomas Malik
164 */
165static void matmul4( GLfloat *product, const GLfloat *a, const GLfloat *b )
166{
167   GLint i;
168   for (i = 0; i < 4; i++) {
169      const GLfloat ai0=A(i,0),  ai1=A(i,1),  ai2=A(i,2),  ai3=A(i,3);
170      P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0) + ai3 * B(3,0);
171      P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1) + ai3 * B(3,1);
172      P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2) + ai3 * B(3,2);
173      P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3 * B(3,3);
174   }
175}
176
177/**
178 * Multiply two matrices known to occupy only the top three rows, such
179 * as typical model matrices, and orthogonal matrices.
180 *
181 * \param a matrix.
182 * \param b matrix.
183 * \param product will receive the product of \p a and \p b.
184 */
185static void matmul34( GLfloat *product, const GLfloat *a, const GLfloat *b )
186{
187   GLint i;
188   for (i = 0; i < 3; i++) {
189      const GLfloat ai0=A(i,0),  ai1=A(i,1),  ai2=A(i,2),  ai3=A(i,3);
190      P(i,0) = ai0 * B(0,0) + ai1 * B(1,0) + ai2 * B(2,0);
191      P(i,1) = ai0 * B(0,1) + ai1 * B(1,1) + ai2 * B(2,1);
192      P(i,2) = ai0 * B(0,2) + ai1 * B(1,2) + ai2 * B(2,2);
193      P(i,3) = ai0 * B(0,3) + ai1 * B(1,3) + ai2 * B(2,3) + ai3;
194   }
195   P(3,0) = 0;
196   P(3,1) = 0;
197   P(3,2) = 0;
198   P(3,3) = 1;
199}
200
201#undef A
202#undef B
203#undef P
204
205/**
206 * Multiply a matrix by an array of floats with known properties.
207 *
208 * \param mat pointer to a GLmatrix structure containing the left multiplication
209 * matrix, and that will receive the product result.
210 * \param m right multiplication matrix array.
211 * \param flags flags of the matrix \p m.
212 *
213 * Joins both flags and marks the type and inverse as dirty.  Calls matmul34()
214 * if both matrices are 3D, or matmul4() otherwise.
215 */
216static void matrix_multf( GLmatrix *mat, const GLfloat *m, GLuint flags )
217{
218   mat->flags |= (flags | MAT_DIRTY_TYPE | MAT_DIRTY_INVERSE);
219
220   if (TEST_MAT_FLAGS(mat, MAT_FLAGS_3D))
221      matmul34( mat->m, mat->m, m );
222   else
223      matmul4( mat->m, mat->m, m );
224}
225
226/**
227 * Matrix multiplication.
228 *
229 * \param dest destination matrix.
230 * \param a left matrix.
231 * \param b right matrix.
232 *
233 * Joins both flags and marks the type and inverse as dirty.  Calls matmul34()
234 * if both matrices are 3D, or matmul4() otherwise.
235 */
236void
237_math_matrix_mul_matrix( GLmatrix *dest, const GLmatrix *a, const GLmatrix *b )
238{
239   dest->flags = (a->flags |
240		  b->flags |
241		  MAT_DIRTY_TYPE |
242		  MAT_DIRTY_INVERSE);
243
244   if (TEST_MAT_FLAGS(dest, MAT_FLAGS_3D))
245      matmul34( dest->m, a->m, b->m );
246   else
247      matmul4( dest->m, a->m, b->m );
248}
249
250/**
251 * Matrix multiplication.
252 *
253 * \param dest left and destination matrix.
254 * \param m right matrix array.
255 *
256 * Marks the matrix flags with general flag, and type and inverse dirty flags.
257 * Calls matmul4() for the multiplication.
258 */
259void
260_math_matrix_mul_floats( GLmatrix *dest, const GLfloat *m )
261{
262   dest->flags |= (MAT_FLAG_GENERAL |
263		   MAT_DIRTY_TYPE |
264		   MAT_DIRTY_INVERSE |
265                   MAT_DIRTY_FLAGS);
266
267   matmul4( dest->m, dest->m, m );
268}
269
270/*@}*/
271
272
273/**********************************************************************/
274/** \name Matrix output */
275/*@{*/
276
277/**
278 * Print a matrix array.
279 *
280 * \param m matrix array.
281 *
282 * Called by _math_matrix_print() to print a matrix or its inverse.
283 */
284static void print_matrix_floats( const GLfloat m[16] )
285{
286   int i;
287   for (i=0;i<4;i++) {
288      _mesa_debug(NULL,"\t%f %f %f %f\n", m[i], m[4+i], m[8+i], m[12+i] );
289   }
290}
291
292/**
293 * Dumps the contents of a GLmatrix structure.
294 *
295 * \param m pointer to the GLmatrix structure.
296 */
297void
298_math_matrix_print( const GLmatrix *m )
299{
300   GLfloat prod[16];
301
302   _mesa_debug(NULL, "Matrix type: %s, flags: %x\n", types[m->type], m->flags);
303   print_matrix_floats(m->m);
304   _mesa_debug(NULL, "Inverse: \n");
305   print_matrix_floats(m->inv);
306   matmul4(prod, m->m, m->inv);
307   _mesa_debug(NULL, "Mat * Inverse:\n");
308   print_matrix_floats(prod);
309}
310
311/*@}*/
312
313
314/**
315 * References an element of 4x4 matrix.
316 *
317 * \param m matrix array.
318 * \param c column of the desired element.
319 * \param r row of the desired element.
320 *
321 * \return value of the desired element.
322 *
323 * Calculate the linear storage index of the element and references it.
324 */
325#define MAT(m,r,c) (m)[(c)*4+(r)]
326
327
328/**********************************************************************/
329/** \name Matrix inversion */
330/*@{*/
331
332/**
333 * Swaps the values of two floating point variables.
334 *
335 * Used by invert_matrix_general() to swap the row pointers.
336 */
337#define SWAP_ROWS(a, b) { GLfloat *_tmp = a; (a)=(b); (b)=_tmp; }
338
339/**
340 * Compute inverse of 4x4 transformation matrix.
341 *
342 * \param mat pointer to a GLmatrix structure. The matrix inverse will be
343 * stored in the GLmatrix::inv attribute.
344 *
345 * \return GL_TRUE for success, GL_FALSE for failure (\p singular matrix).
346 *
347 * \author
348 * Code contributed by Jacques Leroy jle@star.be
349 *
350 * Calculates the inverse matrix by performing the gaussian matrix reduction
351 * with partial pivoting followed by back/substitution with the loops manually
352 * unrolled.
353 */
354static GLboolean invert_matrix_general( GLmatrix *mat )
355{
356   const GLfloat *m = mat->m;
357   GLfloat *out = mat->inv;
358   GLfloat wtmp[4][8];
359   GLfloat m0, m1, m2, m3, s;
360   GLfloat *r0, *r1, *r2, *r3;
361
362   r0 = wtmp[0], r1 = wtmp[1], r2 = wtmp[2], r3 = wtmp[3];
363
364   r0[0] = MAT(m,0,0), r0[1] = MAT(m,0,1),
365   r0[2] = MAT(m,0,2), r0[3] = MAT(m,0,3),
366   r0[4] = 1.0, r0[5] = r0[6] = r0[7] = 0.0,
367
368   r1[0] = MAT(m,1,0), r1[1] = MAT(m,1,1),
369   r1[2] = MAT(m,1,2), r1[3] = MAT(m,1,3),
370   r1[5] = 1.0, r1[4] = r1[6] = r1[7] = 0.0,
371
372   r2[0] = MAT(m,2,0), r2[1] = MAT(m,2,1),
373   r2[2] = MAT(m,2,2), r2[3] = MAT(m,2,3),
374   r2[6] = 1.0, r2[4] = r2[5] = r2[7] = 0.0,
375
376   r3[0] = MAT(m,3,0), r3[1] = MAT(m,3,1),
377   r3[2] = MAT(m,3,2), r3[3] = MAT(m,3,3),
378   r3[7] = 1.0, r3[4] = r3[5] = r3[6] = 0.0;
379
380   /* choose pivot - or die */
381   if (fabsf(r3[0])>fabsf(r2[0])) SWAP_ROWS(r3, r2);
382   if (fabsf(r2[0])>fabsf(r1[0])) SWAP_ROWS(r2, r1);
383   if (fabsf(r1[0])>fabsf(r0[0])) SWAP_ROWS(r1, r0);
384   if (0.0F == r0[0])  return GL_FALSE;
385
386   /* eliminate first variable     */
387   m1 = r1[0]/r0[0]; m2 = r2[0]/r0[0]; m3 = r3[0]/r0[0];
388   s = r0[1]; r1[1] -= m1 * s; r2[1] -= m2 * s; r3[1] -= m3 * s;
389   s = r0[2]; r1[2] -= m1 * s; r2[2] -= m2 * s; r3[2] -= m3 * s;
390   s = r0[3]; r1[3] -= m1 * s; r2[3] -= m2 * s; r3[3] -= m3 * s;
391   s = r0[4];
392   if (s != 0.0F) { r1[4] -= m1 * s; r2[4] -= m2 * s; r3[4] -= m3 * s; }
393   s = r0[5];
394   if (s != 0.0F) { r1[5] -= m1 * s; r2[5] -= m2 * s; r3[5] -= m3 * s; }
395   s = r0[6];
396   if (s != 0.0F) { r1[6] -= m1 * s; r2[6] -= m2 * s; r3[6] -= m3 * s; }
397   s = r0[7];
398   if (s != 0.0F) { r1[7] -= m1 * s; r2[7] -= m2 * s; r3[7] -= m3 * s; }
399
400   /* choose pivot - or die */
401   if (fabsf(r3[1])>fabsf(r2[1])) SWAP_ROWS(r3, r2);
402   if (fabsf(r2[1])>fabsf(r1[1])) SWAP_ROWS(r2, r1);
403   if (0.0F == r1[1])  return GL_FALSE;
404
405   /* eliminate second variable */
406   m2 = r2[1]/r1[1]; m3 = r3[1]/r1[1];
407   r2[2] -= m2 * r1[2]; r3[2] -= m3 * r1[2];
408   r2[3] -= m2 * r1[3]; r3[3] -= m3 * r1[3];
409   s = r1[4]; if (0.0F != s) { r2[4] -= m2 * s; r3[4] -= m3 * s; }
410   s = r1[5]; if (0.0F != s) { r2[5] -= m2 * s; r3[5] -= m3 * s; }
411   s = r1[6]; if (0.0F != s) { r2[6] -= m2 * s; r3[6] -= m3 * s; }
412   s = r1[7]; if (0.0F != s) { r2[7] -= m2 * s; r3[7] -= m3 * s; }
413
414   /* choose pivot - or die */
415   if (fabsf(r3[2])>fabsf(r2[2])) SWAP_ROWS(r3, r2);
416   if (0.0F == r2[2])  return GL_FALSE;
417
418   /* eliminate third variable */
419   m3 = r3[2]/r2[2];
420   r3[3] -= m3 * r2[3], r3[4] -= m3 * r2[4],
421   r3[5] -= m3 * r2[5], r3[6] -= m3 * r2[6],
422   r3[7] -= m3 * r2[7];
423
424   /* last check */
425   if (0.0F == r3[3]) return GL_FALSE;
426
427   s = 1.0F/r3[3];             /* now back substitute row 3 */
428   r3[4] *= s; r3[5] *= s; r3[6] *= s; r3[7] *= s;
429
430   m2 = r2[3];                 /* now back substitute row 2 */
431   s  = 1.0F/r2[2];
432   r2[4] = s * (r2[4] - r3[4] * m2), r2[5] = s * (r2[5] - r3[5] * m2),
433   r2[6] = s * (r2[6] - r3[6] * m2), r2[7] = s * (r2[7] - r3[7] * m2);
434   m1 = r1[3];
435   r1[4] -= r3[4] * m1, r1[5] -= r3[5] * m1,
436   r1[6] -= r3[6] * m1, r1[7] -= r3[7] * m1;
437   m0 = r0[3];
438   r0[4] -= r3[4] * m0, r0[5] -= r3[5] * m0,
439   r0[6] -= r3[6] * m0, r0[7] -= r3[7] * m0;
440
441   m1 = r1[2];                 /* now back substitute row 1 */
442   s  = 1.0F/r1[1];
443   r1[4] = s * (r1[4] - r2[4] * m1), r1[5] = s * (r1[5] - r2[5] * m1),
444   r1[6] = s * (r1[6] - r2[6] * m1), r1[7] = s * (r1[7] - r2[7] * m1);
445   m0 = r0[2];
446   r0[4] -= r2[4] * m0, r0[5] -= r2[5] * m0,
447   r0[6] -= r2[6] * m0, r0[7] -= r2[7] * m0;
448
449   m0 = r0[1];                 /* now back substitute row 0 */
450   s  = 1.0F/r0[0];
451   r0[4] = s * (r0[4] - r1[4] * m0), r0[5] = s * (r0[5] - r1[5] * m0),
452   r0[6] = s * (r0[6] - r1[6] * m0), r0[7] = s * (r0[7] - r1[7] * m0);
453
454   MAT(out,0,0) = r0[4]; MAT(out,0,1) = r0[5],
455   MAT(out,0,2) = r0[6]; MAT(out,0,3) = r0[7],
456   MAT(out,1,0) = r1[4]; MAT(out,1,1) = r1[5],
457   MAT(out,1,2) = r1[6]; MAT(out,1,3) = r1[7],
458   MAT(out,2,0) = r2[4]; MAT(out,2,1) = r2[5],
459   MAT(out,2,2) = r2[6]; MAT(out,2,3) = r2[7],
460   MAT(out,3,0) = r3[4]; MAT(out,3,1) = r3[5],
461   MAT(out,3,2) = r3[6]; MAT(out,3,3) = r3[7];
462
463   return GL_TRUE;
464}
465#undef SWAP_ROWS
466
467/**
468 * Compute inverse of a general 3d transformation matrix.
469 *
470 * \param mat pointer to a GLmatrix structure. The matrix inverse will be
471 * stored in the GLmatrix::inv attribute.
472 *
473 * \return GL_TRUE for success, GL_FALSE for failure (\p singular matrix).
474 *
475 * \author Adapted from graphics gems II.
476 *
477 * Calculates the inverse of the upper left by first calculating its
478 * determinant and multiplying it to the symmetric adjust matrix of each
479 * element. Finally deals with the translation part by transforming the
480 * original translation vector using by the calculated submatrix inverse.
481 */
482static GLboolean invert_matrix_3d_general( GLmatrix *mat )
483{
484   const GLfloat *in = mat->m;
485   GLfloat *out = mat->inv;
486   GLfloat pos, neg, t;
487   GLfloat det;
488
489   /* Calculate the determinant of upper left 3x3 submatrix and
490    * determine if the matrix is singular.
491    */
492   pos = neg = 0.0;
493   t =  MAT(in,0,0) * MAT(in,1,1) * MAT(in,2,2);
494   if (t >= 0.0F) pos += t; else neg += t;
495
496   t =  MAT(in,1,0) * MAT(in,2,1) * MAT(in,0,2);
497   if (t >= 0.0F) pos += t; else neg += t;
498
499   t =  MAT(in,2,0) * MAT(in,0,1) * MAT(in,1,2);
500   if (t >= 0.0F) pos += t; else neg += t;
501
502   t = -MAT(in,2,0) * MAT(in,1,1) * MAT(in,0,2);
503   if (t >= 0.0F) pos += t; else neg += t;
504
505   t = -MAT(in,1,0) * MAT(in,0,1) * MAT(in,2,2);
506   if (t >= 0.0F) pos += t; else neg += t;
507
508   t = -MAT(in,0,0) * MAT(in,2,1) * MAT(in,1,2);
509   if (t >= 0.0F) pos += t; else neg += t;
510
511   det = pos + neg;
512
513   if (fabsf(det) < 1e-25F)
514      return GL_FALSE;
515
516   det = 1.0F / det;
517   MAT(out,0,0) = (  (MAT(in,1,1)*MAT(in,2,2) - MAT(in,2,1)*MAT(in,1,2) )*det);
518   MAT(out,0,1) = (- (MAT(in,0,1)*MAT(in,2,2) - MAT(in,2,1)*MAT(in,0,2) )*det);
519   MAT(out,0,2) = (  (MAT(in,0,1)*MAT(in,1,2) - MAT(in,1,1)*MAT(in,0,2) )*det);
520   MAT(out,1,0) = (- (MAT(in,1,0)*MAT(in,2,2) - MAT(in,2,0)*MAT(in,1,2) )*det);
521   MAT(out,1,1) = (  (MAT(in,0,0)*MAT(in,2,2) - MAT(in,2,0)*MAT(in,0,2) )*det);
522   MAT(out,1,2) = (- (MAT(in,0,0)*MAT(in,1,2) - MAT(in,1,0)*MAT(in,0,2) )*det);
523   MAT(out,2,0) = (  (MAT(in,1,0)*MAT(in,2,1) - MAT(in,2,0)*MAT(in,1,1) )*det);
524   MAT(out,2,1) = (- (MAT(in,0,0)*MAT(in,2,1) - MAT(in,2,0)*MAT(in,0,1) )*det);
525   MAT(out,2,2) = (  (MAT(in,0,0)*MAT(in,1,1) - MAT(in,1,0)*MAT(in,0,1) )*det);
526
527   /* Do the translation part */
528   MAT(out,0,3) = - (MAT(in,0,3) * MAT(out,0,0) +
529		     MAT(in,1,3) * MAT(out,0,1) +
530		     MAT(in,2,3) * MAT(out,0,2) );
531   MAT(out,1,3) = - (MAT(in,0,3) * MAT(out,1,0) +
532		     MAT(in,1,3) * MAT(out,1,1) +
533		     MAT(in,2,3) * MAT(out,1,2) );
534   MAT(out,2,3) = - (MAT(in,0,3) * MAT(out,2,0) +
535		     MAT(in,1,3) * MAT(out,2,1) +
536		     MAT(in,2,3) * MAT(out,2,2) );
537
538   return GL_TRUE;
539}
540
541/**
542 * Compute inverse of a 3d transformation matrix.
543 *
544 * \param mat pointer to a GLmatrix structure. The matrix inverse will be
545 * stored in the GLmatrix::inv attribute.
546 *
547 * \return GL_TRUE for success, GL_FALSE for failure (\p singular matrix).
548 *
549 * If the matrix is not an angle preserving matrix then calls
550 * invert_matrix_3d_general for the actual calculation. Otherwise calculates
551 * the inverse matrix analyzing and inverting each of the scaling, rotation and
552 * translation parts.
553 */
554static GLboolean invert_matrix_3d( GLmatrix *mat )
555{
556   const GLfloat *in = mat->m;
557   GLfloat *out = mat->inv;
558
559   if (!TEST_MAT_FLAGS(mat, MAT_FLAGS_ANGLE_PRESERVING)) {
560      return invert_matrix_3d_general( mat );
561   }
562
563   if (mat->flags & MAT_FLAG_UNIFORM_SCALE) {
564      GLfloat scale = (MAT(in,0,0) * MAT(in,0,0) +
565                       MAT(in,0,1) * MAT(in,0,1) +
566                       MAT(in,0,2) * MAT(in,0,2));
567
568      if (scale == 0.0F)
569         return GL_FALSE;
570
571      scale = 1.0F / scale;
572
573      /* Transpose and scale the 3 by 3 upper-left submatrix. */
574      MAT(out,0,0) = scale * MAT(in,0,0);
575      MAT(out,1,0) = scale * MAT(in,0,1);
576      MAT(out,2,0) = scale * MAT(in,0,2);
577      MAT(out,0,1) = scale * MAT(in,1,0);
578      MAT(out,1,1) = scale * MAT(in,1,1);
579      MAT(out,2,1) = scale * MAT(in,1,2);
580      MAT(out,0,2) = scale * MAT(in,2,0);
581      MAT(out,1,2) = scale * MAT(in,2,1);
582      MAT(out,2,2) = scale * MAT(in,2,2);
583   }
584   else if (mat->flags & MAT_FLAG_ROTATION) {
585      /* Transpose the 3 by 3 upper-left submatrix. */
586      MAT(out,0,0) = MAT(in,0,0);
587      MAT(out,1,0) = MAT(in,0,1);
588      MAT(out,2,0) = MAT(in,0,2);
589      MAT(out,0,1) = MAT(in,1,0);
590      MAT(out,1,1) = MAT(in,1,1);
591      MAT(out,2,1) = MAT(in,1,2);
592      MAT(out,0,2) = MAT(in,2,0);
593      MAT(out,1,2) = MAT(in,2,1);
594      MAT(out,2,2) = MAT(in,2,2);
595   }
596   else {
597      /* pure translation */
598      memcpy( out, Identity, sizeof(Identity) );
599      MAT(out,0,3) = - MAT(in,0,3);
600      MAT(out,1,3) = - MAT(in,1,3);
601      MAT(out,2,3) = - MAT(in,2,3);
602      return GL_TRUE;
603   }
604
605   if (mat->flags & MAT_FLAG_TRANSLATION) {
606      /* Do the translation part */
607      MAT(out,0,3) = - (MAT(in,0,3) * MAT(out,0,0) +
608			MAT(in,1,3) * MAT(out,0,1) +
609			MAT(in,2,3) * MAT(out,0,2) );
610      MAT(out,1,3) = - (MAT(in,0,3) * MAT(out,1,0) +
611			MAT(in,1,3) * MAT(out,1,1) +
612			MAT(in,2,3) * MAT(out,1,2) );
613      MAT(out,2,3) = - (MAT(in,0,3) * MAT(out,2,0) +
614			MAT(in,1,3) * MAT(out,2,1) +
615			MAT(in,2,3) * MAT(out,2,2) );
616   }
617   else {
618      MAT(out,0,3) = MAT(out,1,3) = MAT(out,2,3) = 0.0;
619   }
620
621   return GL_TRUE;
622}
623
624/**
625 * Compute inverse of an identity transformation matrix.
626 *
627 * \param mat pointer to a GLmatrix structure. The matrix inverse will be
628 * stored in the GLmatrix::inv attribute.
629 *
630 * \return always GL_TRUE.
631 *
632 * Simply copies Identity into GLmatrix::inv.
633 */
634static GLboolean invert_matrix_identity( GLmatrix *mat )
635{
636   memcpy( mat->inv, Identity, sizeof(Identity) );
637   return GL_TRUE;
638}
639
640/**
641 * Compute inverse of a no-rotation 3d transformation matrix.
642 *
643 * \param mat pointer to a GLmatrix structure. The matrix inverse will be
644 * stored in the GLmatrix::inv attribute.
645 *
646 * \return GL_TRUE for success, GL_FALSE for failure (\p singular matrix).
647 *
648 * Calculates the
649 */
650static GLboolean invert_matrix_3d_no_rot( GLmatrix *mat )
651{
652   const GLfloat *in = mat->m;
653   GLfloat *out = mat->inv;
654
655   if (MAT(in,0,0) == 0 || MAT(in,1,1) == 0 || MAT(in,2,2) == 0 )
656      return GL_FALSE;
657
658   memcpy( out, Identity, sizeof(Identity) );
659   MAT(out,0,0) = 1.0F / MAT(in,0,0);
660   MAT(out,1,1) = 1.0F / MAT(in,1,1);
661   MAT(out,2,2) = 1.0F / MAT(in,2,2);
662
663   if (mat->flags & MAT_FLAG_TRANSLATION) {
664      MAT(out,0,3) = - (MAT(in,0,3) * MAT(out,0,0));
665      MAT(out,1,3) = - (MAT(in,1,3) * MAT(out,1,1));
666      MAT(out,2,3) = - (MAT(in,2,3) * MAT(out,2,2));
667   }
668
669   return GL_TRUE;
670}
671
672/**
673 * Compute inverse of a no-rotation 2d transformation matrix.
674 *
675 * \param mat pointer to a GLmatrix structure. The matrix inverse will be
676 * stored in the GLmatrix::inv attribute.
677 *
678 * \return GL_TRUE for success, GL_FALSE for failure (\p singular matrix).
679 *
680 * Calculates the inverse matrix by applying the inverse scaling and
681 * translation to the identity matrix.
682 */
683static GLboolean invert_matrix_2d_no_rot( GLmatrix *mat )
684{
685   const GLfloat *in = mat->m;
686   GLfloat *out = mat->inv;
687
688   if (MAT(in,0,0) == 0 || MAT(in,1,1) == 0)
689      return GL_FALSE;
690
691   memcpy( out, Identity, sizeof(Identity) );
692   MAT(out,0,0) = 1.0F / MAT(in,0,0);
693   MAT(out,1,1) = 1.0F / MAT(in,1,1);
694
695   if (mat->flags & MAT_FLAG_TRANSLATION) {
696      MAT(out,0,3) = - (MAT(in,0,3) * MAT(out,0,0));
697      MAT(out,1,3) = - (MAT(in,1,3) * MAT(out,1,1));
698   }
699
700   return GL_TRUE;
701}
702
703#if 0
704/* broken */
705static GLboolean invert_matrix_perspective( GLmatrix *mat )
706{
707   const GLfloat *in = mat->m;
708   GLfloat *out = mat->inv;
709
710   if (MAT(in,2,3) == 0)
711      return GL_FALSE;
712
713   memcpy( out, Identity, sizeof(Identity) );
714
715   MAT(out,0,0) = 1.0F / MAT(in,0,0);
716   MAT(out,1,1) = 1.0F / MAT(in,1,1);
717
718   MAT(out,0,3) = MAT(in,0,2);
719   MAT(out,1,3) = MAT(in,1,2);
720
721   MAT(out,2,2) = 0;
722   MAT(out,2,3) = -1;
723
724   MAT(out,3,2) = 1.0F / MAT(in,2,3);
725   MAT(out,3,3) = MAT(in,2,2) * MAT(out,3,2);
726
727   return GL_TRUE;
728}
729#endif
730
731/**
732 * Matrix inversion function pointer type.
733 */
734typedef GLboolean (*inv_mat_func)( GLmatrix *mat );
735
736/**
737 * Table of the matrix inversion functions according to the matrix type.
738 */
739static inv_mat_func inv_mat_tab[7] = {
740   invert_matrix_general,
741   invert_matrix_identity,
742   invert_matrix_3d_no_rot,
743#if 0
744   /* Don't use this function for now - it fails when the projection matrix
745    * is premultiplied by a translation (ala Chromium's tilesort SPU).
746    */
747   invert_matrix_perspective,
748#else
749   invert_matrix_general,
750#endif
751   invert_matrix_3d,		/* lazy! */
752   invert_matrix_2d_no_rot,
753   invert_matrix_3d
754};
755
756/**
757 * Compute inverse of a transformation matrix.
758 *
759 * \param mat pointer to a GLmatrix structure. The matrix inverse will be
760 * stored in the GLmatrix::inv attribute.
761 *
762 * \return GL_TRUE for success, GL_FALSE for failure (\p singular matrix).
763 *
764 * Calls the matrix inversion function in inv_mat_tab corresponding to the
765 * given matrix type.  In case of failure, updates the MAT_FLAG_SINGULAR flag,
766 * and copies the identity matrix into GLmatrix::inv.
767 */
768static GLboolean matrix_invert( GLmatrix *mat )
769{
770   if (inv_mat_tab[mat->type](mat)) {
771      mat->flags &= ~MAT_FLAG_SINGULAR;
772      return GL_TRUE;
773   } else {
774      mat->flags |= MAT_FLAG_SINGULAR;
775      memcpy( mat->inv, Identity, sizeof(Identity) );
776      return GL_FALSE;
777   }
778}
779
780/*@}*/
781
782
783/**********************************************************************/
784/** \name Matrix generation */
785/*@{*/
786
787/**
788 * Generate a 4x4 transformation matrix from glRotate parameters, and
789 * post-multiply the input matrix by it.
790 *
791 * \author
792 * This function was contributed by Erich Boleyn (erich@uruk.org).
793 * Optimizations contributed by Rudolf Opalla (rudi@khm.de).
794 */
795void
796_math_matrix_rotate( GLmatrix *mat,
797		     GLfloat angle, GLfloat x, GLfloat y, GLfloat z )
798{
799   GLfloat xx, yy, zz, xy, yz, zx, xs, ys, zs, one_c, s, c;
800   GLfloat m[16];
801   GLboolean optimized;
802
803   s = sinf( angle * M_PI / 180.0 );
804   c = cosf( angle * M_PI / 180.0 );
805
806   memcpy(m, Identity, sizeof(Identity));
807   optimized = GL_FALSE;
808
809#define M(row,col)  m[col*4+row]
810
811   if (x == 0.0F) {
812      if (y == 0.0F) {
813         if (z != 0.0F) {
814            optimized = GL_TRUE;
815            /* rotate only around z-axis */
816            M(0,0) = c;
817            M(1,1) = c;
818            if (z < 0.0F) {
819               M(0,1) = s;
820               M(1,0) = -s;
821            }
822            else {
823               M(0,1) = -s;
824               M(1,0) = s;
825            }
826         }
827      }
828      else if (z == 0.0F) {
829         optimized = GL_TRUE;
830         /* rotate only around y-axis */
831         M(0,0) = c;
832         M(2,2) = c;
833         if (y < 0.0F) {
834            M(0,2) = -s;
835            M(2,0) = s;
836         }
837         else {
838            M(0,2) = s;
839            M(2,0) = -s;
840         }
841      }
842   }
843   else if (y == 0.0F) {
844      if (z == 0.0F) {
845         optimized = GL_TRUE;
846         /* rotate only around x-axis */
847         M(1,1) = c;
848         M(2,2) = c;
849         if (x < 0.0F) {
850            M(1,2) = s;
851            M(2,1) = -s;
852         }
853         else {
854            M(1,2) = -s;
855            M(2,1) = s;
856         }
857      }
858   }
859
860   if (!optimized) {
861      const GLfloat mag = sqrtf(x * x + y * y + z * z);
862
863      if (mag <= 1.0e-4F) {
864         /* no rotation, leave mat as-is */
865         return;
866      }
867
868      x /= mag;
869      y /= mag;
870      z /= mag;
871
872
873      /*
874       *     Arbitrary axis rotation matrix.
875       *
876       *  This is composed of 5 matrices, Rz, Ry, T, Ry', Rz', multiplied
877       *  like so:  Rz * Ry * T * Ry' * Rz'.  T is the final rotation
878       *  (which is about the X-axis), and the two composite transforms
879       *  Ry' * Rz' and Rz * Ry are (respectively) the rotations necessary
880       *  from the arbitrary axis to the X-axis then back.  They are
881       *  all elementary rotations.
882       *
883       *  Rz' is a rotation about the Z-axis, to bring the axis vector
884       *  into the x-z plane.  Then Ry' is applied, rotating about the
885       *  Y-axis to bring the axis vector parallel with the X-axis.  The
886       *  rotation about the X-axis is then performed.  Ry and Rz are
887       *  simply the respective inverse transforms to bring the arbitrary
888       *  axis back to its original orientation.  The first transforms
889       *  Rz' and Ry' are considered inverses, since the data from the
890       *  arbitrary axis gives you info on how to get to it, not how
891       *  to get away from it, and an inverse must be applied.
892       *
893       *  The basic calculation used is to recognize that the arbitrary
894       *  axis vector (x, y, z), since it is of unit length, actually
895       *  represents the sines and cosines of the angles to rotate the
896       *  X-axis to the same orientation, with theta being the angle about
897       *  Z and phi the angle about Y (in the order described above)
898       *  as follows:
899       *
900       *  cos ( theta ) = x / sqrt ( 1 - z^2 )
901       *  sin ( theta ) = y / sqrt ( 1 - z^2 )
902       *
903       *  cos ( phi ) = sqrt ( 1 - z^2 )
904       *  sin ( phi ) = z
905       *
906       *  Note that cos ( phi ) can further be inserted to the above
907       *  formulas:
908       *
909       *  cos ( theta ) = x / cos ( phi )
910       *  sin ( theta ) = y / sin ( phi )
911       *
912       *  ...etc.  Because of those relations and the standard trigonometric
913       *  relations, it is pssible to reduce the transforms down to what
914       *  is used below.  It may be that any primary axis chosen will give the
915       *  same results (modulo a sign convention) using thie method.
916       *
917       *  Particularly nice is to notice that all divisions that might
918       *  have caused trouble when parallel to certain planes or
919       *  axis go away with care paid to reducing the expressions.
920       *  After checking, it does perform correctly under all cases, since
921       *  in all the cases of division where the denominator would have
922       *  been zero, the numerator would have been zero as well, giving
923       *  the expected result.
924       */
925
926      xx = x * x;
927      yy = y * y;
928      zz = z * z;
929      xy = x * y;
930      yz = y * z;
931      zx = z * x;
932      xs = x * s;
933      ys = y * s;
934      zs = z * s;
935      one_c = 1.0F - c;
936
937      /* We already hold the identity-matrix so we can skip some statements */
938      M(0,0) = (one_c * xx) + c;
939      M(0,1) = (one_c * xy) - zs;
940      M(0,2) = (one_c * zx) + ys;
941/*    M(0,3) = 0.0F; */
942
943      M(1,0) = (one_c * xy) + zs;
944      M(1,1) = (one_c * yy) + c;
945      M(1,2) = (one_c * yz) - xs;
946/*    M(1,3) = 0.0F; */
947
948      M(2,0) = (one_c * zx) - ys;
949      M(2,1) = (one_c * yz) + xs;
950      M(2,2) = (one_c * zz) + c;
951/*    M(2,3) = 0.0F; */
952
953/*
954      M(3,0) = 0.0F;
955      M(3,1) = 0.0F;
956      M(3,2) = 0.0F;
957      M(3,3) = 1.0F;
958*/
959   }
960#undef M
961
962   matrix_multf( mat, m, MAT_FLAG_ROTATION );
963}
964
965/**
966 * Apply a perspective projection matrix.
967 *
968 * \param mat matrix to apply the projection.
969 * \param left left clipping plane coordinate.
970 * \param right right clipping plane coordinate.
971 * \param bottom bottom clipping plane coordinate.
972 * \param top top clipping plane coordinate.
973 * \param nearval distance to the near clipping plane.
974 * \param farval distance to the far clipping plane.
975 *
976 * Creates the projection matrix and multiplies it with \p mat, marking the
977 * MAT_FLAG_PERSPECTIVE flag.
978 */
979void
980_math_matrix_frustum( GLmatrix *mat,
981		      GLfloat left, GLfloat right,
982		      GLfloat bottom, GLfloat top,
983		      GLfloat nearval, GLfloat farval )
984{
985   GLfloat x, y, a, b, c, d;
986   GLfloat m[16];
987
988   x = (2.0F*nearval) / (right-left);
989   y = (2.0F*nearval) / (top-bottom);
990   a = (right+left) / (right-left);
991   b = (top+bottom) / (top-bottom);
992   c = -(farval+nearval) / ( farval-nearval);
993   d = -(2.0F*farval*nearval) / (farval-nearval);  /* error? */
994
995#define M(row,col)  m[col*4+row]
996   M(0,0) = x;     M(0,1) = 0.0F;  M(0,2) = a;      M(0,3) = 0.0F;
997   M(1,0) = 0.0F;  M(1,1) = y;     M(1,2) = b;      M(1,3) = 0.0F;
998   M(2,0) = 0.0F;  M(2,1) = 0.0F;  M(2,2) = c;      M(2,3) = d;
999   M(3,0) = 0.0F;  M(3,1) = 0.0F;  M(3,2) = -1.0F;  M(3,3) = 0.0F;
1000#undef M
1001
1002   matrix_multf( mat, m, MAT_FLAG_PERSPECTIVE );
1003}
1004
1005/**
1006 * Apply an orthographic projection matrix.
1007 *
1008 * \param mat matrix to apply the projection.
1009 * \param left left clipping plane coordinate.
1010 * \param right right clipping plane coordinate.
1011 * \param bottom bottom clipping plane coordinate.
1012 * \param top top clipping plane coordinate.
1013 * \param nearval distance to the near clipping plane.
1014 * \param farval distance to the far clipping plane.
1015 *
1016 * Creates the projection matrix and multiplies it with \p mat, marking the
1017 * MAT_FLAG_GENERAL_SCALE and MAT_FLAG_TRANSLATION flags.
1018 */
1019void
1020_math_matrix_ortho( GLmatrix *mat,
1021		    GLfloat left, GLfloat right,
1022		    GLfloat bottom, GLfloat top,
1023		    GLfloat nearval, GLfloat farval )
1024{
1025   GLfloat m[16];
1026
1027#define M(row,col)  m[col*4+row]
1028   M(0,0) = 2.0F / (right-left);
1029   M(0,1) = 0.0F;
1030   M(0,2) = 0.0F;
1031   M(0,3) = -(right+left) / (right-left);
1032
1033   M(1,0) = 0.0F;
1034   M(1,1) = 2.0F / (top-bottom);
1035   M(1,2) = 0.0F;
1036   M(1,3) = -(top+bottom) / (top-bottom);
1037
1038   M(2,0) = 0.0F;
1039   M(2,1) = 0.0F;
1040   M(2,2) = -2.0F / (farval-nearval);
1041   M(2,3) = -(farval+nearval) / (farval-nearval);
1042
1043   M(3,0) = 0.0F;
1044   M(3,1) = 0.0F;
1045   M(3,2) = 0.0F;
1046   M(3,3) = 1.0F;
1047#undef M
1048
1049   matrix_multf( mat, m, (MAT_FLAG_GENERAL_SCALE|MAT_FLAG_TRANSLATION));
1050}
1051
1052/**
1053 * Multiply a matrix with a general scaling matrix.
1054 *
1055 * \param mat matrix.
1056 * \param x x axis scale factor.
1057 * \param y y axis scale factor.
1058 * \param z z axis scale factor.
1059 *
1060 * Multiplies in-place the elements of \p mat by the scale factors. Checks if
1061 * the scales factors are roughly the same, marking the MAT_FLAG_UNIFORM_SCALE
1062 * flag, or MAT_FLAG_GENERAL_SCALE. Marks the MAT_DIRTY_TYPE and
1063 * MAT_DIRTY_INVERSE dirty flags.
1064 */
1065void
1066_math_matrix_scale( GLmatrix *mat, GLfloat x, GLfloat y, GLfloat z )
1067{
1068   GLfloat *m = mat->m;
1069   m[0] *= x;   m[4] *= y;   m[8]  *= z;
1070   m[1] *= x;   m[5] *= y;   m[9]  *= z;
1071   m[2] *= x;   m[6] *= y;   m[10] *= z;
1072   m[3] *= x;   m[7] *= y;   m[11] *= z;
1073
1074   if (fabsf(x - y) < 1e-8F && fabsf(x - z) < 1e-8F)
1075      mat->flags |= MAT_FLAG_UNIFORM_SCALE;
1076   else
1077      mat->flags |= MAT_FLAG_GENERAL_SCALE;
1078
1079   mat->flags |= (MAT_DIRTY_TYPE |
1080		  MAT_DIRTY_INVERSE);
1081}
1082
1083/**
1084 * Multiply a matrix with a translation matrix.
1085 *
1086 * \param mat matrix.
1087 * \param x translation vector x coordinate.
1088 * \param y translation vector y coordinate.
1089 * \param z translation vector z coordinate.
1090 *
1091 * Adds the translation coordinates to the elements of \p mat in-place.  Marks
1092 * the MAT_FLAG_TRANSLATION flag, and the MAT_DIRTY_TYPE and MAT_DIRTY_INVERSE
1093 * dirty flags.
1094 */
1095void
1096_math_matrix_translate( GLmatrix *mat, GLfloat x, GLfloat y, GLfloat z )
1097{
1098   GLfloat *m = mat->m;
1099   m[12] = m[0] * x + m[4] * y + m[8]  * z + m[12];
1100   m[13] = m[1] * x + m[5] * y + m[9]  * z + m[13];
1101   m[14] = m[2] * x + m[6] * y + m[10] * z + m[14];
1102   m[15] = m[3] * x + m[7] * y + m[11] * z + m[15];
1103
1104   mat->flags |= (MAT_FLAG_TRANSLATION |
1105		  MAT_DIRTY_TYPE |
1106		  MAT_DIRTY_INVERSE);
1107}
1108
1109
1110/**
1111 * Set matrix to do viewport and depthrange mapping.
1112 * Transforms Normalized Device Coords to window/Z values.
1113 */
1114void
1115_math_matrix_viewport(GLmatrix *m, const float scale[3],
1116                      const float translate[3], double depthMax)
1117{
1118   m->m[MAT_SX] = scale[0];
1119   m->m[MAT_TX] = translate[0];
1120   m->m[MAT_SY] = scale[1];
1121   m->m[MAT_TY] = translate[1];
1122   m->m[MAT_SZ] = depthMax*scale[2];
1123   m->m[MAT_TZ] = depthMax*translate[2];
1124   m->flags = MAT_FLAG_GENERAL_SCALE | MAT_FLAG_TRANSLATION;
1125   m->type = MATRIX_3D_NO_ROT;
1126}
1127
1128
1129/**
1130 * Set a matrix to the identity matrix.
1131 *
1132 * \param mat matrix.
1133 *
1134 * Copies ::Identity into \p GLmatrix::m, and into GLmatrix::inv if not NULL.
1135 * Sets the matrix type to identity, and clear the dirty flags.
1136 */
1137void
1138_math_matrix_set_identity( GLmatrix *mat )
1139{
1140   memcpy( mat->m, Identity, sizeof(Identity) );
1141   memcpy( mat->inv, Identity, sizeof(Identity) );
1142
1143   mat->type = MATRIX_IDENTITY;
1144   mat->flags &= ~(MAT_DIRTY_FLAGS|
1145		   MAT_DIRTY_TYPE|
1146		   MAT_DIRTY_INVERSE);
1147}
1148
1149/*@}*/
1150
1151
1152/**********************************************************************/
1153/** \name Matrix analysis */
1154/*@{*/
1155
1156#define ZERO(x) (1<<x)
1157#define ONE(x)  (1<<(x+16))
1158
1159#define MASK_NO_TRX      (ZERO(12) | ZERO(13) | ZERO(14))
1160#define MASK_NO_2D_SCALE ( ONE(0)  | ONE(5))
1161
1162#define MASK_IDENTITY    ( ONE(0)  | ZERO(4)  | ZERO(8)  | ZERO(12) |\
1163			  ZERO(1)  |  ONE(5)  | ZERO(9)  | ZERO(13) |\
1164			  ZERO(2)  | ZERO(6)  |  ONE(10) | ZERO(14) |\
1165			  ZERO(3)  | ZERO(7)  | ZERO(11) |  ONE(15) )
1166
1167#define MASK_2D_NO_ROT   (           ZERO(4)  | ZERO(8)  |           \
1168			  ZERO(1)  |            ZERO(9)  |           \
1169			  ZERO(2)  | ZERO(6)  |  ONE(10) | ZERO(14) |\
1170			  ZERO(3)  | ZERO(7)  | ZERO(11) |  ONE(15) )
1171
1172#define MASK_2D          (                      ZERO(8)  |           \
1173			                        ZERO(9)  |           \
1174			  ZERO(2)  | ZERO(6)  |  ONE(10) | ZERO(14) |\
1175			  ZERO(3)  | ZERO(7)  | ZERO(11) |  ONE(15) )
1176
1177
1178#define MASK_3D_NO_ROT   (           ZERO(4)  | ZERO(8)  |           \
1179			  ZERO(1)  |            ZERO(9)  |           \
1180			  ZERO(2)  | ZERO(6)  |                      \
1181			  ZERO(3)  | ZERO(7)  | ZERO(11) |  ONE(15) )
1182
1183#define MASK_3D          (                                           \
1184			                                             \
1185			                                             \
1186			  ZERO(3)  | ZERO(7)  | ZERO(11) |  ONE(15) )
1187
1188
1189#define MASK_PERSPECTIVE (           ZERO(4)  |            ZERO(12) |\
1190			  ZERO(1)  |                       ZERO(13) |\
1191			  ZERO(2)  | ZERO(6)  |                      \
1192			  ZERO(3)  | ZERO(7)  |            ZERO(15) )
1193
1194#define SQ(x) ((x)*(x))
1195
1196/**
1197 * Determine type and flags from scratch.
1198 *
1199 * \param mat matrix.
1200 *
1201 * This is expensive enough to only want to do it once.
1202 */
1203static void analyse_from_scratch( GLmatrix *mat )
1204{
1205   const GLfloat *m = mat->m;
1206   GLuint mask = 0;
1207   GLuint i;
1208
1209   for (i = 0 ; i < 16 ; i++) {
1210      if (m[i] == 0.0F) mask |= (1<<i);
1211   }
1212
1213   if (m[0] == 1.0F) mask |= (1<<16);
1214   if (m[5] == 1.0F) mask |= (1<<21);
1215   if (m[10] == 1.0F) mask |= (1<<26);
1216   if (m[15] == 1.0F) mask |= (1<<31);
1217
1218   mat->flags &= ~MAT_FLAGS_GEOMETRY;
1219
1220   /* Check for translation - no-one really cares
1221    */
1222   if ((mask & MASK_NO_TRX) != MASK_NO_TRX)
1223      mat->flags |= MAT_FLAG_TRANSLATION;
1224
1225   /* Do the real work
1226    */
1227   if (mask == (GLuint) MASK_IDENTITY) {
1228      mat->type = MATRIX_IDENTITY;
1229   }
1230   else if ((mask & MASK_2D_NO_ROT) == (GLuint) MASK_2D_NO_ROT) {
1231      mat->type = MATRIX_2D_NO_ROT;
1232
1233      if ((mask & MASK_NO_2D_SCALE) != MASK_NO_2D_SCALE)
1234	 mat->flags |= MAT_FLAG_GENERAL_SCALE;
1235   }
1236   else if ((mask & MASK_2D) == (GLuint) MASK_2D) {
1237      GLfloat mm = DOT2(m, m);
1238      GLfloat m4m4 = DOT2(m+4,m+4);
1239      GLfloat mm4 = DOT2(m,m+4);
1240
1241      mat->type = MATRIX_2D;
1242
1243      /* Check for scale */
1244      if (SQ(mm-1) > SQ(1e-6F) ||
1245	  SQ(m4m4-1) > SQ(1e-6F))
1246	 mat->flags |= MAT_FLAG_GENERAL_SCALE;
1247
1248      /* Check for rotation */
1249      if (SQ(mm4) > SQ(1e-6F))
1250	 mat->flags |= MAT_FLAG_GENERAL_3D;
1251      else
1252	 mat->flags |= MAT_FLAG_ROTATION;
1253
1254   }
1255   else if ((mask & MASK_3D_NO_ROT) == (GLuint) MASK_3D_NO_ROT) {
1256      mat->type = MATRIX_3D_NO_ROT;
1257
1258      /* Check for scale */
1259      if (SQ(m[0]-m[5]) < SQ(1e-6F) &&
1260	  SQ(m[0]-m[10]) < SQ(1e-6F)) {
1261	 if (SQ(m[0]-1.0F) > SQ(1e-6F)) {
1262	    mat->flags |= MAT_FLAG_UNIFORM_SCALE;
1263         }
1264      }
1265      else {
1266	 mat->flags |= MAT_FLAG_GENERAL_SCALE;
1267      }
1268   }
1269   else if ((mask & MASK_3D) == (GLuint) MASK_3D) {
1270      GLfloat c1 = DOT3(m,m);
1271      GLfloat c2 = DOT3(m+4,m+4);
1272      GLfloat c3 = DOT3(m+8,m+8);
1273      GLfloat d1 = DOT3(m, m+4);
1274      GLfloat cp[3];
1275
1276      mat->type = MATRIX_3D;
1277
1278      /* Check for scale */
1279      if (SQ(c1-c2) < SQ(1e-6F) && SQ(c1-c3) < SQ(1e-6F)) {
1280	 if (SQ(c1-1.0F) > SQ(1e-6F))
1281	    mat->flags |= MAT_FLAG_UNIFORM_SCALE;
1282	 /* else no scale at all */
1283      }
1284      else {
1285	 mat->flags |= MAT_FLAG_GENERAL_SCALE;
1286      }
1287
1288      /* Check for rotation */
1289      if (SQ(d1) < SQ(1e-6F)) {
1290	 CROSS3( cp, m, m+4 );
1291	 SUB_3V( cp, cp, (m+8) );
1292	 if (LEN_SQUARED_3FV(cp) < SQ(1e-6F))
1293	    mat->flags |= MAT_FLAG_ROTATION;
1294	 else
1295	    mat->flags |= MAT_FLAG_GENERAL_3D;
1296      }
1297      else {
1298	 mat->flags |= MAT_FLAG_GENERAL_3D; /* shear, etc */
1299      }
1300   }
1301   else if ((mask & MASK_PERSPECTIVE) == MASK_PERSPECTIVE && m[11]==-1.0F) {
1302      mat->type = MATRIX_PERSPECTIVE;
1303      mat->flags |= MAT_FLAG_GENERAL;
1304   }
1305   else {
1306      mat->type = MATRIX_GENERAL;
1307      mat->flags |= MAT_FLAG_GENERAL;
1308   }
1309}
1310
1311/**
1312 * Analyze a matrix given that its flags are accurate.
1313 *
1314 * This is the more common operation, hopefully.
1315 */
1316static void analyse_from_flags( GLmatrix *mat )
1317{
1318   const GLfloat *m = mat->m;
1319
1320   if (TEST_MAT_FLAGS(mat, 0)) {
1321      mat->type = MATRIX_IDENTITY;
1322   }
1323   else if (TEST_MAT_FLAGS(mat, (MAT_FLAG_TRANSLATION |
1324				 MAT_FLAG_UNIFORM_SCALE |
1325				 MAT_FLAG_GENERAL_SCALE))) {
1326      if ( m[10]==1.0F && m[14]==0.0F ) {
1327	 mat->type = MATRIX_2D_NO_ROT;
1328      }
1329      else {
1330	 mat->type = MATRIX_3D_NO_ROT;
1331      }
1332   }
1333   else if (TEST_MAT_FLAGS(mat, MAT_FLAGS_3D)) {
1334      if (                                 m[ 8]==0.0F
1335            &&                             m[ 9]==0.0F
1336            && m[2]==0.0F && m[6]==0.0F && m[10]==1.0F && m[14]==0.0F) {
1337	 mat->type = MATRIX_2D;
1338      }
1339      else {
1340	 mat->type = MATRIX_3D;
1341      }
1342   }
1343   else if (                 m[4]==0.0F                 && m[12]==0.0F
1344            && m[1]==0.0F                               && m[13]==0.0F
1345            && m[2]==0.0F && m[6]==0.0F
1346            && m[3]==0.0F && m[7]==0.0F && m[11]==-1.0F && m[15]==0.0F) {
1347      mat->type = MATRIX_PERSPECTIVE;
1348   }
1349   else {
1350      mat->type = MATRIX_GENERAL;
1351   }
1352}
1353
1354/**
1355 * Analyze and update a matrix.
1356 *
1357 * \param mat matrix.
1358 *
1359 * If the matrix type is dirty then calls either analyse_from_scratch() or
1360 * analyse_from_flags() to determine its type, according to whether the flags
1361 * are dirty or not, respectively. If the matrix has an inverse and it's dirty
1362 * then calls matrix_invert(). Finally clears the dirty flags.
1363 */
1364void
1365_math_matrix_analyse( GLmatrix *mat )
1366{
1367   if (mat->flags & MAT_DIRTY_TYPE) {
1368      if (mat->flags & MAT_DIRTY_FLAGS)
1369	 analyse_from_scratch( mat );
1370      else
1371	 analyse_from_flags( mat );
1372   }
1373
1374   if (mat->inv && (mat->flags & MAT_DIRTY_INVERSE)) {
1375      matrix_invert( mat );
1376      mat->flags &= ~MAT_DIRTY_INVERSE;
1377   }
1378
1379   mat->flags &= ~(MAT_DIRTY_FLAGS | MAT_DIRTY_TYPE);
1380}
1381
1382/*@}*/
1383
1384
1385/**
1386 * Test if the given matrix preserves vector lengths.
1387 */
1388GLboolean
1389_math_matrix_is_length_preserving( const GLmatrix *m )
1390{
1391   return TEST_MAT_FLAGS( m, MAT_FLAGS_LENGTH_PRESERVING);
1392}
1393
1394
1395/**
1396 * Test if the given matrix does any rotation.
1397 * (or perhaps if the upper-left 3x3 is non-identity)
1398 */
1399GLboolean
1400_math_matrix_has_rotation( const GLmatrix *m )
1401{
1402   if (m->flags & (MAT_FLAG_GENERAL |
1403                   MAT_FLAG_ROTATION |
1404                   MAT_FLAG_GENERAL_3D |
1405                   MAT_FLAG_PERSPECTIVE))
1406      return GL_TRUE;
1407   else
1408      return GL_FALSE;
1409}
1410
1411
1412GLboolean
1413_math_matrix_is_general_scale( const GLmatrix *m )
1414{
1415   return (m->flags & MAT_FLAG_GENERAL_SCALE) ? GL_TRUE : GL_FALSE;
1416}
1417
1418
1419GLboolean
1420_math_matrix_is_dirty( const GLmatrix *m )
1421{
1422   return (m->flags & MAT_DIRTY) ? GL_TRUE : GL_FALSE;
1423}
1424
1425
1426/**********************************************************************/
1427/** \name Matrix setup */
1428/*@{*/
1429
1430/**
1431 * Copy a matrix.
1432 *
1433 * \param to destination matrix.
1434 * \param from source matrix.
1435 *
1436 * Copies all fields in GLmatrix, creating an inverse array if necessary.
1437 */
1438void
1439_math_matrix_copy( GLmatrix *to, const GLmatrix *from )
1440{
1441   memcpy(to->m, from->m, 16 * sizeof(GLfloat));
1442   memcpy(to->inv, from->inv, 16 * sizeof(GLfloat));
1443   to->flags = from->flags;
1444   to->type = from->type;
1445}
1446
1447/**
1448 * Loads a matrix array into GLmatrix.
1449 *
1450 * \param m matrix array.
1451 * \param mat matrix.
1452 *
1453 * Copies \p m into GLmatrix::m and marks the MAT_FLAG_GENERAL and MAT_DIRTY
1454 * flags.
1455 */
1456void
1457_math_matrix_loadf( GLmatrix *mat, const GLfloat *m )
1458{
1459   memcpy( mat->m, m, 16*sizeof(GLfloat) );
1460   mat->flags = (MAT_FLAG_GENERAL | MAT_DIRTY);
1461}
1462
1463/**
1464 * Matrix constructor.
1465 *
1466 * \param m matrix.
1467 *
1468 * Initialize the GLmatrix fields.
1469 */
1470void
1471_math_matrix_ctr( GLmatrix *m )
1472{
1473   m->m = _mesa_align_malloc( 16 * sizeof(GLfloat), 16 );
1474   if (m->m)
1475      memcpy( m->m, Identity, sizeof(Identity) );
1476   m->inv = _mesa_align_malloc( 16 * sizeof(GLfloat), 16 );
1477   if (m->inv)
1478      memcpy( m->inv, Identity, sizeof(Identity) );
1479   m->type = MATRIX_IDENTITY;
1480   m->flags = 0;
1481}
1482
1483/**
1484 * Matrix destructor.
1485 *
1486 * \param m matrix.
1487 *
1488 * Frees the data in a GLmatrix.
1489 */
1490void
1491_math_matrix_dtr( GLmatrix *m )
1492{
1493   _mesa_align_free( m->m );
1494   m->m = NULL;
1495
1496   _mesa_align_free( m->inv );
1497   m->inv = NULL;
1498}
1499
1500/*@}*/
1501
1502
1503/**********************************************************************/
1504/** \name Matrix transpose */
1505/*@{*/
1506
1507/**
1508 * Transpose a GLfloat matrix.
1509 *
1510 * \param to destination array.
1511 * \param from source array.
1512 */
1513void
1514_math_transposef( GLfloat to[16], const GLfloat from[16] )
1515{
1516   to[0] = from[0];
1517   to[1] = from[4];
1518   to[2] = from[8];
1519   to[3] = from[12];
1520   to[4] = from[1];
1521   to[5] = from[5];
1522   to[6] = from[9];
1523   to[7] = from[13];
1524   to[8] = from[2];
1525   to[9] = from[6];
1526   to[10] = from[10];
1527   to[11] = from[14];
1528   to[12] = from[3];
1529   to[13] = from[7];
1530   to[14] = from[11];
1531   to[15] = from[15];
1532}
1533
1534/**
1535 * Transpose a GLdouble matrix.
1536 *
1537 * \param to destination array.
1538 * \param from source array.
1539 */
1540void
1541_math_transposed( GLdouble to[16], const GLdouble from[16] )
1542{
1543   to[0] = from[0];
1544   to[1] = from[4];
1545   to[2] = from[8];
1546   to[3] = from[12];
1547   to[4] = from[1];
1548   to[5] = from[5];
1549   to[6] = from[9];
1550   to[7] = from[13];
1551   to[8] = from[2];
1552   to[9] = from[6];
1553   to[10] = from[10];
1554   to[11] = from[14];
1555   to[12] = from[3];
1556   to[13] = from[7];
1557   to[14] = from[11];
1558   to[15] = from[15];
1559}
1560
1561/**
1562 * Transpose a GLdouble matrix and convert to GLfloat.
1563 *
1564 * \param to destination array.
1565 * \param from source array.
1566 */
1567void
1568_math_transposefd( GLfloat to[16], const GLdouble from[16] )
1569{
1570   to[0] = (GLfloat) from[0];
1571   to[1] = (GLfloat) from[4];
1572   to[2] = (GLfloat) from[8];
1573   to[3] = (GLfloat) from[12];
1574   to[4] = (GLfloat) from[1];
1575   to[5] = (GLfloat) from[5];
1576   to[6] = (GLfloat) from[9];
1577   to[7] = (GLfloat) from[13];
1578   to[8] = (GLfloat) from[2];
1579   to[9] = (GLfloat) from[6];
1580   to[10] = (GLfloat) from[10];
1581   to[11] = (GLfloat) from[14];
1582   to[12] = (GLfloat) from[3];
1583   to[13] = (GLfloat) from[7];
1584   to[14] = (GLfloat) from[11];
1585   to[15] = (GLfloat) from[15];
1586}
1587
1588/*@}*/
1589
1590
1591/**
1592 * Transform a 4-element row vector (1x4 matrix) by a 4x4 matrix.  This
1593 * function is used for transforming clipping plane equations and spotlight
1594 * directions.
1595 * Mathematically,  u = v * m.
1596 * Input:  v - input vector
1597 *         m - transformation matrix
1598 * Output:  u - transformed vector
1599 */
1600void
1601_mesa_transform_vector( GLfloat u[4], const GLfloat v[4], const GLfloat m[16] )
1602{
1603   const GLfloat v0 = v[0], v1 = v[1], v2 = v[2], v3 = v[3];
1604#define M(row,col)  m[row + col*4]
1605   u[0] = v0 * M(0,0) + v1 * M(1,0) + v2 * M(2,0) + v3 * M(3,0);
1606   u[1] = v0 * M(0,1) + v1 * M(1,1) + v2 * M(2,1) + v3 * M(3,1);
1607   u[2] = v0 * M(0,2) + v1 * M(1,2) + v2 * M(2,2) + v3 * M(3,2);
1608   u[3] = v0 * M(0,3) + v1 * M(1,3) + v2 * M(2,3) + v3 * M(3,3);
1609#undef M
1610}
1611