2 Copyright (C) 2001-2006, William Joseph.
5 This file is part of GtkRadiant.
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.
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.
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
22 #include "referencecache.h"
23 #include "globaldefs.h"
25 #include "debugging/debugging.h"
27 #include "iscenegraph.h"
28 #include "iselection.h"
32 MapModules& ReferenceAPI_getMapModules();
36 ModelModules& ReferenceAPI_getModelModules();
38 #include "ifilesystem.h"
40 #include "ifiletypes.h"
41 #include "ireference.h"
43 #include "qerplugin.h"
47 #include "container/cache.h"
48 #include "container/hashfunc.h"
50 #include "stream/textfilestream.h"
51 #include "nullmodel.h"
53 #include "stream/stringstream.h"
55 #include "moduleobserver.h"
56 #include "moduleobservers.h"
58 #include "mainframe.h"
60 #include "filetypes.h"
62 extern bool g_writeMapComments;
64 bool References_Saved();
67 Map_SetModified( g_map, !References_Saved() );
71 EntityCreator* g_entityCreator = 0;
73 bool MapResource_loadFile( const MapFormat& format, scene::Node& root, const char* filename ){
74 globalOutputStream() << "Open file " << filename << " for read...";
75 TextFileInputStream file( filename );
76 if ( !file.failed() ) {
77 globalOutputStream() << "success\n";
78 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( filename ), "Loading Map" );
79 ASSERT_NOTNULL( g_entityCreator );
80 format.readGraph( root, file, *g_entityCreator );
85 globalErrorStream() << "failure\n";
90 NodeSmartReference MapResource_load( const MapFormat& format, const char* path, const char* name ){
91 NodeSmartReference root( NewMapRoot( name ) );
93 StringOutputStream fullpath( 256 );
94 fullpath << path << name;
96 if ( path_is_absolute( fullpath.c_str() ) ) {
97 MapResource_loadFile( format, root, fullpath.c_str() );
101 globalErrorStream() << "map path is not fully qualified: " << makeQuoted( fullpath.c_str() ) << "\n";
107 bool MapResource_saveFile( const MapFormat& format, scene::Node& root, GraphTraversalFunc traverse, const char* filename ){
108 //ASSERT_MESSAGE(path_is_absolute(filename), "MapResource_saveFile: path is not absolute: " << makeQuoted(filename));
109 globalOutputStream() << "Open file " << filename << " for write...";
110 TextFileOutputStream file( filename );
111 if ( !file.failed() ) {
112 globalOutputStream() << "success\n";
113 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( filename ), "Saving Map" );
114 format.writeGraph( root, traverse, file, g_writeMapComments );
118 globalErrorStream() << "failure\n";
122 bool file_saveBackup( const char* path ){
123 if ( file_writeable( path ) ) {
124 StringOutputStream backup( 256 );
125 backup << StringRange( path, path_get_extension( path ) ) << "bak";
127 return ( !file_exists( backup.c_str() ) || file_remove( backup.c_str() ) ) // remove backup
128 && file_move( path, backup.c_str() ); // rename current to backup
131 globalErrorStream() << "map path is not writeable: " << makeQuoted( path ) << "\n";
135 bool MapResource_save( const MapFormat& format, scene::Node& root, const char* path, const char* name ){
136 StringOutputStream fullpath( 256 );
137 fullpath << path << name;
139 if ( path_is_absolute( fullpath.c_str() ) ) {
140 if ( !file_exists( fullpath.c_str() ) || file_saveBackup( fullpath.c_str() ) ) {
141 return MapResource_saveFile( format, root, Map_Traverse, fullpath.c_str() );
144 globalErrorStream() << "failed to save a backup map file: " << makeQuoted( fullpath.c_str() ) << "\n";
148 globalErrorStream() << "map path is not fully qualified: " << makeQuoted( fullpath.c_str() ) << "\n";
154 NodeSmartReference g_nullNode( NewNullNode() );
155 NodeSmartReference g_nullModel( g_nullNode );
158 class NullModelLoader : public ModelLoader
161 scene::Node& loadModel( ArchiveFile& file ){
168 NullModelLoader g_NullModelLoader;
172 /// \brief Returns the model loader for the model \p type or 0 if the model \p type has no loader module
173 ModelLoader* ModelLoader_forType( const char* type ){
174 const char* moduleName = findModuleName( &GlobalFiletypes(), ModelLoader::Name(), type );
175 if ( string_not_empty( moduleName ) ) {
176 ModelLoader* table = ReferenceAPI_getModelModules().findModule( moduleName );
182 globalErrorStream() << "ERROR: Model type incorrectly registered: \"" << moduleName << "\"\n";
183 return &g_NullModelLoader;
189 NodeSmartReference ModelResource_load( ModelLoader* loader, const char* name ){
190 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( name ), "Loading Model" );
192 NodeSmartReference model( g_nullModel );
195 ArchiveFile* file = GlobalFileSystem().openFile( name );
198 globalOutputStream() << "Loaded Model: \"" << name << "\"\n";
199 model = loader->loadModel( *file );
204 globalErrorStream() << "Model load failed: \"" << name << "\"\n";
208 model.get().m_isRoot = true;
214 inline hash_t path_hash( const char* path, hash_t previous = 0 ){
216 return string_hash_nocase( path, previous );
218 return string_hash( path, previous );
224 bool operator()( const CopiedString& path, const CopiedString& other ) const {
225 return path_equal( path.c_str(), other.c_str() );
231 typedef hash_t hash_type;
233 hash_type operator()( const CopiedString& path ) const {
234 return path_hash( path.c_str() );
238 typedef std::pair<CopiedString, CopiedString> ModelKey;
242 bool operator()( const ModelKey& key, const ModelKey& other ) const {
243 return path_equal( key.first.c_str(), other.first.c_str() ) && path_equal( key.second.c_str(), other.second.c_str() );
249 typedef hash_t hash_type;
251 hash_type operator()( const ModelKey& key ) const {
252 return hash_combine( path_hash( key.first.c_str() ), path_hash( key.second.c_str() ) );
256 typedef HashTable<ModelKey, NodeSmartReference, ModelKeyHash, ModelKeyEqual> ModelCache;
257 ModelCache g_modelCache;
258 bool g_modelCache_enabled = true;
260 ModelCache::iterator ModelCache_find( const char* path, const char* name ){
261 if ( g_modelCache_enabled ) {
262 return g_modelCache.find( ModelKey( path, name ) );
264 return g_modelCache.end();
267 ModelCache::iterator ModelCache_insert( const char* path, const char* name, scene::Node& node ){
268 if ( g_modelCache_enabled ) {
269 return g_modelCache.insert( ModelKey( path, name ), NodeSmartReference( node ) );
271 return g_modelCache.insert( ModelKey( "", "" ), g_nullModel );
274 void ModelCache_flush( const char* path, const char* name ){
275 ModelCache::iterator i = g_modelCache.find( ModelKey( path, name ) );
276 if ( i != g_modelCache.end() ) {
277 //ASSERT_MESSAGE((*i).value.getCount() == 0, "resource flushed while still in use: " << (*i).key.first.c_str() << (*i).key.second.c_str());
278 g_modelCache.erase( i );
282 void ModelCache_clear(){
283 g_modelCache_enabled = false;
284 g_modelCache.clear();
285 g_modelCache_enabled = true;
288 NodeSmartReference Model_load( ModelLoader* loader, const char* path, const char* name, const char* type ){
290 return ModelResource_load( loader, name );
294 const char* moduleName = findModuleName( &GlobalFiletypes(), MapFormat::Name(), type );
295 if ( string_not_empty( moduleName ) ) {
296 const MapFormat* format = ReferenceAPI_getMapModules().findModule( moduleName );
298 return MapResource_load( *format, path, name );
302 globalErrorStream() << "ERROR: Map type incorrectly registered: \"" << moduleName << "\"\n";
308 if ( string_not_empty( type ) ) {
309 globalErrorStream() << "Model type not supported: \"" << name << "\"\n";
318 bool g_realised = false;
320 // name may be absolute or relative
321 const char* rootPath( const char* name ){
322 return GlobalFileSystem().findRoot(
323 path_is_absolute( name )
325 : GlobalFileSystem().findFile( name )
330 struct ModelResource : public Resource
332 NodeSmartReference m_model;
333 const CopiedString m_originalName;
337 ModelLoader* m_loader;
338 ModuleObservers m_observers;
339 std::time_t m_modified;
340 std::size_t m_unrealised;
342 ModelResource( const CopiedString& name ) :
343 m_model( g_nullModel ),
344 m_originalName( name ),
345 m_type( path_get_extension( name.c_str() ) ),
349 m_loader = ModelLoader_forType( m_type.c_str() );
360 ASSERT_MESSAGE( !realised(), "ModelResource::~ModelResource: resource reference still realised: " << makeQuoted( m_name.c_str() ) );
364 ModelResource( const ModelResource& );
367 ModelResource& operator=( const ModelResource& );
369 void setModel( const NodeSmartReference& model ){
374 m_model = g_nullModel;
378 if ( g_modelCache_enabled ) {
380 ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() );
381 if ( i == g_modelCache.end() ) {
382 i = ModelCache_insert(
385 Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() )
389 setModel( ( *i ).value );
393 setModel( Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() ) );
404 ASSERT_MESSAGE( realised(), "resource not realised" );
405 if ( m_model == g_nullModel ) {
409 return m_model != g_nullModel;
414 const char* moduleName = findModuleName( GetFileTypeRegistry(), MapFormat::Name(), m_type.c_str() );
415 if ( string_not_empty( moduleName ) ) {
416 const MapFormat* format = ReferenceAPI_getMapModules().findModule( moduleName );
417 if ( format != 0 && MapResource_save( *format, m_model.get(), m_path.c_str(), m_name.c_str() ) ) {
428 ModelCache_flush( m_path.c_str(), m_name.c_str() );
432 scene::Node* getNode(){
433 //if(m_model != g_nullModel)
435 return m_model.get_pointer();
440 void setNode( scene::Node* node ){
441 ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() );
442 if ( i != g_modelCache.end() ) {
443 ( *i ).value = NodeSmartReference( *node );
445 setModel( NodeSmartReference( *node ) );
450 void attach( ModuleObserver& observer ){
454 m_observers.attach( observer );
457 void detach( ModuleObserver& observer ){
459 observer.unrealise();
461 m_observers.detach( observer );
465 return m_unrealised == 0;
469 ASSERT_MESSAGE( m_unrealised != 0, "ModelResource::realise: already realised" );
470 if ( --m_unrealised == 0 ) {
471 m_path = rootPath( m_originalName.c_str() );
472 m_name = path_make_relative( m_originalName.c_str(), m_path.c_str() );
474 //globalOutputStream() << "ModelResource::realise: " << m_path.c_str() << m_name.c_str() << "\n";
476 m_observers.realise();
481 if ( ++m_unrealised == 1 ) {
482 m_observers.unrealise();
484 //globalOutputStream() << "ModelResource::unrealise: " << m_path.c_str() << m_name.c_str() << "\n";
490 return Node_getMapFile( m_model ) != 0;
494 MapFile* map = Node_getMapFile( m_model );
496 map->setChangedCallback( makeCallbackF(MapChanged) );
500 std::time_t modified() const {
501 StringOutputStream fullpath( 256 );
502 fullpath << m_path.c_str() << m_name.c_str();
503 return file_modified( fullpath.c_str() );
507 m_modified = modified();
508 MapFile* map = Node_getMapFile( m_model );
514 bool mapSaved() const {
515 MapFile* map = Node_getMapFile( m_model );
517 return m_modified == modified() && map->saved();
522 bool isModified() const {
523 return ( ( !string_empty( m_path.c_str() ) // had or has an absolute path
524 && m_modified != modified() ) // AND disk timestamp changed
525 || !path_equal( rootPath( m_originalName.c_str() ), m_path.c_str() ) ); // OR absolute vfs-root changed
529 if ( isModified() ) {
537 class HashtableReferenceCache : public ReferenceCache, public ModuleObserver
539 typedef HashedCache<CopiedString, ModelResource, PathHash, PathEqual> ModelReferences;
540 ModelReferences m_references;
541 std::size_t m_unrealised;
543 class ModelReferencesSnapshot
545 ModelReferences& m_references;
546 typedef std::list<ModelReferences::iterator> Iterators;
547 Iterators m_iterators;
549 typedef Iterators::iterator iterator;
551 ModelReferencesSnapshot( ModelReferences& references ) : m_references( references ){
552 for ( ModelReferences::iterator i = m_references.begin(); i != m_references.end(); ++i )
554 m_references.capture( i );
555 m_iterators.push_back( i );
559 ~ModelReferencesSnapshot(){
560 for ( Iterators::iterator i = m_iterators.begin(); i != m_iterators.end(); ++i )
562 m_references.release( *i );
567 return m_iterators.begin();
571 return m_iterators.end();
577 typedef ModelReferences::iterator iterator;
579 HashtableReferenceCache() : m_unrealised( 1 ){
583 return m_references.begin();
587 return m_references.end();
591 m_references.clear();
594 Resource* capture( const char* path ){
595 //globalOutputStream() << "capture: \"" << path << "\"\n";
596 return m_references.capture( CopiedString( path ) ).get();
599 void release( const char* path ){
600 m_references.release( CopiedString( path ) );
601 //globalOutputStream() << "release: \"" << path << "\"\n";
604 void setEntityCreator( EntityCreator& entityCreator ){
605 g_entityCreator = &entityCreator;
608 bool realised() const {
609 return m_unrealised == 0;
613 ASSERT_MESSAGE( m_unrealised != 0, "HashtableReferenceCache::realise: already realised" );
614 if ( --m_unrealised == 0 ) {
618 ModelReferencesSnapshot snapshot( m_references );
619 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
621 ModelReferences::value_type& value = *( *i );
622 if ( value.value.count() != 1 ) {
623 value.value.get()->realise();
631 if ( ++m_unrealised == 1 ) {
635 ModelReferencesSnapshot snapshot( m_references );
636 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
638 ModelReferences::value_type& value = *( *i );
639 if ( value.value.count() != 1 ) {
640 value.value.get()->unrealise();
650 ModelReferencesSnapshot snapshot( m_references );
651 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
653 ModelResource* resource = ( *( *i ) ).value.get();
654 if ( !resource->isMap() ) {
663 HashtableReferenceCache g_referenceCache;
667 class ResourceVisitor
670 virtual void visit( const char* name, const char* path, const
674 void SaveReferences(){
675 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Saving Map" );
676 for ( HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i )
678 ( *i ).value->save();
683 bool References_Saved(){
684 for ( HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i )
686 scene::Node* node = ( *i ).value->getNode();
688 MapFile* map = Node_getMapFile( *node );
689 if ( map != 0 && !map->saved() ) {
697 void RefreshReferences(){
698 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Refreshing Models" );
699 g_referenceCache.refresh();
703 void FlushReferences(){
706 g_referenceCache.clear();
709 ReferenceCache& GetReferenceCache(){
710 return g_referenceCache;
714 #include "modulesystem/modulesmap.h"
715 #include "modulesystem/singletonmodule.h"
716 #include "modulesystem/moduleregistry.h"
718 class ReferenceDependencies :
719 public GlobalRadiantModuleRef,
720 public GlobalFileSystemModuleRef,
721 public GlobalFiletypesModuleRef
723 ModelModulesRef m_model_modules;
724 MapModulesRef m_map_modules;
726 ReferenceDependencies() :
727 m_model_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "modeltypes" ) ),
728 m_map_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "maptypes" ) )
732 ModelModules& getModelModules(){
733 return m_model_modules.get();
736 MapModules& getMapModules(){
737 return m_map_modules.get();
741 class ReferenceAPI : public TypeSystemRef
743 ReferenceCache* m_reference;
745 typedef ReferenceCache Type;
747 STRING_CONSTANT( Name, "*" );
750 g_nullModel = NewNullModel();
752 GlobalFileSystem().attach( g_referenceCache );
754 m_reference = &GetReferenceCache();
758 GlobalFileSystem().detach( g_referenceCache );
760 g_nullModel = g_nullNode;
763 ReferenceCache* getTable(){
768 typedef SingletonModule<ReferenceAPI, ReferenceDependencies> ReferenceModule;
769 typedef Static<ReferenceModule> StaticReferenceModule;
770 StaticRegisterModule staticRegisterReference( StaticReferenceModule::instance() );
772 ModelModules& ReferenceAPI_getModelModules(){
773 return StaticReferenceModule::instance().getDependencies().getModelModules();
776 MapModules& ReferenceAPI_getMapModules(){
777 return StaticReferenceModule::instance().getDependencies().getMapModules( );