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"
31 MapModules& ReferenceAPI_getMapModules();
33 ModelModules& ReferenceAPI_getModelModules();
34 #include "ifilesystem.h"
36 #include "ifiletypes.h"
37 #include "ireference.h"
39 #include "qerplugin.h"
43 #include "container/cache.h"
44 #include "container/hashfunc.h"
46 #include "stream/textfilestream.h"
47 #include "nullmodel.h"
49 #include "stream/stringstream.h"
51 #include "moduleobserver.h"
52 #include "moduleobservers.h"
54 #include "mainframe.h"
56 #include "filetypes.h"
59 bool References_Saved();
62 Map_SetModified( g_map, !References_Saved() );
66 EntityCreator* g_entityCreator = 0;
68 bool MapResource_loadFile( const MapFormat& format, scene::Node& root, const char* filename ){
69 globalOutputStream() << "Open file " << filename << " for read...";
70 TextFileInputStream file( filename );
71 if ( !file.failed() ) {
72 globalOutputStream() << "success\n";
73 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( filename ), "Loading Map" );
74 ASSERT_NOTNULL( g_entityCreator );
75 format.readGraph( root, file, *g_entityCreator );
80 globalErrorStream() << "failure\n";
85 NodeSmartReference MapResource_load( const MapFormat& format, const char* path, const char* name ){
86 NodeSmartReference root( NewMapRoot( name ) );
88 StringOutputStream fullpath( 256 );
89 fullpath << path << name;
91 if ( path_is_absolute( fullpath.c_str() ) ) {
92 MapResource_loadFile( format, root, fullpath.c_str() );
96 globalErrorStream() << "map path is not fully qualified: " << makeQuoted( fullpath.c_str() ) << "\n";
102 bool MapResource_saveFile( const MapFormat& format, scene::Node& root, GraphTraversalFunc traverse, const char* filename ){
103 //ASSERT_MESSAGE(path_is_absolute(filename), "MapResource_saveFile: path is not absolute: " << makeQuoted(filename));
104 globalOutputStream() << "Open file " << filename << " for write...";
105 TextFileOutputStream file( filename );
106 if ( !file.failed() ) {
107 globalOutputStream() << "success\n";
108 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( filename ), "Saving Map" );
109 format.writeGraph( root, traverse, file );
113 globalErrorStream() << "failure\n";
117 bool file_saveBackup( const char* path ){
118 if ( file_writeable( path ) ) {
119 StringOutputStream backup( 256 );
120 backup << StringRange( path, path_get_extension( path ) ) << "bak";
122 return ( !file_exists( backup.c_str() ) || file_remove( backup.c_str() ) ) // remove backup
123 && file_move( path, backup.c_str() ); // rename current to backup
126 globalErrorStream() << "map path is not writeable: " << makeQuoted( path ) << "\n";
130 bool MapResource_save( const MapFormat& format, scene::Node& root, const char* path, const char* name ){
131 StringOutputStream fullpath( 256 );
132 fullpath << path << name;
134 if ( path_is_absolute( fullpath.c_str() ) ) {
135 if ( !file_exists( fullpath.c_str() ) || file_saveBackup( fullpath.c_str() ) ) {
136 return MapResource_saveFile( format, root, Map_Traverse, fullpath.c_str() );
139 globalErrorStream() << "failed to save a backup map file: " << makeQuoted( fullpath.c_str() ) << "\n";
143 globalErrorStream() << "map path is not fully qualified: " << makeQuoted( fullpath.c_str() ) << "\n";
149 NodeSmartReference g_nullNode( NewNullNode() );
150 NodeSmartReference g_nullModel( g_nullNode );
153 class NullModelLoader : public ModelLoader
156 scene::Node& loadModel( ArchiveFile& file ){
163 NullModelLoader g_NullModelLoader;
167 /// \brief Returns the model loader for the model \p type or 0 if the model \p type has no loader module
168 ModelLoader* ModelLoader_forType( const char* type ){
169 const char* moduleName = findModuleName( &GlobalFiletypes(), ModelLoader::Name(), type );
170 if ( string_not_empty( moduleName ) ) {
171 ModelLoader* table = ReferenceAPI_getModelModules().findModule( moduleName );
177 globalErrorStream() << "ERROR: Model type incorrectly registered: \"" << moduleName << "\"\n";
178 return &g_NullModelLoader;
184 NodeSmartReference ModelResource_load( ModelLoader* loader, const char* name ){
185 ScopeDisableScreenUpdates disableScreenUpdates( path_get_filename_start( name ), "Loading Model" );
187 NodeSmartReference model( g_nullModel );
190 ArchiveFile* file = GlobalFileSystem().openFile( name );
193 globalOutputStream() << "Loaded Model: \"" << name << "\"\n";
194 model = loader->loadModel( *file );
199 globalErrorStream() << "Model load failed: \"" << name << "\"\n";
203 model.get().m_isRoot = true;
209 inline hash_t path_hash( const char* path, hash_t previous = 0 ){
211 return string_hash_nocase( path, previous );
213 return string_hash( path, previous );
219 bool operator()( const CopiedString& path, const CopiedString& other ) const {
220 return path_equal( path.c_str(), other.c_str() );
226 typedef hash_t hash_type;
227 hash_type operator()( const CopiedString& path ) const {
228 return path_hash( path.c_str() );
232 typedef std::pair<CopiedString, CopiedString> ModelKey;
236 bool operator()( const ModelKey& key, const ModelKey& other ) const {
237 return path_equal( key.first.c_str(), other.first.c_str() ) && path_equal( key.second.c_str(), other.second.c_str() );
243 typedef hash_t hash_type;
244 hash_type operator()( const ModelKey& key ) const {
245 return hash_combine( path_hash( key.first.c_str() ), path_hash( key.second.c_str() ) );
249 typedef HashTable<ModelKey, NodeSmartReference, ModelKeyHash, ModelKeyEqual> ModelCache;
250 ModelCache g_modelCache;
251 bool g_modelCache_enabled = true;
253 ModelCache::iterator ModelCache_find( const char* path, const char* name ){
254 if ( g_modelCache_enabled ) {
255 return g_modelCache.find( ModelKey( path, name ) );
257 return g_modelCache.end();
260 ModelCache::iterator ModelCache_insert( const char* path, const char* name, scene::Node& node ){
261 if ( g_modelCache_enabled ) {
262 return g_modelCache.insert( ModelKey( path, name ), NodeSmartReference( node ) );
264 return g_modelCache.insert( ModelKey( "", "" ), g_nullModel );
267 void ModelCache_flush( const char* path, const char* name ){
268 ModelCache::iterator i = g_modelCache.find( ModelKey( path, name ) );
269 if ( i != g_modelCache.end() ) {
270 //ASSERT_MESSAGE((*i).value.getCount() == 0, "resource flushed while still in use: " << (*i).key.first.c_str() << (*i).key.second.c_str());
271 g_modelCache.erase( i );
275 void ModelCache_clear(){
276 g_modelCache_enabled = false;
277 g_modelCache.clear();
278 g_modelCache_enabled = true;
281 NodeSmartReference Model_load( ModelLoader* loader, const char* path, const char* name, const char* type ){
283 return ModelResource_load( loader, name );
287 const char* moduleName = findModuleName( &GlobalFiletypes(), MapFormat::Name(), type );
288 if ( string_not_empty( moduleName ) ) {
289 const MapFormat* format = ReferenceAPI_getMapModules().findModule( moduleName );
291 return MapResource_load( *format, path, name );
295 globalErrorStream() << "ERROR: Map type incorrectly registered: \"" << moduleName << "\"\n";
301 if ( string_not_empty( type ) ) {
302 globalErrorStream() << "Model type not supported: \"" << name << "\"\n";
311 bool g_realised = false;
313 // name may be absolute or relative
314 const char* rootPath( const char* name ){
315 return GlobalFileSystem().findRoot(
316 path_is_absolute( name )
318 : GlobalFileSystem().findFile( name )
323 struct ModelResource : public Resource
325 NodeSmartReference m_model;
326 const CopiedString m_originalName;
330 ModelLoader* m_loader;
331 ModuleObservers m_observers;
332 std::time_t m_modified;
333 std::size_t m_unrealised;
335 ModelResource( const CopiedString& name ) :
336 m_model( g_nullModel ),
337 m_originalName( name ),
338 m_type( path_get_extension( name.c_str() ) ),
342 m_loader = ModelLoader_forType( m_type.c_str() );
352 ASSERT_MESSAGE( !realised(), "ModelResource::~ModelResource: resource reference still realised: " << makeQuoted( m_name.c_str() ) );
355 ModelResource( const ModelResource& );
357 ModelResource& operator=( const ModelResource& );
359 void setModel( const NodeSmartReference& model ){
363 m_model = g_nullModel;
367 if ( g_modelCache_enabled ) {
369 ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() );
370 if ( i == g_modelCache.end() ) {
371 i = ModelCache_insert(
374 Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() )
378 setModel( ( *i ).value );
382 setModel( Model_load( m_loader, m_path.c_str(), m_name.c_str(), m_type.c_str() ) );
393 ASSERT_MESSAGE( realised(), "resource not realised" );
394 if ( m_model == g_nullModel ) {
398 return m_model != g_nullModel;
402 const char* moduleName = findModuleName( GetFileTypeRegistry(), MapFormat::Name(), m_type.c_str() );
403 if ( string_not_empty( moduleName ) ) {
404 const MapFormat* format = ReferenceAPI_getMapModules().findModule( moduleName );
405 if ( format != 0 && MapResource_save( *format, m_model.get(), m_path.c_str(), m_name.c_str() ) ) {
415 ModelCache_flush( m_path.c_str(), m_name.c_str() );
418 scene::Node* getNode(){
419 //if(m_model != g_nullModel)
421 return m_model.get_pointer();
425 void setNode( scene::Node* node ){
426 ModelCache::iterator i = ModelCache_find( m_path.c_str(), m_name.c_str() );
427 if ( i != g_modelCache.end() ) {
428 ( *i ).value = NodeSmartReference( *node );
430 setModel( NodeSmartReference( *node ) );
434 void attach( ModuleObserver& observer ){
438 m_observers.attach( observer );
440 void detach( ModuleObserver& observer ){
442 observer.unrealise();
444 m_observers.detach( observer );
447 return m_unrealised == 0;
450 ASSERT_MESSAGE( m_unrealised != 0, "ModelResource::realise: already realised" );
451 if ( --m_unrealised == 0 ) {
452 m_path = rootPath( m_originalName.c_str() );
453 m_name = path_make_relative( m_originalName.c_str(), m_path.c_str() );
455 //globalOutputStream() << "ModelResource::realise: " << m_path.c_str() << m_name.c_str() << "\n";
457 m_observers.realise();
461 if ( ++m_unrealised == 1 ) {
462 m_observers.unrealise();
464 //globalOutputStream() << "ModelResource::unrealise: " << m_path.c_str() << m_name.c_str() << "\n";
469 return Node_getMapFile( m_model ) != 0;
472 MapFile* map = Node_getMapFile( m_model );
474 map->setChangedCallback( makeCallbackF(MapChanged) );
477 std::time_t modified() const {
478 StringOutputStream fullpath( 256 );
479 fullpath << m_path.c_str() << m_name.c_str();
480 return file_modified( fullpath.c_str() );
483 m_modified = modified();
484 MapFile* map = Node_getMapFile( m_model );
489 bool mapSaved() const {
490 MapFile* map = Node_getMapFile( m_model );
492 return m_modified == modified() && map->saved();
496 bool isModified() const {
497 return ( ( !string_empty( m_path.c_str() ) // had or has an absolute path
498 && m_modified != modified() ) // AND disk timestamp changed
499 || !path_equal( rootPath( m_originalName.c_str() ), m_path.c_str() ) ); // OR absolute vfs-root changed
502 if ( isModified() ) {
510 class HashtableReferenceCache : public ReferenceCache, public ModuleObserver
512 typedef HashedCache<CopiedString, ModelResource, PathHash, PathEqual> ModelReferences;
513 ModelReferences m_references;
514 std::size_t m_unrealised;
516 class ModelReferencesSnapshot
518 ModelReferences& m_references;
519 typedef std::list<ModelReferences::iterator> Iterators;
520 Iterators m_iterators;
522 typedef Iterators::iterator iterator;
523 ModelReferencesSnapshot( ModelReferences& references ) : m_references( references ){
524 for ( ModelReferences::iterator i = m_references.begin(); i != m_references.end(); ++i )
526 m_references.capture( i );
527 m_iterators.push_back( i );
530 ~ModelReferencesSnapshot(){
531 for ( Iterators::iterator i = m_iterators.begin(); i != m_iterators.end(); ++i )
533 m_references.release( *i );
537 return m_iterators.begin();
540 return m_iterators.end();
546 typedef ModelReferences::iterator iterator;
548 HashtableReferenceCache() : m_unrealised( 1 ){
552 return m_references.begin();
555 return m_references.end();
559 m_references.clear();
562 Resource* capture( const char* path ){
563 //globalOutputStream() << "capture: \"" << path << "\"\n";
564 return m_references.capture( CopiedString( path ) ).get();
566 void release( const char* path ){
567 m_references.release( CopiedString( path ) );
568 //globalOutputStream() << "release: \"" << path << "\"\n";
571 void setEntityCreator( EntityCreator& entityCreator ){
572 g_entityCreator = &entityCreator;
575 bool realised() const {
576 return m_unrealised == 0;
579 ASSERT_MESSAGE( m_unrealised != 0, "HashtableReferenceCache::realise: already realised" );
580 if ( --m_unrealised == 0 ) {
584 ModelReferencesSnapshot snapshot( m_references );
585 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
587 ModelReferences::value_type& value = *( *i );
588 if ( value.value.count() != 1 ) {
589 value.value.get()->realise();
596 if ( ++m_unrealised == 1 ) {
600 ModelReferencesSnapshot snapshot( m_references );
601 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
603 ModelReferences::value_type& value = *( *i );
604 if ( value.value.count() != 1 ) {
605 value.value.get()->unrealise();
614 ModelReferencesSnapshot snapshot( m_references );
615 for ( ModelReferencesSnapshot::iterator i = snapshot.begin(); i != snapshot.end(); ++i )
617 ModelResource* resource = ( *( *i ) ).value.get();
618 if ( !resource->isMap() ) {
627 HashtableReferenceCache g_referenceCache;
631 class ResourceVisitor
634 virtual void visit( const char* name, const char* path, const
638 void SaveReferences(){
639 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Saving Map" );
640 for ( HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i )
642 ( *i ).value->save();
647 bool References_Saved(){
648 for ( HashtableReferenceCache::iterator i = g_referenceCache.begin(); i != g_referenceCache.end(); ++i )
650 scene::Node* node = ( *i ).value->getNode();
652 MapFile* map = Node_getMapFile( *node );
653 if ( map != 0 && !map->saved() ) {
661 void RefreshReferences(){
662 ScopeDisableScreenUpdates disableScreenUpdates( "Processing...", "Refreshing Models" );
663 g_referenceCache.refresh();
667 void FlushReferences(){
670 g_referenceCache.clear();
673 ReferenceCache& GetReferenceCache(){
674 return g_referenceCache;
678 #include "modulesystem/modulesmap.h"
679 #include "modulesystem/singletonmodule.h"
680 #include "modulesystem/moduleregistry.h"
682 class ReferenceDependencies :
683 public GlobalRadiantModuleRef,
684 public GlobalFileSystemModuleRef,
685 public GlobalFiletypesModuleRef
687 ModelModulesRef m_model_modules;
688 MapModulesRef m_map_modules;
690 ReferenceDependencies() :
691 m_model_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "modeltypes" ) ),
692 m_map_modules( GlobalRadiant().getRequiredGameDescriptionKeyValue( "maptypes" ) )
695 ModelModules& getModelModules(){
696 return m_model_modules.get();
698 MapModules& getMapModules(){
699 return m_map_modules.get();
703 class ReferenceAPI : public TypeSystemRef
705 ReferenceCache* m_reference;
707 typedef ReferenceCache Type;
708 STRING_CONSTANT( Name, "*" );
711 g_nullModel = NewNullModel();
713 GlobalFileSystem().attach( g_referenceCache );
715 m_reference = &GetReferenceCache();
718 GlobalFileSystem().detach( g_referenceCache );
720 g_nullModel = g_nullNode;
722 ReferenceCache* getTable(){
727 typedef SingletonModule<ReferenceAPI, ReferenceDependencies> ReferenceModule;
728 typedef Static<ReferenceModule> StaticReferenceModule;
729 StaticRegisterModule staticRegisterReference( StaticReferenceModule::instance() );
731 ModelModules& ReferenceAPI_getModelModules(){
732 return StaticReferenceModule::instance().getDependencies().getModelModules();
734 MapModules& ReferenceAPI_getMapModules(){
735 return StaticReferenceModule::instance().getDependencies().getMapModules( );