1 /**
2  * Defines the static Assets class, a static class which manages all textures, meshes, etc...
3  */
4 module components.assets;
5 import components;
6 import utility.filepath, utility.config;
7 
8 import yaml;
9 import derelict.freeimage.freeimage;
10 
11 final abstract class Assets
12 {
13 public static:
14 	/**
15 	 * Get the asset with the given type and name.
16 	 */
17 	final T get( T )( string name ) if( is( T == Mesh ) || is( T == Texture ) || is( T == Material ) )
18 	{
19 		static if( is( T == Mesh ) )
20 		{
21 			return meshes[ name ];
22 		}
23 		else static if( is( T == Texture ) )
24 		{
25 			return textures[ name ];
26 		}
27 		else static if( is( T == Material ) )
28 		{
29 			return materials[ name ];
30 		}
31 		else static assert( false, "Material of type " ~ T.stringof ~ " is not maintained by Assets." );
32 	}
33 
34 	/**
35 	 * Load all assets in the FilePath.ResourceHome folder.
36 	 */
37 	final void initialize()
38 	{
39 		DerelictFI.load();
40 
41 		foreach( file; FilePath.scanDirectory( FilePath.Resources.Meshes ) )
42 		{
43 			meshes[ file.baseFileName ] = new Mesh( file.fullPath );
44 		}
45 
46 		foreach( file; FilePath.scanDirectory( FilePath.Resources.Textures ) )
47 		{
48 			textures[ file.baseFileName ] = new Texture( file.fullPath );
49 		}
50 
51 		Config.processYamlDirectory(
52 			FilePath.Resources.Materials,
53 			( Node object )
54 			{
55 				auto name = object[ "Name" ].as!string;
56 
57 				materials[ name ] = Material.createFromYaml( object );
58 			} );
59 
60 		meshes.rehash();
61 		textures.rehash();
62 		materials.rehash();
63 	}
64 
65 	/**
66 	 * Unload and destroy all stored assets.
67 	 */
68 	final void shutdown()
69 	{
70 		foreach_reverse( index; 0 .. meshes.length )
71 		{
72 			auto name = meshes.keys[ index ];
73 			meshes[ name ].shutdown();
74 			meshes.remove( name );
75 		}
76 		foreach_reverse( index; 0 .. textures.length )
77 		{
78 			auto name = textures.keys[ index ];
79 			textures[ name ].shutdown();
80 			textures.remove( name );
81 		}
82 		foreach_reverse( index; 0 .. materials.length )
83 		{
84 			auto name = materials.keys[ index ];
85 			materials[ name ].shutdown();
86 			materials.remove( name );
87 		}
88 	}
89 
90 private:
91 	Mesh[string] meshes;
92 	Texture[string] textures;
93 	Material[string] materials;
94 }