Jump to content

  • Log In with Google      Sign In   
  • Create Account

Game 'Resource Manager' Design


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
8 replies to this topic

#1 KeyGames   Members   -  Reputation: 112

Like
0Likes
Like

Posted 12 September 2011 - 06:17 PM

Hello! I'm currently working on a game project with SFML and C++ and I'm writing my games resource manager, if you don't know what that is it's basically a class to take care of storing game assets that can be reused without reloading, and takes care of cleaning them up (RAII).

My design plan is to create a main template interface (or base) class called ResourceManager, the template parameter being the type of resource you want it to manage. It would have a function Get, which would take a std::string argument filename, and which would load the resource if not loaded, and then return it, or just return it if it's already loaded. It would have a typedef T* Resource (T being the template parameter.) It would have a std::map<std::string, Resource> which would store the resources and the key being the filename. The destructor would take care of the resources of cleaning up the resources (SFML's resource types use RAII already anyway, so this is unnecessary for some of them). Lastly it would have a pure virtual function called LoadResource(const std::string& filename);

Next I would create classes like ImageManager, SoundManager, MusicManager, etc. Those would inherit ResourceManager<ResourceType> (Resource type being sf::Image for SFML Images, sf::Sound for SFML sounds, etc.) and Singleton<ManagerClassName> (ManagerClassName being ImageManager for ImageManager, etc.). These classes would then implement the virtual LoadResource() function and load the resource for it's specific resource type, then return the resource for the Get function.

Accessing a resource would be simple, for example I could assign it to ImageManager::Resource logo_image = ImageManager::GetInstance().Get("Data/Textures/Logo.jpg"), which could then be applied to an sf::Sprite via sprite.SetImage(*logo_image). Or I could assign and play music by going ImageManager::GetInstance().Get("Data/Music/Music.ogg")->Play();. Simple as that!
(Resource again being the typedef T*)

Sponsor:

#2 speciesUnknown   Members   -  Reputation: 527

Like
0Likes
Like

Posted 12 September 2011 - 06:42 PM

Hello! I'm currently working on a game project with SFML and C++ and I'm writing my games resource manager, if you don't know what that is it's basically a class to take care of storing game assets that can be reused without reloading, and takes care of cleaning them up (RAII).

My design plan is to create a main template interface (or base) class called ResourceManager, the template parameter being the type of resource you want it to manage. It would have a function Get, which would take a std::string argument filename, and which would load the resource if not loaded, and then return it, or just return it if it's already loaded. It would have a typedef T* Resource (T being the template parameter.) It would have a std::map<std::string, Resource> which would store the resources and the key being the filename. The destructor would take care of the resources of cleaning up the resources (SFML's resource types use RAII already anyway, so this is unnecessary for some of them). Lastly it would have a pure virtual function called LoadResource(const std::string& filename);

Next I would create classes like ImageManager, SoundManager, MusicManager, etc. Those would inherit ResourceManager<ResourceType> (Resource type being sf::Image for SFML Images, sf::Sound for SFML sounds, etc.) and Singleton<ManagerClassName> (ManagerClassName being ImageManager for ImageManager, etc.). These classes would then implement the virtual LoadResource() function and load the resource for it's specific resource type, then return the resource for the Get function.

Accessing a resource would be simple, for example I could assign it to ImageManager::Resource logo_image = ImageManager::GetInstance().Get("Data/Textures/Logo.jpg"), which could then be applied to an sf::Sprite via sprite.SetImage(*logo_image). Or I could assign and play music by going ImageManager::GetInstance().Get("Data/Music/Music.ogg")->Play();. Simple as that!
(Resource again being the typedef T*)

Sorry if any of this is unclear, I'm no prize winning author and I will clarify it if needed (just ask me)! What I'm curious is if there's any major design flaws in this, or anything I shouldn't be doing that I am planning to do. It worked on paper, and I don't want to create an memory leaks with this. Before coding this I want to make sure it will work and that I don't mess up badly or anything like that. Thanks!


