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