]> git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/entity.cpp
Hack around segfault at launch, patch from danfe: https://github.com/TTimo/GtkRadiant...
[xonotic/netradiant.git] / radiant / entity.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 "entity.h"
23
24 #include "ientity.h"
25 #include "iselection.h"
26 #include "imodel.h"
27 #include "ifilesystem.h"
28 #include "iundo.h"
29 #include "editable.h"
30
31 #include "eclasslib.h"
32 #include "scenelib.h"
33 #include "os/path.h"
34 #include "os/file.h"
35 #include "stream/stringstream.h"
36 #include "stringio.h"
37
38 #include "gtkutil/filechooser.h"
39 #include "gtkmisc.h"
40 #include "select.h"
41 #include "map.h"
42 #include "preferences.h"
43 #include "gtkdlgs.h"
44 #include "mainframe.h"
45 #include "qe3.h"
46 #include "commands.h"
47
48 struct entity_globals_t
49 {
50         Vector3 color_entity;
51
52         entity_globals_t() :
53                 color_entity( 0.0f, 0.0f, 0.0f ){
54         }
55 };
56
57 entity_globals_t g_entity_globals;
58
59 class EntitySetKeyValueSelected : public scene::Graph::Walker
60 {
61 const char* m_key;
62 const char* m_value;
63 public:
64 EntitySetKeyValueSelected( const char* key, const char* value )
65         : m_key( key ), m_value( value ){
66 }
67 bool pre( const scene::Path& path, scene::Instance& instance ) const {
68         return true;
69 }
70 void post( const scene::Path& path, scene::Instance& instance ) const {
71         Entity* entity = Node_getEntity( path.top() );
72         if ( entity != 0
73                  && ( instance.childSelected() || Instance_getSelectable( instance )->isSelected() ) ) {
74                 entity->setKeyValue( m_key, m_value );
75         }
76 }
77 };
78
79 class EntitySetClassnameSelected : public scene::Graph::Walker
80 {
81 const char* m_classname;
82 public:
83 EntitySetClassnameSelected( const char* classname )
84         : m_classname( classname ){
85 }
86 bool pre( const scene::Path& path, scene::Instance& instance ) const {
87         return true;
88 }
89 void post( const scene::Path& path, scene::Instance& instance ) const {
90         Entity* entity = Node_getEntity( path.top() );
91         if ( entity != 0
92                  && ( instance.childSelected() || Instance_getSelectable( instance )->isSelected() ) ) {
93                 NodeSmartReference node( GlobalEntityCreator().createEntity( GlobalEntityClassManager().findOrInsert( m_classname, node_is_group( path.top() ) ) ) );
94
95                 EntityCopyingVisitor visitor( *Node_getEntity( node ) );
96
97                 entity->forEachKeyValue( visitor );
98
99                 NodeSmartReference child( path.top().get() );
100                 NodeSmartReference parent( path.parent().get() );
101                 Node_getTraversable( parent )->erase( child );
102                 if ( Node_getTraversable( child ) != 0
103                          && Node_getTraversable( node ) != 0
104                          && node_is_group( node ) ) {
105                         parentBrushes( child, node );
106                 }
107                 Node_getTraversable( parent )->insert( node );
108         }
109 }
110 };
111
112 void Scene_EntitySetKeyValue_Selected( const char* key, const char* value ){
113         GlobalSceneGraph().traverse( EntitySetKeyValueSelected( key, value ) );
114 }
115
116 void Scene_EntitySetClassname_Selected( const char* classname ){
117         GlobalSceneGraph().traverse( EntitySetClassnameSelected( classname ) );
118 }
119
120
121 void Entity_ungroupSelected(){
122         if ( GlobalSelectionSystem().countSelected() < 1 ) {
123                 return;
124         }
125
126         UndoableCommand undo( "ungroupSelectedEntities" );
127
128         scene::Path world_path( makeReference( GlobalSceneGraph().root() ) );
129         world_path.push( makeReference( Map_FindOrInsertWorldspawn( g_map ) ) );
130
131         scene::Instance &instance = GlobalSelectionSystem().ultimateSelected();
132         scene::Path path = instance.path();
133
134         if ( !Node_isEntity( path.top() ) ) {
135                 path.pop();
136         }
137
138         if ( Node_getEntity( path.top() ) != 0
139                  && node_is_group( path.top() ) ) {
140                 if ( world_path.top().get_pointer() != path.top().get_pointer() ) {
141                         parentBrushes( path.top(), world_path.top() );
142                         Path_deleteTop( path );
143                 }
144         }
145 }
146
147
148 class EntityFindSelected : public scene::Graph::Walker
149 {
150 public:
151 mutable const scene::Path *groupPath;
152 mutable scene::Instance *groupInstance;
153 EntityFindSelected() : groupPath( 0 ), groupInstance( 0 ){
154 }
155 bool pre( const scene::Path& path, scene::Instance& instance ) const {
156         return true;
157 }
158 void post( const scene::Path& path, scene::Instance& instance ) const {
159         Entity* entity = Node_getEntity( path.top() );
160         if ( entity != 0
161                  && Instance_getSelectable( instance )->isSelected()
162                  && node_is_group( path.top() )
163                  && !groupPath ) {
164                 groupPath = &path;
165                 groupInstance = &instance;
166         }
167 }
168 };
169
170 class EntityGroupSelected : public scene::Graph::Walker
171 {
172 NodeSmartReference group, worldspawn;
173 //typedef std::pair<NodeSmartReference, NodeSmartReference> DeletionPair;
174 //Stack<DeletionPair> deleteme;
175 public:
176 EntityGroupSelected( const scene::Path &p ) : group( p.top().get() ), worldspawn( Map_FindOrInsertWorldspawn( g_map ) ){
177 }
178 bool pre( const scene::Path& path, scene::Instance& instance ) const {
179         return true;
180 }
181 void post( const scene::Path& path, scene::Instance& instance ) const {
182         Selectable *selectable = Instance_getSelectable( instance );
183         if ( selectable && selectable->isSelected() ) {
184                 Entity* entity = Node_getEntity( path.top() );
185                 if ( entity == 0 && Node_isPrimitive( path.top() ) ) {
186                         NodeSmartReference child( path.top().get() );
187                         NodeSmartReference parent( path.parent().get() );
188
189                         if ( path.size() >= 3 && parent != worldspawn ) {
190                                 NodeSmartReference parentparent( path[path.size() - 3].get() );
191
192                                 Node_getTraversable( parent )->erase( child );
193                                 Node_getTraversable( group )->insert( child );
194
195                                 if ( Node_getTraversable( parent )->empty() ) {
196                                         //deleteme.push(DeletionPair(parentparent, parent));
197                                         Node_getTraversable( parentparent )->erase( parent );
198                                 }
199                         }
200                         else
201                         {
202                                 Node_getTraversable( parent )->erase( child );
203                                 Node_getTraversable( group )->insert( child );
204                         }
205                 }
206         }
207 }
208 };
209
210 void Entity_groupSelected(){
211         if ( GlobalSelectionSystem().countSelected() < 1 ) {
212                 return;
213         }
214
215         UndoableCommand undo( "groupSelectedEntities" );
216
217         scene::Path world_path( makeReference( GlobalSceneGraph().root() ) );
218         world_path.push( makeReference( Map_FindOrInsertWorldspawn( g_map ) ) );
219
220         EntityFindSelected fse;
221         GlobalSceneGraph().traverse( fse );
222         if ( fse.groupPath ) {
223                 GlobalSceneGraph().traverse( EntityGroupSelected( *fse.groupPath ) );
224         }
225         else
226         {
227                 GlobalSceneGraph().traverse( EntityGroupSelected( world_path ) );
228         }
229 }
230
231
232
233 void Entity_connectSelected(){
234         if ( GlobalSelectionSystem().countSelected() == 2 ) {
235                 GlobalEntityCreator().connectEntities(
236                         GlobalSelectionSystem().penultimateSelected().path(),
237                         GlobalSelectionSystem().ultimateSelected().path(),
238                         0
239                         );
240         }
241         else
242         {
243                 globalErrorStream() << "entityConnectSelected: exactly two instances must be selected\n";
244         }
245 }
246
247 void Entity_killconnectSelected(){
248         if ( GlobalSelectionSystem().countSelected() == 2 ) {
249                 GlobalEntityCreator().connectEntities(
250                         GlobalSelectionSystem().penultimateSelected().path(),
251                         GlobalSelectionSystem().ultimateSelected().path(),
252                         1
253                         );
254         }
255         else
256         {
257                 globalErrorStream() << "entityKillConnectSelected: exactly two instances must be selected\n";
258         }
259 }
260
261 AABB Doom3Light_getBounds( const AABB& workzone ){
262         AABB aabb( workzone );
263
264         Vector3 defaultRadius( 300, 300, 300 );
265         if ( !string_parse_vector3( EntityClass_valueForKey( *GlobalEntityClassManager().findOrInsert( "light", false ), "light_radius" ), defaultRadius ) ) {
266                 globalErrorStream() << "Doom3Light_getBounds: failed to parse default light radius\n";
267         }
268
269         if ( aabb.extents[0] == 0 ) {
270                 aabb.extents[0] = defaultRadius[0];
271         }
272         if ( aabb.extents[1] == 0 ) {
273                 aabb.extents[1] = defaultRadius[1];
274         }
275         if ( aabb.extents[2] == 0 ) {
276                 aabb.extents[2] = defaultRadius[2];
277         }
278
279         if ( aabb_valid( aabb ) ) {
280                 return aabb;
281         }
282         return AABB( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
283 }
284
285 int g_iLastLightIntensity;
286
287 void Entity_createFromSelection( const char* name, const Vector3& origin ){
288 #if 0
289         if ( string_equal_nocase( name, "worldspawn" ) ) {
290                 gtk_MessageBox( GTK_WIDGET( MainFrame_getWindow() ), "Can't create an entity with worldspawn.", "info" );
291                 return;
292         }
293 #endif
294
295         EntityClass* entityClass = GlobalEntityClassManager().findOrInsert( name, true );
296
297         bool isModel = ( string_compare_nocase_n( name, "misc_", 5 ) == 0 && string_equal_nocase( name + string_length( name ) - 5, "model" ) ) // misc_*model (also misc_model)
298                                    || string_equal_nocase( name, "model_static" )
299                                    || ( GlobalSelectionSystem().countSelected() == 0 && string_equal_nocase( name, "func_static" ) );
300
301         bool brushesSelected = Scene_countSelectedBrushes( GlobalSceneGraph() ) != 0;
302
303         if ( !( entityClass->fixedsize || isModel ) && !brushesSelected ) {
304                 globalErrorStream() << "failed to create a group entity - no brushes are selected\n";
305                 return;
306         }
307
308         AABB workzone( aabb_for_minmax( Select_getWorkZone().d_work_min, Select_getWorkZone().d_work_max ) );
309
310
311         NodeSmartReference node( GlobalEntityCreator().createEntity( entityClass ) );
312
313         Node_getTraversable( GlobalSceneGraph().root() )->insert( node );
314
315         scene::Path entitypath( makeReference( GlobalSceneGraph().root() ) );
316         entitypath.push( makeReference( node.get() ) );
317         scene::Instance& instance = findInstance( entitypath );
318
319         if ( entityClass->fixedsize || ( isModel && !brushesSelected ) ) {
320                 Select_Delete();
321
322                 Transformable* transform = Instance_getTransformable( instance );
323                 if ( transform != 0 ) {
324                         transform->setType( TRANSFORM_PRIMITIVE );
325                         transform->setTranslation( origin );
326                         transform->freezeTransform();
327                 }
328
329                 GlobalSelectionSystem().setSelectedAll( false );
330
331                 Instance_setSelected( instance, true );
332         }
333         else
334         {
335                 if ( g_pGameDescription->mGameType == "doom3" ) {
336                         Node_getEntity( node )->setKeyValue( "model", Node_getEntity( node )->getKeyValue( "name" ) );
337                 }
338
339                 Scene_parentSelectedBrushesToEntity( GlobalSceneGraph(), node );
340                 Scene_forEachChildSelectable( SelectableSetSelected( true ), instance.path() );
341         }
342
343         // tweaking: when right clic dropping a light entity, ask for light value in a custom dialog box
344         // see SF bug 105383
345
346         if ( g_pGameDescription->mGameType == "hl" ) {
347                 // FIXME - Hydra: really we need a combined light AND color dialog for halflife.
348                 if ( string_equal_nocase( name, "light" )
349                          || string_equal_nocase( name, "light_environment" )
350                          || string_equal_nocase( name, "light_spot" ) ) {
351                         int intensity = g_iLastLightIntensity;
352
353                         if ( DoLightIntensityDlg( &intensity ) == eIDOK ) {
354                                 g_iLastLightIntensity = intensity;
355                                 char buf[30];
356                                 sprintf( buf, "255 255 255 %d", intensity );
357                                 Node_getEntity( node )->setKeyValue( "_light", buf );
358                         }
359                 }
360         }
361         else if ( string_equal_nocase( name, "light" ) ) {
362                 if ( g_pGameDescription->mGameType != "doom3" ) {
363                         int intensity = g_iLastLightIntensity;
364
365                         if ( DoLightIntensityDlg( &intensity ) == eIDOK ) {
366                                 g_iLastLightIntensity = intensity;
367                                 char buf[10];
368                                 sprintf( buf, "%d", intensity );
369                                 Node_getEntity( node )->setKeyValue( "light", buf );
370                         }
371                 }
372                 else if ( brushesSelected ) { // use workzone to set light position/size for doom3 lights, if there are brushes selected
373                         AABB bounds( Doom3Light_getBounds( workzone ) );
374                         StringOutputStream key( 64 );
375                         key << bounds.origin[0] << " " << bounds.origin[1] << " " << bounds.origin[2];
376                         Node_getEntity( node )->setKeyValue( "origin", key.c_str() );
377                         key.clear();
378                         key << bounds.extents[0] << " " << bounds.extents[1] << " " << bounds.extents[2];
379                         Node_getEntity( node )->setKeyValue( "light_radius", key.c_str() );
380                 }
381         }
382
383         if ( isModel ) {
384                 const char* model = misc_model_dialog( GTK_WIDGET( MainFrame_getWindow() ) );
385                 if ( model != 0 ) {
386                         Node_getEntity( node )->setKeyValue( "model", model );
387                 }
388         }
389 }
390
391 #if 0
392 bool DoNormalisedColor( Vector3& color ){
393         if ( !color_dialog( GTK_WIDGET( MainFrame_getWindow() ), color ) ) {
394                 return false;
395         }
396         /*
397         ** scale colors so that at least one component is at 1.0F
398         */
399
400         float largest = 0.0F;
401
402         if ( color[0] > largest ) {
403                 largest = color[0];
404         }
405         if ( color[1] > largest ) {
406                 largest = color[1];
407         }
408         if ( color[2] > largest ) {
409                 largest = color[2];
410         }
411
412         if ( largest == 0.0F ) {
413                 color[0] = 1.0F;
414                 color[1] = 1.0F;
415                 color[2] = 1.0F;
416         }
417         else
418         {
419                 float scaler = 1.0F / largest;
420
421                 color[0] *= scaler;
422                 color[1] *= scaler;
423                 color[2] *= scaler;
424         }
425
426         return true;
427 }
428 #endif
429
430 void NormalizeColor( Vector3& color ){
431         // scale colors so that at least one component is at 1.0F
432
433         float largest = 0.0F;
434
435         if ( color[0] > largest ) {
436                 largest = color[0];
437         }
438         if ( color[1] > largest ) {
439                 largest = color[1];
440         }
441         if ( color[2] > largest ) {
442                 largest = color[2];
443         }
444
445         if ( largest == 0.0F ) {
446                 color[0] = 1.0F;
447                 color[1] = 1.0F;
448                 color[2] = 1.0F;
449         }
450         else
451         {
452                 float scaler = 1.0F / largest;
453
454                 color[0] *= scaler;
455                 color[1] *= scaler;
456                 color[2] *= scaler;
457         }
458 }
459
460 void Entity_normalizeColor(){
461         if ( GlobalSelectionSystem().countSelected() != 0 ) {
462                 const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path();
463                 Entity* entity = Node_getEntity( path.top() );
464
465                 if ( entity != 0 ) {
466                         const char* strColor = entity->getKeyValue( "_color" );
467                         if ( !string_empty( strColor ) ) {
468                                 Vector3 rgb;
469                                 if ( string_parse_vector3( strColor, rgb ) ) {
470                                         g_entity_globals.color_entity = rgb;
471                                         NormalizeColor( g_entity_globals.color_entity );
472
473                                         char buffer[128];
474                                         sprintf( buffer, "%g %g %g", g_entity_globals.color_entity[0],
475                                                          g_entity_globals.color_entity[1],
476                                                          g_entity_globals.color_entity[2] );
477
478                                         Scene_EntitySetKeyValue_Selected( "_color", buffer );
479                                 }
480                         }
481                 }
482         }
483 }
484
485 void Entity_setColour(){
486         if ( GlobalSelectionSystem().countSelected() != 0 ) {
487                 bool normalize = false;
488                 const scene::Path& path = GlobalSelectionSystem().ultimateSelected().path();
489                 Entity* entity = Node_getEntity( path.top() );
490
491                 if ( entity != 0 ) {
492                         const char* strColor = entity->getKeyValue( "_color" );
493                         if ( !string_empty( strColor ) ) {
494                                 Vector3 rgb;
495                                 if ( string_parse_vector3( strColor, rgb ) ) {
496                                         g_entity_globals.color_entity = rgb;
497                                 }
498                         }
499
500                         if ( g_pGameDescription->mGameType == "doom3" ) {
501                                 normalize = false;
502                         }
503
504                         if ( color_dialog( GTK_WIDGET( MainFrame_getWindow() ), g_entity_globals.color_entity ) ) {
505                                 if ( normalize ) {
506                                         NormalizeColor( g_entity_globals.color_entity );
507                                 }
508
509                                 char buffer[128];
510                                 sprintf( buffer, "%g %g %g", g_entity_globals.color_entity[0],
511                                                  g_entity_globals.color_entity[1],
512                                                  g_entity_globals.color_entity[2] );
513
514                                 Scene_EntitySetKeyValue_Selected( "_color", buffer );
515                         }
516                 }
517         }
518 }
519
520 const char* misc_model_dialog( GtkWidget* parent ){
521         StringOutputStream buffer( 1024 );
522
523         buffer << g_qeglobals.m_userGamePath.c_str() << "models/";
524
525         if ( !file_readable( buffer.c_str() ) ) {
526                 // just go to fsmain
527                 buffer.clear();
528                 buffer << g_qeglobals.m_userGamePath.c_str() << "/";
529         }
530
531         const char *filename = file_dialog( parent, TRUE, "Choose Model", buffer.c_str(), ModelLoader::Name() );
532         if ( filename != 0 ) {
533                 // use VFS to get the correct relative path
534                 const char* relative = path_make_relative( filename, GlobalFileSystem().findRoot( filename ) );
535                 if ( relative == filename ) {
536                         globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n";
537                 }
538                 return relative;
539         }
540         return 0;
541 }
542
543 void LightRadiiImport( EntityCreator& self, bool value ){
544         self.setLightRadii( value );
545 }
546 typedef ReferenceCaller1<EntityCreator, bool, LightRadiiImport> LightRadiiImportCaller;
547
548 void LightRadiiExport( EntityCreator& self, const BoolImportCallback& importer ){
549         importer( self.getLightRadii() );
550 }
551 typedef ReferenceCaller1<EntityCreator, const BoolImportCallback&, LightRadiiExport> LightRadiiExportCaller;
552
553 void Entity_constructPreferences( PreferencesPage& page ){
554         page.appendCheckBox(
555                 "Show", "Light Radii",
556                 LightRadiiImportCaller( GlobalEntityCreator() ),
557                 LightRadiiExportCaller( GlobalEntityCreator() )
558                 );
559 }
560 void Entity_constructPage( PreferenceGroup& group ){
561         PreferencesPage page( group.createPage( "Entities", "Entity Display Preferences" ) );
562         Entity_constructPreferences( page );
563 }
564 void Entity_registerPreferencesPage(){
565         PreferencesDialog_addDisplayPage( FreeCaller1<PreferenceGroup&, Entity_constructPage>() );
566 }
567
568
569
570 void Entity_constructMenu( GtkMenu* menu ){
571         create_menu_item_with_mnemonic( menu, "_Regroup", "GroupSelection" );
572         create_menu_item_with_mnemonic( menu, "_Ungroup", "UngroupSelection" );
573         create_menu_item_with_mnemonic( menu, "_Connect", "ConnectSelection" );
574         create_menu_item_with_mnemonic( menu, "_KillConnect", "KillConnectSelection" );
575         create_menu_item_with_mnemonic( menu, "_Select Color...", "EntityColor" );
576         create_menu_item_with_mnemonic( menu, "_Normalize Color...", "NormalizeColor" );
577 }
578
579
580
581 #include "preferencesystem.h"
582 #include "stringio.h"
583
584 void Entity_Construct(){
585         GlobalCommands_insert( "EntityColor", FreeCaller<Entity_setColour>(), Accelerator( 'K' ) );
586         GlobalCommands_insert( "NormalizeColor", FreeCaller<Entity_normalizeColor>() );
587         GlobalCommands_insert( "ConnectSelection", FreeCaller<Entity_connectSelected>(), Accelerator( 'K', (GdkModifierType)GDK_CONTROL_MASK ) );
588         GlobalCommands_insert( "KillConnectSelection", FreeCaller<Entity_killconnectSelected>(), Accelerator( 'K', (GdkModifierType)( GDK_SHIFT_MASK ) ) );
589         GlobalCommands_insert( "GroupSelection", FreeCaller<Entity_groupSelected>() );
590         GlobalCommands_insert( "UngroupSelection", FreeCaller<Entity_ungroupSelected>() );
591
592         GlobalPreferenceSystem().registerPreference( "SI_Colors5", Vector3ImportStringCaller( g_entity_globals.color_entity ), Vector3ExportStringCaller( g_entity_globals.color_entity ) );
593         GlobalPreferenceSystem().registerPreference( "LastLightIntensity", IntImportStringCaller( g_iLastLightIntensity ), IntExportStringCaller( g_iLastLightIntensity ) );
594
595         Entity_registerPreferencesPage();
596 }
597
598 void Entity_Destroy(){
599 }