I've done this many many times, and over the years have settled on a simple solution. The basic principle is that everything, rather than using ResourceType *, uses a sikngle layer wrapper, a ResourceHandle. I don't have my c++ code to hand, but here is my c# implementation,

	public class ResourceHolder <Type>
	{
		protected string name;
		protected Type item;
		protected bool linked;

		public ResourceHolder(string name, Type t)
		{
			this.name = name;
			this.item = t;
			this.linked = true;
		}

		public virtual Type Item { get { return this.item;} set { this.item = value; this.linked = true; } }

		public virtual bool Linked { get { return this.linked; } }

	}

     public class ResourceTable<Type>
	{
		public ResourceTable(string prefix, ContentManager content)
		{
			this.prefix = prefix;
			this.content = content;
		}

		public virtual void linkReference(ref ResourceReference<Type> reference)
		{
			reference.link(this.getResource(reference.Name, true));
		}

		public virtual Type loadResource(string name)
		{
			int pos = items.Count;

			Type r = content.Load<Type>(prefix + "/" + name);
			ResourceHolder<Type> handle = new ResourceHolder<Type>(name, r);

			items[name] = new ResourceHolder<Type>(name, r);
			return handle.Item;
		}

		public virtual Type getResource(string name, bool loadIfNotLoaded)
		{
			ResourceHolder<Type> item;
			bool exists = items.TryGetValue(name, out item);

			if (exists)
			{
				return item.Item;
			}
			else if (loadIfNotLoaded)
			{
				return loadResource(name);
			}
			else
			{
				throw new Exception("No resource could be loaded with the name" + name);
			}
		}

		public virtual Type getResource(string name) 
		{ 
			return getResource(name, true); 
		}

		protected Dictionary<string, ResourceHolder<Type>> items= new Dictionary<string, ResourceHolder<Type>>();

		protected string prefix;
		protected ContentManager content;

	}


The main difference in c++ is that you would use std::map<string, ResourceHolder<Type>> rather than a dictionary, but otherwise the code is almost the same.

the idea is that resources can be loaded at runtime if they were not pre-cached (during development, you can't always load resources during initialization, although it is better to avoid stuttering later on). Now, you are able to decouple ordinary objects which might need access to a resource from your resource manager - the linking of objects with their resources can take place at any time, e.g. during the first time that object is rendered. If a resource has been precached, the step to link an object with its resource is trivial.

Beware of very complicated implementations, especially implementations which make assumptions about usage, because these will bring you more pain than pleasure. A simple and reliable solution, for most games, is often the best considering that resource management is such a core principle.
Don't thank me, thank the moon's gravitation pull! Post in My Journal and help me to not procrastinate!

#3 KeyGames   Members   -  Reputation: 112

Like
0Likes
Like

Posted 12 September 2011 - 07:08 PM

So basically it's like what I was doing with a wrapper layer around the resource type? Sorry I'm a little confused, I'm not sure if there's anything I missed there. Would I still create other classes like ImageManager, etc.?

#4 speciesUnknown   Members   -  Reputation: 527

Like
0Likes
Like

Posted 12 September 2011 - 07:17 PM

So basically it's like what I was doing with a wrapper layer around the resource type? Sorry I'm a little confused, I'm not sure if there's anything I missed there. Would I still create other classes like ImageManager, etc.?


Every type of resource goes in a ResourceHolder; you can also have a series of tables. What you don't do is have an abstract system of resource managers, because every resource loads differently. Some load themselves, and others are loaded from within some kind of table. SFML has a series of tables already implemented for some of its resource types. Most of the time, you will be able to store loaded resources in a table, like the one in my code sample, (i don't call everything a manager because that is just a lazy naming convention). You will have to extend the resource table class to cater for the differences between individual resource types.
Don't thank me, thank the moon's gravitation pull! Post in My Journal and help me to not procrastinate!

#5 KeyGames   Members   -  Reputation: 112

Like
0Likes
Like

Posted 12 September 2011 - 07:48 PM


So basically it's like what I was doing with a wrapper layer around the resource type? Sorry I'm a little confused, I'm not sure if there's anything I missed there. Would I still create other classes like ImageManager, etc.?


Every type of resource goes in a ResourceHolder; you can also have a series of tables. What you don't do is have an abstract system of resource managers, because every resource loads differently. Some load themselves, and others are loaded from within some kind of table. SFML has a series of tables already implemented for some of its resource types. Most of the time, you will be able to store loaded resources in a table, like the one in my code sample, (i don't call everything a manager because that is just a lazy naming convention). You will have to extend the resource table class to cater for the differences between individual resource types.


Sorry, but I'm still slightly confused. I understand that the table stores all the resources and resourceholder wraps around a specific resource, but I'm not sure how you would Load each resource since they have different methods for loading.

#6 rip-off   Moderators   -  Reputation: 8223

Like
0Likes
Like

Posted 13 September 2011 - 07:59 AM

I agree with SpeciesUnknown, you don't need inheritance here. For C++, I'd recommend using something like std::shared_ptr or boost::shared_ptr rather than raw pointers.

I generally go with having a ResourceLocator<>, ResourceLoader<> and a ResourceCache<> as template classes. There is no universal Resource interface, a Resource is really any immutable class. The ResourceLocator worries about getting the bytes that make up the resource into memory in a form that can be consumed. The ResourceLoader uses a ResourceLocator to obtain the bytes, and whatever in-memory API function exists to create a resource from these bytes. The ResourceCache is concerned with avoiding loading a Resource multiple times, but uses a ResourceLoader to generate a resource.

As a result of this separation of concerns, each class is relatively small and focused.

I don't use singletons for these. In my simpler games, I might just use global pointers that point at auto-allocated objects in main(). In more complex games, these objects are often bundled into some kind of "context" structure which is passed through whatever layers until it gets to where objects are loaded.

