]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/brush_primit.cpp
Merge commit '830125fad042fad35dc029b6eb57c8156ad7e176'
[xonotic/netradiant.git] / radiant / brush_primit.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 #include "brush_primit.h"
23
24 #include "debugging/debugging.h"
25
26 #include "itexdef.h"
27 #include "itextures.h"
28
29 #include <algorithm>
30
31 #include "stringio.h"
32 #include "texturelib.h"
33 #include "math/matrix.h"
34 #include "math/plane.h"
35 #include "math/aabb.h"
36
37 #include "winding.h"
38 #include "preferences.h"
39
40
41 /*!
42    \brief Construct a transform from XYZ space to ST space (3d to 2d).
43    This will be one of three axis-aligned spaces, depending on the surface normal.
44    NOTE: could also be done by swapping values.
45  */
46 void Normal_GetTransform( const Vector3& normal, Matrix4& transform ){
47         switch ( projectionaxis_for_normal( normal ) )
48         {
49         case eProjectionAxisZ:
50                 transform[0]  =  1;
51                 transform[1]  =  0;
52                 transform[2]  =  0;
53
54                 transform[4]  =  0;
55                 transform[5]  =  1;
56                 transform[6]  =  0;
57
58                 transform[8]  =  0;
59                 transform[9]  =  0;
60                 transform[10] =  1;
61                 break;
62         case eProjectionAxisY:
63                 transform[0]  =  1;
64                 transform[1]  =  0;
65                 transform[2]  =  0;
66
67                 transform[4]  =  0;
68                 transform[5]  =  0;
69                 transform[6]  = -1;
70
71                 transform[8]  =  0;
72                 transform[9]  =  1;
73                 transform[10] =  0;
74                 break;
75         case eProjectionAxisX:
76                 transform[0]  =  0;
77                 transform[1]  =  0;
78                 transform[2]  =  1;
79
80                 transform[4]  =  1;
81                 transform[5]  =  0;
82                 transform[6]  =  0;
83
84                 transform[8]  =  0;
85                 transform[9]  =  1;
86                 transform[10] =  0;
87                 break;
88         }
89         transform[3] = transform[7] = transform[11] = transform[12] = transform[13] = transform[14] = 0;
90         transform[15] = 1;
91 }
92
93 /*!
94    \brief Construct a transform in ST space from the texdef.
95    Transforms constructed from quake's texdef format are (-shift)*(1/scale)*(-rotate) with x translation sign flipped.
96    This would really make more sense if it was inverseof(shift*rotate*scale).. oh well.
97  */
98 inline void Texdef_toTransform( const texdef_t& texdef, float width, float height, Matrix4& transform ){
99         double inverse_scale[2];
100
101         // transform to texdef shift/scale/rotate
102         inverse_scale[0] = 1 / ( texdef.scale[0] * width );
103         inverse_scale[1] = 1 / ( texdef.scale[1] * -height );
104         transform[12] = texdef.shift[0] / width;
105         transform[13] = -texdef.shift[1] / -height;
106         double c = cos( degrees_to_radians( -texdef.rotate ) );
107         double s = sin( degrees_to_radians( -texdef.rotate ) );
108         transform[0] = static_cast<float>( c * inverse_scale[0] );
109         transform[1] = static_cast<float>( s * inverse_scale[1] );
110         transform[4] = static_cast<float>( -s * inverse_scale[0] );
111         transform[5] = static_cast<float>( c * inverse_scale[1] );
112         transform[2] = transform[3] = transform[6] = transform[7] = transform[8] = transform[9] = transform[11] = transform[14] = 0;
113         transform[10] = transform[15] = 1;
114 }
115
116 inline void BPTexdef_toTransform( const brushprimit_texdef_t& bp_texdef, Matrix4& transform ){
117         transform = g_matrix4_identity;
118         transform.xx() = bp_texdef.coords[0][0];
119         transform.yx() = bp_texdef.coords[0][1];
120         transform.tx() = bp_texdef.coords[0][2];
121         transform.xy() = bp_texdef.coords[1][0];
122         transform.yy() = bp_texdef.coords[1][1];
123         transform.ty() = bp_texdef.coords[1][2];
124 }
125
126 inline void Texdef_toTransform( const TextureProjection& projection, float width, float height, Matrix4& transform ){
127         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
128                 BPTexdef_toTransform( projection.m_brushprimit_texdef, transform );
129         }
130         else
131         {
132                 Texdef_toTransform( projection.m_texdef, width, height, transform );
133         }
134 }
135
136 // handles degenerate cases, just in case library atan2 doesn't
137 inline double arctangent_yx( double y, double x ){
138         if ( fabs( x ) > 1.0E-6 ) {
139                 return atan2( y, x );
140         }
141         else if ( y > 0 ) {
142                 return c_half_pi;
143         }
144         else
145         {
146                 return -c_half_pi;
147         }
148 }
149
150 inline void Texdef_fromTransform( texdef_t& texdef, float width, float height, const Matrix4& transform ){
151         texdef.scale[0] = static_cast<float>( ( 1.0 / vector2_length( Vector2( transform[0], transform[4] ) ) ) / width );
152         texdef.scale[1] = static_cast<float>( ( 1.0 / vector2_length( Vector2( transform[1], transform[5] ) ) ) / height );
153
154         texdef.rotate = static_cast<float>( -radians_to_degrees( arctangent_yx( -transform[4], transform[0] ) ) );
155
156         if ( texdef.rotate == -180.0f ) {
157                 texdef.rotate = 180.0f;
158         }
159
160         texdef.shift[0] = transform[12] * width;
161         texdef.shift[1] = transform[13] * height;
162
163         // If the 2d cross-product of the x and y axes is positive, one of the axes has a negative scale.
164         if ( vector2_cross( Vector2( transform[0], transform[4] ), Vector2( transform[1], transform[5] ) ) > 0 ) {
165                 if ( texdef.rotate >= 180.0f ) {
166                         texdef.rotate -= 180.0f;
167                         texdef.scale[0] = -texdef.scale[0];
168                 }
169                 else
170                 {
171                         texdef.scale[1] = -texdef.scale[1];
172                 }
173         }
174         //globalOutputStream() << "fromTransform: " << texdef.shift[0] << " " << texdef.shift[1] << " " << texdef.scale[0] << " " << texdef.scale[1] << " " << texdef.rotate << "\n";
175 }
176
177 inline void BPTexdef_fromTransform( brushprimit_texdef_t& bp_texdef, const Matrix4& transform ){
178         bp_texdef.coords[0][0] = transform.xx();
179         bp_texdef.coords[0][1] = transform.yx();
180         bp_texdef.coords[0][2] = transform.tx();
181         bp_texdef.coords[1][0] = transform.xy();
182         bp_texdef.coords[1][1] = transform.yy();
183         bp_texdef.coords[1][2] = transform.ty();
184 }
185
186 inline void Texdef_fromTransform( TextureProjection& projection, float width, float height, const Matrix4& transform ){
187         ASSERT_MESSAGE( ( transform[0] != 0 || transform[4] != 0 )
188                                         && ( transform[1] != 0 || transform[5] != 0 ), "invalid texture matrix" );
189
190         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
191                 BPTexdef_fromTransform( projection.m_brushprimit_texdef, transform );
192         }
193         else
194         {
195                 Texdef_fromTransform( projection.m_texdef, width, height, transform );
196         }
197 }
198
199 inline void Texdef_normalise( texdef_t& texdef, float width, float height ){
200         // it may be useful to also normalise the rotation here, if this function is used elsewhere.
201         texdef.shift[0] = float_mod( texdef.shift[0], width );
202         texdef.shift[1] = float_mod( texdef.shift[1], height );
203         //globalOutputStream() << "normalise: " << texdef.shift[0] << " " << texdef.shift[1] << " " << texdef.scale[0] << " " << texdef.scale[1] << " " << texdef.rotate << "\n";
204 }
205
206 inline void BPTexdef_normalise( brushprimit_texdef_t& bp_texdef, float width, float height ){
207         bp_texdef.coords[0][2] = float_mod( bp_texdef.coords[0][2], width );
208         bp_texdef.coords[1][2] = float_mod( bp_texdef.coords[1][2], height );
209 }
210
211 /// \brief Normalise \p projection for a given texture \p width and \p height.
212 ///
213 /// All texture-projection translation (shift) values are congruent modulo the dimensions of the texture.
214 /// This function normalises shift values to the smallest positive congruent values.
215 void Texdef_normalise( TextureProjection& projection, float width, float height ){
216         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
217                 BPTexdef_normalise( projection.m_brushprimit_texdef, width, height );
218         }
219         else
220         {
221                 Texdef_normalise( projection.m_texdef, width, height );
222         }
223 }
224
225 void ComputeAxisBase( const Vector3& normal, Vector3& texS, Vector3& texT );
226
227 inline void DebugAxisBase( const Vector3& normal ){
228         Vector3 x, y;
229         ComputeAxisBase( normal, x, y );
230         globalOutputStream() << "BP debug: " << x << y << normal << "\n";
231 }
232
233 void Texdef_basisForNormal( const TextureProjection& projection, const Vector3& normal, Matrix4& basis ){
234         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
235                 basis = g_matrix4_identity;
236                 ComputeAxisBase( normal, vector4_to_vector3( basis.x() ), vector4_to_vector3( basis.y() ) );
237                 vector4_to_vector3( basis.z() ) = normal;
238                 matrix4_transpose( basis );
239                 //DebugAxisBase(normal);
240         }
241         else if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE ) {
242                 basis = g_matrix4_identity;
243                 vector4_to_vector3( basis.x() ) = projection.m_basis_s;
244                 vector4_to_vector3( basis.y() ) = vector3_negated( projection.m_basis_t );
245                 vector4_to_vector3( basis.z() ) = vector3_normalised( vector3_cross( vector4_to_vector3( basis.x() ), vector4_to_vector3( basis.y() ) ) );
246                 matrix4_multiply_by_matrix4( basis, matrix4_rotation_for_z_degrees( -projection.m_texdef.rotate ) );
247                 //globalOutputStream() << "debug: " << projection.m_basis_s << projection.m_basis_t << normal << "\n";
248                 matrix4_transpose( basis );
249         }
250         else
251         {
252                 Normal_GetTransform( normal, basis );
253         }
254 }
255
256 void Texdef_EmitTextureCoordinates( const TextureProjection& projection, std::size_t width, std::size_t height, Winding& w, const Vector3& normal, const Matrix4& localToWorld ){
257         if ( w.numpoints < 3 ) {
258                 return;
259         }
260         //globalOutputStream() << "normal: " << normal << "\n";
261
262         Matrix4 local2tex;
263         Texdef_toTransform( projection, (float)width, (float)height, local2tex );
264         //globalOutputStream() << "texdef: " << static_cast<const Vector3&>(local2tex.x()) << static_cast<const Vector3&>(local2tex.y()) << "\n";
265
266 #if 0
267         {
268                 TextureProjection tmp;
269                 Texdef_fromTransform( tmp, (float)width, (float)height, local2tex );
270                 Matrix4 tmpTransform;
271                 Texdef_toTransform( tmp, (float)width, (float)height, tmpTransform );
272                 ASSERT_MESSAGE( matrix4_equal_epsilon( local2tex, tmpTransform, 0.0001f ), "bleh" );
273         }
274 #endif
275
276         {
277                 Matrix4 xyz2st;
278                 // we don't care if it's not normalised...
279                 Texdef_basisForNormal( projection, matrix4_transformed_direction( localToWorld, normal ), xyz2st );
280                 //globalOutputStream() << "basis: " << static_cast<const Vector3&>(xyz2st.x()) << static_cast<const Vector3&>(xyz2st.y()) << static_cast<const Vector3&>(xyz2st.z()) << "\n";
281                 matrix4_multiply_by_matrix4( local2tex, xyz2st );
282         }
283
284         Vector3 tangent( vector3_normalised( vector4_to_vector3( matrix4_transposed( local2tex ).x() ) ) );
285         Vector3 bitangent( vector3_normalised( vector4_to_vector3( matrix4_transposed( local2tex ).y() ) ) );
286
287         matrix4_multiply_by_matrix4( local2tex, localToWorld );
288
289         for ( Winding::iterator i = w.begin(); i != w.end(); ++i )
290         {
291                 Vector3 texcoord = matrix4_transformed_point( local2tex, ( *i ).vertex );
292                 ( *i ).texcoord[0] = texcoord[0];
293                 ( *i ).texcoord[1] = texcoord[1];
294
295                 ( *i ).tangent = tangent;
296                 ( *i ).bitangent = bitangent;
297         }
298 }
299
300 /*!
301    \brief Provides the axis-base of the texture ST space for this normal,
302    as they had been transformed to world XYZ space.
303  */
304 void TextureAxisFromNormal( const Vector3& normal, Vector3& s, Vector3& t ){
305         switch ( projectionaxis_for_normal( normal ) )
306         {
307         case eProjectionAxisZ:
308                 s[0]  =  1;
309                 s[1]  =  0;
310                 s[2]  =  0;
311
312                 t[0]  =  0;
313                 t[1]  = -1;
314                 t[2]  =  0;
315
316                 break;
317         case eProjectionAxisY:
318                 s[0]  =  1;
319                 s[1]  =  0;
320                 s[2]  =  0;
321
322                 t[0]  =  0;
323                 t[1]  =  0;
324                 t[2]  = -1;
325
326                 break;
327         case eProjectionAxisX:
328                 s[0]  =  0;
329                 s[1]  =  1;
330                 s[2]  =  0;
331
332                 t[0]  =  0;
333                 t[1]  =  0;
334                 t[2]  = -1;
335
336                 break;
337         }
338 }
339
340 void Texdef_Assign( texdef_t& td, const texdef_t& other ){
341         td = other;
342 }
343
344 void Texdef_Shift( texdef_t& td, float s, float t ){
345         td.shift[0] += s;
346         td.shift[1] += t;
347 }
348
349 void Texdef_Scale( texdef_t& td, float s, float t ){
350         td.scale[0] += s;
351         td.scale[1] += t;
352 }
353
354 void Texdef_Rotate( texdef_t& td, float angle ){
355         td.rotate += angle;
356         td.rotate = static_cast<float>( float_to_integer( td.rotate ) % 360 );
357 }
358
359 // NOTE: added these from Ritual's Q3Radiant
360 void ClearBounds( Vector3& mins, Vector3& maxs ){
361         mins[0] = mins[1] = mins[2] = 99999;
362         maxs[0] = maxs[1] = maxs[2] = -99999;
363 }
364
365 void AddPointToBounds( const Vector3& v, Vector3& mins, Vector3& maxs ){
366         int i;
367         float val;
368
369         for ( i = 0 ; i < 3 ; i++ )
370         {
371                 val = v[i];
372                 if ( val < mins[i] ) {
373                         mins[i] = val;
374                 }
375                 if ( val > maxs[i] ) {
376                         maxs[i] = val;
377                 }
378         }
379 }
380
381 template<typename Element>
382 inline BasicVector3<Element> vector3_inverse( const BasicVector3<Element>& self ){
383         return BasicVector3<Element>(
384                            Element( 1.0 / self.x() ),
385                            Element( 1.0 / self.y() ),
386                            Element( 1.0 / self.z() )
387                            );
388 }
389
390 // low level functions .. put in mathlib?
391 #define BPMatCopy( a,b ) {b[0][0] = a[0][0]; b[0][1] = a[0][1]; b[0][2] = a[0][2]; b[1][0] = a[1][0]; b[1][1] = a[1][1]; b[1][2] = a[1][2]; }
392 // apply a scale transformation to the BP matrix
393 #define BPMatScale( m,sS,sT ) {m[0][0] *= sS; m[1][0] *= sS; m[0][1] *= sT; m[1][1] *= sT; }
394 // apply a translation transformation to a BP matrix
395 #define BPMatTranslate( m,s,t ) {m[0][2] += m[0][0] * s + m[0][1] * t; m[1][2] += m[1][0] * s + m[1][1] * t; }
396 // 2D homogeneous matrix product C = A*B
397 void BPMatMul( float A[2][3], float B[2][3], float C[2][3] );
398 // apply a rotation (degrees)
399 void BPMatRotate( float A[2][3], float theta );
400 #ifdef _DEBUG
401 void BPMatDump( float A[2][3] );
402 #endif
403
404 #ifdef _DEBUG
405 //#define DBG_BP
406 #endif
407
408
409 bp_globals_t g_bp_globals;
410 float g_texdef_default_scale;
411
412 // compute a determinant using Sarrus rule
413 //++timo "inline" this with a macro
414 // NOTE : the three vectors are understood as columns of the matrix
415 inline float SarrusDet( const Vector3& a, const Vector3& b, const Vector3& c ){
416         return a[0] * b[1] * c[2] + b[0] * c[1] * a[2] + c[0] * a[1] * b[2]
417                    - c[0] * b[1] * a[2] - a[1] * b[0] * c[2] - a[0] * b[2] * c[1];
418 }
419
420 // in many case we know three points A,B,C in two axis base B1 and B2
421 // and we want the matrix M so that A(B1) = T * A(B2)
422 // NOTE: 2D homogeneous space stuff
423 // NOTE: we don't do any check to see if there's a solution or we have a particular case .. need to make sure before calling
424 // NOTE: the third coord of the A,B,C point is ignored
425 // NOTE: see the commented out section to fill M and D
426 //++timo TODO: update the other members to use this when possible
427 void MatrixForPoints( Vector3 M[3], Vector3 D[2], brushprimit_texdef_t *T ){
428 //      Vector3 M[3]; // columns of the matrix .. easier that way (the indexing is not standard! it's column-line .. later computations are easier that way)
429         float det;
430 //      Vector3 D[2];
431         M[2][0] = 1.0f; M[2][1] = 1.0f; M[2][2] = 1.0f;
432 #if 0
433         // fill the data vectors
434         M[0][0] = A2[0]; M[0][1] = B2[0]; M[0][2] = C2[0];
435         M[1][0] = A2[1]; M[1][1] = B2[1]; M[1][2] = C2[1];
436         M[2][0] = 1.0f; M[2][1] = 1.0f; M[2][2] = 1.0f;
437         D[0][0] = A1[0];
438         D[0][1] = B1[0];
439         D[0][2] = C1[0];
440         D[1][0] = A1[1];
441         D[1][1] = B1[1];
442         D[1][2] = C1[1];
443 #endif
444         // solve
445         det = SarrusDet( M[0], M[1], M[2] );
446         T->coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det;
447         T->coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det;
448         T->coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det;
449         T->coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det;
450         T->coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det;
451         T->coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det;
452 }
453
454 //++timo replace everywhere texX by texS etc. ( ----> and in q3map !)
455 // NOTE : ComputeAxisBase here and in q3map code must always BE THE SAME !
456 // WARNING : special case behaviour of atan2(y,x) <-> atan(y/x) might not be the same everywhere when x == 0
457 // rotation by (0,RotY,RotZ) assigns X to normal
458 void ComputeAxisBase( const Vector3& normal, Vector3& texS, Vector3& texT ){
459 #if 1
460         const Vector3 up( 0, 0, 1 );
461         const Vector3 down( 0, 0, -1 );
462
463         if ( vector3_equal_epsilon( normal, up, float(1e-6) ) ) {
464                 texS = Vector3( 0, 1, 0 );
465                 texT = Vector3( 1, 0, 0 );
466         }
467         else if ( vector3_equal_epsilon( normal, down, float(1e-6) ) ) {
468                 texS = Vector3( 0, 1, 0 );
469                 texT = Vector3( -1, 0, 0 );
470         }
471         else
472         {
473                 texS = vector3_normalised( vector3_cross( normal, up ) );
474                 texT = vector3_normalised( vector3_cross( normal, texS ) );
475                 vector3_negate( texS );
476         }
477
478 #else
479         float RotY,RotZ;
480         // do some cleaning
481         /*
482            if (fabs(normal[0])<1e-6)
483               normal[0]=0.0f;
484            if (fabs(normal[1])<1e-6)
485               normal[1]=0.0f;
486            if (fabs(normal[2])<1e-6)
487               normal[2]=0.0f;
488          */
489         RotY = -atan2( normal[2],sqrt( normal[1] * normal[1] + normal[0] * normal[0] ) );
490         RotZ = atan2( normal[1],normal[0] );
491         // rotate (0,1,0) and (0,0,1) to compute texS and texT
492         texS[0] = -sin( RotZ );
493         texS[1] = cos( RotZ );
494         texS[2] = 0;
495         // the texT vector is along -Z ( T texture coorinates axis )
496         texT[0] = -sin( RotY ) * cos( RotZ );
497         texT[1] = -sin( RotY ) * sin( RotZ );
498         texT[2] = -cos( RotY );
499 #endif
500 }
501
502 #if 0 // texdef conversion
503 void FaceToBrushPrimitFace( face_t *f ){
504         Vector3 texX,texY;
505         Vector3 proj;
506         // ST of (0,0) (1,0) (0,1)
507         float ST[3][5]; // [ point index ] [ xyz ST ]
508         //++timo not used as long as brushprimit_texdef and texdef are static
509 /*      f->brushprimit_texdef.contents=f->texdef.contents;
510     f->brushprimit_texdef.flags=f->texdef.flags;
511     f->brushprimit_texdef.value=f->texdef.value;
512     strcpy(f->brushprimit_texdef.name,f->texdef.name); */
513 #ifdef DBG_BP
514         if ( f->plane.normal[0] == 0.0f && f->plane.normal[1] == 0.0f && f->plane.normal[2] == 0.0f ) {
515                 globalOutputStream() << "Warning : f->plane.normal is (0,0,0) in FaceToBrushPrimitFace\n";
516         }
517         // check d_texture
518         if ( !f->d_texture ) {
519                 globalOutputStream() << "Warning : f.d_texture is 0 in FaceToBrushPrimitFace\n";
520                 return;
521         }
522 #endif
523         // compute axis base
524         ComputeAxisBase( f->plane.normal,texX,texY );
525         // compute projection vector
526         VectorCopy( f->plane.normal,proj );
527         VectorScale( proj,f->plane.dist,proj );
528         // (0,0) in plane axis base is (0,0,0) in world coordinates + projection on the affine plane
529         // (1,0) in plane axis base is texX in world coordinates + projection on the affine plane
530         // (0,1) in plane axis base is texY in world coordinates + projection on the affine plane
531         // use old texture code to compute the ST coords of these points
532         VectorCopy( proj,ST[0] );
533         EmitTextureCoordinates( ST[0], f->pShader->getTexture(), f );
534         VectorCopy( texX,ST[1] );
535         VectorAdd( ST[1],proj,ST[1] );
536         EmitTextureCoordinates( ST[1], f->pShader->getTexture(), f );
537         VectorCopy( texY,ST[2] );
538         VectorAdd( ST[2],proj,ST[2] );
539         EmitTextureCoordinates( ST[2], f->pShader->getTexture(), f );
540         // compute texture matrix
541         f->brushprimit_texdef.coords[0][2] = ST[0][3];
542         f->brushprimit_texdef.coords[1][2] = ST[0][4];
543         f->brushprimit_texdef.coords[0][0] = ST[1][3] - f->brushprimit_texdef.coords[0][2];
544         f->brushprimit_texdef.coords[1][0] = ST[1][4] - f->brushprimit_texdef.coords[1][2];
545         f->brushprimit_texdef.coords[0][1] = ST[2][3] - f->brushprimit_texdef.coords[0][2];
546         f->brushprimit_texdef.coords[1][1] = ST[2][4] - f->brushprimit_texdef.coords[1][2];
547 }
548
549 // compute texture coordinates for the winding points
550 void EmitBrushPrimitTextureCoordinates( face_t * f, Winding * w ){
551         Vector3 texX,texY;
552         float x,y;
553         // compute axis base
554         ComputeAxisBase( f->plane.normal,texX,texY );
555         // in case the texcoords matrix is empty, build a default one
556         // same behaviour as if scale[0]==0 && scale[1]==0 in old code
557         if ( f->brushprimit_texdef.coords[0][0] == 0 && f->brushprimit_texdef.coords[1][0] == 0 && f->brushprimit_texdef.coords[0][1] == 0 && f->brushprimit_texdef.coords[1][1] == 0 ) {
558                 f->brushprimit_texdef.coords[0][0] = 1.0f;
559                 f->brushprimit_texdef.coords[1][1] = 1.0f;
560                 ConvertTexMatWithQTexture( &f->brushprimit_texdef, 0, &f->brushprimit_texdef, f->pShader->getTexture() );
561         }
562         int i;
563         for ( i = 0 ; i < w.numpoints ; i++ )
564         {
565                 x = vector3_dot( w.point_at( i ),texX );
566                 y = vector3_dot( w.point_at( i ),texY );
567 #if 0
568 #ifdef DBG_BP
569                 if ( g_bp_globals.bNeedConvert ) {
570                         // check we compute the same ST as the traditional texture computation used before
571                         float S = f->brushprimit_texdef.coords[0][0] * x + f->brushprimit_texdef.coords[0][1] * y + f->brushprimit_texdef.coords[0][2];
572                         float T = f->brushprimit_texdef.coords[1][0] * x + f->brushprimit_texdef.coords[1][1] * y + f->brushprimit_texdef.coords[1][2];
573                         if ( fabs( S - w.point_at( i )[3] ) > 1e-2 || fabs( T - w.point_at( i )[4] ) > 1e-2 ) {
574                                 if ( fabs( S - w.point_at( i )[3] ) > 1e-4 || fabs( T - w.point_at( i )[4] ) > 1e-4 ) {
575                                         globalOutputStream() << "Warning : precision loss in brush -> brush primitive texture computation\n";
576                                 }
577                                 else{
578                                         globalOutputStream() << "Warning : brush -> brush primitive texture computation bug detected\n";
579                                 }
580                         }
581                 }
582 #endif
583 #endif
584                 w.point_at( i )[3] = f->brushprimit_texdef.coords[0][0] * x + f->brushprimit_texdef.coords[0][1] * y + f->brushprimit_texdef.coords[0][2];
585                 w.point_at( i )[4] = f->brushprimit_texdef.coords[1][0] * x + f->brushprimit_texdef.coords[1][1] * y + f->brushprimit_texdef.coords[1][2];
586         }
587 }
588 #endif
589
590 typedef float texmat_t[2][3];
591
592 void TexMat_Scale( texmat_t texmat, float s, float t ){
593         texmat[0][0] *= s;
594         texmat[0][1] *= s;
595         texmat[0][2] *= s;
596         texmat[1][0] *= t;
597         texmat[1][1] *= t;
598         texmat[1][2] *= t;
599 }
600
601 void TexMat_Assign( texmat_t texmat, const texmat_t other ){
602         texmat[0][0] = other[0][0];
603         texmat[0][1] = other[0][1];
604         texmat[0][2] = other[0][2];
605         texmat[1][0] = other[1][0];
606         texmat[1][1] = other[1][1];
607         texmat[1][2] = other[1][2];
608 }
609
610 void ConvertTexMatWithDimensions( const texmat_t texmat1, std::size_t w1, std::size_t h1,
611                                                                   texmat_t texmat2, std::size_t w2, std::size_t h2 ){
612         TexMat_Assign( texmat2, texmat1 );
613         TexMat_Scale( texmat2, static_cast<float>( w1 ) / static_cast<float>( w2 ), static_cast<float>( h1 ) / static_cast<float>( h2 ) );
614 }
615
616 #if 0
617 // convert a texture matrix between two qtexture_t
618 // if 0 for qtexture_t, basic 2x2 texture is assumed ( straight mapping between s/t coordinates and geometric coordinates )
619 void ConvertTexMatWithQTexture( const float texMat1[2][3], const qtexture_t *qtex1, float texMat2[2][3], const qtexture_t *qtex2 ){
620         ConvertTexMatWithDimensions( texMat1, ( qtex1 ) ? qtex1->width : 2, ( qtex1 ) ? qtex1->height : 2,
621                                                                  texMat2, ( qtex2 ) ? qtex2->width : 2, ( qtex2 ) ? qtex2->height : 2 );
622 }
623
624 void ConvertTexMatWithQTexture( const brushprimit_texdef_t *texMat1, const qtexture_t *qtex1, brushprimit_texdef_t *texMat2, const qtexture_t *qtex2 ){
625         ConvertTexMatWithQTexture( texMat1->coords, qtex1, texMat2->coords, qtex2 );
626 }
627 #endif
628
629 // compute a fake shift scale rot representation from the texture matrix
630 // these shift scale rot values are to be understood in the local axis base
631 // Note: this code looks similar to Texdef_fromTransform, but the algorithm is slightly different.
632
633 void TexMatToFakeTexCoords( const brushprimit_texdef_t& bp_texdef, texdef_t& texdef ){
634         texdef.scale[0] = static_cast<float>( 1.0 / vector2_length( Vector2( bp_texdef.coords[0][0], bp_texdef.coords[1][0] ) ) );
635         texdef.scale[1] = static_cast<float>( 1.0 / vector2_length( Vector2( bp_texdef.coords[0][1], bp_texdef.coords[1][1] ) ) );
636
637         texdef.rotate = -static_cast<float>( radians_to_degrees( arctangent_yx( bp_texdef.coords[1][0], bp_texdef.coords[0][0] ) ) );
638
639         texdef.shift[0] = -bp_texdef.coords[0][2];
640         texdef.shift[1] = bp_texdef.coords[1][2];
641
642         // determine whether or not an axis is flipped using a 2d cross-product
643         double cross = vector2_cross( Vector2( bp_texdef.coords[0][0], bp_texdef.coords[0][1] ), Vector2( bp_texdef.coords[1][0], bp_texdef.coords[1][1] ) );
644         if ( cross < 0 ) {
645                 // This is a bit of a compromise when using BPs--since we don't know *which* axis was flipped,
646                 // we pick one (rather arbitrarily) using the following convention: If the X-axis is between
647                 // 0 and 180, we assume it's the Y-axis that flipped, otherwise we assume it's the X-axis and
648                 // subtract out 180 degrees to compensate.
649                 if ( texdef.rotate >= 180.0f ) {
650                         texdef.rotate -= 180.0f;
651                         texdef.scale[0] = -texdef.scale[0];
652                 }
653                 else
654                 {
655                         texdef.scale[1] = -texdef.scale[1];
656                 }
657         }
658 }
659
660 // compute back the texture matrix from fake shift scale rot
661 void FakeTexCoordsToTexMat( const texdef_t& texdef, brushprimit_texdef_t& bp_texdef ){
662         double r = degrees_to_radians( -texdef.rotate );
663         double c = cos( r );
664         double s = sin( r );
665         double x = 1.0f / texdef.scale[0];
666         double y = 1.0f / texdef.scale[1];
667         bp_texdef.coords[0][0] = static_cast<float>( x * c );
668         bp_texdef.coords[1][0] = static_cast<float>( x * s );
669         bp_texdef.coords[0][1] = static_cast<float>( y * -s );
670         bp_texdef.coords[1][1] = static_cast<float>( y * c );
671         bp_texdef.coords[0][2] = -texdef.shift[0];
672         bp_texdef.coords[1][2] = texdef.shift[1];
673 }
674
675 #if 0 // texture locking (brush primit)
676 // used for texture locking
677 // will move the texture according to a geometric vector
678 void ShiftTextureGeometric_BrushPrimit( face_t *f, Vector3& delta ){
679         Vector3 texS,texT;
680         float tx,ty;
681         Vector3 M[3]; // columns of the matrix .. easier that way
682         float det;
683         Vector3 D[2];
684         // compute plane axis base ( doesn't change with translation )
685         ComputeAxisBase( f->plane.normal, texS, texT );
686         // compute translation vector in plane axis base
687         tx = vector3_dot( delta, texS );
688         ty = vector3_dot( delta, texT );
689         // fill the data vectors
690         M[0][0] = tx; M[0][1] = 1.0f + tx; M[0][2] = tx;
691         M[1][0] = ty; M[1][1] = ty; M[1][2] = 1.0f + ty;
692         M[2][0] = 1.0f; M[2][1] = 1.0f; M[2][2] = 1.0f;
693         D[0][0] = f->brushprimit_texdef.coords[0][2];
694         D[0][1] = f->brushprimit_texdef.coords[0][0] + f->brushprimit_texdef.coords[0][2];
695         D[0][2] = f->brushprimit_texdef.coords[0][1] + f->brushprimit_texdef.coords[0][2];
696         D[1][0] = f->brushprimit_texdef.coords[1][2];
697         D[1][1] = f->brushprimit_texdef.coords[1][0] + f->brushprimit_texdef.coords[1][2];
698         D[1][2] = f->brushprimit_texdef.coords[1][1] + f->brushprimit_texdef.coords[1][2];
699         // solve
700         det = SarrusDet( M[0], M[1], M[2] );
701         f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det;
702         f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det;
703         f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det;
704         f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det;
705         f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det;
706         f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det;
707 }
708
709 // shift a texture (texture adjustments) along it's current texture axes
710 // x and y are geometric values, which we must compute as ST increments
711 // this depends on the texture size and the pixel/texel ratio
712 void ShiftTextureRelative_BrushPrimit( face_t *f, float x, float y ){
713         float s,t;
714         // as a ratio against texture size
715         // the scale of the texture is not relevant here (we work directly on a transformation from the base vectors)
716         s = ( x * 2.0 ) / (float)f->pShader->getTexture().width;
717         t = ( y * 2.0 ) / (float)f->pShader->getTexture().height;
718         f->brushprimit_texdef.coords[0][2] -= s;
719         f->brushprimit_texdef.coords[1][2] -= t;
720 }
721 #endif
722
723 // TTimo: FIXME: I don't like that, it feels broken
724 //   (and it's likely that it's not used anymore)
725 // best fitted 2D vector is x.X+y.Y
726 void ComputeBest2DVector( Vector3& v, Vector3& X, Vector3& Y, int &x, int &y ){
727         double sx,sy;
728         sx = vector3_dot( v, X );
729         sy = vector3_dot( v, Y );
730         if ( fabs( sy ) > fabs( sx ) ) {
731                 x = 0;
732                 if ( sy > 0.0 ) {
733                         y =  1;
734                 }
735                 else{
736                         y = -1;
737                 }
738         }
739         else
740         {
741                 y = 0;
742                 if ( sx > 0.0 ) {
743                         x =  1;
744                 }
745                 else{
746                         x = -1;
747                 }
748         }
749 }
750
751
752 #if 0 // texdef conversion
753 void BrushPrimitFaceToFace( face_t *face ){
754         // we have parsed brush primitives and need conversion back to standard format
755         // NOTE: converting back is a quick hack, there's some information lost and we can't do anything about it
756         // FIXME: if we normalize the texture matrix to a standard 2x2 size, we end up with wrong scaling
757         // I tried various tweaks, no luck .. seems shifting is lost
758         brushprimit_texdef_t aux;
759         ConvertTexMatWithQTexture( &face->brushprimit_texdef, face->pShader->getTexture(), &aux, 0 );
760         TexMatToFakeTexCoords( aux.coords, face->texdef.shift, &face->texdef.rotate, face->texdef.scale );
761         face->texdef.scale[0] /= 2.0;
762         face->texdef.scale[1] /= 2.0;
763 }
764 #endif
765
766
767 #if 0 // texture locking (brush primit)
768 // TEXTURE LOCKING -----------------------------------------------------------------------------------------------------
769 // (Relevant to the editor only?)
770
771 // internally used for texture locking on rotation and flipping
772 // the general algorithm is the same for both lockings, it's only the geometric transformation part that changes
773 // so I wanted to keep it in a single function
774 // if there are more linear transformations that need the locking, going to a C++ or code pointer solution would be best
775 // (but right now I want to keep brush_primit.cpp striclty C)
776
777 bool txlock_bRotation;
778
779 // rotation locking params
780 int txl_nAxis;
781 float txl_fDeg;
782 Vector3 txl_vOrigin;
783
784 // flip locking params
785 Vector3 txl_matrix[3];
786 Vector3 txl_origin;
787
788 void TextureLockTransformation_BrushPrimit( face_t *f ){
789         Vector3 Orig,texS,texT;      // axis base of initial plane
790         // used by transformation algo
791         Vector3 temp; int j;
792         Vector3 vRotate;                        // rotation vector
793
794         Vector3 rOrig,rvecS,rvecT;   // geometric transformation of (0,0) (1,0) (0,1) { initial plane axis base }
795         Vector3 rNormal,rtexS,rtexT; // axis base for the transformed plane
796         Vector3 lOrig,lvecS,lvecT;  // [2] are not used ( but usefull for debugging )
797         Vector3 M[3];
798         float det;
799         Vector3 D[2];
800
801         // compute plane axis base
802         ComputeAxisBase( f->plane.normal, texS, texT );
803         VectorSet( Orig, 0.0f, 0.0f, 0.0f );
804
805         // compute coordinates of (0,0) (1,0) (0,1) ( expressed in initial plane axis base ) after transformation
806         // (0,0) (1,0) (0,1) ( expressed in initial plane axis base ) <-> (0,0,0) texS texT ( expressed world axis base )
807         // input: Orig, texS, texT (and the global locking params)
808         // ouput: rOrig, rvecS, rvecT, rNormal
809         if ( txlock_bRotation ) {
810                 // rotation vector
811                 VectorSet( vRotate, 0.0f, 0.0f, 0.0f );
812                 vRotate[txl_nAxis] = txl_fDeg;
813                 VectorRotateOrigin( Orig, vRotate, txl_vOrigin, rOrig );
814                 VectorRotateOrigin( texS, vRotate, txl_vOrigin, rvecS );
815                 VectorRotateOrigin( texT, vRotate, txl_vOrigin, rvecT );
816                 // compute normal of plane after rotation
817                 VectorRotate( f->plane.normal, vRotate, rNormal );
818         }
819         else
820         {
821                 for ( j = 0 ; j < 3 ; j++ )
822                         rOrig[j] = vector3_dot( vector3_subtracted( Orig, txl_origin ), txl_matrix[j] ) + txl_origin[j];
823                 for ( j = 0 ; j < 3 ; j++ )
824                         rvecS[j] = vector3_dot( vector3_subtracted( texS, txl_origin ), txl_matrix[j] ) + txl_origin[j];
825                 for ( j = 0 ; j < 3 ; j++ )
826                         rvecT[j] = vector3_dot( vector3_subtracted( texT, txl_origin ), txl_matrix[j] ) + txl_origin[j];
827                 // we also need the axis base of the target plane, apply the transformation matrix to the normal too..
828                 for ( j = 0 ; j < 3 ; j++ )
829                         rNormal[j] = vector3_dot( f->plane.normal, txl_matrix[j] );
830         }
831
832         // compute rotated plane axis base
833         ComputeAxisBase( rNormal, rtexS, rtexT );
834         // compute S/T coordinates of the three points in rotated axis base ( in M matrix )
835         lOrig[0] = vector3_dot( rOrig, rtexS );
836         lOrig[1] = vector3_dot( rOrig, rtexT );
837         lvecS[0] = vector3_dot( rvecS, rtexS );
838         lvecS[1] = vector3_dot( rvecS, rtexT );
839         lvecT[0] = vector3_dot( rvecT, rtexS );
840         lvecT[1] = vector3_dot( rvecT, rtexT );
841         M[0][0] = lOrig[0]; M[1][0] = lOrig[1]; M[2][0] = 1.0f;
842         M[0][1] = lvecS[0]; M[1][1] = lvecS[1]; M[2][1] = 1.0f;
843         M[0][2] = lvecT[0]; M[1][2] = lvecT[1]; M[2][2] = 1.0f;
844         // fill data vector
845         D[0][0] = f->brushprimit_texdef.coords[0][2];
846         D[0][1] = f->brushprimit_texdef.coords[0][0] + f->brushprimit_texdef.coords[0][2];
847         D[0][2] = f->brushprimit_texdef.coords[0][1] + f->brushprimit_texdef.coords[0][2];
848         D[1][0] = f->brushprimit_texdef.coords[1][2];
849         D[1][1] = f->brushprimit_texdef.coords[1][0] + f->brushprimit_texdef.coords[1][2];
850         D[1][2] = f->brushprimit_texdef.coords[1][1] + f->brushprimit_texdef.coords[1][2];
851         // solve
852         det = SarrusDet( M[0], M[1], M[2] );
853         f->brushprimit_texdef.coords[0][0] = SarrusDet( D[0], M[1], M[2] ) / det;
854         f->brushprimit_texdef.coords[0][1] = SarrusDet( M[0], D[0], M[2] ) / det;
855         f->brushprimit_texdef.coords[0][2] = SarrusDet( M[0], M[1], D[0] ) / det;
856         f->brushprimit_texdef.coords[1][0] = SarrusDet( D[1], M[1], M[2] ) / det;
857         f->brushprimit_texdef.coords[1][1] = SarrusDet( M[0], D[1], M[2] ) / det;
858         f->brushprimit_texdef.coords[1][2] = SarrusDet( M[0], M[1], D[1] ) / det;
859 }
860
861 // texture locking
862 // called before the points on the face are actually rotated
863 void RotateFaceTexture_BrushPrimit( face_t *f, int nAxis, float fDeg, Vector3& vOrigin ){
864         // this is a placeholder to call the general texture locking algorithm
865         txlock_bRotation = true;
866         txl_nAxis = nAxis;
867         txl_fDeg = fDeg;
868         VectorCopy( vOrigin, txl_vOrigin );
869         TextureLockTransformation_BrushPrimit( f );
870 }
871
872 // compute the new brush primit texture matrix for a transformation matrix and a flip order flag (change plane orientation)
873 // this matches the select_matrix algo used in select.cpp
874 // this needs to be called on the face BEFORE any geometric transformation
875 // it will compute the texture matrix that will represent the same texture on the face after the geometric transformation is done
876 void ApplyMatrix_BrushPrimit( face_t *f, Vector3 matrix[3], Vector3& origin ){
877         // this is a placeholder to call the general texture locking algorithm
878         txlock_bRotation = false;
879         VectorCopy( matrix[0], txl_matrix[0] );
880         VectorCopy( matrix[1], txl_matrix[1] );
881         VectorCopy( matrix[2], txl_matrix[2] );
882         VectorCopy( origin, txl_origin );
883         TextureLockTransformation_BrushPrimit( f );
884 }
885 #endif
886
887 // don't do C==A!
888 void BPMatMul( float A[2][3], float B[2][3], float C[2][3] ){
889         C[0][0] = A[0][0] * B[0][0] + A[0][1] * B[1][0];
890         C[1][0] = A[1][0] * B[0][0] + A[1][1] * B[1][0];
891         C[0][1] = A[0][0] * B[0][1] + A[0][1] * B[1][1];
892         C[1][1] = A[1][0] * B[0][1] + A[1][1] * B[1][1];
893         C[0][2] = A[0][0] * B[0][2] + A[0][1] * B[1][2] + A[0][2];
894         C[1][2] = A[1][0] * B[0][2] + A[1][1] * B[1][2] + A[1][2];
895 }
896
897 void BPMatDump( float A[2][3] ){
898         globalOutputStream() << "" << A[0][0]
899                                                  << " " << A[0][1]
900                                                  << " " << A[0][2]
901                                                  << "\n" << A[1][0]
902                                                  << " " << A[1][2]
903                                                  << " " << A[1][2]
904                                                  << "\n0 0 1\n";
905 }
906
907 void BPMatRotate( float A[2][3], float theta ){
908         float m[2][3];
909         float aux[2][3];
910         memset( &m, 0, sizeof( float ) * 6 );
911         m[0][0] = static_cast<float>( cos( degrees_to_radians( theta ) ) );
912         m[0][1] = static_cast<float>( -sin( degrees_to_radians( theta ) ) );
913         m[1][0] = -m[0][1];
914         m[1][1] = m[0][0];
915         BPMatMul( A, m, aux );
916         BPMatCopy( aux,A );
917 }
918
919 #if 0 // camera-relative texture shift
920 // get the relative axes of the current texturing
921 void BrushPrimit_GetRelativeAxes( face_t *f, Vector3& vecS, Vector3& vecT ){
922         float vS[2],vT[2];
923         // first we compute them as expressed in plane axis base
924         // BP matrix has coordinates of plane axis base expressed in geometric axis base
925         // so we use the line vectors
926         vS[0] = f->brushprimit_texdef.coords[0][0];
927         vS[1] = f->brushprimit_texdef.coords[0][1];
928         vT[0] = f->brushprimit_texdef.coords[1][0];
929         vT[1] = f->brushprimit_texdef.coords[1][1];
930         // now compute those vectors in geometric space
931         Vector3 texS, texT; // axis base of the plane (geometric)
932         ComputeAxisBase( f->plane.normal, texS, texT );
933         // vecS[] = vS[0].texS[] + vS[1].texT[]
934         // vecT[] = vT[0].texS[] + vT[1].texT[]
935         vecS[0] = vS[0] * texS[0] + vS[1] * texT[0];
936         vecS[1] = vS[0] * texS[1] + vS[1] * texT[1];
937         vecS[2] = vS[0] * texS[2] + vS[1] * texT[2];
938         vecT[0] = vT[0] * texS[0] + vT[1] * texT[0];
939         vecT[1] = vT[0] * texS[1] + vT[1] * texT[1];
940         vecT[2] = vT[0] * texS[2] + vT[1] * texT[2];
941 }
942
943 // brush primitive texture adjustments, use the camera view to map adjustments
944 // ShiftTextureRelative_BrushPrimit ( s , t ) will shift relative to the texture
945 void ShiftTextureRelative_Camera( face_t *f, int x, int y ){
946         Vector3 vecS, vecT;
947         float XY[2]; // the values we are going to send for translation
948         float sgn[2]; // +1 or -1
949         int axis[2];
950         CamWnd* pCam;
951
952         // get the two relative texture axes for the current texturing
953         BrushPrimit_GetRelativeAxes( f, vecS, vecT );
954
955         // center point of the face, project it on the camera space
956         Vector3 C;
957         VectorClear( C );
958         int i;
959         for ( i = 0; i < f->face_winding->numpoints; i++ )
960         {
961                 VectorAdd( C,f->face_winding->point_at( i ),C );
962         }
963         VectorScale( C,1.0 / f->face_winding->numpoints,C );
964
965         pCam = g_pParentWnd->GetCamWnd();
966         pCam->MatchViewAxes( C, vecS, axis[0], sgn[0] );
967         pCam->MatchViewAxes( C, vecT, axis[1], sgn[1] );
968
969         // this happens when the two directions can't be mapped on two different directions on the screen
970         // then the move will occur against a single axis
971         // (i.e. the user is not positioned well enough to send understandable shift commands)
972         // NOTE: in most cases this warning is not very relevant because the user would use one of the two axes
973         // for which the solution is easy (the other one being unknown)
974         // so this warning could be removed
975         if ( axis[0] == axis[1] ) {
976                 globalOutputStream() << "Warning: degenerate in ShiftTextureRelative_Camera\n";
977         }
978
979         // compute the X Y geometric increments
980         // those geometric increments will be applied along the texture axes (the ones we computed above)
981         XY[0] = 0;
982         XY[1] = 0;
983         if ( x != 0 ) {
984                 // moving right/left
985                 XY[axis[0]] += sgn[0] * x;
986         }
987         if ( y != 0 ) {
988                 XY[axis[1]] += sgn[1] * y;
989         }
990         // we worked out a move along vecS vecT, and we now it's geometric amplitude
991         // apply it
992         ShiftTextureRelative_BrushPrimit( f, XY[0], XY[1] );
993 }
994 #endif
995
996
997 void BPTexdef_Assign( brushprimit_texdef_t& bp_td, const brushprimit_texdef_t& bp_other ){
998         bp_td = bp_other;
999 }
1000
1001 void BPTexdef_Shift( brushprimit_texdef_t& bp_td, float s, float t ){
1002         // shift a texture (texture adjustments) along it's current texture axes
1003         // x and y are geometric values, which we must compute as ST increments
1004         // this depends on the texture size and the pixel/texel ratio
1005         // as a ratio against texture size
1006         // the scale of the texture is not relevant here (we work directly on a transformation from the base vectors)
1007         bp_td.coords[0][2] -= s;
1008         bp_td.coords[1][2] += t;
1009 }
1010
1011 void BPTexdef_Scale( brushprimit_texdef_t& bp_td, float s, float t ){
1012         // apply same scale as the spinner button of the surface inspector
1013         texdef_t texdef;
1014         // compute fake shift scale rot
1015         TexMatToFakeTexCoords( bp_td, texdef );
1016         // update
1017         texdef.scale[0] += s;
1018         texdef.scale[1] += t;
1019         // compute new normalized texture matrix
1020         FakeTexCoordsToTexMat( texdef, bp_td );
1021 }
1022
1023 void BPTexdef_Rotate( brushprimit_texdef_t& bp_td, float angle ){
1024         // apply same scale as the spinner button of the surface inspector
1025         texdef_t texdef;
1026         // compute fake shift scale rot
1027         TexMatToFakeTexCoords( bp_td, texdef );
1028         // update
1029         texdef.rotate += angle;
1030         // compute new normalized texture matrix
1031         FakeTexCoordsToTexMat( texdef, bp_td );
1032 }
1033
1034 void BPTexdef_Construct( brushprimit_texdef_t& bp_td, std::size_t width, std::size_t height ){
1035         bp_td.coords[0][0] = 1.0f;
1036         bp_td.coords[1][1] = 1.0f;
1037         ConvertTexMatWithDimensions( bp_td.coords, 2, 2, bp_td.coords, width, height );
1038 }
1039
1040 void Texdef_Assign( TextureProjection& projection, const TextureProjection& other ){
1041         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
1042                 BPTexdef_Assign( projection.m_brushprimit_texdef, other.m_brushprimit_texdef );
1043         }
1044         else
1045         {
1046                 Texdef_Assign( projection.m_texdef, other.m_texdef );
1047                 if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE ) {
1048                         projection.m_basis_s = other.m_basis_s;
1049                         projection.m_basis_t = other.m_basis_t;
1050                 }
1051         }
1052 }
1053
1054 void Texdef_Shift( TextureProjection& projection, float s, float t ){
1055         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
1056                 BPTexdef_Shift( projection.m_brushprimit_texdef, s, t );
1057         }
1058         else
1059         {
1060                 Texdef_Shift( projection.m_texdef, s, t );
1061         }
1062 }
1063
1064 void Texdef_Scale( TextureProjection& projection, float s, float t ){
1065         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
1066                 BPTexdef_Scale( projection.m_brushprimit_texdef, s, t );
1067         }
1068         else
1069         {
1070                 Texdef_Scale( projection.m_texdef, s, t );
1071         }
1072 }
1073
1074 void Texdef_Rotate( TextureProjection& projection, float angle ){
1075         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
1076                 BPTexdef_Rotate( projection.m_brushprimit_texdef, angle );
1077         }
1078         else
1079         {
1080                 Texdef_Rotate( projection.m_texdef, angle );
1081         }
1082 }
1083
1084 void Texdef_FitTexture( TextureProjection& projection, std::size_t width, std::size_t height, const Vector3& normal, const Winding& w, float s_repeat, float t_repeat ){
1085         if ( w.numpoints < 3 ) {
1086                 return;
1087         }
1088
1089         Matrix4 st2tex;
1090         Texdef_toTransform( projection, (float)width, (float)height, st2tex );
1091
1092         // the current texture transform
1093         Matrix4 local2tex = st2tex;
1094         {
1095                 Matrix4 xyz2st;
1096                 Texdef_basisForNormal( projection, normal, xyz2st );
1097                 matrix4_multiply_by_matrix4( local2tex, xyz2st );
1098         }
1099
1100         // the bounds of the current texture transform
1101         AABB bounds;
1102         for ( Winding::const_iterator i = w.begin(); i != w.end(); ++i )
1103         {
1104                 Vector3 texcoord = matrix4_transformed_point( local2tex, ( *i ).vertex );
1105                 aabb_extend_by_point_safe( bounds, texcoord );
1106         }
1107         bounds.origin.z() = 0;
1108         bounds.extents.z() = 1;
1109
1110         // the bounds of a perfectly fitted texture transform
1111         AABB perfect( Vector3( s_repeat * 0.5, t_repeat * 0.5, 0 ), Vector3( s_repeat * 0.5, t_repeat * 0.5, 1 ) );
1112
1113         // the difference between the current texture transform and the perfectly fitted transform
1114         Matrix4 matrix( matrix4_translation_for_vec3( bounds.origin - perfect.origin ) );
1115         matrix4_pivoted_scale_by_vec3( matrix, bounds.extents / perfect.extents, perfect.origin );
1116         matrix4_affine_invert( matrix );
1117
1118         // apply the difference to the current texture transform
1119         matrix4_premultiply_by_matrix4( st2tex, matrix );
1120
1121         Texdef_fromTransform( projection, (float)width, (float)height, st2tex );
1122         Texdef_normalise( projection, (float)width, (float)height );
1123 }
1124
1125 float Texdef_getDefaultTextureScale(){
1126         return g_texdef_default_scale;
1127 }
1128
1129 void TexDef_Construct_Default( TextureProjection& projection ){
1130         projection.m_texdef.scale[0] = Texdef_getDefaultTextureScale();
1131         projection.m_texdef.scale[1] = Texdef_getDefaultTextureScale();
1132
1133         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
1134                 FakeTexCoordsToTexMat( projection.m_texdef, projection.m_brushprimit_texdef );
1135         }
1136 }
1137
1138
1139
1140 void ShiftScaleRotate_fromFace( texdef_t& shiftScaleRotate, const TextureProjection& projection ){
1141         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
1142                 TexMatToFakeTexCoords( projection.m_brushprimit_texdef, shiftScaleRotate );
1143         }
1144         else
1145         {
1146                 shiftScaleRotate = projection.m_texdef;
1147         }
1148 }
1149
1150 void ShiftScaleRotate_toFace( const texdef_t& shiftScaleRotate, TextureProjection& projection ){
1151         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_BRUSHPRIMITIVES ) {
1152                 // compute texture matrix
1153                 // the matrix returned must be understood as a qtexture_t with width=2 height=2
1154                 FakeTexCoordsToTexMat( shiftScaleRotate, projection.m_brushprimit_texdef );
1155         }
1156         else
1157         {
1158                 projection.m_texdef = shiftScaleRotate;
1159         }
1160 }
1161
1162
1163 inline void print_vector3( const Vector3& v ){
1164         globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n";
1165 }
1166
1167 inline void print_3x3( const Matrix4& m ){
1168         globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) "
1169                                                  << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) "
1170                                                  << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n";
1171 }
1172
1173
1174 inline Matrix4 matrix4_rotation_for_vector3( const Vector3& x, const Vector3& y, const Vector3& z ){
1175         return Matrix4(
1176                            x.x(), x.y(), x.z(), 0,
1177                            y.x(), y.y(), y.z(), 0,
1178                            z.x(), z.y(), z.z(), 0,
1179                            0, 0, 0, 1
1180                            );
1181 }
1182
1183 inline Matrix4 matrix4_swap_axes( const Vector3& from, const Vector3& to ){
1184         if ( from.x() != 0 && to.y() != 0 ) {
1185                 return matrix4_rotation_for_vector3( to, from, g_vector3_axis_z );
1186         }
1187
1188         if ( from.x() != 0 && to.z() != 0 ) {
1189                 return matrix4_rotation_for_vector3( to, g_vector3_axis_y, from );
1190         }
1191
1192         if ( from.y() != 0 && to.z() != 0 ) {
1193                 return matrix4_rotation_for_vector3( g_vector3_axis_x, to, from );
1194         }
1195
1196         if ( from.y() != 0 && to.x() != 0 ) {
1197                 return matrix4_rotation_for_vector3( from, to, g_vector3_axis_z );
1198         }
1199
1200         if ( from.z() != 0 && to.x() != 0 ) {
1201                 return matrix4_rotation_for_vector3( from, g_vector3_axis_y, to );
1202         }
1203
1204         if ( from.z() != 0 && to.y() != 0 ) {
1205                 return matrix4_rotation_for_vector3( g_vector3_axis_x, from, to );
1206         }
1207
1208         ERROR_MESSAGE( "unhandled axis swap case" );
1209
1210         return g_matrix4_identity;
1211 }
1212
1213 inline Matrix4 matrix4_reflection_for_plane( const Plane3& plane ){
1214         return Matrix4(
1215                            static_cast<float>( 1 - ( 2 * plane.a * plane.a ) ),
1216                            static_cast<float>( -2 * plane.a * plane.b ),
1217                            static_cast<float>( -2 * plane.a * plane.c ),
1218                            0,
1219                            static_cast<float>( -2 * plane.b * plane.a ),
1220                            static_cast<float>( 1 - ( 2 * plane.b * plane.b ) ),
1221                            static_cast<float>( -2 * plane.b * plane.c ),
1222                            0,
1223                            static_cast<float>( -2 * plane.c * plane.a ),
1224                            static_cast<float>( -2 * plane.c * plane.b ),
1225                            static_cast<float>( 1 - ( 2 * plane.c * plane.c ) ),
1226                            0,
1227                            static_cast<float>( -2 * plane.d * plane.a ),
1228                            static_cast<float>( -2 * plane.d * plane.b ),
1229                            static_cast<float>( -2 * plane.d * plane.c ),
1230                            1
1231                            );
1232 }
1233
1234 inline Matrix4 matrix4_reflection_for_plane45( const Plane3& plane, const Vector3& from, const Vector3& to ){
1235         Vector3 first = from;
1236         Vector3 second = to;
1237
1238         if ( vector3_dot( from, plane.normal() ) > 0 == vector3_dot( to, plane.normal() ) > 0 ) {
1239                 first = vector3_negated( first );
1240                 second = vector3_negated( second );
1241         }
1242
1243 #if 0
1244         globalOutputStream() << "normal: ";
1245         print_vector3( plane.normal() );
1246
1247         globalOutputStream() << "from: ";
1248         print_vector3( first );
1249
1250         globalOutputStream() << "to: ";
1251         print_vector3( second );
1252 #endif
1253
1254         Matrix4 swap = matrix4_swap_axes( first, second );
1255
1256         Matrix4 tmp = matrix4_reflection_for_plane( plane );
1257
1258         swap.tx() = -static_cast<float>( -2 * plane.a * plane.d );
1259         swap.ty() = -static_cast<float>( -2 * plane.b * plane.d );
1260         swap.tz() = -static_cast<float>( -2 * plane.c * plane.d );
1261
1262         return swap;
1263 }
1264
1265 void Texdef_transformLocked( TextureProjection& projection, std::size_t width, std::size_t height, const Plane3& plane, const Matrix4& identity2transformed ){
1266         //globalOutputStream() << "identity2transformed: " << identity2transformed << "\n";
1267
1268         //globalOutputStream() << "plane.normal(): " << plane.normal() << "\n";
1269
1270         Vector3 normalTransformed( matrix4_transformed_direction( identity2transformed, plane.normal() ) );
1271
1272         //globalOutputStream() << "normalTransformed: " << normalTransformed << "\n";
1273
1274         // identity: identity space
1275         // transformed: transformation
1276         // stIdentity: base st projection space before transformation
1277         // stTransformed: base st projection space after transformation
1278         // stOriginal: original texdef space
1279
1280         // stTransformed2stOriginal = stTransformed -> transformed -> identity -> stIdentity -> stOriginal
1281
1282         Matrix4 identity2stIdentity;
1283         Texdef_basisForNormal( projection, plane.normal(), identity2stIdentity );
1284         //globalOutputStream() << "identity2stIdentity: " << identity2stIdentity << "\n";
1285
1286         if ( g_bp_globals.m_texdefTypeId == TEXDEFTYPEID_HALFLIFE ) {
1287                 matrix4_transform_direction( identity2transformed, projection.m_basis_s );
1288                 matrix4_transform_direction( identity2transformed, projection.m_basis_t );
1289         }
1290
1291         Matrix4 transformed2stTransformed;
1292         Texdef_basisForNormal( projection, normalTransformed, transformed2stTransformed );
1293
1294         Matrix4 stTransformed2identity( matrix4_affine_inverse( matrix4_multiplied_by_matrix4( transformed2stTransformed, identity2transformed ) ) );
1295
1296         Vector3 originalProjectionAxis( vector4_to_vector3( matrix4_affine_inverse( identity2stIdentity ).z() ) );
1297
1298         Vector3 transformedProjectionAxis( vector4_to_vector3( stTransformed2identity.z() ) );
1299
1300         Matrix4 stIdentity2stOriginal;
1301         Texdef_toTransform( projection, (float)width, (float)height, stIdentity2stOriginal );
1302         Matrix4 identity2stOriginal( matrix4_multiplied_by_matrix4( stIdentity2stOriginal, identity2stIdentity ) );
1303
1304         //globalOutputStream() << "originalProj: " << originalProjectionAxis << "\n";
1305         //globalOutputStream() << "transformedProj: " << transformedProjectionAxis << "\n";
1306         double dot = vector3_dot( originalProjectionAxis, transformedProjectionAxis );
1307         //globalOutputStream() << "dot: " << dot << "\n";
1308         if ( dot == 0 ) {
1309                 // The projection axis chosen for the transformed normal is at 90 degrees
1310                 // to the transformed projection axis chosen for the original normal.
1311                 // This happens when the projection axis is ambiguous - e.g. for the plane
1312                 // 'X == Y' the projection axis could be either X or Y.
1313                 //globalOutputStream() << "flipped\n";
1314 #if 0
1315                 globalOutputStream() << "projection off by 90\n";
1316                 globalOutputStream() << "normal: ";
1317                 print_vector3( plane.normal() );
1318                 globalOutputStream() << "original projection: ";
1319                 print_vector3( originalProjectionAxis );
1320                 globalOutputStream() << "transformed projection: ";
1321                 print_vector3( transformedProjectionAxis );
1322 #endif
1323
1324                 Matrix4 identityCorrected = matrix4_reflection_for_plane45( plane, originalProjectionAxis, transformedProjectionAxis );
1325
1326                 identity2stOriginal = matrix4_multiplied_by_matrix4( identity2stOriginal, identityCorrected );
1327         }
1328
1329         Matrix4 stTransformed2stOriginal = matrix4_multiplied_by_matrix4( identity2stOriginal, stTransformed2identity );
1330
1331         Texdef_fromTransform( projection, (float)width, (float)height, stTransformed2stOriginal );
1332         Texdef_normalise( projection, (float)width, (float)height );
1333 }
1334
1335 #if 1
1336 void Q3_to_matrix( const texdef_t& texdef, float width, float height, const Vector3& normal, Matrix4& matrix ){
1337         Normal_GetTransform( normal, matrix );
1338
1339         Matrix4 transform;
1340
1341         Texdef_toTransform( texdef, width, height, transform );
1342
1343         matrix4_multiply_by_matrix4( matrix, transform );
1344 }
1345
1346 void BP_from_matrix( brushprimit_texdef_t& bp_texdef, const Vector3& normal, const Matrix4& transform ){
1347         Matrix4 basis;
1348         basis = g_matrix4_identity;
1349         ComputeAxisBase( normal, vector4_to_vector3( basis.x() ), vector4_to_vector3( basis.y() ) );
1350         vector4_to_vector3( basis.z() ) = normal;
1351         matrix4_transpose( basis );
1352         matrix4_affine_invert( basis );
1353
1354         Matrix4 basis2texture = matrix4_multiplied_by_matrix4( basis, transform );
1355
1356         BPTexdef_fromTransform( bp_texdef, basis2texture );
1357 }
1358
1359 void Q3_to_BP( const texdef_t& texdef, float width, float height, const Vector3& normal, brushprimit_texdef_t& bp_texdef ){
1360         Matrix4 matrix;
1361         Q3_to_matrix( texdef, width, height, normal, matrix );
1362         BP_from_matrix( bp_texdef, normal, matrix );
1363 }
1364 #endif