]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/selection.cpp
Merge commit 'd079351041fe957ab2cf6b36dab38e5546003dc3' into garux-merge
[xonotic/netradiant.git] / radiant / selection.cpp
1 /*
2    Copyright (C) 2001-2006, William Joseph.
3    All Rights Reserved.
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 "selection.h"
23 #include "globaldefs.h"
24
25 #include "debugging/debugging.h"
26
27 #include <map>
28 #include <list>
29 #include <set>
30
31 #include "windowobserver.h"
32 #include "iundo.h"
33 #include "ientity.h"
34 #include "cullable.h"
35 #include "renderable.h"
36 #include "selectable.h"
37 #include "editable.h"
38
39 #include "math/frustum.h"
40 #include "signal/signal.h"
41 #include "generic/object.h"
42 #include "selectionlib.h"
43 #include "render.h"
44 #include "view.h"
45 #include "renderer.h"
46 #include "stream/stringstream.h"
47 #include "eclasslib.h"
48 #include "generic/bitfield.h"
49 #include "generic/static.h"
50 #include "pivot.h"
51 #include "stringio.h"
52 #include "container/container.h"
53
54 #include "grid.h"
55
56 TextOutputStream& ostream_write( TextOutputStream& t, const Vector4& v ){
57         return t << "[ " << v.x() << " " << v.y() << " " << v.z() << " " << v.w() << " ]";
58 }
59
60 TextOutputStream& ostream_write( TextOutputStream& t, const Matrix4& m ){
61         return t << "[ " << m.x() << " " << m.y() << " " << m.z() << " " << m.t() << " ]";
62 }
63
64 struct Pivot2World
65 {
66         Matrix4 m_worldSpace;
67         Matrix4 m_viewpointSpace;
68         Matrix4 m_viewplaneSpace;
69         Vector3 m_axis_screen;
70
71         void update( const Matrix4& pivot2world, const Matrix4& modelview, const Matrix4& projection, const Matrix4& viewport ){
72                 Pivot2World_worldSpace( m_worldSpace, pivot2world, modelview, projection, viewport );
73                 Pivot2World_viewpointSpace( m_viewpointSpace, m_axis_screen, pivot2world, modelview, projection, viewport );
74                 Pivot2World_viewplaneSpace( m_viewplaneSpace, pivot2world, modelview, projection, viewport );
75         }
76 };
77
78
79 void point_for_device_point( Vector3& point, const Matrix4& device2object, const float x, const float y, const float z ){
80         // transform from normalised device coords to object coords
81         point = vector4_projected( matrix4_transformed_vector4( device2object, Vector4( x, y, z, 1 ) ) );
82 }
83
84 void ray_for_device_point( Ray& ray, const Matrix4& device2object, const float x, const float y ){
85         // point at x, y, zNear
86         point_for_device_point( ray.origin, device2object, x, y, -1 );
87
88         // point at x, y, zFar
89         point_for_device_point( ray.direction, device2object, x, y, 1 );
90
91         // construct ray
92         vector3_subtract( ray.direction, ray.origin );
93         vector3_normalise( ray.direction );
94 }
95
96 bool sphere_intersect_ray( const Vector3& origin, float radius, const Ray& ray, Vector3& intersection ){
97         intersection = vector3_subtracted( origin, ray.origin );
98         const double a = vector3_dot( intersection, ray.direction );
99         const double d = radius * radius - ( vector3_dot( intersection, intersection ) - a * a );
100
101         if ( d > 0 ) {
102                 intersection = vector3_added( ray.origin, vector3_scaled( ray.direction, a - sqrt( d ) ) );
103                 return true;
104         }
105         else
106         {
107                 intersection = vector3_added( ray.origin, vector3_scaled( ray.direction, a ) );
108                 return false;
109         }
110 }
111
112 void ray_intersect_ray( const Ray& ray, const Ray& other, Vector3& intersection ){
113         intersection = vector3_subtracted( ray.origin, other.origin );
114         //float a = 1;//vector3_dot(ray.direction, ray.direction);        // always >= 0
115         double dot = vector3_dot( ray.direction, other.direction );
116         //float c = 1;//vector3_dot(other.direction, other.direction);        // always >= 0
117         double d = vector3_dot( ray.direction, intersection );
118         double e = vector3_dot( other.direction, intersection );
119         double D = 1 - dot * dot; //a*c - dot*dot;       // always >= 0
120
121         if ( D < 0.000001 ) {
122                 // the lines are almost parallel
123                 intersection = vector3_added( other.origin, vector3_scaled( other.direction, e ) );
124         }
125         else
126         {
127                 intersection = vector3_added( other.origin, vector3_scaled( other.direction, ( e - dot * d ) / D ) );
128         }
129 }
130
131 const Vector3 g_origin( 0, 0, 0 );
132 const float g_radius = 64;
133
134 void point_on_sphere( Vector3& point, const Matrix4& device2object, const float x, const float y ){
135         Ray ray;
136         ray_for_device_point( ray, device2object, x, y );
137         sphere_intersect_ray( g_origin, g_radius, ray, point );
138 }
139
140 void point_on_axis( Vector3& point, const Vector3& axis, const Matrix4& device2object, const float x, const float y ){
141         Ray ray;
142         ray_for_device_point( ray, device2object, x, y );
143         ray_intersect_ray( ray, Ray( Vector3( 0, 0, 0 ), axis ), point );
144 }
145
146 void point_on_plane( Vector3& point, const Matrix4& device2object, const float x, const float y ){
147         Matrix4 object2device( matrix4_full_inverse( device2object ) );
148         point = vector4_projected( matrix4_transformed_vector4( device2object, Vector4( x, y, object2device[14] / object2device[15], 1 ) ) );
149 }
150
151 //! a and b are unit vectors .. returns angle in radians
152 inline float angle_between( const Vector3& a, const Vector3& b ){
153         return static_cast<float>( 2.0 * atan2(
154                                                                    vector3_length( vector3_subtracted( a, b ) ),
155                                                                    vector3_length( vector3_added( a, b ) )
156                                                                    ) );
157 }
158
159
160 #if GDEF_DEBUG
161 class test_quat
162 {
163 public:
164 test_quat( const Vector3& from, const Vector3& to ){
165         Vector4 quaternion( quaternion_for_unit_vectors( from, to ) );
166         Matrix4 matrix( matrix4_rotation_for_quaternion( quaternion_multiplied_by_quaternion( quaternion, c_quaternion_identity ) ) );
167 }
168 private:
169 };
170
171 static test_quat bleh( g_vector3_axis_x, g_vector3_axis_y );
172 #endif
173
174 //! axis is a unit vector
175 inline void constrain_to_axis( Vector3& vec, const Vector3& axis ){
176         vec = vector3_normalised( vector3_added( vec, vector3_scaled( axis, -vector3_dot( vec, axis ) ) ) );
177 }
178
179 //! a and b are unit vectors .. a and b must be orthogonal to axis .. returns angle in radians
180 float angle_for_axis( const Vector3& a, const Vector3& b, const Vector3& axis ){
181         if ( vector3_dot( axis, vector3_cross( a, b ) ) > 0.0 ) {
182                 return angle_between( a, b );
183         }
184         else{
185                 return -angle_between( a, b );
186         }
187 }
188
189 float distance_for_axis( const Vector3& a, const Vector3& b, const Vector3& axis ){
190         return static_cast<float>( vector3_dot( b, axis ) - vector3_dot( a, axis ) );
191 }
192
193 class Manipulatable
194 {
195 public:
196 virtual void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ) = 0;
197 virtual void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ) = 0;
198 };
199
200 void transform_local2object( Matrix4& object, const Matrix4& local, const Matrix4& local2object ){
201         object = matrix4_multiplied_by_matrix4(
202                 matrix4_multiplied_by_matrix4( local2object, local ),
203                 matrix4_full_inverse( local2object )
204                 );
205 }
206
207 class Rotatable
208 {
209 public:
210 virtual ~Rotatable() = default;
211 virtual void rotate( const Quaternion& rotation ) = 0;
212 };
213
214 class RotateFree : public Manipulatable
215 {
216 Vector3 m_start;
217 Rotatable& m_rotatable;
218 public:
219 RotateFree( Rotatable& rotatable )
220         : m_rotatable( rotatable ){
221 }
222 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
223         point_on_sphere( m_start, device2manip, x, y );
224         vector3_normalise( m_start );
225 }
226 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
227         Vector3 current;
228         point_on_sphere( current, device2manip, x, y );
229
230         if( snap ){
231                 Vector3 axis( 0, 0, 0 );
232                 for( std::size_t i = 0; i < 3; ++i ){
233                         if( current[i] == 0.0f ){
234                                 axis[i] = 1.0f;
235                                 break;
236                         }
237                 }
238                 if( vector3_length_squared( axis ) != 0 ){
239                         constrain_to_axis( current, axis );
240                         m_rotatable.rotate( quaternion_for_axisangle( axis, float_snapped( angle_for_axis( m_start, current, axis ), static_cast<float>( c_pi / 12.0 ) ) ) );
241                         return;
242                 }
243         }
244
245         vector3_normalise( current );
246         m_rotatable.rotate( quaternion_for_unit_vectors( m_start, current ) );
247 }
248 };
249
250 class RotateAxis : public Manipulatable
251 {
252 Vector3 m_axis;
253 Vector3 m_start;
254 Rotatable& m_rotatable;
255 public:
256 RotateAxis( Rotatable& rotatable )
257         : m_rotatable( rotatable ){
258 }
259 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
260         point_on_sphere( m_start, device2manip, x, y );
261         constrain_to_axis( m_start, m_axis );
262 }
263 /// \brief Converts current position to a normalised vector orthogonal to axis.
264 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
265         Vector3 current;
266         point_on_sphere( current, device2manip, x, y );
267         constrain_to_axis( current, m_axis );
268
269         if( snap ){
270                 m_rotatable.rotate( quaternion_for_axisangle( m_axis, float_snapped( angle_for_axis( m_start, current, m_axis ), static_cast<float>( c_pi / 12.0 ) ) ) );
271         }
272         else{
273                 m_rotatable.rotate( quaternion_for_axisangle( m_axis, angle_for_axis( m_start, current, m_axis ) ) );
274         }
275 }
276
277 void SetAxis( const Vector3& axis ){
278         m_axis = axis;
279 }
280 };
281
282 void translation_local2object( Vector3& object, const Vector3& local, const Matrix4& local2object ){
283         object = matrix4_get_translation_vec3(
284                 matrix4_multiplied_by_matrix4(
285                         matrix4_translated_by_vec3( local2object, local ),
286                         matrix4_full_inverse( local2object )
287                         )
288                 );
289 }
290
291 class Translatable
292 {
293 public:
294 virtual ~Translatable() = default;
295 virtual void translate( const Vector3& translation ) = 0;
296 };
297
298 class TranslateAxis : public Manipulatable
299 {
300 Vector3 m_start;
301 Vector3 m_axis;
302 Translatable& m_translatable;
303 AABB m_bounds;
304 public:
305 TranslateAxis( Translatable& translatable )
306         : m_translatable( translatable ){
307 }
308 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
309         point_on_axis( m_start, m_axis, device2manip, x, y );
310         m_bounds = bounds;
311 }
312 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
313         Vector3 current;
314         point_on_axis( current, m_axis, device2manip, x, y );
315         current = vector3_scaled( m_axis, distance_for_axis( m_start, current, m_axis ) );
316
317         translation_local2object( current, current, manip2object );
318         if( snapbbox ){
319                 float grid = GetSnapGridSize();
320                 Vector3 maxs( m_bounds.origin + m_bounds.extents );
321                 Vector3 mins( m_bounds.origin - m_bounds.extents );
322 //              globalOutputStream() << "current: " << current << "\n";
323                 for( std::size_t i = 0; i < 3; ++i ){
324                         if( m_axis[i] != 0.f ){
325                                 float snapto1 = float_snapped( maxs[i] + current[i] , grid );
326                                 float snapto2 = float_snapped( mins[i] + current[i] , grid );
327
328                                 float dist1 = fabs( fabs( maxs[i] + current[i] ) - fabs( snapto1 ) );
329                                 float dist2 = fabs( fabs( mins[i] + current[i] ) - fabs( snapto2 ) );
330
331 //                              globalOutputStream() << "maxs[i] + current[i]: " << maxs[i] + current[i]  << "    snapto1: " << snapto1 << "   dist1: " << dist1 << "\n";
332 //                              globalOutputStream() << "mins[i] + current[i]: " << mins[i] + current[i]  << "    snapto2: " << snapto2 << "   dist2: " << dist2 << "\n";
333                                 current[i] = dist2 > dist1 ? snapto1 - maxs[i] : snapto2 - mins[i];
334                         }
335                 }
336         }
337         else{
338                 vector3_snap( current, GetSnapGridSize() );
339         }
340
341         m_translatable.translate( current );
342 }
343
344 void SetAxis( const Vector3& axis ){
345         m_axis = axis;
346 }
347 };
348
349 class TranslateFree : public Manipulatable
350 {
351 private:
352 Vector3 m_start;
353 Translatable& m_translatable;
354 AABB m_bounds;
355 public:
356 TranslateFree( Translatable& translatable )
357         : m_translatable( translatable ){
358 }
359 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
360         point_on_plane( m_start, device2manip, x, y );
361         m_bounds = bounds;
362 }
363 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
364         Vector3 current;
365         point_on_plane( current, device2manip, x, y );
366         current = vector3_subtracted( current, m_start );
367
368         if( snap ){
369                 for ( std::size_t i = 0; i < 3 ; ++i ){
370                         if( fabs( current[i] ) >= fabs( current[(i + 1) % 3] ) ){
371                                 current[(i + 1) % 3] = 0.0f;
372                         }
373                         else{
374                                 current[i] = 0.0f;
375                         }
376                 }
377         }
378
379         translation_local2object( current, current, manip2object );
380         if( snapbbox ){
381                 float grid = GetSnapGridSize();
382                 Vector3 maxs( m_bounds.origin + m_bounds.extents );
383                 Vector3 mins( m_bounds.origin - m_bounds.extents );
384 //              globalOutputStream() << "current: " << current << "\n";
385                 for( std::size_t i = 0; i < 3; ++i ){
386                         if( current[i] != 0.f ){
387                                 float snapto1 = float_snapped( maxs[i] + current[i] , grid );
388                                 float snapto2 = float_snapped( mins[i] + current[i] , grid );
389
390                                 float dist1 = fabs( fabs( maxs[i] + current[i] ) - fabs( snapto1 ) );
391                                 float dist2 = fabs( fabs( mins[i] + current[i] ) - fabs( snapto2 ) );
392
393                                 current[i] = dist2 > dist1 ? snapto1 - maxs[i] : snapto2 - mins[i];
394                         }
395                 }
396         }
397         else{
398                 vector3_snap( current, GetSnapGridSize() );
399         }
400
401         m_translatable.translate( current );
402 }
403 };
404
405 class Scalable
406 {
407 public:
408 virtual ~Scalable() = default;
409 virtual void scale( const Vector3& scaling ) = 0;
410 };
411
412
413 class ScaleAxis : public Manipulatable
414 {
415 private:
416 Vector3 m_start;
417 Vector3 m_axis;
418 Scalable& m_scalable;
419
420 Vector3 m_choosen_extent;
421 AABB m_bounds;
422
423 public:
424 ScaleAxis( Scalable& scalable )
425         : m_scalable( scalable ){
426 }
427 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
428         point_on_axis( m_start, m_axis, device2manip, x, y );
429
430         m_choosen_extent = Vector3(
431                                         std::max( bounds.origin[0] + bounds.extents[0] - transform_origin[0], - bounds.origin[0] + bounds.extents[0] + transform_origin[0] ),
432                                         std::max( bounds.origin[1] + bounds.extents[1] - transform_origin[1], - bounds.origin[1] + bounds.extents[1] + transform_origin[1] ),
433                                         std::max( bounds.origin[2] + bounds.extents[2] - transform_origin[2], - bounds.origin[2] + bounds.extents[2] + transform_origin[2] )
434                                                         );
435         m_bounds = bounds;
436 }
437 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
438         //globalOutputStream() << "manip2object: " << manip2object << "  device2manip: " << device2manip << "  x: " << x << "  y:" << y <<"\n";
439         Vector3 current;
440         point_on_axis( current, m_axis, device2manip, x, y );
441         Vector3 delta = vector3_subtracted( current, m_start );
442
443         translation_local2object( delta, delta, manip2object );
444         vector3_snap( delta, GetSnapGridSize() );
445
446         Vector3 start( vector3_snapped( m_start, GetSnapGridSize() != 0.0f ? GetSnapGridSize() : 0.001f ) );
447         for ( std::size_t i = 0; i < 3 ; ++i ){ //prevent snapping to 0 with big gridsize
448                 if( float_snapped( m_start[i], 0.001f ) != 0.0f && start[i] == 0.0f ){
449                         start[i] = GetSnapGridSize();
450                 }
451         }
452         //globalOutputStream() << "m_start: " << m_start << "   start: " << start << "   delta: " << delta <<"\n";
453         Vector3 scale(
454                 start[0] == 0 ? 1 : 1 + delta[0] / start[0],
455                 start[1] == 0 ? 1 : 1 + delta[1] / start[1],
456                 start[2] == 0 ? 1 : 1 + delta[2] / start[2]
457                 );
458
459         for( std::size_t i = 0; i < 3; i++ ){
460                 if( m_choosen_extent[i] > 0.0625f && m_axis[i] != 0.f ){ //epsilon to prevent super high scale for set of models, having really small extent, formed by origins
461                         scale[i] = ( m_choosen_extent[i] + delta[i] ) / m_choosen_extent[i];
462                         if( snapbbox ){
463                                 float snappdwidth = float_snapped( scale[i] * m_bounds.extents[i] * 2.f, GetSnapGridSize() );
464                                 scale[i] = snappdwidth / ( m_bounds.extents[i] * 2.f );
465                         }
466                 }
467         }
468         if( snap ){
469                 for( std::size_t i = 0; i < 3; i++ ){
470                         if( scale[i] == 1.0f ){
471                                 scale[i] = vector3_dot( scale, m_axis );
472                         }
473                 }
474         }
475         //globalOutputStream() << "scale: " << scale <<"\n";
476         m_scalable.scale( scale );
477 }
478
479 void SetAxis( const Vector3& axis ){
480         m_axis = axis;
481 }
482 };
483
484 class ScaleFree : public Manipulatable
485 {
486 private:
487 Vector3 m_start;
488 Scalable& m_scalable;
489
490 Vector3 m_choosen_extent;
491 AABB m_bounds;
492
493 public:
494 ScaleFree( Scalable& scalable )
495         : m_scalable( scalable ){
496 }
497 void Construct( const Matrix4& device2manip, const float x, const float y, const AABB bounds, const Vector3 transform_origin ){
498         point_on_plane( m_start, device2manip, x, y );
499
500         m_choosen_extent = Vector3(
501                                         std::max( bounds.origin[0] + bounds.extents[0] - transform_origin[0], - bounds.origin[0] + bounds.extents[0] + transform_origin[0] ),
502                                         std::max( bounds.origin[1] + bounds.extents[1] - transform_origin[1], - bounds.origin[1] + bounds.extents[1] + transform_origin[1] ),
503                                         std::max( bounds.origin[2] + bounds.extents[2] - transform_origin[2], - bounds.origin[2] + bounds.extents[2] + transform_origin[2] )
504                                                         );
505         m_bounds = bounds;
506 }
507 void Transform( const Matrix4& manip2object, const Matrix4& device2manip, const float x, const float y, const bool snap, const bool snapbbox ){
508         Vector3 current;
509         point_on_plane( current, device2manip, x, y );
510         Vector3 delta = vector3_subtracted( current, m_start );
511
512         translation_local2object( delta, delta, manip2object );
513         vector3_snap( delta, GetSnapGridSize() );
514
515         Vector3 start( vector3_snapped( m_start, GetSnapGridSize() != 0.0f ? GetSnapGridSize() : 0.001f ) );
516         for ( std::size_t i = 0; i < 3 ; ++i ){ //prevent snapping to 0 with big gridsize
517                 if( float_snapped( m_start[i], 0.001f ) != 0.0f && start[i] == 0.0f ){
518                         start[i] = GetSnapGridSize();
519                 }
520         }
521         Vector3 scale(
522                 start[0] == 0 ? 1 : 1 + delta[0] / start[0],
523                 start[1] == 0 ? 1 : 1 + delta[1] / start[1],
524                 start[2] == 0 ? 1 : 1 + delta[2] / start[2]
525                 );
526
527         //globalOutputStream() << "m_start: " << m_start << "   start: " << start << "   delta: " << delta <<"\n";
528         for( std::size_t i = 0; i < 3; i++ ){
529                 if( m_choosen_extent[i] > 0.0625f ){
530                         scale[i] = ( m_choosen_extent[i] + delta[i] ) / m_choosen_extent[i];
531                         if( snapbbox && start[i] != 0.f ){
532                                 float snappdwidth = float_snapped( scale[i] * m_bounds.extents[i] * 2.f, GetSnapGridSize() );
533                                 scale[i] = snappdwidth / ( m_bounds.extents[i] * 2.f );
534                         }
535                 }
536         }
537         //globalOutputStream() << "pre snap scale: " << scale <<"\n";
538         if( snap ){
539                 float bestscale = scale[0];
540                 for( std::size_t i = 1; i < 3; i++ ){
541                         //if( fabs( 1.0f - fabs( scale[i] ) ) > fabs( 1.0f - fabs( bestscale ) ) ){
542                         if( fabs( scale[i] ) > fabs( bestscale ) && scale[i] != 1.0f ){ //harder to scale down with this, but glitchier with upper one
543                                 bestscale = scale[i];
544                         }
545                         //globalOutputStream() << "bestscale: " << bestscale <<"\n";
546                 }
547                 for( std::size_t i = 0; i < 3; i++ ){
548                         if( start[i] != 0.0f ){ // !!!!check grid == 0 case
549                                 scale[i] = ( scale[i] < 0.0f ) ? -fabs( bestscale ) : fabs( bestscale );
550                         }
551                 }
552         }
553         //globalOutputStream() << "scale: " << scale <<"\n";
554         m_scalable.scale( scale );
555 }
556 };
557
558
559
560
561
562
563
564
565
566
567 class RenderableClippedPrimitive : public OpenGLRenderable
568 {
569 struct primitive_t
570 {
571         PointVertex m_points[9];
572         std::size_t m_count;
573 };
574 Matrix4 m_inverse;
575 std::vector<primitive_t> m_primitives;
576 public:
577 Matrix4 m_world;
578
579 void render( RenderStateFlags state ) const {
580         for ( std::size_t i = 0; i < m_primitives.size(); ++i )
581         {
582                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_primitives[i].m_points[0].colour );
583                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_primitives[i].m_points[0].vertex );
584                 switch ( m_primitives[i].m_count )
585                 {
586                 case 1: break;
587                 case 2: glDrawArrays( GL_LINES, 0, GLsizei( m_primitives[i].m_count ) ); break;
588                 default: glDrawArrays( GL_POLYGON, 0, GLsizei( m_primitives[i].m_count ) ); break;
589                 }
590         }
591 }
592
593 void construct( const Matrix4& world2device ){
594         m_inverse = matrix4_full_inverse( world2device );
595         m_world = g_matrix4_identity;
596 }
597
598 void insert( const Vector4 clipped[9], std::size_t count ){
599         add_one();
600
601         m_primitives.back().m_count = count;
602         for ( std::size_t i = 0; i < count; ++i )
603         {
604                 Vector3 world_point( vector4_projected( matrix4_transformed_vector4( m_inverse, clipped[i] ) ) );
605                 m_primitives.back().m_points[i].vertex = vertex3f_for_vector3( world_point );
606         }
607 }
608
609 void destroy(){
610         m_primitives.clear();
611 }
612 private:
613 void add_one(){
614         m_primitives.push_back( primitive_t() );
615
616         const Colour4b colour_clipped( 255, 127, 0, 255 );
617
618         for ( std::size_t i = 0; i < 9; ++i )
619                 m_primitives.back().m_points[i].colour = colour_clipped;
620 }
621 };
622
623 #if GDEF_DEBUG
624 #define DEBUG_SELECTION
625 #endif
626
627 #if defined( DEBUG_SELECTION )
628 Shader* g_state_clipped;
629 RenderableClippedPrimitive g_render_clipped;
630 #endif
631
632
633 #if 0
634 // dist_Point_to_Line(): get the distance of a point to a line.
635 //    Input:  a Point P and a Line L (in any dimension)
636 //    Return: the shortest distance from P to L
637 float
638 dist_Point_to_Line( Point P, Line L ){
639         Vector v = L.P1 - L.P0;
640         Vector w = P - L.P0;
641
642         double c1 = dot( w,v );
643         double c2 = dot( v,v );
644         double b = c1 / c2;
645
646         Point Pb = L.P0 + b * v;
647         return d( P, Pb );
648 }
649 #endif
650
651 class Segment3D
652 {
653 typedef Vector3 point_type;
654 public:
655 Segment3D( const point_type& _p0, const point_type& _p1 )
656         : p0( _p0 ), p1( _p1 ){
657 }
658
659 point_type p0, p1;
660 };
661
662 typedef Vector3 Point3D;
663
664 inline double vector3_distance_squared( const Point3D& a, const Point3D& b ){
665         return vector3_length_squared( b - a );
666 }
667
668 // get the distance of a point to a segment.
669 Point3D segment_closest_point_to_point( const Segment3D& segment, const Point3D& point ){
670         Vector3 v = segment.p1 - segment.p0;
671         Vector3 w = point - segment.p0;
672
673         double c1 = vector3_dot( w,v );
674         if ( c1 <= 0 ) {
675                 return segment.p0;
676         }
677
678         double c2 = vector3_dot( v,v );
679         if ( c2 <= c1 ) {
680                 return segment.p1;
681         }
682
683         return Point3D( segment.p0 + v * ( c1 / c2 ) );
684 }
685
686 double segment_dist_to_point_3d( const Segment3D& segment, const Point3D& point ){
687         return vector3_distance_squared( point, segment_closest_point_to_point( segment, point ) );
688 }
689
690 typedef Vector3 point_t;
691 typedef const Vector3* point_iterator_t;
692
693 // crossing number test for a point in a polygon
694 // This code is patterned after [Franklin, 2000]
695 bool point_test_polygon_2d( const point_t& P, point_iterator_t start, point_iterator_t finish ){
696         std::size_t crossings = 0;
697
698         // loop through all edges of the polygon
699         for ( point_iterator_t prev = finish - 1, cur = start; cur != finish; prev = cur, ++cur )
700         {  // edge from (*prev) to (*cur)
701                 if ( ( ( ( *prev )[1] <= P[1] ) && ( ( *cur )[1] > P[1] ) ) // an upward crossing
702                          || ( ( ( *prev )[1] > P[1] ) && ( ( *cur )[1] <= P[1] ) ) ) { // a downward crossing
703                                                                                       // compute the actual edge-ray intersect x-coordinate
704                         float vt = (float)( P[1] - ( *prev )[1] ) / ( ( *cur )[1] - ( *prev )[1] );
705                         if ( P[0] < ( *prev )[0] + vt * ( ( *cur )[0] - ( *prev )[0] ) ) { // P[0] < intersect
706                                 ++crossings; // a valid crossing of y=P[1] right of P[0]
707                         }
708                 }
709         }
710         return ( crossings & 0x1 ) != 0; // 0 if even (out), and 1 if odd (in)
711 }
712
713 inline double triangle_signed_area_XY( const Vector3& p0, const Vector3& p1, const Vector3& p2 ){
714         return ( ( p1[0] - p0[0] ) * ( p2[1] - p0[1] ) ) - ( ( p2[0] - p0[0] ) * ( p1[1] - p0[1] ) );
715 }
716
717 enum clipcull_t
718 {
719         eClipCullNone,
720         eClipCullCW,
721         eClipCullCCW,
722 };
723
724
725 inline SelectionIntersection select_point_from_clipped( Vector4& clipped ){
726         return SelectionIntersection( clipped[2] / clipped[3], static_cast<float>( vector3_length_squared( Vector3( clipped[0] / clipped[3], clipped[1] / clipped[3], 0 ) ) ) );
727 }
728
729 void BestPoint( std::size_t count, Vector4 clipped[9], SelectionIntersection& best, clipcull_t cull ){
730         Vector3 normalised[9];
731
732         {
733                 for ( std::size_t i = 0; i < count; ++i )
734                 {
735                         normalised[i][0] = clipped[i][0] / clipped[i][3];
736                         normalised[i][1] = clipped[i][1] / clipped[i][3];
737                         normalised[i][2] = clipped[i][2] / clipped[i][3];
738                 }
739         }
740
741         if ( cull != eClipCullNone && count > 2 ) {
742                 double signed_area = triangle_signed_area_XY( normalised[0], normalised[1], normalised[2] );
743
744                 if ( ( cull == eClipCullCW && signed_area > 0 )
745                          || ( cull == eClipCullCCW && signed_area < 0 ) ) {
746                         return;
747                 }
748         }
749
750         if ( count == 2 ) {
751                 Segment3D segment( normalised[0], normalised[1] );
752                 Point3D point = segment_closest_point_to_point( segment, Vector3( 0, 0, 0 ) );
753                 assign_if_closer( best, SelectionIntersection( point.z(), 0 ) );
754         }
755         else if ( count > 2 && !point_test_polygon_2d( Vector3( 0, 0, 0 ), normalised, normalised + count ) ) {
756                 point_iterator_t end = normalised + count;
757                 for ( point_iterator_t previous = end - 1, current = normalised; current != end; previous = current, ++current )
758                 {
759                         Segment3D segment( *previous, *current );
760                         Point3D point = segment_closest_point_to_point( segment, Vector3( 0, 0, 0 ) );
761                         float depth = point.z();
762                         point.z() = 0;
763                         float distance = static_cast<float>( vector3_length_squared( point ) );
764
765                         assign_if_closer( best, SelectionIntersection( depth, distance ) );
766                 }
767         }
768         else if ( count > 2 ) {
769                 assign_if_closer(
770                         best,
771                         SelectionIntersection(
772                                 static_cast<float>( ray_distance_to_plane(
773                                                                                 Ray( Vector3( 0, 0, 0 ), Vector3( 0, 0, 1 ) ),
774                                                                                 plane3_for_points( normalised[0], normalised[1], normalised[2] )
775                                                                                 ) ),
776                                 0
777                                 )
778                         );
779         }
780
781 #if defined( DEBUG_SELECTION )
782         if ( count >= 2 ) {
783                 g_render_clipped.insert( clipped, count );
784         }
785 #endif
786 }
787
788 void LineStrip_BestPoint( const Matrix4& local2view, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best ){
789         Vector4 clipped[2];
790         for ( std::size_t i = 0; ( i + 1 ) < size; ++i )
791         {
792                 const std::size_t count = matrix4_clip_line( local2view, vertex3f_to_vector3( vertices[i].vertex ), vertex3f_to_vector3( vertices[i + 1].vertex ), clipped );
793                 BestPoint( count, clipped, best, eClipCullNone );
794         }
795 }
796
797 void LineLoop_BestPoint( const Matrix4& local2view, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best ){
798         Vector4 clipped[2];
799         for ( std::size_t i = 0; i < size; ++i )
800         {
801                 const std::size_t count = matrix4_clip_line( local2view, vertex3f_to_vector3( vertices[i].vertex ), vertex3f_to_vector3( vertices[( i + 1 ) % size].vertex ), clipped );
802                 BestPoint( count, clipped, best, eClipCullNone );
803         }
804 }
805
806 void Line_BestPoint( const Matrix4& local2view, const PointVertex vertices[2], SelectionIntersection& best ){
807         Vector4 clipped[2];
808         const std::size_t count = matrix4_clip_line( local2view, vertex3f_to_vector3( vertices[0].vertex ), vertex3f_to_vector3( vertices[1].vertex ), clipped );
809         BestPoint( count, clipped, best, eClipCullNone );
810 }
811
812 void Circle_BestPoint( const Matrix4& local2view, clipcull_t cull, const PointVertex* vertices, const std::size_t size, SelectionIntersection& best ){
813         Vector4 clipped[9];
814         for ( std::size_t i = 0; i < size; ++i )
815         {
816                 const std::size_t count = matrix4_clip_triangle( local2view, g_vector3_identity, vertex3f_to_vector3( vertices[i].vertex ), vertex3f_to_vector3( vertices[( i + 1 ) % size].vertex ), clipped );
817                 BestPoint( count, clipped, best, cull );
818         }
819 }
820
821 void Quad_BestPoint( const Matrix4& local2view, clipcull_t cull, const PointVertex* vertices, SelectionIntersection& best ){
822         Vector4 clipped[9];
823         {
824                 const std::size_t count = matrix4_clip_triangle( local2view, vertex3f_to_vector3( vertices[0].vertex ), vertex3f_to_vector3( vertices[1].vertex ), vertex3f_to_vector3( vertices[3].vertex ), clipped );
825                 BestPoint( count, clipped, best, cull );
826         }
827         {
828                 const std::size_t count = matrix4_clip_triangle( local2view, vertex3f_to_vector3( vertices[1].vertex ), vertex3f_to_vector3( vertices[2].vertex ), vertex3f_to_vector3( vertices[3].vertex ), clipped );
829                 BestPoint( count, clipped, best, cull );
830         }
831 }
832
833 struct FlatShadedVertex
834 {
835         Vertex3f vertex;
836         Colour4b colour;
837         Normal3f normal;
838
839         FlatShadedVertex(){
840         }
841 };
842
843
844 typedef FlatShadedVertex* FlatShadedVertexIterator;
845 void Triangles_BestPoint( const Matrix4& local2view, clipcull_t cull, FlatShadedVertexIterator first, FlatShadedVertexIterator last, SelectionIntersection& best ){
846         for ( FlatShadedVertexIterator x( first ), y( first + 1 ), z( first + 2 ); x != last; x += 3, y += 3, z += 3 )
847         {
848                 Vector4 clipped[9];
849                 BestPoint(
850                         matrix4_clip_triangle(
851                                 local2view,
852                                 reinterpret_cast<const Vector3&>( ( *x ).vertex ),
853                                 reinterpret_cast<const Vector3&>( ( *y ).vertex ),
854                                 reinterpret_cast<const Vector3&>( ( *z ).vertex ),
855                                 clipped
856                                 ),
857                         clipped,
858                         best,
859                         cull
860                         );
861         }
862 }
863
864
865 typedef std::multimap<SelectionIntersection, Selectable*> SelectableSortedSet;
866
867 class SelectionPool : public Selector
868 {
869 SelectableSortedSet m_pool;
870 SelectionIntersection m_intersection;
871 Selectable* m_selectable;
872
873 public:
874 void pushSelectable( Selectable& selectable ){
875         m_intersection = SelectionIntersection();
876         m_selectable = &selectable;
877 }
878 void popSelectable(){
879         addSelectable( m_intersection, m_selectable );
880         m_intersection = SelectionIntersection();
881 }
882 void addIntersection( const SelectionIntersection& intersection ){
883         assign_if_closer( m_intersection, intersection );
884 }
885 void addSelectable( const SelectionIntersection& intersection, Selectable* selectable ){
886         if ( intersection.valid() ) {
887                 m_pool.insert( SelectableSortedSet::value_type( intersection, selectable ) );
888         }
889 }
890
891 typedef SelectableSortedSet::iterator iterator;
892
893 iterator begin(){
894         return m_pool.begin();
895 }
896 iterator end(){
897         return m_pool.end();
898 }
899
900 bool failed(){
901         return m_pool.empty();
902 }
903 };
904
905
906 const Colour4b g_colour_sphere( 0, 0, 0, 255 );
907 const Colour4b g_colour_screen( 0, 255, 255, 255 );
908 const Colour4b g_colour_selected( 255, 255, 0, 255 );
909
910 inline const Colour4b& colourSelected( const Colour4b& colour, bool selected ){
911         return ( selected ) ? g_colour_selected : colour;
912 }
913
914 template<typename remap_policy>
915 inline void draw_semicircle( const std::size_t segments, const float radius, PointVertex* vertices, remap_policy remap ){
916         const double increment = c_pi / double(segments << 2);
917
918         std::size_t count = 0;
919         float x = radius;
920         float y = 0;
921         remap_policy::set( vertices[segments << 2].vertex, -radius, 0, 0 );
922         while ( count < segments )
923         {
924                 PointVertex* i = vertices + count;
925                 PointVertex* j = vertices + ( ( segments << 1 ) - ( count + 1 ) );
926
927                 PointVertex* k = i + ( segments << 1 );
928                 PointVertex* l = j + ( segments << 1 );
929
930 #if 0
931                 PointVertex* m = i + ( segments << 2 );
932                 PointVertex* n = j + ( segments << 2 );
933                 PointVertex* o = k + ( segments << 2 );
934                 PointVertex* p = l + ( segments << 2 );
935 #endif
936
937                 remap_policy::set( i->vertex, x,-y, 0 );
938                 remap_policy::set( k->vertex,-y,-x, 0 );
939 #if 0
940                 remap_policy::set( m->vertex,-x, y, 0 );
941                 remap_policy::set( o->vertex, y, x, 0 );
942 #endif
943
944                 ++count;
945
946                 {
947                         const double theta = increment * count;
948                         x = static_cast<float>( radius * cos( theta ) );
949                         y = static_cast<float>( radius * sin( theta ) );
950                 }
951
952                 remap_policy::set( j->vertex, y,-x, 0 );
953                 remap_policy::set( l->vertex,-x,-y, 0 );
954 #if 0
955                 remap_policy::set( n->vertex,-y, x, 0 );
956                 remap_policy::set( p->vertex, x, y, 0 );
957 #endif
958         }
959 }
960
961 class Manipulator
962 {
963 public:
964 virtual Manipulatable* GetManipulatable() = 0;
965 virtual void testSelect( const View& view, const Matrix4& pivot2world ){
966 }
967 virtual void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){
968 }
969 virtual void setSelected( bool select ) = 0;
970 virtual bool isSelected() const = 0;
971 };
972
973
974 inline Vector3 normalised_safe( const Vector3& self ){
975         if ( vector3_equal( self, g_vector3_identity ) ) {
976                 return g_vector3_identity;
977         }
978         return vector3_normalised( self );
979 }
980
981
982 class RotateManipulator : public Manipulator
983 {
984 struct RenderableCircle : public OpenGLRenderable
985 {
986         Array<PointVertex> m_vertices;
987
988         RenderableCircle( std::size_t size ) : m_vertices( size ){
989         }
990         void render( RenderStateFlags state ) const {
991                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour );
992                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex );
993                 glDrawArrays( GL_LINE_LOOP, 0, GLsizei( m_vertices.size() ) );
994         }
995         void setColour( const Colour4b& colour ){
996                 for ( Array<PointVertex>::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i )
997                 {
998                         ( *i ).colour = colour;
999                 }
1000         }
1001 };
1002
1003 struct RenderableSemiCircle : public OpenGLRenderable
1004 {
1005         Array<PointVertex> m_vertices;
1006
1007         RenderableSemiCircle( std::size_t size ) : m_vertices( size ){
1008         }
1009         void render( RenderStateFlags state ) const {
1010                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_vertices.data()->colour );
1011                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_vertices.data()->vertex );
1012                 glDrawArrays( GL_LINE_STRIP, 0, GLsizei( m_vertices.size() ) );
1013         }
1014         void setColour( const Colour4b& colour ){
1015                 for ( Array<PointVertex>::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i )
1016                 {
1017                         ( *i ).colour = colour;
1018                 }
1019         }
1020 };
1021
1022 RotateFree m_free;
1023 RotateAxis m_axis;
1024 Vector3 m_axis_screen;
1025 RenderableSemiCircle m_circle_x;
1026 RenderableSemiCircle m_circle_y;
1027 RenderableSemiCircle m_circle_z;
1028 RenderableCircle m_circle_screen;
1029 RenderableCircle m_circle_sphere;
1030 SelectableBool m_selectable_x;
1031 SelectableBool m_selectable_y;
1032 SelectableBool m_selectable_z;
1033 SelectableBool m_selectable_screen;
1034 SelectableBool m_selectable_sphere;
1035 Pivot2World m_pivot;
1036 Matrix4 m_local2world_x;
1037 Matrix4 m_local2world_y;
1038 Matrix4 m_local2world_z;
1039 bool m_circle_x_visible;
1040 bool m_circle_y_visible;
1041 bool m_circle_z_visible;
1042 public:
1043 static Shader* m_state_outer;
1044
1045 RotateManipulator( Rotatable& rotatable, std::size_t segments, float radius ) :
1046         m_free( rotatable ),
1047         m_axis( rotatable ),
1048         m_circle_x( ( segments << 2 ) + 1 ),
1049         m_circle_y( ( segments << 2 ) + 1 ),
1050         m_circle_z( ( segments << 2 ) + 1 ),
1051         m_circle_screen( segments << 3 ),
1052         m_circle_sphere( segments << 3 ){
1053         draw_semicircle( segments, radius, m_circle_x.m_vertices.data(), RemapYZX() );
1054         draw_semicircle( segments, radius, m_circle_y.m_vertices.data(), RemapZXY() );
1055         draw_semicircle( segments, radius, m_circle_z.m_vertices.data(), RemapXYZ() );
1056
1057         draw_circle( segments, radius * 1.15f, m_circle_screen.m_vertices.data(), RemapXYZ() );
1058         draw_circle( segments, radius, m_circle_sphere.m_vertices.data(), RemapXYZ() );
1059
1060         m_selectable_sphere.setSelected( true );
1061 }
1062
1063
1064 void UpdateColours(){
1065         m_circle_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) );
1066         m_circle_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) );
1067         m_circle_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) );
1068         m_circle_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) );
1069         m_circle_sphere.setColour( colourSelected( g_colour_sphere, false ) );
1070 }
1071
1072 void updateCircleTransforms(){
1073         Vector3 localViewpoint( matrix4_transformed_direction( matrix4_transposed( m_pivot.m_worldSpace ), vector4_to_vector3( m_pivot.m_viewpointSpace.z() ) ) );
1074
1075         m_circle_x_visible = !vector3_equal_epsilon( g_vector3_axis_x, localViewpoint, 1e-6f );
1076         if ( m_circle_x_visible ) {
1077                 m_local2world_x = g_matrix4_identity;
1078                 vector4_to_vector3( m_local2world_x.y() ) = normalised_safe(
1079                         vector3_cross( g_vector3_axis_x, localViewpoint )
1080                         );
1081                 vector4_to_vector3( m_local2world_x.z() ) = normalised_safe(
1082                         vector3_cross( vector4_to_vector3( m_local2world_x.x() ), vector4_to_vector3( m_local2world_x.y() ) )
1083                         );
1084                 matrix4_premultiply_by_matrix4( m_local2world_x, m_pivot.m_worldSpace );
1085         }
1086
1087         m_circle_y_visible = !vector3_equal_epsilon( g_vector3_axis_y, localViewpoint, 1e-6f );
1088         if ( m_circle_y_visible ) {
1089                 m_local2world_y = g_matrix4_identity;
1090                 vector4_to_vector3( m_local2world_y.z() ) = normalised_safe(
1091                         vector3_cross( g_vector3_axis_y, localViewpoint )
1092                         );
1093                 vector4_to_vector3( m_local2world_y.x() ) = normalised_safe(
1094                         vector3_cross( vector4_to_vector3( m_local2world_y.y() ), vector4_to_vector3( m_local2world_y.z() ) )
1095                         );
1096                 matrix4_premultiply_by_matrix4( m_local2world_y, m_pivot.m_worldSpace );
1097         }
1098
1099         m_circle_z_visible = !vector3_equal_epsilon( g_vector3_axis_z, localViewpoint, 1e-6f );
1100         if ( m_circle_z_visible ) {
1101                 m_local2world_z = g_matrix4_identity;
1102                 vector4_to_vector3( m_local2world_z.x() ) = normalised_safe(
1103                         vector3_cross( g_vector3_axis_z, localViewpoint )
1104                         );
1105                 vector4_to_vector3( m_local2world_z.y() ) = normalised_safe(
1106                         vector3_cross( vector4_to_vector3( m_local2world_z.z() ), vector4_to_vector3( m_local2world_z.x() ) )
1107                         );
1108                 matrix4_premultiply_by_matrix4( m_local2world_z, m_pivot.m_worldSpace );
1109         }
1110 }
1111
1112 void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){
1113         m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() );
1114         updateCircleTransforms();
1115
1116         // temp hack
1117         UpdateColours();
1118
1119         renderer.SetState( m_state_outer, Renderer::eWireframeOnly );
1120         renderer.SetState( m_state_outer, Renderer::eFullMaterials );
1121
1122         renderer.addRenderable( m_circle_screen, m_pivot.m_viewpointSpace );
1123         renderer.addRenderable( m_circle_sphere, m_pivot.m_viewpointSpace );
1124
1125         if ( m_circle_x_visible ) {
1126                 renderer.addRenderable( m_circle_x, m_local2world_x );
1127         }
1128         if ( m_circle_y_visible ) {
1129                 renderer.addRenderable( m_circle_y, m_local2world_y );
1130         }
1131         if ( m_circle_z_visible ) {
1132                 renderer.addRenderable( m_circle_z, m_local2world_z );
1133         }
1134 }
1135 void testSelect( const View& view, const Matrix4& pivot2world ){
1136         m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() );
1137         updateCircleTransforms();
1138
1139         SelectionPool selector;
1140
1141         {
1142                 {
1143                         Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_x ) );
1144
1145 #if defined( DEBUG_SELECTION )
1146                         g_render_clipped.construct( view.GetViewMatrix() );
1147 #endif
1148
1149                         SelectionIntersection best;
1150                         LineStrip_BestPoint( local2view, m_circle_x.m_vertices.data(), m_circle_x.m_vertices.size(), best );
1151                         selector.addSelectable( best, &m_selectable_x );
1152                 }
1153
1154                 {
1155                         Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_y ) );
1156
1157 #if defined( DEBUG_SELECTION )
1158                         g_render_clipped.construct( view.GetViewMatrix() );
1159 #endif
1160
1161                         SelectionIntersection best;
1162                         LineStrip_BestPoint( local2view, m_circle_y.m_vertices.data(), m_circle_y.m_vertices.size(), best );
1163                         selector.addSelectable( best, &m_selectable_y );
1164                 }
1165
1166                 {
1167                         Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_local2world_z ) );
1168
1169 #if defined( DEBUG_SELECTION )
1170                         g_render_clipped.construct( view.GetViewMatrix() );
1171 #endif
1172
1173                         SelectionIntersection best;
1174                         LineStrip_BestPoint( local2view, m_circle_z.m_vertices.data(), m_circle_z.m_vertices.size(), best );
1175                         selector.addSelectable( best, &m_selectable_z );
1176                 }
1177         }
1178
1179         {
1180                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) );
1181
1182                 {
1183                         SelectionIntersection best;
1184                         LineLoop_BestPoint( local2view, m_circle_screen.m_vertices.data(), m_circle_screen.m_vertices.size(), best );
1185                         selector.addSelectable( best, &m_selectable_screen );
1186                 }
1187
1188                 {
1189                         SelectionIntersection best;
1190                         Circle_BestPoint( local2view, eClipCullCW, m_circle_sphere.m_vertices.data(), m_circle_sphere.m_vertices.size(), best );
1191                         selector.addSelectable( best, &m_selectable_sphere );
1192                 }
1193         }
1194
1195         m_axis_screen = m_pivot.m_axis_screen;
1196
1197         if ( !selector.failed() ) {
1198                 ( *selector.begin() ).second->setSelected( true );
1199         }
1200 }
1201
1202 Manipulatable* GetManipulatable(){
1203         if ( m_selectable_x.isSelected() ) {
1204                 m_axis.SetAxis( g_vector3_axis_x );
1205                 return &m_axis;
1206         }
1207         else if ( m_selectable_y.isSelected() ) {
1208                 m_axis.SetAxis( g_vector3_axis_y );
1209                 return &m_axis;
1210         }
1211         else if ( m_selectable_z.isSelected() ) {
1212                 m_axis.SetAxis( g_vector3_axis_z );
1213                 return &m_axis;
1214         }
1215         else if ( m_selectable_screen.isSelected() ) {
1216                 m_axis.SetAxis( m_axis_screen );
1217                 return &m_axis;
1218         }
1219         else{
1220                 return &m_free;
1221         }
1222 }
1223
1224 void setSelected( bool select ){
1225         m_selectable_x.setSelected( select );
1226         m_selectable_y.setSelected( select );
1227         m_selectable_z.setSelected( select );
1228         m_selectable_screen.setSelected( select );
1229 }
1230 bool isSelected() const {
1231         return m_selectable_x.isSelected()
1232                    | m_selectable_y.isSelected()
1233                    | m_selectable_z.isSelected()
1234                    | m_selectable_screen.isSelected()
1235                    | m_selectable_sphere.isSelected();
1236 }
1237 };
1238
1239 Shader* RotateManipulator::m_state_outer;
1240
1241
1242 const float arrowhead_length = 16;
1243 const float arrowhead_radius = 4;
1244
1245 inline void draw_arrowline( const float length, PointVertex* line, const std::size_t axis ){
1246         ( *line++ ).vertex = vertex3f_identity;
1247         ( *line ).vertex = vertex3f_identity;
1248         vertex3f_to_array( ( *line ).vertex )[axis] = length - arrowhead_length;
1249 }
1250
1251 template<typename VertexRemap, typename NormalRemap>
1252 inline void draw_arrowhead( const std::size_t segments, const float length, FlatShadedVertex* vertices, VertexRemap, NormalRemap ){
1253         std::size_t head_tris = ( segments << 3 );
1254         const double head_segment = c_2pi / head_tris;
1255         for ( std::size_t i = 0; i < head_tris; ++i )
1256         {
1257                 {
1258                         FlatShadedVertex& point = vertices[i * 6 + 0];
1259                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1260                         VertexRemap::y( point.vertex ) = arrowhead_radius * static_cast<float>( cos( i * head_segment ) );
1261                         VertexRemap::z( point.vertex ) = arrowhead_radius * static_cast<float>( sin( i * head_segment ) );
1262                         NormalRemap::x( point.normal ) = arrowhead_radius / arrowhead_length;
1263                         NormalRemap::y( point.normal ) = static_cast<float>( cos( i * head_segment ) );
1264                         NormalRemap::z( point.normal ) = static_cast<float>( sin( i * head_segment ) );
1265                 }
1266                 {
1267                         FlatShadedVertex& point = vertices[i * 6 + 1];
1268                         VertexRemap::x( point.vertex ) = length;
1269                         VertexRemap::y( point.vertex ) = 0;
1270                         VertexRemap::z( point.vertex ) = 0;
1271                         NormalRemap::x( point.normal ) = arrowhead_radius / arrowhead_length;
1272                         NormalRemap::y( point.normal ) = static_cast<float>( cos( ( i + 0.5 ) * head_segment ) );
1273                         NormalRemap::z( point.normal ) = static_cast<float>( sin( ( i + 0.5 ) * head_segment ) );
1274                 }
1275                 {
1276                         FlatShadedVertex& point = vertices[i * 6 + 2];
1277                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1278                         VertexRemap::y( point.vertex ) = arrowhead_radius * static_cast<float>( cos( ( i + 1 ) * head_segment ) );
1279                         VertexRemap::z( point.vertex ) = arrowhead_radius * static_cast<float>( sin( ( i + 1 ) * head_segment ) );
1280                         NormalRemap::x( point.normal ) = arrowhead_radius / arrowhead_length;
1281                         NormalRemap::y( point.normal ) = static_cast<float>( cos( ( i + 1 ) * head_segment ) );
1282                         NormalRemap::z( point.normal ) = static_cast<float>( sin( ( i + 1 ) * head_segment ) );
1283                 }
1284
1285                 {
1286                         FlatShadedVertex& point = vertices[i * 6 + 3];
1287                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1288                         VertexRemap::y( point.vertex ) = 0;
1289                         VertexRemap::z( point.vertex ) = 0;
1290                         NormalRemap::x( point.normal ) = -1;
1291                         NormalRemap::y( point.normal ) = 0;
1292                         NormalRemap::z( point.normal ) = 0;
1293                 }
1294                 {
1295                         FlatShadedVertex& point = vertices[i * 6 + 4];
1296                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1297                         VertexRemap::y( point.vertex ) = arrowhead_radius * static_cast<float>( cos( i * head_segment ) );
1298                         VertexRemap::z( point.vertex ) = arrowhead_radius * static_cast<float>( sin( i * head_segment ) );
1299                         NormalRemap::x( point.normal ) = -1;
1300                         NormalRemap::y( point.normal ) = 0;
1301                         NormalRemap::z( point.normal ) = 0;
1302                 }
1303                 {
1304                         FlatShadedVertex& point = vertices[i * 6 + 5];
1305                         VertexRemap::x( point.vertex ) = length - arrowhead_length;
1306                         VertexRemap::y( point.vertex ) = arrowhead_radius * static_cast<float>( cos( ( i + 1 ) * head_segment ) );
1307                         VertexRemap::z( point.vertex ) = arrowhead_radius * static_cast<float>( sin( ( i + 1 ) * head_segment ) );
1308                         NormalRemap::x( point.normal ) = -1;
1309                         NormalRemap::y( point.normal ) = 0;
1310                         NormalRemap::z( point.normal ) = 0;
1311                 }
1312         }
1313 }
1314
1315 template<typename Triple>
1316 class TripleRemapXYZ
1317 {
1318 public:
1319 static float& x( Triple& triple ){
1320         return triple.x();
1321 }
1322 static float& y( Triple& triple ){
1323         return triple.y();
1324 }
1325 static float& z( Triple& triple ){
1326         return triple.z();
1327 }
1328 };
1329
1330 template<typename Triple>
1331 class TripleRemapYZX
1332 {
1333 public:
1334 static float& x( Triple& triple ){
1335         return triple.y();
1336 }
1337 static float& y( Triple& triple ){
1338         return triple.z();
1339 }
1340 static float& z( Triple& triple ){
1341         return triple.x();
1342 }
1343 };
1344
1345 template<typename Triple>
1346 class TripleRemapZXY
1347 {
1348 public:
1349 static float& x( Triple& triple ){
1350         return triple.z();
1351 }
1352 static float& y( Triple& triple ){
1353         return triple.x();
1354 }
1355 static float& z( Triple& triple ){
1356         return triple.y();
1357 }
1358 };
1359
1360 void vector3_print( const Vector3& v ){
1361         globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )";
1362 }
1363
1364 class TranslateManipulator : public Manipulator
1365 {
1366 struct RenderableArrowLine : public OpenGLRenderable
1367 {
1368         PointVertex m_line[2];
1369
1370         RenderableArrowLine(){
1371         }
1372         void render( RenderStateFlags state ) const {
1373                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_line[0].colour );
1374                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_line[0].vertex );
1375                 glDrawArrays( GL_LINES, 0, 2 );
1376         }
1377         void setColour( const Colour4b& colour ){
1378                 m_line[0].colour = colour;
1379                 m_line[1].colour = colour;
1380         }
1381 };
1382 struct RenderableArrowHead : public OpenGLRenderable
1383 {
1384         Array<FlatShadedVertex> m_vertices;
1385
1386         RenderableArrowHead( std::size_t size )
1387                 : m_vertices( size ){
1388         }
1389         void render( RenderStateFlags state ) const {
1390                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( FlatShadedVertex ), &m_vertices.data()->colour );
1391                 glVertexPointer( 3, GL_FLOAT, sizeof( FlatShadedVertex ), &m_vertices.data()->vertex );
1392                 glNormalPointer( GL_FLOAT, sizeof( FlatShadedVertex ), &m_vertices.data()->normal );
1393                 glDrawArrays( GL_TRIANGLES, 0, GLsizei( m_vertices.size() ) );
1394         }
1395         void setColour( const Colour4b& colour ){
1396                 for ( Array<FlatShadedVertex>::iterator i = m_vertices.begin(); i != m_vertices.end(); ++i )
1397                 {
1398                         ( *i ).colour = colour;
1399                 }
1400         }
1401 };
1402 struct RenderableQuad : public OpenGLRenderable
1403 {
1404         PointVertex m_quad[4];
1405         void render( RenderStateFlags state ) const {
1406                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_quad[0].colour );
1407                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_quad[0].vertex );
1408                 glDrawArrays( GL_LINE_LOOP, 0, 4 );
1409         }
1410         void setColour( const Colour4b& colour ){
1411                 m_quad[0].colour = colour;
1412                 m_quad[1].colour = colour;
1413                 m_quad[2].colour = colour;
1414                 m_quad[3].colour = colour;
1415         }
1416 };
1417
1418 TranslateFree m_free;
1419 TranslateAxis m_axis;
1420 RenderableArrowLine m_arrow_x;
1421 RenderableArrowLine m_arrow_y;
1422 RenderableArrowLine m_arrow_z;
1423 RenderableArrowHead m_arrow_head_x;
1424 RenderableArrowHead m_arrow_head_y;
1425 RenderableArrowHead m_arrow_head_z;
1426 RenderableQuad m_quad_screen;
1427 SelectableBool m_selectable_x;
1428 SelectableBool m_selectable_y;
1429 SelectableBool m_selectable_z;
1430 SelectableBool m_selectable_screen;
1431 Pivot2World m_pivot;
1432 public:
1433 static Shader* m_state_wire;
1434 static Shader* m_state_fill;
1435
1436 TranslateManipulator( Translatable& translatable, std::size_t segments, float length ) :
1437         m_free( translatable ),
1438         m_axis( translatable ),
1439         m_arrow_head_x( 3 * 2 * ( segments << 3 ) ),
1440         m_arrow_head_y( 3 * 2 * ( segments << 3 ) ),
1441         m_arrow_head_z( 3 * 2 * ( segments << 3 ) ){
1442         draw_arrowline( length, m_arrow_x.m_line, 0 );
1443         draw_arrowhead( segments, length, m_arrow_head_x.m_vertices.data(), TripleRemapXYZ<Vertex3f>(), TripleRemapXYZ<Normal3f>() );
1444         draw_arrowline( length, m_arrow_y.m_line, 1 );
1445         draw_arrowhead( segments, length, m_arrow_head_y.m_vertices.data(), TripleRemapYZX<Vertex3f>(), TripleRemapYZX<Normal3f>() );
1446         draw_arrowline( length, m_arrow_z.m_line, 2 );
1447         draw_arrowhead( segments, length, m_arrow_head_z.m_vertices.data(), TripleRemapZXY<Vertex3f>(), TripleRemapZXY<Normal3f>() );
1448
1449         draw_quad( 16, m_quad_screen.m_quad );
1450 }
1451
1452 void UpdateColours(){
1453         m_arrow_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) );
1454         m_arrow_head_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) );
1455         m_arrow_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) );
1456         m_arrow_head_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) );
1457         m_arrow_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) );
1458         m_arrow_head_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) );
1459         m_quad_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) );
1460 }
1461
1462 bool manipulator_show_axis( const Pivot2World& pivot, const Vector3& axis ){
1463         return fabs( vector3_dot( pivot.m_axis_screen, axis ) ) < 0.95;
1464 }
1465
1466 void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){
1467         m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() );
1468
1469         // temp hack
1470         UpdateColours();
1471
1472         Vector3 x = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.x() ) );
1473         bool show_x = manipulator_show_axis( m_pivot, x );
1474
1475         Vector3 y = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.y() ) );
1476         bool show_y = manipulator_show_axis( m_pivot, y );
1477
1478         Vector3 z = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.z() ) );
1479         bool show_z = manipulator_show_axis( m_pivot, z );
1480
1481         renderer.SetState( m_state_wire, Renderer::eWireframeOnly );
1482         renderer.SetState( m_state_wire, Renderer::eFullMaterials );
1483
1484         if ( show_x ) {
1485                 renderer.addRenderable( m_arrow_x, m_pivot.m_worldSpace );
1486         }
1487         if ( show_y ) {
1488                 renderer.addRenderable( m_arrow_y, m_pivot.m_worldSpace );
1489         }
1490         if ( show_z ) {
1491                 renderer.addRenderable( m_arrow_z, m_pivot.m_worldSpace );
1492         }
1493
1494         renderer.addRenderable( m_quad_screen, m_pivot.m_viewplaneSpace );
1495
1496         renderer.SetState( m_state_fill, Renderer::eWireframeOnly );
1497         renderer.SetState( m_state_fill, Renderer::eFullMaterials );
1498
1499         if ( show_x ) {
1500                 renderer.addRenderable( m_arrow_head_x, m_pivot.m_worldSpace );
1501         }
1502         if ( show_y ) {
1503                 renderer.addRenderable( m_arrow_head_y, m_pivot.m_worldSpace );
1504         }
1505         if ( show_z ) {
1506                 renderer.addRenderable( m_arrow_head_z, m_pivot.m_worldSpace );
1507         }
1508 }
1509 void testSelect( const View& view, const Matrix4& pivot2world ){
1510         m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() );
1511
1512         SelectionPool selector;
1513
1514         Vector3 x = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.x() ) );
1515         bool show_x = manipulator_show_axis( m_pivot, x );
1516
1517         Vector3 y = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.y() ) );
1518         bool show_y = manipulator_show_axis( m_pivot, y );
1519
1520         Vector3 z = vector3_normalised( vector4_to_vector3( m_pivot.m_worldSpace.z() ) );
1521         bool show_z = manipulator_show_axis( m_pivot, z );
1522
1523         {
1524                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) );
1525
1526                 {
1527                         SelectionIntersection best;
1528                         Quad_BestPoint( local2view, eClipCullCW, m_quad_screen.m_quad, best );
1529                         if ( best.valid() ) {
1530                                 best = SelectionIntersection( 0, 0 );
1531                                 selector.addSelectable( best, &m_selectable_screen );
1532                         }
1533                 }
1534         }
1535
1536         {
1537                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_worldSpace ) );
1538
1539 #if defined( DEBUG_SELECTION )
1540                 g_render_clipped.construct( view.GetViewMatrix() );
1541 #endif
1542
1543                 if ( show_x ) {
1544                         SelectionIntersection best;
1545                         Line_BestPoint( local2view, m_arrow_x.m_line, best );
1546                         Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_x.m_vertices.begin(), m_arrow_head_x.m_vertices.end(), best );
1547                         selector.addSelectable( best, &m_selectable_x );
1548                 }
1549
1550                 if ( show_y ) {
1551                         SelectionIntersection best;
1552                         Line_BestPoint( local2view, m_arrow_y.m_line, best );
1553                         Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_y.m_vertices.begin(), m_arrow_head_y.m_vertices.end(), best );
1554                         selector.addSelectable( best, &m_selectable_y );
1555                 }
1556
1557                 if ( show_z ) {
1558                         SelectionIntersection best;
1559                         Line_BestPoint( local2view, m_arrow_z.m_line, best );
1560                         Triangles_BestPoint( local2view, eClipCullCW, m_arrow_head_z.m_vertices.begin(), m_arrow_head_z.m_vertices.end(), best );
1561                         selector.addSelectable( best, &m_selectable_z );
1562                 }
1563         }
1564
1565         if ( !selector.failed() ) {
1566                 ( *selector.begin() ).second->setSelected( true );
1567         }
1568 }
1569
1570 Manipulatable* GetManipulatable(){
1571         if ( m_selectable_x.isSelected() ) {
1572                 m_axis.SetAxis( g_vector3_axis_x );
1573                 return &m_axis;
1574         }
1575         else if ( m_selectable_y.isSelected() ) {
1576                 m_axis.SetAxis( g_vector3_axis_y );
1577                 return &m_axis;
1578         }
1579         else if ( m_selectable_z.isSelected() ) {
1580                 m_axis.SetAxis( g_vector3_axis_z );
1581                 return &m_axis;
1582         }
1583         else
1584         {
1585                 return &m_free;
1586         }
1587 }
1588
1589 void setSelected( bool select ){
1590         m_selectable_x.setSelected( select );
1591         m_selectable_y.setSelected( select );
1592         m_selectable_z.setSelected( select );
1593         m_selectable_screen.setSelected( select );
1594 }
1595 bool isSelected() const {
1596         return m_selectable_x.isSelected()
1597                    | m_selectable_y.isSelected()
1598                    | m_selectable_z.isSelected()
1599                    | m_selectable_screen.isSelected();
1600 }
1601 };
1602
1603 Shader* TranslateManipulator::m_state_wire;
1604 Shader* TranslateManipulator::m_state_fill;
1605
1606 class ScaleManipulator : public Manipulator
1607 {
1608 struct RenderableArrow : public OpenGLRenderable
1609 {
1610         PointVertex m_line[2];
1611
1612         void render( RenderStateFlags state ) const {
1613                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_line[0].colour );
1614                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_line[0].vertex );
1615                 glDrawArrays( GL_LINES, 0, 2 );
1616         }
1617         void setColour( const Colour4b& colour ){
1618                 m_line[0].colour = colour;
1619                 m_line[1].colour = colour;
1620         }
1621 };
1622 struct RenderableQuad : public OpenGLRenderable
1623 {
1624         PointVertex m_quad[4];
1625         void render( RenderStateFlags state ) const {
1626                 glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof( PointVertex ), &m_quad[0].colour );
1627                 glVertexPointer( 3, GL_FLOAT, sizeof( PointVertex ), &m_quad[0].vertex );
1628                 glDrawArrays( GL_QUADS, 0, 4 );
1629         }
1630         void setColour( const Colour4b& colour ){
1631                 m_quad[0].colour = colour;
1632                 m_quad[1].colour = colour;
1633                 m_quad[2].colour = colour;
1634                 m_quad[3].colour = colour;
1635         }
1636 };
1637
1638 ScaleFree m_free;
1639 ScaleAxis m_axis;
1640 RenderableArrow m_arrow_x;
1641 RenderableArrow m_arrow_y;
1642 RenderableArrow m_arrow_z;
1643 RenderableQuad m_quad_screen;
1644 SelectableBool m_selectable_x;
1645 SelectableBool m_selectable_y;
1646 SelectableBool m_selectable_z;
1647 SelectableBool m_selectable_screen;
1648 Pivot2World m_pivot;
1649 public:
1650 ScaleManipulator( Scalable& scalable, std::size_t segments, float length ) :
1651         m_free( scalable ),
1652         m_axis( scalable ){
1653         draw_arrowline( length, m_arrow_x.m_line, 0 );
1654         draw_arrowline( length, m_arrow_y.m_line, 1 );
1655         draw_arrowline( length, m_arrow_z.m_line, 2 );
1656
1657         draw_quad( 16, m_quad_screen.m_quad );
1658 }
1659
1660 Pivot2World& getPivot(){
1661         return m_pivot;
1662 }
1663
1664 void UpdateColours(){
1665         m_arrow_x.setColour( colourSelected( g_colour_x, m_selectable_x.isSelected() ) );
1666         m_arrow_y.setColour( colourSelected( g_colour_y, m_selectable_y.isSelected() ) );
1667         m_arrow_z.setColour( colourSelected( g_colour_z, m_selectable_z.isSelected() ) );
1668         m_quad_screen.setColour( colourSelected( g_colour_screen, m_selectable_screen.isSelected() ) );
1669 }
1670
1671 void render( Renderer& renderer, const VolumeTest& volume, const Matrix4& pivot2world ){
1672         m_pivot.update( pivot2world, volume.GetModelview(), volume.GetProjection(), volume.GetViewport() );
1673
1674         // temp hack
1675         UpdateColours();
1676
1677         renderer.addRenderable( m_arrow_x, m_pivot.m_worldSpace );
1678         renderer.addRenderable( m_arrow_y, m_pivot.m_worldSpace );
1679         renderer.addRenderable( m_arrow_z, m_pivot.m_worldSpace );
1680
1681         renderer.addRenderable( m_quad_screen, m_pivot.m_viewpointSpace );
1682 }
1683 void testSelect( const View& view, const Matrix4& pivot2world ){
1684         m_pivot.update( pivot2world, view.GetModelview(), view.GetProjection(), view.GetViewport() );
1685
1686         SelectionPool selector;
1687
1688         {
1689                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_worldSpace ) );
1690
1691 #if defined( DEBUG_SELECTION )
1692                 g_render_clipped.construct( view.GetViewMatrix() );
1693 #endif
1694
1695                 {
1696                         SelectionIntersection best;
1697                         Line_BestPoint( local2view, m_arrow_x.m_line, best );
1698                         selector.addSelectable( best, &m_selectable_x );
1699                 }
1700
1701                 {
1702                         SelectionIntersection best;
1703                         Line_BestPoint( local2view, m_arrow_y.m_line, best );
1704                         selector.addSelectable( best, &m_selectable_y );
1705                 }
1706
1707                 {
1708                         SelectionIntersection best;
1709                         Line_BestPoint( local2view, m_arrow_z.m_line, best );
1710                         selector.addSelectable( best, &m_selectable_z );
1711                 }
1712         }
1713
1714         {
1715                 Matrix4 local2view( matrix4_multiplied_by_matrix4( view.GetViewMatrix(), m_pivot.m_viewpointSpace ) );
1716
1717                 {
1718                         SelectionIntersection best;
1719                         Quad_BestPoint( local2view, eClipCullCW, m_quad_screen.m_quad, best );
1720                         selector.addSelectable( best, &m_selectable_screen );
1721                 }
1722         }
1723
1724         if ( !selector.failed() ) {
1725                 ( *selector.begin() ).second->setSelected( true );
1726         }
1727 }
1728
1729 Manipulatable* GetManipulatable(){
1730         if ( m_selectable_x.isSelected() ) {
1731                 m_axis.SetAxis( g_vector3_axis_x );
1732                 return &m_axis;
1733         }
1734         else if ( m_selectable_y.isSelected() ) {
1735                 m_axis.SetAxis( g_vector3_axis_y );
1736                 return &m_axis;
1737         }
1738         else if ( m_selectable_z.isSelected() ) {
1739                 m_axis.SetAxis( g_vector3_axis_z );
1740                 return &m_axis;
1741         }
1742         else{
1743                 return &m_free;
1744         }
1745 }
1746
1747 void setSelected( bool select ){
1748         m_selectable_x.setSelected( select );
1749         m_selectable_y.setSelected( select );
1750         m_selectable_z.setSelected( select );
1751         m_selectable_screen.setSelected( select );
1752 }
1753 bool isSelected() const {
1754         return m_selectable_x.isSelected()
1755                    | m_selectable_y.isSelected()
1756                    | m_selectable_z.isSelected()
1757                    | m_selectable_screen.isSelected();
1758 }
1759 };
1760
1761
1762 inline PlaneSelectable* Instance_getPlaneSelectable( scene::Instance& instance ){
1763         return InstanceTypeCast<PlaneSelectable>::cast( instance );
1764 }
1765
1766 class PlaneSelectableSelectPlanes : public scene::Graph::Walker
1767 {
1768 Selector& m_selector;
1769 SelectionTest& m_test;
1770 PlaneCallback m_selectedPlaneCallback;
1771 public:
1772 PlaneSelectableSelectPlanes( Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback )
1773         : m_selector( selector ), m_test( test ), m_selectedPlaneCallback( selectedPlaneCallback ){
1774 }
1775 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1776         if ( path.top().get().visible() ) {
1777                 Selectable* selectable = Instance_getSelectable( instance );
1778                 if ( selectable != 0 && selectable->isSelected() ) {
1779                         PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance );
1780                         if ( planeSelectable != 0 ) {
1781                                 planeSelectable->selectPlanes( m_selector, m_test, m_selectedPlaneCallback );
1782                         }
1783                 }
1784         }
1785         return true;
1786 }
1787 };
1788
1789 class PlaneSelectableSelectReversedPlanes : public scene::Graph::Walker
1790 {
1791 Selector& m_selector;
1792 const SelectedPlanes& m_selectedPlanes;
1793 public:
1794 PlaneSelectableSelectReversedPlanes( Selector& selector, const SelectedPlanes& selectedPlanes )
1795         : m_selector( selector ), m_selectedPlanes( selectedPlanes ){
1796 }
1797 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1798         if ( path.top().get().visible() ) {
1799                 Selectable* selectable = Instance_getSelectable( instance );
1800                 if ( selectable != 0 && selectable->isSelected() ) {
1801                         PlaneSelectable* planeSelectable = Instance_getPlaneSelectable( instance );
1802                         if ( planeSelectable != 0 ) {
1803                                 planeSelectable->selectReversedPlanes( m_selector, m_selectedPlanes );
1804                         }
1805                 }
1806         }
1807         return true;
1808 }
1809 };
1810
1811 void Scene_forEachPlaneSelectable_selectPlanes( scene::Graph& graph, Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback ){
1812         graph.traverse( PlaneSelectableSelectPlanes( selector, test, selectedPlaneCallback ) );
1813 }
1814
1815 void Scene_forEachPlaneSelectable_selectReversedPlanes( scene::Graph& graph, Selector& selector, const SelectedPlanes& selectedPlanes ){
1816         graph.traverse( PlaneSelectableSelectReversedPlanes( selector, selectedPlanes ) );
1817 }
1818
1819
1820 class PlaneLess
1821 {
1822 public:
1823 bool operator()( const Plane3& plane, const Plane3& other ) const {
1824         if ( plane.a < other.a ) {
1825                 return true;
1826         }
1827         if ( other.a < plane.a ) {
1828                 return false;
1829         }
1830
1831         if ( plane.b < other.b ) {
1832                 return true;
1833         }
1834         if ( other.b < plane.b ) {
1835                 return false;
1836         }
1837
1838         if ( plane.c < other.c ) {
1839                 return true;
1840         }
1841         if ( other.c < plane.c ) {
1842                 return false;
1843         }
1844
1845         if ( plane.d < other.d ) {
1846                 return true;
1847         }
1848         if ( other.d < plane.d ) {
1849                 return false;
1850         }
1851
1852         return false;
1853 }
1854 };
1855
1856 typedef std::set<Plane3, PlaneLess> PlaneSet;
1857
1858 inline void PlaneSet_insert( PlaneSet& self, const Plane3& plane ){
1859         self.insert( plane );
1860 }
1861
1862 inline bool PlaneSet_contains( const PlaneSet& self, const Plane3& plane ){
1863         return self.find( plane ) != self.end();
1864 }
1865
1866
1867 class SelectedPlaneSet : public SelectedPlanes
1868 {
1869 PlaneSet m_selectedPlanes;
1870 public:
1871 bool empty() const {
1872         return m_selectedPlanes.empty();
1873 }
1874
1875 void insert( const Plane3& plane ){
1876         PlaneSet_insert( m_selectedPlanes, plane );
1877 }
1878 bool contains( const Plane3& plane ) const {
1879         return PlaneSet_contains( m_selectedPlanes, plane );
1880 }
1881 typedef MemberCaller<SelectedPlaneSet, void(const Plane3&), &SelectedPlaneSet::insert> InsertCaller;
1882 };
1883
1884
1885 bool Scene_forEachPlaneSelectable_selectPlanes( scene::Graph& graph, Selector& selector, SelectionTest& test ){
1886         SelectedPlaneSet selectedPlanes;
1887
1888         Scene_forEachPlaneSelectable_selectPlanes( graph, selector, test, SelectedPlaneSet::InsertCaller( selectedPlanes ) );
1889         Scene_forEachPlaneSelectable_selectReversedPlanes( graph, selector, selectedPlanes );
1890
1891         return !selectedPlanes.empty();
1892 }
1893
1894
1895 #include "brush.h"
1896 /*
1897 class TestedBrushPlanesSelectVeritces : public scene::Graph::Walker
1898 {
1899 SelectionTest& m_test;
1900 public:
1901 TestedBrushPlanesSelectVeritces( SelectionTest& test )
1902         : m_test( test ){
1903 }
1904 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1905         if ( path.top().get().visible() ) {
1906                 Selectable* selectable = Instance_getSelectable( instance );
1907                 if ( selectable != 0 && selectable->isSelected() ) {
1908                         BrushInstance* brushInstance = Instance_getBrush( instance );
1909                         if ( brushInstance != 0 ) {
1910                                 brushInstance->selectVerticesOnPlanes( m_test );
1911                         }
1912                 }
1913         }
1914         return true;
1915 }
1916 };
1917
1918 void Scene_forEachTestedBrushPlane_selectVertices( scene::Graph& graph, SelectionTest& test ){
1919         graph.traverse( TestedBrushPlanesSelectVeritces( test ) );
1920 }
1921 */
1922 class BrushPlanesSelectVeritces : public scene::Graph::Walker
1923 {
1924 SelectionTest& m_test;
1925 public:
1926 BrushPlanesSelectVeritces( SelectionTest& test )
1927         : m_test( test ){
1928 }
1929 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1930         if ( path.top().get().visible() ) {
1931                 Selectable* selectable = Instance_getSelectable( instance );
1932                 if ( selectable != 0 && selectable->isSelected() ) {
1933                         BrushInstance* brushInstance = Instance_getBrush( instance );
1934                         if ( brushInstance != 0 ) {
1935                                 brushInstance->selectVerticesOnPlanes( m_test );
1936                         }
1937                 }
1938         }
1939         return true;
1940 }
1941 };
1942
1943 void Scene_forEachBrushPlane_selectVertices( scene::Graph& graph, SelectionTest& test ){
1944         graph.traverse( BrushPlanesSelectVeritces( test ) );
1945 }
1946
1947 void Scene_Translate_Component_Selected( scene::Graph& graph, const Vector3& translation );
1948 void Scene_Translate_Selected( scene::Graph& graph, const Vector3& translation );
1949 void Scene_TestSelect_Primitive( Selector& selector, SelectionTest& test, const VolumeTest& volume );
1950 void Scene_TestSelect_Component( Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode );
1951 void Scene_TestSelect_Component_Selected( Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode );
1952 void Scene_SelectAll_Component( bool select, SelectionSystem::EComponentMode componentMode );
1953
1954 class ResizeTranslatable : public Translatable
1955 {
1956 void translate( const Vector3& translation ){
1957         Scene_Translate_Component_Selected( GlobalSceneGraph(), translation );
1958 }
1959 };
1960
1961 class DragTranslatable : public Translatable
1962 {
1963 void translate( const Vector3& translation ){
1964         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
1965                 Scene_Translate_Component_Selected( GlobalSceneGraph(), translation );
1966         }
1967         else
1968         {
1969                 Scene_Translate_Selected( GlobalSceneGraph(), translation );
1970         }
1971 }
1972 };
1973
1974 class SelectionVolume : public SelectionTest
1975 {
1976 Matrix4 m_local2view;
1977 const View& m_view;
1978 clipcull_t m_cull;
1979 Vector3 m_near;
1980 Vector3 m_far;
1981 public:
1982 SelectionVolume( const View& view )
1983         : m_view( view ){
1984 }
1985
1986 const VolumeTest& getVolume() const {
1987         return m_view;
1988 }
1989
1990 const Vector3& getNear() const {
1991         return m_near;
1992 }
1993 const Vector3& getFar() const {
1994         return m_far;
1995 }
1996
1997 void BeginMesh( const Matrix4& localToWorld, bool twoSided ){
1998         m_local2view = matrix4_multiplied_by_matrix4( m_view.GetViewMatrix(), localToWorld );
1999
2000         // Cull back-facing polygons based on winding being clockwise or counter-clockwise.
2001         // Don't cull if the view is wireframe and the polygons are two-sided.
2002         m_cull = twoSided && !m_view.fill() ? eClipCullNone : ( matrix4_handedness( localToWorld ) == MATRIX4_RIGHTHANDED ) ? eClipCullCW : eClipCullCCW;
2003
2004         {
2005                 Matrix4 screen2world( matrix4_full_inverse( m_local2view ) );
2006
2007                 m_near = vector4_projected(
2008                         matrix4_transformed_vector4(
2009                                 screen2world,
2010                                 Vector4( 0, 0, -1, 1 )
2011                                 )
2012                         );
2013
2014                 m_far = vector4_projected(
2015                         matrix4_transformed_vector4(
2016                                 screen2world,
2017                                 Vector4( 0, 0, 1, 1 )
2018                                 )
2019                         );
2020         }
2021
2022 #if defined( DEBUG_SELECTION )
2023         g_render_clipped.construct( m_view.GetViewMatrix() );
2024 #endif
2025 }
2026 void TestPoint( const Vector3& point, SelectionIntersection& best ){
2027         Vector4 clipped;
2028         if ( matrix4_clip_point( m_local2view, point, clipped ) == c_CLIP_PASS ) {
2029                 best = select_point_from_clipped( clipped );
2030         }
2031 }
2032 void TestPolygon( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){
2033         Vector4 clipped[9];
2034         for ( std::size_t i = 0; i + 2 < count; ++i )
2035         {
2036                 BestPoint(
2037                         matrix4_clip_triangle(
2038                                 m_local2view,
2039                                 reinterpret_cast<const Vector3&>( vertices[0] ),
2040                                 reinterpret_cast<const Vector3&>( vertices[i + 1] ),
2041                                 reinterpret_cast<const Vector3&>( vertices[i + 2] ),
2042                                 clipped
2043                                 ),
2044                         clipped,
2045                         best,
2046                         m_cull
2047                         );
2048         }
2049 }
2050 void TestLineLoop( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){
2051         if ( count == 0 ) {
2052                 return;
2053         }
2054         Vector4 clipped[9];
2055         for ( VertexPointer::iterator i = vertices.begin(), end = i + count, prev = i + ( count - 1 ); i != end; prev = i, ++i )
2056         {
2057                 BestPoint(
2058                         matrix4_clip_line(
2059                                 m_local2view,
2060                                 reinterpret_cast<const Vector3&>( ( *prev ) ),
2061                                 reinterpret_cast<const Vector3&>( ( *i ) ),
2062                                 clipped
2063                                 ),
2064                         clipped,
2065                         best,
2066                         m_cull
2067                         );
2068         }
2069 }
2070 void TestLineStrip( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){
2071         if ( count == 0 ) {
2072                 return;
2073         }
2074         Vector4 clipped[9];
2075         for ( VertexPointer::iterator i = vertices.begin(), end = i + count, next = i + 1; next != end; i = next, ++next )
2076         {
2077                 BestPoint(
2078                         matrix4_clip_line(
2079                                 m_local2view,
2080                                 reinterpret_cast<const Vector3&>( ( *i ) ),
2081                                 reinterpret_cast<const Vector3&>( ( *next ) ),
2082                                 clipped
2083                                 ),
2084                         clipped,
2085                         best,
2086                         m_cull
2087                         );
2088         }
2089 }
2090 void TestLines( const VertexPointer& vertices, std::size_t count, SelectionIntersection& best ){
2091         if ( count == 0 ) {
2092                 return;
2093         }
2094         Vector4 clipped[9];
2095         for ( VertexPointer::iterator i = vertices.begin(), end = i + count; i != end; i += 2 )
2096         {
2097                 BestPoint(
2098                         matrix4_clip_line(
2099                                 m_local2view,
2100                                 reinterpret_cast<const Vector3&>( ( *i ) ),
2101                                 reinterpret_cast<const Vector3&>( ( *( i + 1 ) ) ),
2102                                 clipped
2103                                 ),
2104                         clipped,
2105                         best,
2106                         m_cull
2107                         );
2108         }
2109 }
2110 void TestTriangles( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){
2111         Vector4 clipped[9];
2112         for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 3 )
2113         {
2114                 BestPoint(
2115                         matrix4_clip_triangle(
2116                                 m_local2view,
2117                                 reinterpret_cast<const Vector3&>( vertices[*i] ),
2118                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2119                                 reinterpret_cast<const Vector3&>( vertices[*( i + 2 )] ),
2120                                 clipped
2121                                 ),
2122                         clipped,
2123                         best,
2124                         m_cull
2125                         );
2126         }
2127 }
2128 void TestQuads( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){
2129         Vector4 clipped[9];
2130         for ( IndexPointer::iterator i( indices.begin() ); i != indices.end(); i += 4 )
2131         {
2132                 BestPoint(
2133                         matrix4_clip_triangle(
2134                                 m_local2view,
2135                                 reinterpret_cast<const Vector3&>( vertices[*i] ),
2136                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2137                                 reinterpret_cast<const Vector3&>( vertices[*( i + 3 )] ),
2138                                 clipped
2139                                 ),
2140                         clipped,
2141                         best,
2142                         m_cull
2143                         );
2144                 BestPoint(
2145                         matrix4_clip_triangle(
2146                                 m_local2view,
2147                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2148                                 reinterpret_cast<const Vector3&>( vertices[*( i + 2 )] ),
2149                                 reinterpret_cast<const Vector3&>( vertices[*( i + 3 )] ),
2150                                 clipped
2151                                 ),
2152                         clipped,
2153                         best,
2154                         m_cull
2155                         );
2156         }
2157 }
2158 void TestQuadStrip( const VertexPointer& vertices, const IndexPointer& indices, SelectionIntersection& best ){
2159         Vector4 clipped[9];
2160         for ( IndexPointer::iterator i( indices.begin() ); i + 2 != indices.end(); i += 2 )
2161         {
2162                 BestPoint(
2163                         matrix4_clip_triangle(
2164                                 m_local2view,
2165                                 reinterpret_cast<const Vector3&>( vertices[*i] ),
2166                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2167                                 reinterpret_cast<const Vector3&>( vertices[*( i + 2 )] ),
2168                                 clipped
2169                                 ),
2170                         clipped,
2171                         best,
2172                         m_cull
2173                         );
2174                 BestPoint(
2175                         matrix4_clip_triangle(
2176                                 m_local2view,
2177                                 reinterpret_cast<const Vector3&>( vertices[*( i + 2 )] ),
2178                                 reinterpret_cast<const Vector3&>( vertices[*( i + 1 )] ),
2179                                 reinterpret_cast<const Vector3&>( vertices[*( i + 3 )] ),
2180                                 clipped
2181                                 ),
2182                         clipped,
2183                         best,
2184                         m_cull
2185                         );
2186         }
2187 }
2188 };
2189
2190 class SelectionCounter
2191 {
2192 public:
2193 using func = void(const Selectable &);
2194
2195 SelectionCounter( const SelectionChangeCallback& onchanged )
2196         : m_count( 0 ), m_onchanged( onchanged ){
2197 }
2198 void operator()( const Selectable& selectable ){
2199         if ( selectable.isSelected() ) {
2200                 ++m_count;
2201         }
2202         else
2203         {
2204                 ASSERT_MESSAGE( m_count != 0, "selection counter underflow" );
2205                 --m_count;
2206         }
2207
2208         m_onchanged( selectable );
2209 }
2210 bool empty() const {
2211         return m_count == 0;
2212 }
2213 std::size_t size() const {
2214         return m_count;
2215 }
2216 private:
2217 std::size_t m_count;
2218 SelectionChangeCallback m_onchanged;
2219 };
2220
2221 inline void ConstructSelectionTest( View& view, const rect_t selection_box ){
2222         view.EnableScissor( selection_box.min[0], selection_box.max[0], selection_box.min[1], selection_box.max[1] );
2223 }
2224
2225 inline const rect_t SelectionBoxForPoint( const float device_point[2], const float device_epsilon[2] ){
2226         rect_t selection_box;
2227         selection_box.min[0] = device_point[0] - device_epsilon[0];
2228         selection_box.min[1] = device_point[1] - device_epsilon[1];
2229         selection_box.max[0] = device_point[0] + device_epsilon[0];
2230         selection_box.max[1] = device_point[1] + device_epsilon[1];
2231         return selection_box;
2232 }
2233
2234 inline const rect_t SelectionBoxForArea( const float device_point[2], const float device_delta[2] ){
2235         rect_t selection_box;
2236         selection_box.min[0] = ( device_delta[0] < 0 ) ? ( device_point[0] + device_delta[0] ) : ( device_point[0] );
2237         selection_box.min[1] = ( device_delta[1] < 0 ) ? ( device_point[1] + device_delta[1] ) : ( device_point[1] );
2238         selection_box.max[0] = ( device_delta[0] > 0 ) ? ( device_point[0] + device_delta[0] ) : ( device_point[0] );
2239         selection_box.max[1] = ( device_delta[1] > 0 ) ? ( device_point[1] + device_delta[1] ) : ( device_point[1] );
2240         return selection_box;
2241 }
2242
2243 Quaternion construct_local_rotation( const Quaternion& world, const Quaternion& localToWorld ){
2244         return quaternion_normalised( quaternion_multiplied_by_quaternion(
2245                                                                           quaternion_normalised( quaternion_multiplied_by_quaternion(
2246                                                                                                                                  quaternion_inverse( localToWorld ),
2247                                                                                                                                  world
2248                                                                                                                                  ) ),
2249                                                                           localToWorld
2250                                                                           ) );
2251 }
2252
2253 inline void matrix4_assign_rotation( Matrix4& matrix, const Matrix4& other ){
2254         matrix[0] = other[0];
2255         matrix[1] = other[1];
2256         matrix[2] = other[2];
2257         matrix[4] = other[4];
2258         matrix[5] = other[5];
2259         matrix[6] = other[6];
2260         matrix[8] = other[8];
2261         matrix[9] = other[9];
2262         matrix[10] = other[10];
2263 }
2264
2265 void matrix4_assign_rotation_for_pivot( Matrix4& matrix, scene::Instance& instance ){
2266         Editable* editable = Node_getEditable( instance.path().top() );
2267         if ( editable != 0 ) {
2268                 matrix4_assign_rotation( matrix, matrix4_multiplied_by_matrix4( instance.localToWorld(), editable->getLocalPivot() ) );
2269         }
2270         else
2271         {
2272                 matrix4_assign_rotation( matrix, instance.localToWorld() );
2273         }
2274 }
2275
2276 inline bool Instance_isSelectedComponents( scene::Instance& instance ){
2277         ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance );
2278         return componentSelectionTestable != 0
2279                    && componentSelectionTestable->isSelectedComponents();
2280 }
2281
2282 class TranslateSelected : public SelectionSystem::Visitor
2283 {
2284 const Vector3& m_translate;
2285 public:
2286 TranslateSelected( const Vector3& translate )
2287         : m_translate( translate ){
2288 }
2289 void visit( scene::Instance& instance ) const {
2290         Transformable* transform = Instance_getTransformable( instance );
2291         if ( transform != 0 ) {
2292                 transform->setType( TRANSFORM_PRIMITIVE );
2293                 transform->setTranslation( m_translate );
2294         }
2295 }
2296 };
2297
2298 void Scene_Translate_Selected( scene::Graph& graph, const Vector3& translation ){
2299         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2300                 GlobalSelectionSystem().foreachSelected( TranslateSelected( translation ) );
2301         }
2302 }
2303
2304 Vector3 get_local_pivot( const Vector3& world_pivot, const Matrix4& localToWorld ){
2305         return Vector3(
2306                            matrix4_transformed_point(
2307                                    matrix4_full_inverse( localToWorld ),
2308                                    world_pivot
2309                                    )
2310                            );
2311 }
2312
2313 void translation_for_pivoted_matrix_transform( Vector3& parent_translation, const Matrix4& local_transform, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent ){
2314         // we need a translation inside the parent system to move the origin of this object to the right place
2315
2316         // mathematically, it must fulfill:
2317         //
2318         //   local_translation local_transform local_pivot = local_pivot
2319         //   local_translation = local_pivot - local_transform local_pivot
2320         //
2321         //   or maybe?
2322         //   local_transform local_translation local_pivot = local_pivot
2323         //                   local_translation local_pivot = local_transform^-1 local_pivot
2324         //                 local_translation + local_pivot = local_transform^-1 local_pivot
2325         //                   local_translation             = local_transform^-1 local_pivot - local_pivot
2326
2327         Vector3 local_pivot( get_local_pivot( world_pivot, localToWorld ) );
2328
2329         Vector3 local_translation(
2330                 vector3_subtracted(
2331                         local_pivot,
2332                         matrix4_transformed_point(
2333                                 local_transform,
2334                                 local_pivot
2335                                 )
2336                 /*
2337                     matrix4_transformed_point(
2338                         matrix4_full_inverse(local_transform),
2339                         local_pivot
2340                     ),
2341                     local_pivot
2342                  */
2343                         )
2344                 );
2345
2346         translation_local2object( parent_translation, local_translation, localToParent );
2347
2348         /*
2349            // verify it!
2350            globalOutputStream() << "World pivot is at " << world_pivot << "\n";
2351            globalOutputStream() << "Local pivot is at " << local_pivot << "\n";
2352            globalOutputStream() << "Transformation " << local_transform << " moves it to: " << matrix4_transformed_point(local_transform, local_pivot) << "\n";
2353            globalOutputStream() << "Must move by " << local_translation << " in the local system" << "\n";
2354            globalOutputStream() << "Must move by " << parent_translation << " in the parent system" << "\n";
2355          */
2356 }
2357
2358 void translation_for_pivoted_rotation( Vector3& parent_translation, const Quaternion& local_rotation, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent ){
2359         translation_for_pivoted_matrix_transform( parent_translation, matrix4_rotation_for_quaternion_quantised( local_rotation ), world_pivot, localToWorld, localToParent );
2360 }
2361
2362 void translation_for_pivoted_scale( Vector3& parent_translation, const Vector3& world_scale, const Vector3& world_pivot, const Matrix4& localToWorld, const Matrix4& localToParent ){
2363         Matrix4 local_transform(
2364                 matrix4_multiplied_by_matrix4(
2365                         matrix4_full_inverse( localToWorld ),
2366                         matrix4_multiplied_by_matrix4(
2367                                 matrix4_scale_for_vec3( world_scale ),
2368                                 localToWorld
2369                                 )
2370                         )
2371                 );
2372         local_transform.tx() = local_transform.ty() = local_transform.tz() = 0; // cancel translation parts
2373         translation_for_pivoted_matrix_transform( parent_translation, local_transform, world_pivot, localToWorld, localToParent );
2374 }
2375
2376 class rotate_selected : public SelectionSystem::Visitor
2377 {
2378 const Quaternion& m_rotate;
2379 const Vector3& m_world_pivot;
2380 public:
2381 rotate_selected( const Quaternion& rotation, const Vector3& world_pivot )
2382         : m_rotate( rotation ), m_world_pivot( world_pivot ){
2383 }
2384 void visit( scene::Instance& instance ) const {
2385         TransformNode* transformNode = Node_getTransformNode( instance.path().top() );
2386         if ( transformNode != 0 ) {
2387                 Transformable* transform = Instance_getTransformable( instance );
2388                 if ( transform != 0 ) {
2389                         transform->setType( TRANSFORM_PRIMITIVE );
2390                         transform->setScale( c_scale_identity );
2391                         transform->setTranslation( c_translation_identity );
2392
2393                         transform->setType( TRANSFORM_PRIMITIVE );
2394                         transform->setRotation( m_rotate );
2395
2396                         {
2397                                 Editable* editable = Node_getEditable( instance.path().top() );
2398                                 const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity;
2399
2400                                 Vector3 parent_translation;
2401                                 translation_for_pivoted_rotation(
2402                                         parent_translation,
2403                                         m_rotate,
2404                                         m_world_pivot,
2405                                         matrix4_multiplied_by_matrix4( instance.localToWorld(), localPivot ),
2406                                         matrix4_multiplied_by_matrix4( transformNode->localToParent(), localPivot )
2407                                         );
2408
2409                                 transform->setTranslation( parent_translation );
2410                         }
2411                 }
2412         }
2413 }
2414 };
2415
2416 void Scene_Rotate_Selected( scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot ){
2417         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2418                 GlobalSelectionSystem().foreachSelected( rotate_selected( rotation, world_pivot ) );
2419         }
2420 }
2421
2422 class scale_selected : public SelectionSystem::Visitor
2423 {
2424 const Vector3& m_scale;
2425 const Vector3& m_world_pivot;
2426 public:
2427 scale_selected( const Vector3& scaling, const Vector3& world_pivot )
2428         : m_scale( scaling ), m_world_pivot( world_pivot ){
2429 }
2430 void visit( scene::Instance& instance ) const {
2431         TransformNode* transformNode = Node_getTransformNode( instance.path().top() );
2432         if ( transformNode != 0 ) {
2433                 Transformable* transform = Instance_getTransformable( instance );
2434                 if ( transform != 0 ) {
2435                         transform->setType( TRANSFORM_PRIMITIVE );
2436                         transform->setScale( c_scale_identity );
2437                         transform->setTranslation( c_translation_identity );
2438
2439                         transform->setType( TRANSFORM_PRIMITIVE );
2440                         transform->setScale( m_scale );
2441                         {
2442                                 Editable* editable = Node_getEditable( instance.path().top() );
2443                                 const Matrix4& localPivot = editable != 0 ? editable->getLocalPivot() : g_matrix4_identity;
2444
2445                                 Vector3 parent_translation;
2446                                 translation_for_pivoted_scale(
2447                                         parent_translation,
2448                                         m_scale,
2449                                         m_world_pivot,
2450                                         matrix4_multiplied_by_matrix4( instance.localToWorld(), localPivot ),
2451                                         matrix4_multiplied_by_matrix4( transformNode->localToParent(), localPivot )
2452                                         );
2453
2454                                 transform->setTranslation( parent_translation );
2455                         }
2456                 }
2457         }
2458 }
2459 };
2460
2461 void Scene_Scale_Selected( scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot ){
2462         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2463                 GlobalSelectionSystem().foreachSelected( scale_selected( scaling, world_pivot ) );
2464         }
2465 }
2466
2467
2468 class translate_component_selected : public SelectionSystem::Visitor
2469 {
2470 const Vector3& m_translate;
2471 public:
2472 translate_component_selected( const Vector3& translate )
2473         : m_translate( translate ){
2474 }
2475 void visit( scene::Instance& instance ) const {
2476         Transformable* transform = Instance_getTransformable( instance );
2477         if ( transform != 0 ) {
2478                 transform->setType( TRANSFORM_COMPONENT );
2479                 transform->setTranslation( m_translate );
2480         }
2481 }
2482 };
2483
2484 void Scene_Translate_Component_Selected( scene::Graph& graph, const Vector3& translation ){
2485         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2486                 GlobalSelectionSystem().foreachSelectedComponent( translate_component_selected( translation ) );
2487         }
2488 }
2489
2490 class rotate_component_selected : public SelectionSystem::Visitor
2491 {
2492 const Quaternion& m_rotate;
2493 const Vector3& m_world_pivot;
2494 public:
2495 rotate_component_selected( const Quaternion& rotation, const Vector3& world_pivot )
2496         : m_rotate( rotation ), m_world_pivot( world_pivot ){
2497 }
2498 void visit( scene::Instance& instance ) const {
2499         Transformable* transform = Instance_getTransformable( instance );
2500         if ( transform != 0 ) {
2501                 Vector3 parent_translation;
2502                 translation_for_pivoted_rotation( parent_translation, m_rotate, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() );
2503
2504                 transform->setType( TRANSFORM_COMPONENT );
2505                 transform->setRotation( m_rotate );
2506                 transform->setTranslation( parent_translation );
2507         }
2508 }
2509 };
2510
2511 void Scene_Rotate_Component_Selected( scene::Graph& graph, const Quaternion& rotation, const Vector3& world_pivot ){
2512         if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
2513                 GlobalSelectionSystem().foreachSelectedComponent( rotate_component_selected( rotation, world_pivot ) );
2514         }
2515 }
2516
2517 class scale_component_selected : public SelectionSystem::Visitor
2518 {
2519 const Vector3& m_scale;
2520 const Vector3& m_world_pivot;
2521 public:
2522 scale_component_selected( const Vector3& scaling, const Vector3& world_pivot )
2523         : m_scale( scaling ), m_world_pivot( world_pivot ){
2524 }
2525 void visit( scene::Instance& instance ) const {
2526         Transformable* transform = Instance_getTransformable( instance );
2527         if ( transform != 0 ) {
2528                 Vector3 parent_translation;
2529                 translation_for_pivoted_scale( parent_translation, m_scale, m_world_pivot, instance.localToWorld(), Node_getTransformNode( instance.path().top() )->localToParent() );
2530
2531                 transform->setType( TRANSFORM_COMPONENT );
2532                 transform->setScale( m_scale );
2533                 transform->setTranslation( parent_translation );
2534         }
2535 }
2536 };
2537
2538 void Scene_Scale_Component_Selected( scene::Graph& graph, const Vector3& scaling, const Vector3& world_pivot ){
2539         if ( GlobalSelectionSystem().countSelectedComponents() != 0 ) {
2540                 GlobalSelectionSystem().foreachSelectedComponent( scale_component_selected( scaling, world_pivot ) );
2541         }
2542 }
2543
2544
2545 class BooleanSelector : public Selector
2546 {
2547 bool m_selected;
2548 SelectionIntersection m_intersection;
2549 Selectable* m_selectable;
2550 public:
2551 BooleanSelector() : m_selected( false ){
2552 }
2553
2554 void pushSelectable( Selectable& selectable ){
2555         m_intersection = SelectionIntersection();
2556         m_selectable = &selectable;
2557 }
2558 void popSelectable(){
2559         if ( m_intersection.valid() ) {
2560                 m_selected = true;
2561         }
2562         m_intersection = SelectionIntersection();
2563 }
2564 void addIntersection( const SelectionIntersection& intersection ){
2565         if ( m_selectable->isSelected() ) {
2566                 assign_if_closer( m_intersection, intersection );
2567         }
2568 }
2569
2570 bool isSelected(){
2571         return m_selected;
2572 }
2573 };
2574
2575 class BestSelector : public Selector
2576 {
2577 SelectionIntersection m_intersection;
2578 Selectable* m_selectable;
2579 SelectionIntersection m_bestIntersection;
2580 std::list<Selectable*> m_bestSelectable;
2581 public:
2582 BestSelector() : m_bestIntersection( SelectionIntersection() ), m_bestSelectable( 0 ){
2583 }
2584
2585 void pushSelectable( Selectable& selectable ){
2586         m_intersection = SelectionIntersection();
2587         m_selectable = &selectable;
2588 }
2589 void popSelectable(){
2590         if ( m_intersection.equalEpsilon( m_bestIntersection, 0.25f, 0.001f ) ) {
2591                 m_bestSelectable.push_back( m_selectable );
2592                 m_bestIntersection = m_intersection;
2593         }
2594         else if ( m_intersection < m_bestIntersection ) {
2595                 m_bestSelectable.clear();
2596                 m_bestSelectable.push_back( m_selectable );
2597                 m_bestIntersection = m_intersection;
2598         }
2599         m_intersection = SelectionIntersection();
2600 }
2601 void addIntersection( const SelectionIntersection& intersection ){
2602         assign_if_closer( m_intersection, intersection );
2603 }
2604
2605 std::list<Selectable*>& best(){
2606         return m_bestSelectable;
2607 }
2608 };
2609
2610 class DeepBestSelector : public Selector
2611 {
2612 SelectionIntersection m_intersection;
2613 Selectable* m_selectable;
2614 SelectionIntersection m_bestIntersection;
2615 std::list<Selectable*> m_bestSelectable;
2616 public:
2617 DeepBestSelector() : m_bestIntersection( SelectionIntersection() ), m_bestSelectable( 0 ){
2618 }
2619
2620 void pushSelectable( Selectable& selectable ){
2621         m_intersection = SelectionIntersection();
2622         m_selectable = &selectable;
2623 }
2624 void popSelectable(){
2625         if ( m_intersection.equalEpsilon( m_bestIntersection, 0.25f, 2.f ) ) {
2626                 m_bestSelectable.push_back( m_selectable );
2627                 m_bestIntersection = m_intersection;
2628         }
2629         else if ( m_intersection < m_bestIntersection ) {
2630                 m_bestSelectable.clear();
2631                 m_bestSelectable.push_back( m_selectable );
2632                 m_bestIntersection = m_intersection;
2633         }
2634         m_intersection = SelectionIntersection();
2635 }
2636 void addIntersection( const SelectionIntersection& intersection ){
2637         assign_if_closer( m_intersection, intersection );
2638 }
2639
2640 std::list<Selectable*>& best(){
2641         return m_bestSelectable;
2642 }
2643 };
2644
2645 bool g_bAltDragManipulatorResize = false;
2646
2647 class DragManipulator : public Manipulator
2648 {
2649 TranslateFree m_freeResize;
2650 TranslateFree m_freeDrag;
2651 ResizeTranslatable m_resize;
2652 DragTranslatable m_drag;
2653 SelectableBool m_dragSelectable; //drag already selected stuff
2654 public:
2655
2656 bool m_selected; //selected temporally for drag
2657
2658 DragManipulator() : m_freeResize( m_resize ), m_freeDrag( m_drag ), m_selected( false ){
2659 }
2660
2661 Manipulatable* GetManipulatable(){
2662         return m_dragSelectable.isSelected() ? &m_freeDrag : &m_freeResize;
2663 }
2664
2665 void testSelect( const View& view, const Matrix4& pivot2world ){
2666         SelectionPool selector;
2667
2668         SelectionVolume test( view );
2669
2670         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
2671                 BooleanSelector booleanSelector;
2672
2673                 Scene_TestSelect_Primitive( booleanSelector, test, view );
2674
2675                 if ( booleanSelector.isSelected() ) {
2676                         if( g_bAltDragManipulatorResize ){
2677                                 DeepBestSelector deepSelector;
2678                                 Scene_TestSelect_Component_Selected( deepSelector, test, view, SelectionSystem::eVertex );
2679                                 for ( std::list<Selectable*>::iterator i = deepSelector.best().begin(); i != deepSelector.best().end(); ++i )
2680                                 {
2681                                         if ( !( *i )->isSelected() ) {
2682                                                 GlobalSelectionSystem().setSelectedAllComponents( false );
2683                                         }
2684                                         selector.addSelectable( SelectionIntersection( 0, 0 ), ( *i ) );
2685                                         m_selected = true;
2686                                         m_dragSelectable.setSelected( false );
2687                                 }
2688                                 if( deepSelector.best().empty() ){
2689                                         //Scene_forEachTestedBrushPlane_selectVertices( GlobalSceneGraph(), test );     //todo? drag clicked face
2690                                         Scene_forEachBrushPlane_selectVertices( GlobalSceneGraph(), test );
2691                                         m_selected = true;
2692                                 }
2693                         }
2694                         else{
2695                                 selector.addSelectable( SelectionIntersection( 0, 0 ), &m_dragSelectable );
2696                                 m_selected = false;
2697                         }
2698                 }
2699                 else
2700                 {
2701                         if( g_bAltDragManipulatorResize ){
2702                                 Scene_forEachBrushPlane_selectVertices( GlobalSceneGraph(), test );
2703                                 m_selected = true;
2704                         }
2705                         else{
2706                                 m_selected = Scene_forEachPlaneSelectable_selectPlanes( GlobalSceneGraph(), selector, test );
2707                         }
2708                 }
2709         }
2710         else
2711         {
2712                 BestSelector bestSelector;
2713                 Scene_TestSelect_Component_Selected( bestSelector, test, view, GlobalSelectionSystem().ComponentMode() );
2714                 for ( std::list<Selectable*>::iterator i = bestSelector.best().begin(); i != bestSelector.best().end(); ++i )
2715                 {
2716                         if ( !( *i )->isSelected() ) {
2717                                 GlobalSelectionSystem().setSelectedAllComponents( false );
2718                         }
2719                         m_selected = false;
2720                         selector.addSelectable( SelectionIntersection( 0, 0 ), ( *i ) );
2721                         m_dragSelectable.setSelected( true );
2722                 }
2723                 if( GlobalSelectionSystem().countSelectedComponents() != 0 ){
2724                         m_dragSelectable.setSelected( true );
2725                 }
2726         }
2727
2728         for ( SelectionPool::iterator i = selector.begin(); i != selector.end(); ++i )
2729         {
2730                 ( *i ).second->setSelected( true );
2731         }
2732 }
2733
2734 void setSelected( bool select ){
2735         m_selected = select;
2736         m_dragSelectable.setSelected( select );
2737 }
2738 bool isSelected() const {
2739         return m_selected || m_dragSelectable.isSelected();
2740 }
2741 };
2742
2743 class ClipManipulator : public Manipulator
2744 {
2745 public:
2746
2747 Manipulatable* GetManipulatable(){
2748         ERROR_MESSAGE( "clipper is not manipulatable" );
2749         return 0;
2750 }
2751
2752 void setSelected( bool select ){
2753 }
2754 bool isSelected() const {
2755         return false;
2756 }
2757 };
2758
2759 class select_all : public scene::Graph::Walker
2760 {
2761 bool m_select;
2762 public:
2763 select_all( bool select )
2764         : m_select( select ){
2765 }
2766 bool pre( const scene::Path& path, scene::Instance& instance ) const {
2767         Selectable* selectable = Instance_getSelectable( instance );
2768         if ( selectable != 0 ) {
2769                 selectable->setSelected( m_select );
2770         }
2771         return true;
2772 }
2773 };
2774
2775 class select_all_component : public scene::Graph::Walker
2776 {
2777 bool m_select;
2778 SelectionSystem::EComponentMode m_mode;
2779 public:
2780 select_all_component( bool select, SelectionSystem::EComponentMode mode )
2781         : m_select( select ), m_mode( mode ){
2782 }
2783 bool pre( const scene::Path& path, scene::Instance& instance ) const {
2784         ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance );
2785         if ( componentSelectionTestable ) {
2786                 componentSelectionTestable->setSelectedComponents( m_select, m_mode );
2787         }
2788         return true;
2789 }
2790 };
2791
2792 void Scene_SelectAll_Component( bool select, SelectionSystem::EComponentMode componentMode ){
2793         GlobalSceneGraph().traverse( select_all_component( select, componentMode ) );
2794 }
2795
2796
2797 // RadiantSelectionSystem
2798 class RadiantSelectionSystem :
2799         public SelectionSystem,
2800         public Translatable,
2801         public Rotatable,
2802         public Scalable,
2803         public Renderable
2804 {
2805 mutable Matrix4 m_pivot2world;
2806 Matrix4 m_pivot2world_start;
2807 Matrix4 m_manip2pivot_start;
2808 Translation m_translation;
2809 Rotation m_rotation;
2810 Scale m_scale;
2811 public:
2812 static Shader* m_state;
2813 bool m_bPreferPointEntsIn2D;
2814 private:
2815 EManipulatorMode m_manipulator_mode;
2816 Manipulator* m_manipulator;
2817
2818 // state
2819 bool m_undo_begun;
2820 EMode m_mode;
2821 EComponentMode m_componentmode;
2822
2823 SelectionCounter m_count_primitive;
2824 SelectionCounter m_count_component;
2825
2826 TranslateManipulator m_translate_manipulator;
2827 RotateManipulator m_rotate_manipulator;
2828 ScaleManipulator m_scale_manipulator;
2829 DragManipulator m_drag_manipulator;
2830 ClipManipulator m_clip_manipulator;
2831
2832 typedef SelectionList<scene::Instance> selection_t;
2833 selection_t m_selection;
2834 selection_t m_component_selection;
2835
2836 Signal1<const Selectable&> m_selectionChanged_callbacks;
2837
2838 void ConstructPivot() const;
2839 void setCustomPivotOrigin( Vector3& point ) const;
2840 public:
2841 AABB getSelectionAABB() const;
2842 private:
2843 mutable bool m_pivotChanged;
2844 bool m_pivot_moving;
2845 mutable bool m_pivotIsCustom;
2846
2847 void Scene_TestSelect( Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode );
2848
2849 bool nothingSelected() const {
2850         return ( Mode() == eComponent && m_count_component.empty() )
2851                    || ( Mode() == ePrimitive && m_count_primitive.empty() );
2852 }
2853
2854
2855 public:
2856 enum EModifier
2857 {
2858         eManipulator,
2859         eToggle,
2860         eReplace,
2861         eCycle,
2862         eSelect,
2863         eDeselect,
2864 };
2865
2866 RadiantSelectionSystem() :
2867         m_bPreferPointEntsIn2D( true ),
2868         m_undo_begun( false ),
2869         m_mode( ePrimitive ),
2870         m_componentmode( eDefault ),
2871         m_count_primitive( SelectionChangedCaller( *this ) ),
2872         m_count_component( SelectionChangedCaller( *this ) ),
2873         m_translate_manipulator( *this, 2, 64 ),
2874         m_rotate_manipulator( *this, 8, 64 ),
2875         m_scale_manipulator( *this, 0, 64 ),
2876         m_pivotChanged( false ),
2877         m_pivot_moving( false ),
2878         m_pivotIsCustom( false ){
2879         SetManipulatorMode( eTranslate );
2880         pivotChanged();
2881         addSelectionChangeCallback( PivotChangedSelectionCaller( *this ) );
2882         AddGridChangeCallback( PivotChangedCaller( *this ) );
2883 }
2884 void pivotChanged() const {
2885         m_pivotChanged = true;
2886         SceneChangeNotify();
2887 }
2888 typedef ConstMemberCaller<RadiantSelectionSystem, void(), &RadiantSelectionSystem::pivotChanged> PivotChangedCaller;
2889 void pivotChangedSelection( const Selectable& selectable ){
2890         pivotChanged();
2891 }
2892 typedef MemberCaller<RadiantSelectionSystem, void(const Selectable&), &RadiantSelectionSystem::pivotChangedSelection> PivotChangedSelectionCaller;
2893
2894 void SetMode( EMode mode ){
2895         if ( m_mode != mode ) {
2896                 m_mode = mode;
2897                 pivotChanged();
2898         }
2899 }
2900 EMode Mode() const {
2901         return m_mode;
2902 }
2903 void SetComponentMode( EComponentMode mode ){
2904         m_componentmode = mode;
2905 }
2906 EComponentMode ComponentMode() const {
2907         return m_componentmode;
2908 }
2909 void SetManipulatorMode( EManipulatorMode mode ){
2910         m_pivotIsCustom = false;
2911         m_manipulator_mode = mode;
2912         switch ( m_manipulator_mode )
2913         {
2914         case eTranslate: m_manipulator = &m_translate_manipulator; break;
2915         case eRotate: m_manipulator = &m_rotate_manipulator; break;
2916         case eScale: m_manipulator = &m_scale_manipulator; break;
2917         case eDrag: m_manipulator = &m_drag_manipulator; break;
2918         case eClip: m_manipulator = &m_clip_manipulator; break;
2919         }
2920         pivotChanged();
2921 }
2922 EManipulatorMode ManipulatorMode() const {
2923         return m_manipulator_mode;
2924 }
2925
2926 SelectionChangeCallback getObserver( EMode mode ){
2927         if ( mode == ePrimitive ) {
2928                 return makeCallback( m_count_primitive );
2929         }
2930         else
2931         {
2932                 return makeCallback( m_count_component );
2933         }
2934 }
2935 std::size_t countSelected() const {
2936         return m_count_primitive.size();
2937 }
2938 std::size_t countSelectedComponents() const {
2939         return m_count_component.size();
2940 }
2941 void onSelectedChanged( scene::Instance& instance, const Selectable& selectable ){
2942         if ( selectable.isSelected() ) {
2943                 m_selection.append( instance );
2944         }
2945         else
2946         {
2947                 m_selection.erase( instance );
2948         }
2949
2950         ASSERT_MESSAGE( m_selection.size() == m_count_primitive.size(), "selection-tracking error" );
2951 }
2952 void onComponentSelection( scene::Instance& instance, const Selectable& selectable ){
2953         if ( selectable.isSelected() ) {
2954                 m_component_selection.append( instance );
2955         }
2956         else
2957         {
2958                 m_component_selection.erase( instance );
2959         }
2960
2961         ASSERT_MESSAGE( m_component_selection.size() == m_count_component.size(), "selection-tracking error" );
2962 }
2963 scene::Instance& ultimateSelected() const {
2964         ASSERT_MESSAGE( m_selection.size() > 0, "no instance selected" );
2965         return m_selection.back();
2966 }
2967 scene::Instance& penultimateSelected() const {
2968         ASSERT_MESSAGE( m_selection.size() > 1, "only one instance selected" );
2969         return *( *( --( --m_selection.end() ) ) );
2970 }
2971 void setSelectedAll( bool selected ){
2972         GlobalSceneGraph().traverse( select_all( selected ) );
2973
2974         m_manipulator->setSelected( selected );
2975 }
2976 void setSelectedAllComponents( bool selected ){
2977         Scene_SelectAll_Component( selected, SelectionSystem::eVertex );
2978         Scene_SelectAll_Component( selected, SelectionSystem::eEdge );
2979         Scene_SelectAll_Component( selected, SelectionSystem::eFace );
2980
2981         m_manipulator->setSelected( selected );
2982 }
2983
2984 void foreachSelected( const Visitor& visitor ) const {
2985         selection_t::const_iterator i = m_selection.begin();
2986         while ( i != m_selection.end() )
2987         {
2988                 visitor.visit( *( *( i++ ) ) );
2989         }
2990 }
2991 void foreachSelectedComponent( const Visitor& visitor ) const {
2992         selection_t::const_iterator i = m_component_selection.begin();
2993         while ( i != m_component_selection.end() )
2994         {
2995                 visitor.visit( *( *( i++ ) ) );
2996         }
2997 }
2998
2999 void addSelectionChangeCallback( const SelectionChangeHandler& handler ){
3000         m_selectionChanged_callbacks.connectLast( handler );
3001 }
3002 void selectionChanged( const Selectable& selectable ){
3003         m_selectionChanged_callbacks( selectable );
3004 }
3005 typedef MemberCaller<RadiantSelectionSystem, void(const Selectable&), &RadiantSelectionSystem::selectionChanged> SelectionChangedCaller;
3006
3007
3008 void startMove(){
3009         m_pivot2world_start = GetPivot2World();
3010 }
3011
3012 bool SelectManipulator( const View& view, const float device_point[2], const float device_epsilon[2] ){
3013         if ( !nothingSelected() || ( ManipulatorMode() == eDrag && Mode() == eComponent ) ) {
3014 #if defined ( DEBUG_SELECTION )
3015                 g_render_clipped.destroy();
3016 #endif
3017
3018                 m_manipulator->setSelected( false );
3019
3020                 if ( !nothingSelected() || ( ManipulatorMode() == eDrag && Mode() == eComponent ) ) {
3021                         View scissored( view );
3022                         ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) );
3023                         m_manipulator->testSelect( scissored, GetPivot2World() );
3024                 }
3025
3026                 startMove();
3027
3028                 m_pivot_moving = m_manipulator->isSelected();
3029
3030                 if ( m_pivot_moving ) {
3031                         Pivot2World pivot;
3032                         pivot.update( GetPivot2World(), view.GetModelview(), view.GetProjection(), view.GetViewport() );
3033
3034                         m_manip2pivot_start = matrix4_multiplied_by_matrix4( matrix4_full_inverse( m_pivot2world_start ), pivot.m_worldSpace );
3035
3036                         Matrix4 device2manip;
3037                         ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() );
3038                         m_manipulator->GetManipulatable()->Construct( device2manip, device_point[0], device_point[1], getSelectionAABB(), vector4_to_vector3( GetPivot2World().t() ) );
3039
3040                         m_undo_begun = false;
3041                 }
3042
3043                 SceneChangeNotify();
3044         }
3045
3046         return m_pivot_moving;
3047 }
3048
3049 void deselectAll(){
3050         if ( Mode() == eComponent ) {
3051                 setSelectedAllComponents( false );
3052         }
3053         else
3054         {
3055                 setSelectedAll( false );
3056         }
3057 }
3058
3059 void deselectComponentsOrAll( bool components ){
3060         if ( components ) {
3061                 setSelectedAllComponents( false );
3062         }
3063         else
3064         {
3065                 deselectAll();
3066         }
3067 }
3068
3069 void SelectPoint( const View& view, const float device_point[2], const float device_epsilon[2], RadiantSelectionSystem::EModifier modifier, bool face ){
3070         //globalOutputStream() << device_point[0] << "   " << device_point[1] << "\n";
3071         ASSERT_MESSAGE( fabs( device_point[0] ) <= 1.0f && fabs( device_point[1] ) <= 1.0f, "point-selection error" );
3072
3073         if ( modifier == eReplace ) {
3074                 deselectComponentsOrAll( face );
3075         }
3076 /*
3077 //nothingSelected() doesn't consider faces, selected in non-component mode, m
3078         if ( modifier == eCycle && nothingSelected() ){
3079                 modifier = eReplace;
3080         }
3081 */
3082   #if defined ( DEBUG_SELECTION )
3083         g_render_clipped.destroy();
3084   #endif
3085
3086         {
3087                 View scissored( view );
3088                 ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) );
3089
3090                 SelectionVolume volume( scissored );
3091                 SelectionPool selector;
3092                 SelectionPool selector_point_ents;
3093                 const bool prefer_point_ents = m_bPreferPointEntsIn2D && Mode() == ePrimitive && !view.fill() && !face
3094                         && ( modifier == RadiantSelectionSystem::eReplace || modifier == RadiantSelectionSystem::eSelect || modifier == RadiantSelectionSystem::eDeselect );
3095
3096                 if( prefer_point_ents ){
3097                         Scene_TestSelect( selector_point_ents, volume, scissored, eEntity, ComponentMode() );
3098                 }
3099                 if( prefer_point_ents && !selector_point_ents.failed() ){
3100                         switch ( modifier )
3101                         {
3102                         // if cycle mode not enabled, enable it
3103                         case RadiantSelectionSystem::eReplace:
3104                         {
3105                                 // select closest
3106                                 ( *selector_point_ents.begin() ).second->setSelected( true );
3107                         }
3108                         break;
3109                         case RadiantSelectionSystem::eSelect:
3110                         {
3111                                 SelectionPool::iterator best = selector_point_ents.begin();
3112                                 if( !( *best ).second->isSelected() ){
3113                                         ( *best ).second->setSelected( true );
3114                                 }
3115                                 SelectionPool::iterator i = best;
3116                                 ++i;
3117                                 while ( i != selector_point_ents.end() )
3118                                 {
3119                                         if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3120                                                 if( !( *i ).second->isSelected() ){
3121                                                         ( *i ).second->setSelected( true );
3122                                                 }
3123                                         }
3124                                         else{
3125                                                 break;
3126                                         }
3127                                         ++i;
3128                                 }
3129                         }
3130                         break;
3131                         case RadiantSelectionSystem::eDeselect:
3132                         {
3133                                 SelectionPool::iterator best = selector_point_ents.begin();
3134                                 if( ( *best ).second->isSelected() ){
3135                                         ( *best ).second->setSelected( false );
3136                                 }
3137                                 SelectionPool::iterator i = best;
3138                                 ++i;
3139                                 while ( i != selector_point_ents.end() )
3140                                 {
3141                                         if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3142                                                 if( ( *i ).second->isSelected() ){
3143                                                         ( *i ).second->setSelected( false );
3144                                                 }
3145                                         }
3146                                         else{
3147                                                 break;
3148                                         }
3149                                         ++i;
3150                                 }
3151                         }
3152                         break;
3153                         default:
3154                                 break;
3155                         }
3156                 }
3157                 else{
3158                         if ( face ){
3159                                 Scene_TestSelect_Component( selector, volume, scissored, eFace );
3160                         }
3161                         else{
3162                                 Scene_TestSelect( selector, volume, scissored, Mode(), ComponentMode() );
3163                         }
3164
3165                         if ( !selector.failed() ) {
3166                                 switch ( modifier )
3167                                 {
3168                                 case RadiantSelectionSystem::eToggle:
3169                                 {
3170                                         SelectableSortedSet::iterator best = selector.begin();
3171                                         // toggle selection of the object with least depth
3172                                         if ( ( *best ).second->isSelected() ) {
3173                                                 ( *best ).second->setSelected( false );
3174                                         }
3175                                         else{
3176                                                 ( *best ).second->setSelected( true );
3177                                         }
3178                                 }
3179                                 break;
3180                                 // if cycle mode not enabled, enable it
3181                                 case RadiantSelectionSystem::eReplace:
3182                                 {
3183                                         // select closest
3184                                         ( *selector.begin() ).second->setSelected( true );
3185                                 }
3186                                 break;
3187                                 // select the next object in the list from the one already selected
3188                                 case RadiantSelectionSystem::eCycle:
3189                                 {
3190                                         bool CycleSelectionOccured = false;
3191                                         SelectionPool::iterator i = selector.begin();
3192                                         while ( i != selector.end() )
3193                                         {
3194                                                 if ( ( *i ).second->isSelected() ) {
3195                                                         deselectComponentsOrAll( face );
3196                                                         ++i;
3197                                                         if ( i != selector.end() ) {
3198                                                                 i->second->setSelected( true );
3199                                                         }
3200                                                         else
3201                                                         {
3202                                                                 selector.begin()->second->setSelected( true );
3203                                                         }
3204                                                         CycleSelectionOccured = true;
3205                                                         break;
3206                                                 }
3207                                                 ++i;
3208                                         }
3209                                         if( !CycleSelectionOccured ){
3210                                                 deselectComponentsOrAll( face );
3211                                                 ( *selector.begin() ).second->setSelected( true );
3212                                         }
3213                                 }
3214                                 break;
3215                                 case RadiantSelectionSystem::eSelect:
3216                                 {
3217                                         SelectionPool::iterator best = selector.begin();
3218                                         if( !( *best ).second->isSelected() ){
3219                                                 ( *best ).second->setSelected( true );
3220                                         }
3221                                         SelectionPool::iterator i = best;
3222                                         ++i;
3223                                         while ( i != selector.end() )
3224                                         {
3225                                                 if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3226                                                         if( !( *i ).second->isSelected() ){
3227                                                                 ( *i ).second->setSelected( true );
3228                                                         }
3229                                                 }
3230                                                 else{
3231                                                         break;
3232                                                 }
3233                                                 ++i;
3234                                         }
3235                                 }
3236                                 break;
3237                                 case RadiantSelectionSystem::eDeselect:
3238                                 {
3239                                         SelectionPool::iterator best = selector.begin();
3240                                         if( ( *best ).second->isSelected() ){
3241                                                 ( *best ).second->setSelected( false );
3242                                         }
3243                                         SelectionPool::iterator i = best;
3244                                         ++i;
3245                                         while ( i != selector.end() )
3246                                         {
3247                                                 if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3248                                                         if( ( *i ).second->isSelected() ){
3249                                                                 ( *i ).second->setSelected( false );
3250                                                         }
3251                                                 }
3252                                                 else{
3253                                                         break;
3254                                                 }
3255                                                 ++i;
3256                                         }
3257                                 }
3258                                 break;
3259                                 default:
3260                                         break;
3261                                 }
3262                         }
3263                         else if( modifier == eCycle ){
3264                                 deselectComponentsOrAll( face );
3265                         }
3266                 }
3267         }
3268 }
3269
3270 bool SelectPoint_InitPaint( const View& view, const float device_point[2], const float device_epsilon[2], bool face ){
3271         ASSERT_MESSAGE( fabs( device_point[0] ) <= 1.0f && fabs( device_point[1] ) <= 1.0f, "point-selection error" );
3272   #if defined ( DEBUG_SELECTION )
3273         g_render_clipped.destroy();
3274   #endif
3275
3276         {
3277                 View scissored( view );
3278                 ConstructSelectionTest( scissored, SelectionBoxForPoint( device_point, device_epsilon ) );
3279
3280                 SelectionVolume volume( scissored );
3281                 SelectionPool selector;
3282                 SelectionPool selector_point_ents;
3283                 const bool prefer_point_ents = m_bPreferPointEntsIn2D && Mode() == ePrimitive && !view.fill() && !face;
3284
3285                 if( prefer_point_ents ){
3286                         Scene_TestSelect( selector_point_ents, volume, scissored, eEntity, ComponentMode() );
3287                 }
3288                 if( prefer_point_ents && !selector_point_ents.failed() ){
3289                         SelectableSortedSet::iterator best = selector_point_ents.begin();
3290                         const bool wasSelected = ( *best ).second->isSelected();
3291                         ( *best ).second->setSelected( !wasSelected );
3292                         SelectableSortedSet::iterator i = best;
3293                         ++i;
3294                         while ( i != selector_point_ents.end() )
3295                         {
3296                                 if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3297                                         ( *i ).second->setSelected( !wasSelected );
3298                                 }
3299                                 else{
3300                                         break;
3301                                 }
3302                                 ++i;
3303                         }
3304                         return !wasSelected;
3305                 }
3306                 else{//do primitives, if ents failed
3307                         if ( face ){
3308                                 Scene_TestSelect_Component( selector, volume, scissored, eFace );
3309                         }
3310                         else{
3311                                 Scene_TestSelect( selector, volume, scissored, Mode(), ComponentMode() );
3312                         }
3313                         if ( !selector.failed() ){
3314                                 SelectableSortedSet::iterator best = selector.begin();
3315                                 const bool wasSelected = ( *best ).second->isSelected();
3316                                 ( *best ).second->setSelected( !wasSelected );
3317                                 SelectableSortedSet::iterator i = best;
3318                                 ++i;
3319                                 while ( i != selector.end() )
3320                                 {
3321                                         if( ( *i ).first.equalEpsilon( ( *best ).first, 0.25f, 0.000001f ) ){
3322                                                 ( *i ).second->setSelected( !wasSelected );
3323                                         }
3324                                         else{
3325                                                 break;
3326                                         }
3327                                         ++i;
3328                                 }
3329                                 return !wasSelected;
3330                         }
3331                         else{
3332                                 return true;
3333                         }
3334                 }
3335         }
3336 }
3337
3338 void SelectArea( const View& view, const float device_point[2], const float device_delta[2], RadiantSelectionSystem::EModifier modifier, bool face ){
3339         if ( modifier == eReplace ) {
3340                 deselectComponentsOrAll( face );
3341         }
3342
3343   #if defined ( DEBUG_SELECTION )
3344         g_render_clipped.destroy();
3345   #endif
3346
3347         {
3348                 View scissored( view );
3349                 ConstructSelectionTest( scissored, SelectionBoxForArea( device_point, device_delta ) );
3350
3351                 SelectionVolume volume( scissored );
3352                 SelectionPool pool;
3353                 if ( face ) {
3354                         Scene_TestSelect_Component( pool, volume, scissored, eFace );
3355                 }
3356                 else
3357                 {
3358                         Scene_TestSelect( pool, volume, scissored, Mode(), ComponentMode() );
3359                 }
3360
3361                 for ( SelectionPool::iterator i = pool.begin(); i != pool.end(); ++i )
3362                 {
3363                         ( *i ).second->setSelected( !( modifier == RadiantSelectionSystem::eToggle && ( *i ).second->isSelected() ) );
3364                 }
3365         }
3366 }
3367
3368
3369 void translate( const Vector3& translation ){
3370         if ( !nothingSelected() ) {
3371                 //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid");
3372
3373                 m_translation = translation;
3374
3375                 m_pivot2world = m_pivot2world_start;
3376                 matrix4_translate_by_vec3( m_pivot2world, translation );
3377
3378                 if ( Mode() == eComponent ) {
3379                         Scene_Translate_Component_Selected( GlobalSceneGraph(), m_translation );
3380                 }
3381                 else
3382                 {
3383                         Scene_Translate_Selected( GlobalSceneGraph(), m_translation );
3384                 }
3385
3386                 SceneChangeNotify();
3387         }
3388 }
3389 void outputTranslation( TextOutputStream& ostream ){
3390         ostream << " -xyz " << m_translation.x() << " " << m_translation.y() << " " << m_translation.z();
3391 }
3392 void rotate( const Quaternion& rotation ){
3393         if ( !nothingSelected() ) {
3394                 //ASSERT_MESSAGE(!m_pivotChanged, "pivot is invalid");
3395
3396                 m_rotation = rotation;
3397
3398                 if ( Mode() == eComponent ) {
3399                         Scene_Rotate_Component_Selected( GlobalSceneGraph(), m_rotation, vector4_to_vector3( m_pivot2world.t() ) );
3400
3401                         matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3402                 }
3403                 else
3404                 {
3405                         Scene_Rotate_Selected( GlobalSceneGraph(), m_rotation, vector4_to_vector3( m_pivot2world.t() ) );
3406
3407                         matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3408                 }
3409
3410                 SceneChangeNotify();
3411         }
3412 }
3413 void outputRotation( TextOutputStream& ostream ){
3414         ostream << " -eulerXYZ " << m_rotation.x() << " " << m_rotation.y() << " " << m_rotation.z();
3415 }
3416 void scale( const Vector3& scaling ){
3417         if ( !nothingSelected() ) {
3418                 m_scale = scaling;
3419
3420                 if ( Mode() == eComponent ) {
3421                         Scene_Scale_Component_Selected( GlobalSceneGraph(), m_scale, vector4_to_vector3( m_pivot2world.t() ) );
3422                 }
3423                 else
3424                 {
3425                         Scene_Scale_Selected( GlobalSceneGraph(), m_scale, vector4_to_vector3( m_pivot2world.t() ) );
3426                 }
3427
3428                 SceneChangeNotify();
3429         }
3430 }
3431 void outputScale( TextOutputStream& ostream ){
3432         ostream << " -scale " << m_scale.x() << " " << m_scale.y() << " " << m_scale.z();
3433 }
3434
3435 void rotateSelected( const Quaternion& rotation, bool snapOrigin ){
3436         if( snapOrigin && !m_pivotIsCustom ){
3437                 m_pivot2world.tx() = float_snapped( m_pivot2world.tx(), GetSnapGridSize() );
3438                 m_pivot2world.ty() = float_snapped( m_pivot2world.ty(), GetSnapGridSize() );
3439                 m_pivot2world.tz() = float_snapped( m_pivot2world.tz(), GetSnapGridSize() );
3440         }
3441         startMove();
3442         rotate( rotation );
3443         freezeTransforms();
3444 }
3445 void translateSelected( const Vector3& translation ){
3446         startMove();
3447         translate( translation );
3448         freezeTransforms();
3449 }
3450 void scaleSelected( const Vector3& scaling ){
3451         startMove();
3452         scale( scaling );
3453         freezeTransforms();
3454 }
3455
3456 void MoveSelected( const View& view, const float device_point[2], bool snap, bool snapbbox ){
3457         if ( m_manipulator->isSelected() ) {
3458                 if ( !m_undo_begun ) {
3459                         m_undo_begun = true;
3460                         GlobalUndoSystem().start();
3461                 }
3462
3463                 Matrix4 device2manip;
3464                 ConstructDevice2Manip( device2manip, m_pivot2world_start, view.GetModelview(), view.GetProjection(), view.GetViewport() );
3465                 m_manipulator->GetManipulatable()->Transform( m_manip2pivot_start, device2manip, device_point[0], device_point[1], snap, snapbbox );
3466         }
3467 }
3468
3469 /// \todo Support view-dependent nudge.
3470 void NudgeManipulator( const Vector3& nudge, const Vector3& view ){
3471         if ( ManipulatorMode() == eTranslate || ManipulatorMode() == eDrag ) {
3472                 translateSelected( nudge );
3473         }
3474 }
3475
3476 void endMove();
3477 void freezeTransforms();
3478
3479 void renderSolid( Renderer& renderer, const VolumeTest& volume ) const;
3480 void renderWireframe( Renderer& renderer, const VolumeTest& volume ) const {
3481         renderSolid( renderer, volume );
3482 }
3483
3484 const Matrix4& GetPivot2World() const {
3485         ConstructPivot();
3486         return m_pivot2world;
3487 }
3488
3489 static void constructStatic(){
3490         m_state = GlobalShaderCache().capture( "$POINT" );
3491   #if defined( DEBUG_SELECTION )
3492         g_state_clipped = GlobalShaderCache().capture( "$DEBUG_CLIPPED" );
3493   #endif
3494         TranslateManipulator::m_state_wire = GlobalShaderCache().capture( "$WIRE_OVERLAY" );
3495         TranslateManipulator::m_state_fill = GlobalShaderCache().capture( "$FLATSHADE_OVERLAY" );
3496         RotateManipulator::m_state_outer = GlobalShaderCache().capture( "$WIRE_OVERLAY" );
3497 }
3498
3499 static void destroyStatic(){
3500   #if defined( DEBUG_SELECTION )
3501         GlobalShaderCache().release( "$DEBUG_CLIPPED" );
3502   #endif
3503         GlobalShaderCache().release( "$WIRE_OVERLAY" );
3504         GlobalShaderCache().release( "$FLATSHADE_OVERLAY" );
3505         GlobalShaderCache().release( "$WIRE_OVERLAY" );
3506         GlobalShaderCache().release( "$POINT" );
3507 }
3508 };
3509
3510 Shader* RadiantSelectionSystem::m_state = 0;
3511
3512
3513 namespace
3514 {
3515 RadiantSelectionSystem* g_RadiantSelectionSystem;
3516
3517 inline RadiantSelectionSystem& getSelectionSystem(){
3518         return *g_RadiantSelectionSystem;
3519 }
3520 }
3521
3522 #include "map.h"
3523
3524 class testselect_entity_visible : public scene::Graph::Walker
3525 {
3526 Selector& m_selector;
3527 SelectionTest& m_test;
3528 public:
3529 testselect_entity_visible( Selector& selector, SelectionTest& test )
3530         : m_selector( selector ), m_test( test ){
3531 }
3532 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3533         if( path.top().get_pointer() == Map_GetWorldspawn( g_map ) ||
3534                 node_is_group( path.top().get() ) ){
3535                 return false;
3536         }
3537         Selectable* selectable = Instance_getSelectable( instance );
3538         if ( selectable != 0
3539                  && Node_isEntity( path.top() ) ) {
3540                 m_selector.pushSelectable( *selectable );
3541         }
3542
3543         SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance );
3544         if ( selectionTestable ) {
3545                 selectionTestable->testSelect( m_selector, m_test );
3546         }
3547
3548         return true;
3549 }
3550 void post( const scene::Path& path, scene::Instance& instance ) const {
3551         Selectable* selectable = Instance_getSelectable( instance );
3552         if ( selectable != 0
3553                  && Node_isEntity( path.top() ) ) {
3554                 m_selector.popSelectable();
3555         }
3556 }
3557 };
3558
3559 class testselect_primitive_visible : public scene::Graph::Walker
3560 {
3561 Selector& m_selector;
3562 SelectionTest& m_test;
3563 public:
3564 testselect_primitive_visible( Selector& selector, SelectionTest& test )
3565         : m_selector( selector ), m_test( test ){
3566 }
3567 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3568         Selectable* selectable = Instance_getSelectable( instance );
3569         if ( selectable != 0 ) {
3570                 m_selector.pushSelectable( *selectable );
3571         }
3572
3573         SelectionTestable* selectionTestable = Instance_getSelectionTestable( instance );
3574         if ( selectionTestable ) {
3575                 selectionTestable->testSelect( m_selector, m_test );
3576         }
3577
3578         return true;
3579 }
3580 void post( const scene::Path& path, scene::Instance& instance ) const {
3581         Selectable* selectable = Instance_getSelectable( instance );
3582         if ( selectable != 0 ) {
3583                 m_selector.popSelectable();
3584         }
3585 }
3586 };
3587
3588 class testselect_component_visible : public scene::Graph::Walker
3589 {
3590 Selector& m_selector;
3591 SelectionTest& m_test;
3592 SelectionSystem::EComponentMode m_mode;
3593 public:
3594 testselect_component_visible( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode )
3595         : m_selector( selector ), m_test( test ), m_mode( mode ){
3596 }
3597 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3598         ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance );
3599         if ( componentSelectionTestable ) {
3600                 componentSelectionTestable->testSelectComponents( m_selector, m_test, m_mode );
3601         }
3602
3603         return true;
3604 }
3605 };
3606
3607
3608 class testselect_component_visible_selected : public scene::Graph::Walker
3609 {
3610 Selector& m_selector;
3611 SelectionTest& m_test;
3612 SelectionSystem::EComponentMode m_mode;
3613 public:
3614 testselect_component_visible_selected( Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode )
3615         : m_selector( selector ), m_test( test ), m_mode( mode ){
3616 }
3617 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3618         Selectable* selectable = Instance_getSelectable( instance );
3619         if ( selectable != 0 && selectable->isSelected() ) {
3620                 ComponentSelectionTestable* componentSelectionTestable = Instance_getComponentSelectionTestable( instance );
3621                 if ( componentSelectionTestable ) {
3622                         componentSelectionTestable->testSelectComponents( m_selector, m_test, m_mode );
3623                 }
3624         }
3625
3626         return true;
3627 }
3628 };
3629
3630 void Scene_TestSelect_Primitive( Selector& selector, SelectionTest& test, const VolumeTest& volume ){
3631         Scene_forEachVisible( GlobalSceneGraph(), volume, testselect_primitive_visible( selector, test ) );
3632 }
3633
3634 void Scene_TestSelect_Component_Selected( Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode ){
3635         Scene_forEachVisible( GlobalSceneGraph(), volume, testselect_component_visible_selected( selector, test, componentMode ) );
3636 }
3637
3638 void Scene_TestSelect_Component( Selector& selector, SelectionTest& test, const VolumeTest& volume, SelectionSystem::EComponentMode componentMode ){
3639         Scene_forEachVisible( GlobalSceneGraph(), volume, testselect_component_visible( selector, test, componentMode ) );
3640 }
3641
3642 void RadiantSelectionSystem::Scene_TestSelect( Selector& selector, SelectionTest& test, const View& view, SelectionSystem::EMode mode, SelectionSystem::EComponentMode componentMode ){
3643         switch ( mode )
3644         {
3645         case eEntity:
3646         {
3647                 Scene_forEachVisible( GlobalSceneGraph(), view, testselect_entity_visible( selector, test ) );
3648         }
3649         break;
3650         case ePrimitive:
3651                 Scene_TestSelect_Primitive( selector, test, view );
3652                 break;
3653         case eComponent:
3654                 Scene_TestSelect_Component_Selected( selector, test, view, componentMode );
3655                 break;
3656         }
3657 }
3658
3659 class FreezeTransforms : public scene::Graph::Walker
3660 {
3661 public:
3662 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3663         TransformNode* transformNode = Node_getTransformNode( path.top() );
3664         if ( transformNode != 0 ) {
3665                 Transformable* transform = Instance_getTransformable( instance );
3666                 if ( transform != 0 ) {
3667                         transform->freezeTransform();
3668                 }
3669         }
3670         return true;
3671 }
3672 };
3673
3674 void RadiantSelectionSystem::freezeTransforms(){
3675         GlobalSceneGraph().traverse( FreezeTransforms() );
3676 }
3677
3678
3679 void RadiantSelectionSystem::endMove(){
3680         freezeTransforms();
3681
3682         if ( Mode() == ePrimitive ) {
3683                 if ( ManipulatorMode() == eDrag ) {
3684                         if( g_bAltDragManipulatorResize ){
3685                                 Scene_SelectAll_Component( false, SelectionSystem::eVertex );
3686                         }
3687                         else{
3688                                 Scene_SelectAll_Component( false, SelectionSystem::eFace );
3689                         }
3690                 }
3691         }
3692
3693         m_pivot_moving = false;
3694         pivotChanged();
3695
3696         SceneChangeNotify();
3697
3698         if ( m_undo_begun ) {
3699                 StringOutputStream command;
3700
3701                 if ( ManipulatorMode() == eTranslate ) {
3702                         command << "translateTool";
3703                         outputTranslation( command );
3704                 }
3705                 else if ( ManipulatorMode() == eRotate ) {
3706                         command << "rotateTool";
3707                         outputRotation( command );
3708                 }
3709                 else if ( ManipulatorMode() == eScale ) {
3710                         command << "scaleTool";
3711                         outputScale( command );
3712                 }
3713                 else if ( ManipulatorMode() == eDrag ) {
3714                         command << "dragTool";
3715                 }
3716
3717                 GlobalUndoSystem().finish( command.c_str() );
3718         }
3719
3720 }
3721
3722 inline AABB Instance_getPivotBounds( scene::Instance& instance ){
3723         Entity* entity = Node_getEntity( instance.path().top() );
3724         if ( entity != 0
3725                  && ( entity->getEntityClass().fixedsize
3726                           || !node_is_group( instance.path().top() ) ) ) {
3727                 Editable* editable = Node_getEditable( instance.path().top() );
3728                 if ( editable != 0 ) {
3729                         return AABB( vector4_to_vector3( matrix4_multiplied_by_matrix4( instance.localToWorld(), editable->getLocalPivot() ).t() ), Vector3( 0, 0, 0 ) );
3730                 }
3731                 else
3732                 {
3733                         return AABB( vector4_to_vector3( instance.localToWorld().t() ), Vector3( 0, 0, 0 ) );
3734                 }
3735         }
3736
3737         return instance.worldAABB();
3738 }
3739
3740 class bounds_selected : public scene::Graph::Walker
3741 {
3742 AABB& m_bounds;
3743 public:
3744 bounds_selected( AABB& bounds )
3745         : m_bounds( bounds ){
3746         m_bounds = AABB();
3747 }
3748 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3749         Selectable* selectable = Instance_getSelectable( instance );
3750         if ( selectable != 0
3751                  && selectable->isSelected() ) {
3752                 aabb_extend_by_aabb_safe( m_bounds, Instance_getPivotBounds( instance ) );
3753         }
3754         return true;
3755 }
3756 };
3757
3758 class bounds_selected_component : public scene::Graph::Walker
3759 {
3760 AABB& m_bounds;
3761 public:
3762 bounds_selected_component( AABB& bounds )
3763         : m_bounds( bounds ){
3764         m_bounds = AABB();
3765 }
3766 bool pre( const scene::Path& path, scene::Instance& instance ) const {
3767         Selectable* selectable = Instance_getSelectable( instance );
3768         if ( selectable != 0
3769                  && selectable->isSelected() ) {
3770                 ComponentEditable* componentEditable = Instance_getComponentEditable( instance );
3771                 if ( componentEditable ) {
3772                         aabb_extend_by_aabb_safe( m_bounds, aabb_for_oriented_aabb_safe( componentEditable->getSelectedComponentsBounds(), instance.localToWorld() ) );
3773                 }
3774         }
3775         return true;
3776 }
3777 };
3778
3779 void Scene_BoundsSelected( scene::Graph& graph, AABB& bounds ){
3780         graph.traverse( bounds_selected( bounds ) );
3781 }
3782
3783 void Scene_BoundsSelectedComponent( scene::Graph& graph, AABB& bounds ){
3784         graph.traverse( bounds_selected_component( bounds ) );
3785 }
3786
3787 #if 0
3788 inline void pivot_for_node( Matrix4& pivot, scene::Node& node, scene::Instance& instance ){
3789         ComponentEditable* componentEditable = Instance_getComponentEditable( instance );
3790         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent
3791                  && componentEditable != 0 ) {
3792                 pivot = matrix4_translation_for_vec3( componentEditable->getSelectedComponentsBounds().origin );
3793         }
3794         else
3795         {
3796                 Bounded* bounded = Instance_getBounded( instance );
3797                 if ( bounded != 0 ) {
3798                         pivot = matrix4_translation_for_vec3( bounded->localAABB().origin );
3799                 }
3800                 else
3801                 {
3802                         pivot = g_matrix4_identity;
3803                 }
3804         }
3805 }
3806 #endif
3807
3808 void RadiantSelectionSystem::ConstructPivot() const {
3809         if ( !m_pivotChanged || m_pivot_moving || m_pivotIsCustom ) {
3810                 return;
3811         }
3812         m_pivotChanged = false;
3813
3814         Vector3 m_object_pivot;
3815
3816         if ( !nothingSelected() ) {
3817                 {
3818                         AABB bounds;
3819                         if ( Mode() == eComponent ) {
3820                                 Scene_BoundsSelectedComponent( GlobalSceneGraph(), bounds );
3821                         }
3822                         else
3823                         {
3824                                 Scene_BoundsSelected( GlobalSceneGraph(), bounds );
3825                         }
3826                         m_object_pivot = bounds.origin;
3827                 }
3828
3829                 //vector3_snap( m_object_pivot, GetSnapGridSize() );
3830                 //globalOutputStream() << m_object_pivot << "\n";
3831                 m_pivot2world = matrix4_translation_for_vec3( m_object_pivot );
3832
3833                 switch ( m_manipulator_mode )
3834                 {
3835                 case eTranslate:
3836                         break;
3837                 case eRotate:
3838                         if ( Mode() == eComponent ) {
3839                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3840                         }
3841                         else
3842                         {
3843                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3844                         }
3845                         break;
3846                 case eScale:
3847                         if ( Mode() == eComponent ) {
3848                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3849                         }
3850                         else
3851                         {
3852                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3853                         }
3854                         break;
3855                 default:
3856                         break;
3857                 }
3858         }
3859 }
3860
3861 void RadiantSelectionSystem::setCustomPivotOrigin( Vector3& point ) const {
3862         if ( !nothingSelected() && ( m_manipulator_mode == eTranslate || m_manipulator_mode == eRotate || m_manipulator_mode == eScale ) ) {
3863                 AABB bounds;
3864                 if ( Mode() == eComponent ) {
3865                         Scene_BoundsSelectedComponent( GlobalSceneGraph(), bounds );
3866                 }
3867                 else
3868                 {
3869                         Scene_BoundsSelected( GlobalSceneGraph(), bounds );
3870                 }
3871                 //globalOutputStream() << point << "\n";
3872                 for( std::size_t i = 0; i < 3; i++ ){
3873                         if( point[i] < 900000.0f ){
3874                                 float bestsnapDist = fabs( bounds.origin[i] - point[i] );
3875                                 float bestsnapTo = bounds.origin[i];
3876                                 float othersnapDist = fabs( bounds.origin[i] + bounds.extents[i] - point[i] );
3877                                 if( othersnapDist < bestsnapDist ){
3878                                         bestsnapDist = othersnapDist;
3879                                         bestsnapTo = bounds.origin[i] + bounds.extents[i];
3880                                 }
3881                                 othersnapDist = fabs( bounds.origin[i] - bounds.extents[i] - point[i] );
3882                                 if( othersnapDist < bestsnapDist ){
3883                                         bestsnapDist = othersnapDist;
3884                                         bestsnapTo = bounds.origin[i] - bounds.extents[i];
3885                                 }
3886                                 othersnapDist = fabs( float_snapped( point[i], GetSnapGridSize() ) - point[i] );
3887                                 if( othersnapDist < bestsnapDist ){
3888                                         bestsnapDist = othersnapDist;
3889                                         bestsnapTo = float_snapped( point[i], GetSnapGridSize() );
3890                                 }
3891                                 point[i] = bestsnapTo;
3892
3893                                 m_pivot2world[i + 12] = point[i]; //m_pivot2world.tx() .ty() .tz()
3894                         }
3895                 }
3896
3897                 switch ( m_manipulator_mode )
3898                 {
3899                 case eTranslate:
3900                         break;
3901                 case eRotate:
3902                         if ( Mode() == eComponent ) {
3903                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3904                         }
3905                         else
3906                         {
3907                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3908                         }
3909                         break;
3910                 case eScale:
3911                         if ( Mode() == eComponent ) {
3912                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_component_selection.back() );
3913                         }
3914                         else
3915                         {
3916                                 matrix4_assign_rotation_for_pivot( m_pivot2world, m_selection.back() );
3917                         }
3918                         break;
3919                 default:
3920                         break;
3921                 }
3922
3923                 m_pivotIsCustom = true;
3924         }
3925 }
3926
3927 AABB RadiantSelectionSystem::getSelectionAABB() const {
3928         AABB bounds;
3929         if ( !nothingSelected() ) {
3930                 if ( Mode() == eComponent ) {
3931                         Scene_BoundsSelectedComponent( GlobalSceneGraph(), bounds );
3932                 }
3933                 else
3934                 {
3935                         Scene_BoundsSelected( GlobalSceneGraph(), bounds );
3936                 }
3937         }
3938         return bounds;
3939 }
3940
3941 void RadiantSelectionSystem::renderSolid( Renderer& renderer, const VolumeTest& volume ) const {
3942         //if(view->TestPoint(m_object_pivot))
3943         if ( !nothingSelected() ) {
3944                 renderer.Highlight( Renderer::ePrimitive, false );
3945                 renderer.Highlight( Renderer::eFace, false );
3946
3947                 renderer.SetState( m_state, Renderer::eWireframeOnly );
3948                 renderer.SetState( m_state, Renderer::eFullMaterials );
3949
3950                 m_manipulator->render( renderer, volume, GetPivot2World() );
3951         }
3952
3953 #if defined( DEBUG_SELECTION )
3954         renderer.SetState( g_state_clipped, Renderer::eWireframeOnly );
3955         renderer.SetState( g_state_clipped, Renderer::eFullMaterials );
3956         renderer.addRenderable( g_render_clipped, g_render_clipped.m_world );
3957 #endif
3958 }
3959
3960 #include "preferencesystem.h"
3961 #include "preferences.h"
3962
3963 void SelectionSystem_constructPreferences( PreferencesPage& page ){
3964         page.appendCheckBox( "", "Prefer point entities in 2D", getSelectionSystem().m_bPreferPointEntsIn2D );
3965 }
3966 void SelectionSystem_constructPage( PreferenceGroup& group ){
3967         PreferencesPage page( group.createPage( "Selection", "Selection System Settings" ) );
3968         SelectionSystem_constructPreferences( page );
3969 }
3970 void SelectionSystem_registerPreferencesPage(){
3971         PreferencesDialog_addSettingsPage( FreeCaller<void(PreferenceGroup&), SelectionSystem_constructPage>() );
3972 }
3973
3974
3975
3976 void SelectionSystem_OnBoundsChanged(){
3977         getSelectionSystem().pivotChanged();
3978 }
3979
3980 SignalHandlerId SelectionSystem_boundsChanged;
3981
3982 void SelectionSystem_Construct(){
3983         RadiantSelectionSystem::constructStatic();
3984
3985         g_RadiantSelectionSystem = new RadiantSelectionSystem;
3986
3987         SelectionSystem_boundsChanged = GlobalSceneGraph().addBoundsChangedCallback( FreeCaller<void(), SelectionSystem_OnBoundsChanged>() );
3988
3989         GlobalShaderCache().attachRenderable( getSelectionSystem() );
3990
3991         GlobalPreferenceSystem().registerPreference( "PreferPointEntsIn2D", make_property_string( getSelectionSystem().m_bPreferPointEntsIn2D ) );
3992         SelectionSystem_registerPreferencesPage();
3993 }
3994
3995 void SelectionSystem_Destroy(){
3996         GlobalShaderCache().detachRenderable( getSelectionSystem() );
3997
3998         GlobalSceneGraph().removeBoundsChangedCallback( SelectionSystem_boundsChanged );
3999
4000         delete g_RadiantSelectionSystem;
4001
4002         RadiantSelectionSystem::destroyStatic();
4003 }
4004
4005
4006
4007
4008 inline float screen_normalised( float pos, std::size_t size ){
4009         return ( ( 2.0f * pos ) / size ) - 1.0f;
4010 }
4011
4012 typedef Vector2 DeviceVector;
4013
4014 inline DeviceVector window_to_normalised_device( WindowVector window, std::size_t width, std::size_t height ){
4015         return DeviceVector( screen_normalised( window.x(), width ), screen_normalised( height - 1 - window.y(), height ) );
4016 }
4017
4018 inline float device_constrained( float pos ){
4019         return std::min( 1.0f, std::max( -1.0f, pos ) );
4020 }
4021
4022 inline DeviceVector device_constrained( DeviceVector device ){
4023         return DeviceVector( device_constrained( device.x() ), device_constrained( device.y() ) );
4024 }
4025
4026 inline float window_constrained( float pos, std::size_t origin, std::size_t size ){
4027         return std::min( static_cast<float>( origin + size ), std::max( static_cast<float>( origin ), pos ) );
4028 }
4029
4030 inline WindowVector window_constrained( WindowVector window, std::size_t x, std::size_t y, std::size_t width, std::size_t height ){
4031         return WindowVector( window_constrained( window.x(), x, width ), window_constrained( window.y(), y, height ) );
4032 }
4033
4034 typedef Callback<void(DeviceVector)> MouseEventCallback;
4035
4036 Single<MouseEventCallback> g_mouseMovedCallback;
4037 Single<MouseEventCallback> g_mouseUpCallback;
4038
4039 #if 1
4040 const ButtonIdentifier c_button_select = c_buttonLeft;
4041 const ButtonIdentifier c_button_select2 = c_buttonRight;
4042 const ModifierFlags c_modifier_manipulator = c_modifierNone;
4043 const ModifierFlags c_modifier_toggle = c_modifierShift;
4044 const ModifierFlags c_modifier_replace = c_modifierShift | c_modifierAlt;
4045 const ModifierFlags c_modifier_face = c_modifierControl;
4046 #else
4047 const ButtonIdentifier c_button_select = c_buttonLeft;
4048 const ModifierFlags c_modifier_manipulator = c_modifierNone;
4049 const ModifierFlags c_modifier_toggle = c_modifierControl;
4050 const ModifierFlags c_modifier_replace = c_modifierNone;
4051 const ModifierFlags c_modifier_face = c_modifierShift;
4052 #endif
4053 const ModifierFlags c_modifier_toggle_face = c_modifier_toggle | c_modifier_face;
4054 const ModifierFlags c_modifier_replace_face = c_modifier_replace | c_modifier_face;
4055
4056 const ButtonIdentifier c_button_texture = c_buttonMiddle;
4057 const ModifierFlags c_modifier_apply_texture1 = c_modifierControl | c_modifierShift;
4058 const ModifierFlags c_modifier_apply_texture2 = c_modifierControl;
4059 const ModifierFlags c_modifier_apply_texture3 =                     c_modifierShift;
4060 const ModifierFlags c_modifier_copy_texture = c_modifierNone;
4061
4062 class Selector_
4063 {
4064 RadiantSelectionSystem::EModifier modifier_for_state( ModifierFlags state ){
4065         if ( ( state == c_modifier_toggle || state == c_modifier_toggle_face || state == c_modifier_face ) ) {
4066                 if( m_mouse2 ){
4067                         return RadiantSelectionSystem::eReplace;
4068                 }
4069                 else{
4070                         return RadiantSelectionSystem::eToggle;
4071                 }
4072         }
4073         return RadiantSelectionSystem::eManipulator;
4074 }
4075
4076 rect_t getDeviceArea() const {
4077         DeviceVector delta( m_current - m_start );
4078         if ( selecting() && fabs( delta.x() ) > m_epsilon.x() && fabs( delta.y() ) > m_epsilon.y() ) {
4079                 return SelectionBoxForArea( &m_start[0], &delta[0] );
4080         }
4081         else
4082         {
4083                 rect_t default_area = { { 0, 0, }, { 0, 0, }, };
4084                 return default_area;
4085         }
4086 }
4087
4088 public:
4089 DeviceVector m_start;
4090 DeviceVector m_current;
4091 DeviceVector m_epsilon;
4092 ModifierFlags m_state;
4093 bool m_mouse2;
4094 bool m_mouseMoved;
4095 bool m_mouseMovedWhilePressed;
4096 bool m_paintSelect;
4097 const View* m_view;
4098 RectangleCallback m_window_update;
4099
4100 Selector_() : m_start( 0.0f, 0.0f ), m_current( 0.0f, 0.0f ), m_state( c_modifierNone ), m_mouse2( false ), m_mouseMoved( false ), m_mouseMovedWhilePressed( false ){
4101 }
4102
4103 void draw_area(){
4104         m_window_update( getDeviceArea() );
4105 }
4106
4107 void testSelect( DeviceVector position ){
4108         RadiantSelectionSystem::EModifier modifier = modifier_for_state( m_state );
4109         if ( modifier != RadiantSelectionSystem::eManipulator ) {
4110                 DeviceVector delta( position - m_start );
4111                 if ( fabs( delta.x() ) > m_epsilon.x() && fabs( delta.y() ) > m_epsilon.y() ) {
4112                         DeviceVector delta( position - m_start );
4113                         //getSelectionSystem().SelectArea( *m_view, &m_start[0], &delta[0], modifier, ( m_state & c_modifier_face ) != c_modifierNone );
4114                         getSelectionSystem().SelectArea( *m_view, &m_start[0], &delta[0], RadiantSelectionSystem::eToggle, ( m_state & c_modifier_face ) != c_modifierNone );
4115                 }
4116                 else if( !m_mouseMovedWhilePressed ){
4117                         if ( modifier == RadiantSelectionSystem::eReplace && !m_mouseMoved ) {
4118                                 modifier = RadiantSelectionSystem::eCycle;
4119                         }
4120                         getSelectionSystem().SelectPoint( *m_view, &position[0], &m_epsilon[0], modifier, ( m_state & c_modifier_face ) != c_modifierNone );
4121                 }
4122         }
4123
4124         m_start = m_current = DeviceVector( 0.0f, 0.0f );
4125         draw_area();
4126 }
4127
4128 void testSelect_simpleM1( DeviceVector position ){
4129         /*RadiantSelectionSystem::EModifier modifier = RadiantSelectionSystem::eReplace;
4130         DeviceVector delta( position - m_start );
4131         if ( fabs( delta.x() ) < m_epsilon.x() && fabs( delta.y() ) < m_epsilon.y() ) {
4132                 modifier = RadiantSelectionSystem::eCycle;
4133         }
4134         getSelectionSystem().SelectPoint( *m_view, &position[0], &m_epsilon[0], modifier, false );*/
4135         getSelectionSystem().SelectPoint( *m_view, &position[0], &m_epsilon[0], m_mouseMoved ? RadiantSelectionSystem::eReplace : RadiantSelectionSystem::eCycle, false );
4136         m_start = m_current = device_constrained( position );
4137 }
4138
4139
4140 bool selecting() const {
4141         return m_state != c_modifier_manipulator && m_mouse2;
4142 }
4143
4144 void setState( ModifierFlags state ){
4145         bool was_selecting = selecting();
4146         m_state = state;
4147         if ( was_selecting ^ selecting() ) {
4148                 draw_area();
4149         }
4150 }
4151
4152 ModifierFlags getState() const {
4153         return m_state;
4154 }
4155
4156 void modifierEnable( ModifierFlags type ){
4157         setState( bitfield_enable( getState(), type ) );
4158 }
4159 void modifierDisable( ModifierFlags type ){
4160         setState( bitfield_disable( getState(), type ) );
4161 }
4162
4163 void mouseDown( DeviceVector position ){
4164         m_start = m_current = device_constrained( position );
4165         if( !m_mouse2 && m_state != c_modifierNone ){
4166                 m_paintSelect = getSelectionSystem().SelectPoint_InitPaint( *m_view, &position[0], &m_epsilon[0], ( m_state & c_modifier_face ) != c_modifierNone );
4167         }
4168 }
4169
4170 void mouseMoved( DeviceVector position ){
4171         m_current = device_constrained( position );
4172         m_mouseMovedWhilePressed = true;
4173         if( m_mouse2 ){
4174                 draw_area();
4175         }
4176         else if( m_state != c_modifier_manipulator ){
4177                 getSelectionSystem().SelectPoint( *m_view, &m_current[0], &m_epsilon[0],
4178                                                                                 m_paintSelect ? RadiantSelectionSystem::eSelect : RadiantSelectionSystem::eDeselect,
4179                                                                                 ( m_state & c_modifier_face ) != c_modifierNone );
4180         }
4181 }
4182 typedef MemberCaller<Selector_, void(DeviceVector), &Selector_::mouseMoved> MouseMovedCaller;
4183
4184 void mouseUp( DeviceVector position ){
4185         if( m_mouse2 ){
4186                 testSelect( device_constrained( position ) );
4187         }
4188         else{
4189                 m_start = m_current = DeviceVector( 0.0f, 0.0f );
4190         }
4191
4192         g_mouseMovedCallback.clear();
4193         g_mouseUpCallback.clear();
4194 }
4195 typedef MemberCaller<Selector_, void(DeviceVector), &Selector_::mouseUp> MouseUpCaller;
4196 };
4197
4198
4199 class Manipulator_
4200 {
4201 public:
4202 DeviceVector m_epsilon;
4203 const View* m_view;
4204 ModifierFlags m_state;
4205
4206 Manipulator_() : m_state( c_modifierNone ){
4207 }
4208
4209 bool mouseDown( DeviceVector position ){
4210         return getSelectionSystem().SelectManipulator( *m_view, &position[0], &m_epsilon[0] );
4211 }
4212
4213 void mouseMoved( DeviceVector position ){
4214         getSelectionSystem().MoveSelected( *m_view, &position[0], ( m_state & c_modifierShift ) == c_modifierShift, ( m_state & c_modifierControl ) == c_modifierControl );
4215 }
4216 typedef MemberCaller<Manipulator_, void(DeviceVector), &Manipulator_::mouseMoved> MouseMovedCaller;
4217
4218 void mouseUp( DeviceVector position ){
4219         getSelectionSystem().endMove();
4220         g_mouseMovedCallback.clear();
4221         g_mouseUpCallback.clear();
4222 }
4223 typedef MemberCaller<Manipulator_, void(DeviceVector), &Manipulator_::mouseUp> MouseUpCaller;
4224
4225 void setState( ModifierFlags state ){
4226         m_state = state;
4227 }
4228
4229 ModifierFlags getState() const {
4230         return m_state;
4231 }
4232
4233 void modifierEnable( ModifierFlags type ){
4234         setState( bitfield_enable( getState(), type ) );
4235 }
4236 void modifierDisable( ModifierFlags type ){
4237         setState( bitfield_disable( getState(), type ) );
4238 }
4239 };
4240
4241 void Scene_copyClosestTexture( SelectionTest& test );
4242 void Scene_applyClosestTexture( SelectionTest& test );
4243
4244 class RadiantWindowObserver : public SelectionSystemWindowObserver
4245 {
4246 enum
4247 {
4248         SELECT_EPSILON = 8,
4249 };
4250
4251 int m_width;
4252 int m_height;
4253
4254 bool m_mouse_down;
4255
4256 public:
4257 Selector_ m_selector;
4258 Manipulator_ m_manipulator;
4259
4260 RadiantWindowObserver() : m_mouse_down( false ){
4261 }
4262 void release(){
4263         delete this;
4264 }
4265 void setView( const View& view ){
4266         m_selector.m_view = &view;
4267         m_manipulator.m_view = &view;
4268 }
4269 void setRectangleDrawCallback( const RectangleCallback& callback ){
4270         m_selector.m_window_update = callback;
4271 }
4272 void onSizeChanged( int width, int height ){
4273         m_width = width;
4274         m_height = height;
4275         DeviceVector epsilon( SELECT_EPSILON / static_cast<float>( m_width ), SELECT_EPSILON / static_cast<float>( m_height ) );
4276         m_selector.m_epsilon = m_manipulator.m_epsilon = epsilon;
4277 }
4278 void onMouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){
4279         if ( button == c_button_select || ( button == c_button_select2 && modifiers != c_modifierNone ) ) {
4280                 m_mouse_down = true;
4281                 //m_selector.m_mouseMoved = false;
4282
4283                 DeviceVector devicePosition( window_to_normalised_device( position, m_width, m_height ) );
4284                 g_bAltDragManipulatorResize = ( modifiers == c_modifierAlt ) ? true : false;
4285                 if ( ( modifiers == c_modifier_manipulator || modifiers == c_modifierAlt ) && m_manipulator.mouseDown( devicePosition ) ) {
4286                         g_mouseMovedCallback.insert( MouseEventCallback( Manipulator_::MouseMovedCaller( m_manipulator ) ) );
4287                         g_mouseUpCallback.insert( MouseEventCallback( Manipulator_::MouseUpCaller( m_manipulator ) ) );
4288                 }
4289                 else
4290                 {
4291                         if ( button == c_button_select ) {
4292                                 m_selector.m_mouse2 = false;
4293                         }
4294                         else{
4295                                 m_selector.m_mouse2 = true;
4296                         }
4297                         m_selector.mouseDown( devicePosition );
4298                         g_mouseMovedCallback.insert( MouseEventCallback( Selector_::MouseMovedCaller( m_selector ) ) );
4299                         g_mouseUpCallback.insert( MouseEventCallback( Selector_::MouseUpCaller( m_selector ) ) );
4300                 }
4301         }
4302         else if ( button == c_button_texture ) {
4303                 DeviceVector devicePosition( device_constrained( window_to_normalised_device( position, m_width, m_height ) ) );
4304
4305                 View scissored( *m_selector.m_view );
4306                 ConstructSelectionTest( scissored, SelectionBoxForPoint( &devicePosition[0], &m_selector.m_epsilon[0] ) );
4307                 SelectionVolume volume( scissored );
4308
4309                 if ( modifiers == c_modifier_apply_texture1 || modifiers == c_modifier_apply_texture2 || modifiers == c_modifier_apply_texture3 ) {
4310                         Scene_applyClosestTexture( volume );
4311                 }
4312                 else if ( modifiers == c_modifier_copy_texture ) {
4313                         Scene_copyClosestTexture( volume );
4314                 }
4315         }
4316 }
4317 void onMouseMotion( const WindowVector& position, ModifierFlags modifiers ){
4318         m_selector.m_mouseMoved = true;
4319         if ( m_mouse_down && !g_mouseMovedCallback.empty() ) {
4320                 m_selector.m_mouseMovedWhilePressed = true;
4321                 g_mouseMovedCallback.get() ( window_to_normalised_device( position, m_width, m_height ) );
4322         }
4323 }
4324 void onMouseUp( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){
4325         if ( ( button == c_button_select || button == c_button_select2 ) && !g_mouseUpCallback.empty() ) {
4326                 m_mouse_down = false;
4327
4328                 g_mouseUpCallback.get() ( window_to_normalised_device( position, m_width, m_height ) );
4329         }
4330         //L button w/o scene changed = tunnel selection
4331         if( // !getSelectionSystem().m_undo_begun &&
4332                 modifiers == c_modifierNone && button == c_button_select &&
4333                 //( !m_selector.m_mouseMoved || !m_mouse_down ) &&
4334                 !m_selector.m_mouseMovedWhilePressed &&
4335                 ( getSelectionSystem().Mode() != SelectionSystem::eComponent || getSelectionSystem().ManipulatorMode() != SelectionSystem::eDrag ) ){
4336                 m_selector.testSelect_simpleM1( device_constrained( window_to_normalised_device( position, m_width, m_height ) ) );
4337         }
4338         //getSelectionSystem().m_undo_begun = false;
4339         m_selector.m_mouseMoved = false;
4340         m_selector.m_mouseMovedWhilePressed = false;
4341 }
4342 void onModifierDown( ModifierFlags type ){
4343         m_selector.modifierEnable( type );
4344         m_manipulator.modifierEnable( type );
4345 }
4346 void onModifierUp( ModifierFlags type ){
4347         m_selector.modifierDisable( type );
4348         m_manipulator.modifierDisable( type );
4349 }
4350 };
4351
4352
4353
4354 SelectionSystemWindowObserver* NewWindowObserver(){
4355         return new RadiantWindowObserver;
4356 }
4357
4358
4359
4360 #include "modulesystem/singletonmodule.h"
4361 #include "modulesystem/moduleregistry.h"
4362
4363 class SelectionDependencies :
4364         public GlobalSceneGraphModuleRef,
4365         public GlobalShaderCacheModuleRef,
4366         public GlobalOpenGLModuleRef
4367 {
4368 };
4369
4370 class SelectionAPI : public TypeSystemRef
4371 {
4372 SelectionSystem* m_selection;
4373 public:
4374 typedef SelectionSystem Type;
4375 STRING_CONSTANT( Name, "*" );
4376
4377 SelectionAPI(){
4378         SelectionSystem_Construct();
4379
4380         m_selection = &getSelectionSystem();
4381 }
4382 ~SelectionAPI(){
4383         SelectionSystem_Destroy();
4384 }
4385 SelectionSystem* getTable(){
4386         return m_selection;
4387 }
4388 };
4389
4390 typedef SingletonModule<SelectionAPI, SelectionDependencies> SelectionModule;
4391 typedef Static<SelectionModule> StaticSelectionModule;
4392 StaticRegisterModule staticRegisterSelection( StaticSelectionModule::instance() );