More complex games often use chained resource caching. Each game "level" has its own cache, which is purged. To avoid re-loading common resources between levels, the previous level's cache is temporarily set as a "parent" to the next level's cache (each cache will look locally, then to its parent, before creating a new resource). Once loading is complete, I undo the parental relationship and drop the old cache, which unloads any unused resources.

#7 KeyGames   Members   -  Reputation: 112

Like
0Likes
Like

Posted 13 September 2011 - 10:11 AM

I agree with SpeciesUnknown, you don't need inheritance here. For C++, I'd recommend using something like std::shared_ptr or boost::shared_ptr rather than raw pointers.

I generally go with having a ResourceLocator<>, ResourceLoader<> and a ResourceCache<> as template classes. There is no universal Resource interface, a Resource is really any immutable class. The ResourceLocator worries about getting the bytes that make up the resource into memory in a form that can be consumed. The ResourceLoader uses a ResourceLocator to obtain the bytes, and whatever in-memory API function exists to create a resource from these bytes. The ResourceCache is concerned with avoiding loading a Resource multiple times, but uses a ResourceLoader to generate a resource.

As a result of this separation of concerns, each class is relatively small and focused.

I don't use singletons for these. In my simpler games, I might just use global pointers that point at auto-allocated objects in main(). In more complex games, these objects are often bundled into some kind of "context" structure which is passed through whatever layers until it gets to where objects are loaded.

More complex games often use chained resource caching. Each game "level" has its own cache, which is purged. To avoid re-loading common resources between levels, the previous level's cache is temporarily set as a "parent" to the next level's cache (each cache will look locally, then to its parent, before creating a new resource). Once loading is complete, I undo the parental relationship and drop the old cache, which unloads any unused resources.


SFML's resource classes already take care of loading the resource into memory, what I want is something to take care of all of the resources after they are loaded that can be globally accessed. Would this eliminate the need for a resource loader and locator?

#8 rip-off   Moderators   -  Reputation: 8223

Like
0Likes
Like

Posted 13 September 2011 - 10:38 AM

Sure. I'm just describing how I have done this in the past. The point I was trying to illustrate is how the design features no inheritance.

Global access is a separate concern. The ResourceCache shouldn't need to care about this.

#9 Scourage   Members   -  Reputation: 740

Like
2Likes
Like

Posted 13 September 2011 - 07:09 PM

They way I designed my resource manager is similar to rip-off and SpeciesUnknown have done. I have a ResourceDescriptor, Resource, and ResourceManager. The ResourceManager maintains a list of resources that have already been loaded. When you want something, create a ResourceDescriptor and use it to ask theResourceManager for the resource. If the resource doesn't exist yet, the ResourceManager uses the ResourceDescriptor to do the actual load of the resource. It's a kind of double dispatch pattern to get the resource specific loading behavior.

The nice thing about this is that the ResourceManager doesn't need to know how to load the specific types of resources since it's the resource descriptor that handles that. The resource manager probably should have some memory tracking functions and priority system, but I haven't needed them yet.


Below is how I implemented my ResourceManager, ResourceDescriptors and a texture resource descriptor in C#.


Cheers,

Bob



using System;
using System.Collections.Generic;

namespace SimEngine
{
   public static class ResourceManager
   {
      static Dictionary<String, IResource> myResources;

      static ResourceManager()
      {
 		myResources = new Dictionary<String, IResource>();
      }

      public static bool init(Initializer init)
      {
 		return true;
      }

      public static IResource getResource(ResourceDescriptor desc)
      {
 		IResource res;
 		if (myResources.TryGetValue(desc.filename, out res))
 		{
            return res;
 		}

 		//need to try and load the IResource here
 		res = load(desc);

 		return res;
      }

      static IResource load(ResourceDescriptor desc)
      {
 		IResource res;

 		if (System.IO.File.Exists(desc.filename) == false)
 		{
            Warn.print("Cannot find file {0}", desc.filename);
            return null;
 		}

 		res = desc.create();

 		if (res != null)
 		{
            myResources[desc.filename] = res;
 		}

 		return res;
      }

   }
}



using System;

namespace SimEngine
{
   public interface IResource
   {
   }

   public abstract class ResourceDescriptor
   {
      public ResourceDescriptor()
      {
      }

      public ResourceDescriptor(String name)
      {
 		filename = name;
      }

      public string filename { get; set; }

      public abstract IResource create();
   }
}



   public class TextureDescriptor : ResourceDescriptor
   {
      bool myFlip=false;

      public TextureDescriptor(string name) : this(name, false)  { }
      public TextureDescriptor(string name, bool flip)
 		: base(name)
      {
 		myFlip = flip;
      }

      public override IResource create()
      {
 		Texture t = new Texture(filename, myFlip);
 		if (t.isValid == false)
 		{
            return null;
 		}
 		return t;
      }
   }



Halfway down the trail to Hell...




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS