5c2560b574ff2cd0bca2d6a84d5c0a70d7c3bef1
[xonotic/netradiant.git] / radiant / select.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 #include "select.h"
23
24 #include "debugging/debugging.h"
25
26 #include "ientity.h"
27 #include "iselection.h"
28 #include "iundo.h"
29
30 #include <vector>
31
32 #include "stream/stringstream.h"
33 #include "signal/isignal.h"
34 #include "shaderlib.h"
35 #include "scenelib.h"
36
37 #include "gtkutil/idledraw.h"
38 #include "gtkutil/dialog.h"
39 #include "gtkutil/widget.h"
40 #include "brushmanip.h"
41 #include "brush.h"
42 #include "patchmanip.h"
43 #include "patchdialog.h"
44 #include "selection.h"
45 #include "texwindow.h"
46 #include "gtkmisc.h"
47 #include "mainframe.h"
48 #include "grid.h"
49 #include "map.h"
50 #include "entityinspector.h"
51
52
53
54 select_workzone_t g_select_workzone;
55
56
57 /**
58    Loops over all selected brushes and stores their
59    world AABBs in the specified array.
60  */
61 class CollectSelectedBrushesBounds : public SelectionSystem::Visitor
62 {
63 AABB* m_bounds;     // array of AABBs
64 Unsigned m_max;     // max AABB-elements in array
65 Unsigned& m_count;  // count of valid AABBs stored in array
66
67 public:
68 CollectSelectedBrushesBounds( AABB* bounds, Unsigned max, Unsigned& count )
69         : m_bounds( bounds ),
70         m_max( max ),
71         m_count( count ){
72         m_count = 0;
73 }
74
75 void visit( scene::Instance& instance ) const {
76         ASSERT_MESSAGE( m_count <= m_max, "Invalid m_count in CollectSelectedBrushesBounds" );
77
78         // stop if the array is already full
79         if ( m_count == m_max ) {
80                 return;
81         }
82
83         Selectable* selectable = Instance_getSelectable( instance );
84         if ( ( selectable != 0 )
85                  && instance.isSelected() ) {
86                 // brushes only
87                 if ( Instance_getBrush( instance ) != 0 ) {
88                         m_bounds[m_count] = instance.worldAABB();
89                         ++m_count;
90                 }
91         }
92 }
93 };
94
95 /**
96    Selects all objects that intersect one of the bounding AABBs.
97    The exact intersection-method is specified through TSelectionPolicy
98  */
99 template<class TSelectionPolicy>
100 class SelectByBounds : public scene::Graph::Walker
101 {
102 AABB* m_aabbs;             // selection aabbs
103 Unsigned m_count;          // number of aabbs in m_aabbs
104 TSelectionPolicy policy;   // type that contains a custom intersection method aabb<->aabb
105
106 public:
107 SelectByBounds( AABB* aabbs, Unsigned count )
108         : m_aabbs( aabbs ),
109         m_count( count ){
110 }
111
112 bool pre( const scene::Path& path, scene::Instance& instance ) const {
113         Selectable* selectable = Instance_getSelectable( instance );
114
115         // ignore worldspawn
116         Entity* entity = Node_getEntity( path.top() );
117         if ( entity ) {
118                 if ( string_equal( entity->getKeyValue( "classname" ), "worldspawn" ) ) {
119                         return true;
120                 }
121         }
122
123         if ( ( path.size() > 1 ) &&
124                  ( !path.top().get().isRoot() ) &&
125                  ( selectable != 0 )
126                  ) {
127                 for ( Unsigned i = 0; i < m_count; ++i )
128                 {
129                         if ( policy.Evaluate( m_aabbs[i], instance ) ) {
130                                 selectable->setSelected( true );
131                         }
132                 }
133         }
134
135         return true;
136 }
137
138 /**
139    Performs selection operation on the global scenegraph.
140    If delete_bounds_src is true, then the objects which were
141    used as source for the selection aabbs will be deleted.
142  */
143 static void DoSelection( bool delete_bounds_src = true ){
144         if ( GlobalSelectionSystem().Mode() == SelectionSystem::ePrimitive ) {
145                 // we may not need all AABBs since not all selected objects have to be brushes
146                 const Unsigned max = (Unsigned)GlobalSelectionSystem().countSelected();
147                 AABB* aabbs = new AABB[max];
148
149                 Unsigned count;
150                 CollectSelectedBrushesBounds collector( aabbs, max, count );
151                 GlobalSelectionSystem().foreachSelected( collector );
152
153                 // nothing usable in selection
154                 if ( !count ) {
155                         delete[] aabbs;
156                         return;
157                 }
158
159                 // delete selected objects
160                 if ( delete_bounds_src ) { // see deleteSelection
161                         UndoableCommand undo( "deleteSelected" );
162                         Select_Delete();
163                 }
164
165                 // select objects with bounds
166                 GlobalSceneGraph().traverse( SelectByBounds<TSelectionPolicy>( aabbs, count ) );
167
168                 SceneChangeNotify();
169                 delete[] aabbs;
170         }
171 }
172 };
173
174 /**
175    SelectionPolicy for SelectByBounds
176    Returns true if box and the AABB of instance intersect
177  */
178 class SelectionPolicy_Touching
179 {
180 public:
181 bool Evaluate( const AABB& box, scene::Instance& instance ) const {
182         const AABB& other( instance.worldAABB() );
183         for ( Unsigned i = 0; i < 3; ++i )
184         {
185                 if ( fabsf( box.origin[i] - other.origin[i] ) > ( box.extents[i] + other.extents[i] ) ) {
186                         return false;
187                 }
188         }
189         return true;
190 }
191 };
192
193 /**
194    SelectionPolicy for SelectByBounds
195    Returns true if the AABB of instance is inside box
196  */
197 class SelectionPolicy_Inside
198 {
199 public:
200 bool Evaluate( const AABB& box, scene::Instance& instance ) const {
201         const AABB& other( instance.worldAABB() );
202         for ( Unsigned i = 0; i < 3; ++i )
203         {
204                 if ( fabsf( box.origin[i] - other.origin[i] ) > ( box.extents[i] - other.extents[i] ) ) {
205                         return false;
206                 }
207         }
208         return true;
209 }
210 };
211
212 class DeleteSelected : public scene::Graph::Walker
213 {
214 mutable bool m_remove;
215 mutable bool m_removedChild;
216 public:
217 DeleteSelected()
218         : m_remove( false ), m_removedChild( false ){
219 }
220 bool pre( const scene::Path& path, scene::Instance& instance ) const {
221         m_removedChild = false;
222
223         Selectable* selectable = Instance_getSelectable( instance );
224         if ( selectable != 0
225                  && selectable->isSelected()
226                  && path.size() > 1
227                  && !path.top().get().isRoot() ) {
228                 m_remove = true;
229
230                 return false; // dont traverse into child elements
231         }
232         return true;
233 }
234 void post( const scene::Path& path, scene::Instance& instance ) const {
235
236         if ( m_removedChild ) {
237                 m_removedChild = false;
238
239                 // delete empty entities
240                 Entity* entity = Node_getEntity( path.top() );
241                 if ( entity != 0
242                          && path.top().get_pointer() != Map_FindWorldspawn( g_map )
243                          && Node_getTraversable( path.top() )->empty() ) {
244                         Path_deleteTop( path );
245                 }
246         }
247
248         // node should be removed
249         if ( m_remove ) {
250                 if ( Node_isEntity( path.parent() ) != 0 ) {
251                         m_removedChild = true;
252                 }
253
254                 m_remove = false;
255                 Path_deleteTop( path );
256         }
257 }
258 };
259
260 void Scene_DeleteSelected( scene::Graph& graph ){
261         graph.traverse( DeleteSelected() );
262         SceneChangeNotify();
263 }
264
265 void Select_Delete( void ){
266         Scene_DeleteSelected( GlobalSceneGraph() );
267 }
268
269 class InvertSelectionWalker : public scene::Graph::Walker
270 {
271 SelectionSystem::EMode m_mode;
272 mutable Selectable* m_selectable;
273 public:
274 InvertSelectionWalker( SelectionSystem::EMode mode )
275         : m_mode( mode ), m_selectable( 0 ){
276 }
277 bool pre( const scene::Path& path, scene::Instance& instance ) const {
278         Selectable* selectable = Instance_getSelectable( instance );
279         if ( selectable ) {
280                 switch ( m_mode )
281                 {
282                 case SelectionSystem::eEntity:
283                         if ( Node_isEntity( path.top() ) != 0 ) {
284                                 m_selectable = path.top().get().visible() ? selectable : 0;
285                         }
286                         break;
287                 case SelectionSystem::ePrimitive:
288                         m_selectable = path.top().get().visible() ? selectable : 0;
289                         break;
290                 case SelectionSystem::eComponent:
291                         break;
292                 }
293         }
294         return true;
295 }
296 void post( const scene::Path& path, scene::Instance& instance ) const {
297         if ( m_selectable != 0 ) {
298                 m_selectable->setSelected( !m_selectable->isSelected() );
299                 m_selectable = 0;
300         }
301 }
302 };
303
304 void Scene_Invert_Selection( scene::Graph& graph ){
305         graph.traverse( InvertSelectionWalker( GlobalSelectionSystem().Mode() ) );
306 }
307
308 void Select_Invert(){
309         Scene_Invert_Selection( GlobalSceneGraph() );
310 }
311
312 class ExpandSelectionToEntitiesWalker : public scene::Graph::Walker
313 {
314 mutable std::size_t m_depth;
315 NodeSmartReference worldspawn;
316 public:
317 ExpandSelectionToEntitiesWalker() : m_depth( 0 ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){
318 }
319 bool pre( const scene::Path& path, scene::Instance& instance ) const {
320         ++m_depth;
321
322         // ignore worldspawn
323         NodeSmartReference me( path.top().get() );
324         if ( me == worldspawn ) {
325                 return false;
326         }
327
328         if ( m_depth == 2 ) { // entity depth
329                 // traverse and select children if any one is selected
330                 if ( instance.childSelected() ) {
331                         Instance_setSelected( instance, true );
332                 }
333                 return Node_getEntity( path.top() )->isContainer() && instance.isSelected();
334         }
335         else if ( m_depth == 3 ) { // primitive depth
336                 Instance_setSelected( instance, true );
337                 return false;
338         }
339         return true;
340 }
341 void post( const scene::Path& path, scene::Instance& instance ) const {
342         --m_depth;
343 }
344 };
345
346 void Scene_ExpandSelectionToEntities(){
347         GlobalSceneGraph().traverse( ExpandSelectionToEntitiesWalker() );
348 }
349
350
351 namespace
352 {
353 void Selection_UpdateWorkzone(){
354         if ( GlobalSelectionSystem().countSelected() != 0 ) {
355                 Select_GetBounds( g_select_workzone.d_work_min, g_select_workzone.d_work_max );
356         }
357 }
358 typedef FreeCaller<Selection_UpdateWorkzone> SelectionUpdateWorkzoneCaller;
359
360 IdleDraw g_idleWorkzone = IdleDraw( SelectionUpdateWorkzoneCaller() );
361 }
362
363 const select_workzone_t& Select_getWorkZone(){
364         g_idleWorkzone.flush();
365         return g_select_workzone;
366 }
367
368 void UpdateWorkzone_ForSelection(){
369         g_idleWorkzone.queueDraw();
370 }
371
372 // update the workzone to the current selection
373 void UpdateWorkzone_ForSelectionChanged( const Selectable& selectable ){
374         if ( selectable.isSelected() ) {
375                 UpdateWorkzone_ForSelection();
376         }
377 }
378
379 void Select_SetShader( const char* shader ){
380         if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) {
381                 Scene_BrushSetShader_Selected( GlobalSceneGraph(), shader );
382                 Scene_PatchSetShader_Selected( GlobalSceneGraph(), shader );
383         }
384         Scene_BrushSetShader_Component_Selected( GlobalSceneGraph(), shader );
385 }
386
387 void Select_SetTexdef( const TextureProjection& projection ){
388         if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) {
389                 Scene_BrushSetTexdef_Selected( GlobalSceneGraph(), projection );
390         }
391         Scene_BrushSetTexdef_Component_Selected( GlobalSceneGraph(), projection );
392 }
393
394 void Select_SetFlags( const ContentsFlagsValue& flags ){
395         if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) {
396                 Scene_BrushSetFlags_Selected( GlobalSceneGraph(), flags );
397         }
398         Scene_BrushSetFlags_Component_Selected( GlobalSceneGraph(), flags );
399 }
400
401 void Select_GetBounds( Vector3& mins, Vector3& maxs ){
402         AABB bounds;
403         Scene_BoundsSelected( GlobalSceneGraph(), bounds );
404         maxs = vector3_added( bounds.origin, bounds.extents );
405         mins = vector3_subtracted( bounds.origin, bounds.extents );
406 }
407
408 void Select_GetMid( Vector3& mid ){
409         AABB bounds;
410         Scene_BoundsSelected( GlobalSceneGraph(), bounds );
411         mid = vector3_snapped( bounds.origin );
412 }
413
414
415 void Select_FlipAxis( int axis ){
416         Vector3 flip( 1, 1, 1 );
417         flip[axis] = -1;
418         GlobalSelectionSystem().scaleSelected( flip );
419 }
420
421
422 void Select_Scale( float x, float y, float z ){
423         GlobalSelectionSystem().scaleSelected( Vector3( x, y, z ) );
424 }
425
426 enum axis_t
427 {
428         eAxisX = 0,
429         eAxisY = 1,
430         eAxisZ = 2,
431 };
432
433 enum sign_t
434 {
435         eSignPositive = 1,
436         eSignNegative = -1,
437 };
438
439 inline Matrix4 matrix4_rotation_for_axis90( axis_t axis, sign_t sign ){
440         switch ( axis )
441         {
442         case eAxisX:
443                 if ( sign == eSignPositive ) {
444                         return matrix4_rotation_for_sincos_x( 1, 0 );
445                 }
446                 else
447                 {
448                         return matrix4_rotation_for_sincos_x( -1, 0 );
449                 }
450         case eAxisY:
451                 if ( sign == eSignPositive ) {
452                         return matrix4_rotation_for_sincos_y( 1, 0 );
453                 }
454                 else
455                 {
456                         return matrix4_rotation_for_sincos_y( -1, 0 );
457                 }
458         default: //case eAxisZ:
459                 if ( sign == eSignPositive ) {
460                         return matrix4_rotation_for_sincos_z( 1, 0 );
461                 }
462                 else
463                 {
464                         return matrix4_rotation_for_sincos_z( -1, 0 );
465                 }
466         }
467 }
468
469 inline void matrix4_rotate_by_axis90( Matrix4& matrix, axis_t axis, sign_t sign ){
470         matrix4_multiply_by_matrix4( matrix, matrix4_rotation_for_axis90( axis, sign ) );
471 }
472
473 inline void matrix4_pivoted_rotate_by_axis90( Matrix4& matrix, axis_t axis, sign_t sign, const Vector3& pivotpoint ){
474         matrix4_translate_by_vec3( matrix, pivotpoint );
475         matrix4_rotate_by_axis90( matrix, axis, sign );
476         matrix4_translate_by_vec3( matrix, vector3_negated( pivotpoint ) );
477 }
478
479 inline Quaternion quaternion_for_axis90( axis_t axis, sign_t sign ){
480 #if 1
481         switch ( axis )
482         {
483         case eAxisX:
484                 if ( sign == eSignPositive ) {
485                         return Quaternion( c_half_sqrt2f, 0, 0, c_half_sqrt2f );
486                 }
487                 else
488                 {
489                         return Quaternion( -c_half_sqrt2f, 0, 0, -c_half_sqrt2f );
490                 }
491         case eAxisY:
492                 if ( sign == eSignPositive ) {
493                         return Quaternion( 0, c_half_sqrt2f, 0, c_half_sqrt2f );
494                 }
495                 else
496                 {
497                         return Quaternion( 0, -c_half_sqrt2f, 0, -c_half_sqrt2f );
498                 }
499         default: //case eAxisZ:
500                 if ( sign == eSignPositive ) {
501                         return Quaternion( 0, 0, c_half_sqrt2f, c_half_sqrt2f );
502                 }
503                 else
504                 {
505                         return Quaternion( 0, 0, -c_half_sqrt2f, -c_half_sqrt2f );
506                 }
507         }
508 #else
509         quaternion_for_matrix4_rotation( matrix4_rotation_for_axis90( (axis_t)axis, ( deg > 0 ) ? eSignPositive : eSignNegative ) );
510 #endif
511 }
512
513 void Select_RotateAxis( int axis, float deg ){
514         if ( fabs( deg ) == 90.f ) {
515                 GlobalSelectionSystem().rotateSelected( quaternion_for_axis90( (axis_t)axis, ( deg > 0 ) ? eSignPositive : eSignNegative ) );
516         }
517         else
518         {
519                 switch ( axis )
520                 {
521                 case 0:
522                         GlobalSelectionSystem().rotateSelected( quaternion_for_matrix4_rotation( matrix4_rotation_for_x_degrees( deg ) ) );
523                         break;
524                 case 1:
525                         GlobalSelectionSystem().rotateSelected( quaternion_for_matrix4_rotation( matrix4_rotation_for_y_degrees( deg ) ) );
526                         break;
527                 case 2:
528                         GlobalSelectionSystem().rotateSelected( quaternion_for_matrix4_rotation( matrix4_rotation_for_z_degrees( deg ) ) );
529                         break;
530                 }
531         }
532 }
533
534
535 void Select_ShiftTexture( float x, float y ){
536         if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) {
537                 Scene_BrushShiftTexdef_Selected( GlobalSceneGraph(), x, y );
538                 Scene_PatchTranslateTexture_Selected( GlobalSceneGraph(), x, y );
539         }
540         //globalOutputStream() << "shift selected face textures: s=" << x << " t=" << y << '\n';
541         Scene_BrushShiftTexdef_Component_Selected( GlobalSceneGraph(), x, y );
542 }
543
544 void Select_ScaleTexture( float x, float y ){
545         if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) {
546                 Scene_BrushScaleTexdef_Selected( GlobalSceneGraph(), x, y );
547                 Scene_PatchScaleTexture_Selected( GlobalSceneGraph(), x, y );
548         }
549         Scene_BrushScaleTexdef_Component_Selected( GlobalSceneGraph(), x, y );
550 }
551
552 void Select_RotateTexture( float amt ){
553         if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) {
554                 Scene_BrushRotateTexdef_Selected( GlobalSceneGraph(), amt );
555                 Scene_PatchRotateTexture_Selected( GlobalSceneGraph(), amt );
556         }
557         Scene_BrushRotateTexdef_Component_Selected( GlobalSceneGraph(), amt );
558 }
559
560 // TTimo modified to handle shader architecture:
561 // expects shader names at input, comparison relies on shader names .. texture names no longer relevant
562 void FindReplaceTextures( const char* pFind, const char* pReplace, bool bSelected ){
563         if ( !texdef_name_valid( pFind ) ) {
564                 globalErrorStream() << "FindReplaceTextures: invalid texture name: '" << pFind << "', aborted\n";
565                 return;
566         }
567         if ( !texdef_name_valid( pReplace ) ) {
568                 globalErrorStream() << "FindReplaceTextures: invalid texture name: '" << pReplace << "', aborted\n";
569                 return;
570         }
571
572         StringOutputStream command;
573         command << "textureFindReplace -find " << pFind << " -replace " << pReplace;
574         UndoableCommand undo( command.c_str() );
575
576         if ( bSelected ) {
577                 if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) {
578                         Scene_BrushFindReplaceShader_Selected( GlobalSceneGraph(), pFind, pReplace );
579                         Scene_PatchFindReplaceShader_Selected( GlobalSceneGraph(), pFind, pReplace );
580                 }
581                 Scene_BrushFindReplaceShader_Component_Selected( GlobalSceneGraph(), pFind, pReplace );
582         }
583         else
584         {
585                 Scene_BrushFindReplaceShader( GlobalSceneGraph(), pFind, pReplace );
586                 Scene_PatchFindReplaceShader( GlobalSceneGraph(), pFind, pReplace );
587         }
588 }
589
590 typedef std::vector<const char*> PropertyValues;
591
592 bool propertyvalues_contain( const PropertyValues& propertyvalues, const char *str ){
593         for ( PropertyValues::const_iterator i = propertyvalues.begin(); i != propertyvalues.end(); ++i )
594         {
595                 if ( string_equal( str, *i ) ) {
596                         return true;
597                 }
598         }
599         return false;
600 }
601
602 class EntityFindByPropertyValueWalker : public scene::Graph::Walker
603 {
604 const PropertyValues& m_propertyvalues;
605 const char *m_prop;
606 public:
607 EntityFindByPropertyValueWalker( const char *prop, const PropertyValues& propertyvalues )
608         : m_propertyvalues( propertyvalues ), m_prop( prop ){
609 }
610 bool pre( const scene::Path& path, scene::Instance& instance ) const {
611         Entity* entity = Node_getEntity( path.top() );
612         if ( entity != 0
613                  && propertyvalues_contain( m_propertyvalues, entity->getKeyValue( m_prop ) ) ) {
614                 Instance_getSelectable( instance )->setSelected( true );
615         }
616         return true;
617 }
618 };
619
620 void Scene_EntitySelectByPropertyValues( scene::Graph& graph, const char *prop, const PropertyValues& propertyvalues ){
621         graph.traverse( EntityFindByPropertyValueWalker( prop, propertyvalues ) );
622 }
623
624 class EntityGetSelectedPropertyValuesWalker : public scene::Graph::Walker
625 {
626 PropertyValues& m_propertyvalues;
627 const char *m_prop;
628 public:
629 EntityGetSelectedPropertyValuesWalker( const char *prop, PropertyValues& propertyvalues )
630         : m_propertyvalues( propertyvalues ), m_prop( prop ){
631 }
632 bool pre( const scene::Path& path, scene::Instance& instance ) const {
633         Selectable* selectable = Instance_getSelectable( instance );
634         if ( selectable != 0
635                  && selectable->isSelected() ) {
636                 Entity* entity = Node_getEntity( path.top() );
637                 if ( entity != 0 ) {
638                         if ( !propertyvalues_contain( m_propertyvalues, entity->getKeyValue( m_prop ) ) ) {
639                                 m_propertyvalues.push_back( entity->getKeyValue( m_prop ) );
640                         }
641                 }
642         }
643         return true;
644 }
645 };
646
647 void Scene_EntityGetPropertyValues( scene::Graph& graph, const char *prop, PropertyValues& propertyvalues ){
648         graph.traverse( EntityGetSelectedPropertyValuesWalker( prop, propertyvalues ) );
649 }
650
651 void Select_AllOfType(){
652         if ( GlobalSelectionSystem().Mode() == SelectionSystem::eComponent ) {
653                 if ( GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace ) {
654                         GlobalSelectionSystem().setSelectedAllComponents( false );
655                         Scene_BrushSelectByShader_Component( GlobalSceneGraph(), TextureBrowser_GetSelectedShader( GlobalTextureBrowser() ) );
656                 }
657         }
658         else
659         {
660                 PropertyValues propertyvalues;
661                 const char *prop = EntityInspector_getCurrentKey();
662                 if ( !prop || !*prop ) {
663                         prop = "classname";
664                 }
665                 Scene_EntityGetPropertyValues( GlobalSceneGraph(), prop, propertyvalues );
666                 GlobalSelectionSystem().setSelectedAll( false );
667                 if ( !propertyvalues.empty() ) {
668                         Scene_EntitySelectByPropertyValues( GlobalSceneGraph(), prop, propertyvalues );
669                 }
670                 else
671                 {
672                         Scene_BrushSelectByShader( GlobalSceneGraph(), TextureBrowser_GetSelectedShader( GlobalTextureBrowser() ) );
673                         Scene_PatchSelectByShader( GlobalSceneGraph(), TextureBrowser_GetSelectedShader( GlobalTextureBrowser() ) );
674                 }
675         }
676 }
677
678 void Select_Inside( void ){
679         SelectByBounds<SelectionPolicy_Inside>::DoSelection();
680 }
681
682 void Select_Touching( void ){
683         SelectByBounds<SelectionPolicy_Touching>::DoSelection( false );
684 }
685
686 void Select_FitTexture( float horizontal, float vertical ){
687         if ( GlobalSelectionSystem().Mode() != SelectionSystem::eComponent ) {
688                 Scene_BrushFitTexture_Selected( GlobalSceneGraph(), horizontal, vertical );
689         }
690         Scene_BrushFitTexture_Component_Selected( GlobalSceneGraph(), horizontal, vertical );
691
692         SceneChangeNotify();
693 }
694
695 inline void hide_node( scene::Node& node, bool hide ){
696         hide
697         ? node.enable( scene::Node::eHidden )
698         : node.disable( scene::Node::eHidden );
699 }
700
701 class HideSelectedWalker : public scene::Graph::Walker
702 {
703 bool m_hide;
704 public:
705 HideSelectedWalker( bool hide )
706         : m_hide( hide ){
707 }
708 bool pre( const scene::Path& path, scene::Instance& instance ) const {
709         Selectable* selectable = Instance_getSelectable( instance );
710         if ( selectable != 0
711                  && selectable->isSelected() ) {
712                 hide_node( path.top(), m_hide );
713         }
714         return true;
715 }
716 };
717
718 void Scene_Hide_Selected( bool hide ){
719         GlobalSceneGraph().traverse( HideSelectedWalker( hide ) );
720 }
721
722 void Select_Hide(){
723         Scene_Hide_Selected( true );
724         SceneChangeNotify();
725 }
726
727 void HideSelected(){
728         Select_Hide();
729         GlobalSelectionSystem().setSelectedAll( false );
730 }
731
732
733 class HideAllWalker : public scene::Graph::Walker
734 {
735 bool m_hide;
736 public:
737 HideAllWalker( bool hide )
738         : m_hide( hide ){
739 }
740 bool pre( const scene::Path& path, scene::Instance& instance ) const {
741         hide_node( path.top(), m_hide );
742         return true;
743 }
744 };
745
746 void Scene_Hide_All( bool hide ){
747         GlobalSceneGraph().traverse( HideAllWalker( hide ) );
748 }
749
750 void Select_ShowAllHidden(){
751         Scene_Hide_All( false );
752         SceneChangeNotify();
753 }
754
755
756
757 void Selection_Flipx(){
758         UndoableCommand undo( "mirrorSelected -axis x" );
759         Select_FlipAxis( 0 );
760 }
761
762 void Selection_Flipy(){
763         UndoableCommand undo( "mirrorSelected -axis y" );
764         Select_FlipAxis( 1 );
765 }
766
767 void Selection_Flipz(){
768         UndoableCommand undo( "mirrorSelected -axis z" );
769         Select_FlipAxis( 2 );
770 }
771
772 void Selection_Rotatex(){
773         UndoableCommand undo( "rotateSelected -axis x -angle -90" );
774         Select_RotateAxis( 0,-90 );
775 }
776
777 void Selection_Rotatey(){
778         UndoableCommand undo( "rotateSelected -axis y -angle 90" );
779         Select_RotateAxis( 1, 90 );
780 }
781
782 void Selection_Rotatez(){
783         UndoableCommand undo( "rotateSelected -axis z -angle -90" );
784         Select_RotateAxis( 2,-90 );
785 }
786
787
788
789 void Nudge( int nDim, float fNudge ){
790         Vector3 translate( 0, 0, 0 );
791         translate[nDim] = fNudge;
792
793         GlobalSelectionSystem().translateSelected( translate );
794 }
795
796 void Selection_NudgeZ( float amount ){
797         StringOutputStream command;
798         command << "nudgeSelected -axis z -amount " << amount;
799         UndoableCommand undo( command.c_str() );
800
801         Nudge( 2, amount );
802 }
803
804 void Selection_MoveDown(){
805         Selection_NudgeZ( -GetGridSize() );
806 }
807
808 void Selection_MoveUp(){
809         Selection_NudgeZ( GetGridSize() );
810 }
811
812 void SceneSelectionChange( const Selectable& selectable ){
813         SceneChangeNotify();
814 }
815
816 SignalHandlerId Selection_boundsChanged;
817
818 void Selection_construct(){
819         typedef FreeCaller1<const Selectable&, SceneSelectionChange> SceneSelectionChangeCaller;
820         GlobalSelectionSystem().addSelectionChangeCallback( SceneSelectionChangeCaller() );
821         typedef FreeCaller1<const Selectable&, UpdateWorkzone_ForSelectionChanged> UpdateWorkzoneForSelectionChangedCaller;
822         GlobalSelectionSystem().addSelectionChangeCallback( UpdateWorkzoneForSelectionChangedCaller() );
823         typedef FreeCaller<UpdateWorkzone_ForSelection> UpdateWorkzoneForSelectionCaller;
824         Selection_boundsChanged = GlobalSceneGraph().addBoundsChangedCallback( UpdateWorkzoneForSelectionCaller() );
825 }
826
827 void Selection_destroy(){
828         GlobalSceneGraph().removeBoundsChangedCallback( Selection_boundsChanged );
829 }
830
831
832 #include "gtkdlgs.h"
833 #include <gdk/gdkkeysyms.h>
834
835
836 inline Quaternion quaternion_for_euler_xyz_degrees( const Vector3& eulerXYZ ){
837 #if 0
838         return quaternion_for_matrix4_rotation( matrix4_rotation_for_euler_xyz_degrees( eulerXYZ ) );
839 #elif 0
840         return quaternion_multiplied_by_quaternion(
841                            quaternion_multiplied_by_quaternion(
842                                    quaternion_for_z( degrees_to_radians( eulerXYZ[2] ) ),
843                                    quaternion_for_y( degrees_to_radians( eulerXYZ[1] ) )
844                                    ),
845                            quaternion_for_x( degrees_to_radians( eulerXYZ[0] ) )
846                            );
847 #elif 1
848         double cx = cos( degrees_to_radians( eulerXYZ[0] * 0.5 ) );
849         double sx = sin( degrees_to_radians( eulerXYZ[0] * 0.5 ) );
850         double cy = cos( degrees_to_radians( eulerXYZ[1] * 0.5 ) );
851         double sy = sin( degrees_to_radians( eulerXYZ[1] * 0.5 ) );
852         double cz = cos( degrees_to_radians( eulerXYZ[2] * 0.5 ) );
853         double sz = sin( degrees_to_radians( eulerXYZ[2] * 0.5 ) );
854
855         return Quaternion(
856                            cz * cy * sx - sz * sy * cx,
857                            cz * sy * cx + sz * cy * sx,
858                            sz * cy * cx - cz * sy * sx,
859                            cz * cy * cx + sz * sy * sx
860                            );
861 #endif
862 }
863
864 struct RotateDialog
865 {
866         GtkSpinButton* x;
867         GtkSpinButton* y;
868         GtkSpinButton* z;
869         ui::Window window;
870 };
871
872 static gboolean rotatedlg_apply( ui::Widget widget, RotateDialog* rotateDialog ){
873         Vector3 eulerXYZ;
874
875         eulerXYZ[0] = static_cast<float>( gtk_spin_button_get_value( rotateDialog->x ) );
876         eulerXYZ[1] = static_cast<float>( gtk_spin_button_get_value( rotateDialog->y ) );
877         eulerXYZ[2] = static_cast<float>( gtk_spin_button_get_value( rotateDialog->z ) );
878
879         StringOutputStream command;
880         command << "rotateSelectedEulerXYZ -x " << eulerXYZ[0] << " -y " << eulerXYZ[1] << " -z " << eulerXYZ[2];
881         UndoableCommand undo( command.c_str() );
882
883         GlobalSelectionSystem().rotateSelected( quaternion_for_euler_xyz_degrees( eulerXYZ ) );
884         return TRUE;
885 }
886
887 static gboolean rotatedlg_cancel( ui::Widget widget, RotateDialog* rotateDialog ){
888         gtk_widget_hide( GTK_WIDGET( rotateDialog->window ) );
889
890         gtk_spin_button_set_value( rotateDialog->x, 0.0f ); // reset to 0 on close
891         gtk_spin_button_set_value( rotateDialog->y, 0.0f );
892         gtk_spin_button_set_value( rotateDialog->z, 0.0f );
893
894         return TRUE;
895 }
896
897 static gboolean rotatedlg_ok( ui::Widget widget, RotateDialog* rotateDialog ){
898         rotatedlg_apply( widget, rotateDialog );
899         gtk_widget_hide( GTK_WIDGET( rotateDialog->window ) );
900         return TRUE;
901 }
902
903 static gboolean rotatedlg_delete( ui::Widget widget, GdkEventAny *event, RotateDialog* rotateDialog ){
904         rotatedlg_cancel( widget, rotateDialog );
905         return TRUE;
906 }
907
908 RotateDialog g_rotate_dialog;
909 void DoRotateDlg(){
910         if ( !g_rotate_dialog.window ) {
911                 g_rotate_dialog.window = MainFrame_getWindow().create_dialog_window("Arbitrary rotation", G_CALLBACK(rotatedlg_delete ), &g_rotate_dialog );
912
913                 auto accel = ui::AccelGroup();
914                 g_rotate_dialog.window.add_accel_group( accel );
915
916                 {
917                         GtkHBox* hbox = create_dialog_hbox( 4, 4 );
918                         gtk_container_add( GTK_CONTAINER( g_rotate_dialog.window ), GTK_WIDGET( hbox ) );
919                         {
920                                 GtkTable* table = create_dialog_table( 3, 2, 4, 4 );
921                                 gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( table ), TRUE, TRUE, 0 );
922                                 {
923                                         ui::Widget label = ui::Label( "  X  " );
924                                         gtk_widget_show( label );
925                                         gtk_table_attach( table, label, 0, 1, 0, 1,
926                                                                           (GtkAttachOptions) ( 0 ),
927                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
928                                 }
929                                 {
930                                         ui::Widget label = ui::Label( "  Y  " );
931                                         gtk_widget_show( label );
932                                         gtk_table_attach( table, label, 0, 1, 1, 2,
933                                                                           (GtkAttachOptions) ( 0 ),
934                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
935                                 }
936                                 {
937                                         ui::Widget label = ui::Label( "  Z  " );
938                                         gtk_widget_show( label );
939                                         gtk_table_attach( table, label, 0, 1, 2, 3,
940                                                                           (GtkAttachOptions) ( 0 ),
941                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
942                                 }
943                                 {
944                                         auto adj = ui::Adjustment( 0, -359, 359, 1, 10, 0 );
945                                         GtkSpinButton* spin = ui::SpinButton( adj, 1, 0 );
946                                         gtk_widget_show( GTK_WIDGET( spin ) );
947                                         gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 0, 1,
948                                                                           (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
949                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
950                                         gtk_widget_set_size_request( GTK_WIDGET( spin ), 64, -1 );
951                                         gtk_spin_button_set_wrap( spin, TRUE );
952
953                                         gtk_widget_grab_focus( GTK_WIDGET( spin ) );
954
955                                         g_rotate_dialog.x = spin;
956                                 }
957                                 {
958                                         auto adj = ui::Adjustment( 0, -359, 359, 1, 10, 0 );
959                                         GtkSpinButton* spin = ui::SpinButton( adj, 1, 0 );
960                                         gtk_widget_show( GTK_WIDGET( spin ) );
961                                         gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 1, 2,
962                                                                           (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
963                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
964                                         gtk_widget_set_size_request( GTK_WIDGET( spin ), 64, -1 );
965                                         gtk_spin_button_set_wrap( spin, TRUE );
966
967                                         g_rotate_dialog.y = spin;
968                                 }
969                                 {
970                                         auto adj = ui::Adjustment( 0, -359, 359, 1, 10, 0 );
971                                         GtkSpinButton* spin = ui::SpinButton( adj, 1, 0 );
972                                         gtk_widget_show( GTK_WIDGET( spin ) );
973                                         gtk_table_attach( table, GTK_WIDGET( spin ), 1, 2, 2, 3,
974                                                                           (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
975                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
976                                         gtk_widget_set_size_request( GTK_WIDGET( spin ), 64, -1 );
977                                         gtk_spin_button_set_wrap( spin, TRUE );
978
979                                         g_rotate_dialog.z = spin;
980                                 }
981                         }
982                         {
983                                 GtkVBox* vbox = create_dialog_vbox( 4 );
984                                 gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( vbox ), TRUE, TRUE, 0 );
985                                 {
986                                         auto button = create_dialog_button( "OK", G_CALLBACK( rotatedlg_ok ), &g_rotate_dialog );
987                                         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
988                                         widget_make_default( button );
989                                         gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0 );
990                                 }
991                                 {
992                                         GtkButton* button = create_dialog_button( "Cancel", G_CALLBACK( rotatedlg_cancel ), &g_rotate_dialog );
993                                         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
994                                         gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0 );
995                                 }
996                                 {
997                                         GtkButton* button = create_dialog_button( "Apply", G_CALLBACK( rotatedlg_apply ), &g_rotate_dialog );
998                                         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
999                                 }
1000                         }
1001                 }
1002         }
1003
1004         gtk_widget_show( GTK_WIDGET( g_rotate_dialog.window ) );
1005 }
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015 struct ScaleDialog
1016 {
1017         ui::Widget x;
1018         ui::Widget y;
1019         ui::Widget z;
1020         ui::Window window;
1021 };
1022
1023 static gboolean scaledlg_apply( ui::Widget widget, ScaleDialog* scaleDialog ){
1024         float sx, sy, sz;
1025
1026         sx = static_cast<float>( atof( gtk_entry_get_text( GTK_ENTRY( scaleDialog->x ) ) ) );
1027         sy = static_cast<float>( atof( gtk_entry_get_text( GTK_ENTRY( scaleDialog->y ) ) ) );
1028         sz = static_cast<float>( atof( gtk_entry_get_text( GTK_ENTRY( scaleDialog->z ) ) ) );
1029
1030         StringOutputStream command;
1031         command << "scaleSelected -x " << sx << " -y " << sy << " -z " << sz;
1032         UndoableCommand undo( command.c_str() );
1033
1034         Select_Scale( sx, sy, sz );
1035
1036         return TRUE;
1037 }
1038
1039 static gboolean scaledlg_cancel( ui::Widget widget, ScaleDialog* scaleDialog ){
1040         gtk_widget_hide( GTK_WIDGET( scaleDialog->window ) );
1041
1042         gtk_entry_set_text( GTK_ENTRY( scaleDialog->x ), "1.0" );
1043         gtk_entry_set_text( GTK_ENTRY( scaleDialog->y ), "1.0" );
1044         gtk_entry_set_text( GTK_ENTRY( scaleDialog->z ), "1.0" );
1045
1046         return TRUE;
1047 }
1048
1049 static gboolean scaledlg_ok( ui::Widget widget, ScaleDialog* scaleDialog ){
1050         scaledlg_apply( widget, scaleDialog );
1051         gtk_widget_hide( GTK_WIDGET( scaleDialog->window ) );
1052         return TRUE;
1053 }
1054
1055 static gboolean scaledlg_delete( ui::Widget widget, GdkEventAny *event, ScaleDialog* scaleDialog ){
1056         scaledlg_cancel( widget, scaleDialog );
1057         return TRUE;
1058 }
1059
1060 ScaleDialog g_scale_dialog;
1061
1062 void DoScaleDlg(){
1063         if ( !g_scale_dialog.window ) {
1064                 g_scale_dialog.window = MainFrame_getWindow().create_dialog_window("Arbitrary scale", G_CALLBACK(scaledlg_delete ), &g_scale_dialog );
1065
1066                 auto accel = ui::AccelGroup();
1067                 g_scale_dialog.window.add_accel_group( accel );
1068
1069                 {
1070                         GtkHBox* hbox = create_dialog_hbox( 4, 4 );
1071                         gtk_container_add( GTK_CONTAINER( g_scale_dialog.window ), GTK_WIDGET( hbox ) );
1072                         {
1073                                 GtkTable* table = create_dialog_table( 3, 2, 4, 4 );
1074                                 gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( table ), TRUE, TRUE, 0 );
1075                                 {
1076                                         ui::Widget label = ui::Label( "  X  " );
1077                                         gtk_widget_show( label );
1078                                         gtk_table_attach( table, label, 0, 1, 0, 1,
1079                                                                           (GtkAttachOptions) ( 0 ),
1080                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
1081                                 }
1082                                 {
1083                                         ui::Widget label = ui::Label( "  Y  " );
1084                                         gtk_widget_show( label );
1085                                         gtk_table_attach( table, label, 0, 1, 1, 2,
1086                                                                           (GtkAttachOptions) ( 0 ),
1087                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
1088                                 }
1089                                 {
1090                                         ui::Widget label = ui::Label( "  Z  " );
1091                                         gtk_widget_show( label );
1092                                         gtk_table_attach( table, label, 0, 1, 2, 3,
1093                                                                           (GtkAttachOptions) ( 0 ),
1094                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
1095                                 }
1096                                 {
1097                                         ui::Widget entry = ui::Entry();
1098                                         gtk_entry_set_text( GTK_ENTRY( entry ), "1.0" );
1099                                         gtk_widget_show( entry );
1100                                         gtk_table_attach( table, entry, 1, 2, 0, 1,
1101                                                                           (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
1102                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
1103
1104                                         g_scale_dialog.x = entry;
1105                                 }
1106                                 {
1107                                         ui::Widget entry = ui::Entry();
1108                                         gtk_entry_set_text( GTK_ENTRY( entry ), "1.0" );
1109                                         gtk_widget_show( entry );
1110                                         gtk_table_attach( table, entry, 1, 2, 1, 2,
1111                                                                           (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
1112                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
1113
1114                                         g_scale_dialog.y = entry;
1115                                 }
1116                                 {
1117                                         ui::Widget entry = ui::Entry();
1118                                         gtk_entry_set_text( GTK_ENTRY( entry ), "1.0" );
1119                                         gtk_widget_show( entry );
1120                                         gtk_table_attach( table, entry, 1, 2, 2, 3,
1121                                                                           (GtkAttachOptions) ( GTK_EXPAND | GTK_FILL ),
1122                                                                           (GtkAttachOptions) ( 0 ), 0, 0 );
1123
1124                                         g_scale_dialog.z = entry;
1125                                 }
1126                         }
1127                         {
1128                                 GtkVBox* vbox = create_dialog_vbox( 4 );
1129                                 gtk_box_pack_start( GTK_BOX( hbox ), GTK_WIDGET( vbox ), TRUE, TRUE, 0 );
1130                                 {
1131                                         auto button = create_dialog_button( "OK", G_CALLBACK( scaledlg_ok ), &g_scale_dialog );
1132                                         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
1133                                         widget_make_default( button );
1134                                         gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Return, (GdkModifierType)0, (GtkAccelFlags)0 );
1135                                 }
1136                                 {
1137                                         GtkButton* button = create_dialog_button( "Cancel", G_CALLBACK( scaledlg_cancel ), &g_scale_dialog );
1138                                         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
1139                                         gtk_widget_add_accelerator( GTK_WIDGET( button ), "clicked", accel, GDK_Escape, (GdkModifierType)0, (GtkAccelFlags)0 );
1140                                 }
1141                                 {
1142                                         GtkButton* button = create_dialog_button( "Apply", G_CALLBACK( scaledlg_apply ), &g_scale_dialog );
1143                                         gtk_box_pack_start( GTK_BOX( vbox ), GTK_WIDGET( button ), FALSE, FALSE, 0 );
1144                                 }
1145                         }
1146                 }
1147         }
1148
1149         gtk_widget_show( GTK_WIDGET( g_scale_dialog.window ) );
1150 }