1 /**
2  * This is the Interface for component providers. Component providers are used to supply components 
3  * for states within an EntityStateMachine. Ash includes three standard component providers,
4  * ComponentTypeProvider, ComponentInstanceProvider and ComponentSingletonProvider. Developers
5  * may wish to create more.
6  */
7 module ashd.fsm.IComponentProvider;
8 
9 import std.conv: to;
10 
11 public interface IComponentProvider
12 {
13     /**
14      * Used to request a component from the provider.
15      * 
16      * @return A component for use in the state that the entity is entering
17      */
18     // This is a final method (templates can't be virtual)
19     T getComponent(T)()
20     {
21         auto i = cast(T)createDynamicInstance( typeid(T) );
22         if ( i is null ) 
23             throw new Exception( "Unable to create " ~ T.stringof );
24         return i;
25     }
26 
27     protected Object createDynamicInstance( ClassInfo type_a );
28   
29     final Object getComponent( ClassInfo class_a )
30     {
31         Object i = createDynamicInstance( class_a );
32         if ( i is null ) 
33             throw new Exception( "Unable to create component " ~ to!string(class_a) );
34         return i;
35     }
36 
37 
38     /**
39      * Returns an identifier that is used to determine whether two component providers will
40      * return the equivalent components.
41      * 
42      * <p>If an entity is changing state and the state it is leaving and the state is is 
43      * entering have components of the same type, then the identifiers of the component
44      * provders are compared. If the two identifiers are the same then the component
45      * is not removed. If they are different, the component from the old state is removed
46      * and a component for the new state is added.</p>
47      * 
48      * @return An object
49      */
50     hash_t identifier();
51 
52     final public hash_t toHash( string str_a )
53     {
54         try 
55         {
56             return to!long( str_a );
57         } 
58         catch(Exception e) 
59         {
60             hash_t hash; foreach (char c; str_a ) hash = (hash * 9) + c;
61             return hash;
62         }
63     }
64 
65 
66 }