Advice/Hate that templated resource cache class of mine...

Started by
4 comments, last by King Mir 11 years, 8 months ago
So, after 2 years trying to make this class...kidding, but it really hurt my mind, first time trying to make good use of templates (instead of "hey, look, Im using templates ;D")..

I get really lost on how I could achieve this, and got into stuff like variadic templates and inplace factories, but I couldnt manage to do with these..so my current one ended needing 3 classes:

the resourceCache, who stores the resources, fully templated, no overloads or specialization;
the resourceDescriptor, a templated class completely empty, i need to provide a specialization for each resource, the point is make the cache class above not need overloads or specialization..
the resourceCreator, a class with a bunch of static Create overloaded functions, witch takes descriptors as params...

Resuming, I remove some burden of the cache class by creating 2 more classes.

The problem was that the resources (dx ID3D11... resources/states/layouts) need a different call on ID3D11Device, with different params, and that screw me from the very beginning..

I really dont know if I did a big shit here (i just finished it), like, maybe was better giving up the template and create a cache class for each resource?

Heres the code, dont mind the simpleness, I wanted it to be really straightforward:


//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
/*
created: 2012/07/15
created: 15:7:2012 23:09
filename: DXResourceCache.h
file base: DXResourceCache
file ext: h
author: Giuliano Suminsky (a.k.a. Icebone1000)

purpose: Creating and storing dx resources made centralized.
© Giuliano Suminsky (a.k.a. Icebone1000) , rights reserved.
*/
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
#pragma once
#pragma comment( lib, "D3D11.lib")
#pragma comment( lib, "D3DX11.lib")
// dx includes
#include <D3Dcommon.h>
#include <D3D11.h>
#include <D3DX11core.h> //including because of D3DERR_INVALIDCALL
// stl includes
#include <exception>
// my includes
#include "../../../myMACROS.h"

// Note that dx SDK doesnt consider states and layouts as resources...just a note ;D

namespace dx{

template< class T >
struct DX_Resource_Descriptor{

};
template<>
struct DX_Resource_Descriptor<ID3D11InputLayout>{
D3D11_INPUT_ELEMENT_DESC * inputElementsDesc_p;
UINT nElements;
void* pShaderSig_p;
SIZE_T iSizeShaderSig_p;
};
//TODO:
//specialization for each resource
//------------------------------------------------------------------------
// A fixed size resource cache class.
//------------------------------------------------------------------------
template< class T, int fixedSize >
class DX_Resource_Cache{
private:
ID3D11Device * m_pDeviceRef; // the one that actually can create stuff
UINT m_iCurrentIndex; // next slot to be allocated, also the ID of the resources
//UINT m_nFreedSlots; // how many freed slot there are?
T* m_cache[fixedSize]; // the container per se
public:

//------------------------------------------------------------------------
// Receives a descriptor for the current template type.
//------------------------------------------------------------------------
UINT CreateResource( T *& pResource_p, DX_Resource_Descriptor<T> resourceDesc_p )
{
if( m_iCurrentIndex > fixedSize)
{
throw std::exception("resource cache limit achieved");
}
pResource_p = m_cache[m_iCurrentIndex] = DX_ResourceCreator.Create(m_pDeviceRef, resourceDesc_p);
++m_iCurrentIndex; //points to next element
return (m_iCurrentIndex-1);
}
//------------------------------------------------------------------------
public:
//------------------------------------------------------------------------
// Main function to return stored resources.
//------------------------------------------------------------------------
T* Acquire( const UINT id_p ) const
{
if( id_p > fixedSize )
{
throw std::exception("cache overflow, wtf is that id?");
}
//assert(m_slotsInfo[id_p].useCount != 0);
//++m_slotsInfo[id_p].useCount;
//m_slotsInfo[id_p].desc.Create(m_pDeviceRef);
return m_cache[id_p];
}
//------------------------------------------------------------------------
public:
//------------------------------------------------------------------------
// Releases all non null pointers in the cache.
//------------------------------------------------------------------------
virtual ~DX_Resource_Cache()
{
for( UINT it = 0; it < fixedSize; it++ )
{
donne( m_cache[it]);
}
}
//------------------------------------------------------------------------
};
//------------------------------------------------------------------------

//------------------------------------------------------------------------
// Simple class to provide overloads for creating resources with the same call.
//------------------------------------------------------------------------
class DX_ResourceCreator{
static ID3D11InputLayout* Create( ID3D11Device *pDeviceRef_p, DX_Resource_Descriptor<ID3D11InputLayout> resourceDesc_p ){
ID3D11InputLayout *pInputLayout;
pDeviceRef_p->CreateInputLayout( resourceDesc_p.inputElementsDesc_p, resourceDesc_p.nElements, resourceDesc_p.pShaderSig_p, resourceDesc_p.iSizeShaderSig_p, &pInputLayout);
//TODO:
//error handling

return pInputLayout;
}
//TODO:
//overloads for each resource here
};
//------------------------------------------------------------------------
}
Advertisement
DirectX is not a good canidate for Templates. Unless its something mathmatical like vectors or matrix addition.
My question is: what is your definition of resource? Typically a resource is something that you could load or unload like a texure or sound.
I been looking at your code for a while and I got confused. So I started tinkering with your code and dropped Templates all together.
[source lang="cpp"]// Note that dx SDK doesnt consider states and layouts as resources...just a note ;D
// I agree that states and layouts are not really resources ;)

namespace dx
{

struct DX_SHADER_ITEM
{
unsigned int ID; //ID for Shader
D3D11_INPUT_ELEMENT_DESC* pInputDesc; //Decription of Shader Inputs
SIZE_T nInput; //Number of Inputs
void* pByteCode; //Compiled Shader Using Input Signature
SIZE_T nByteCodeSize; //Size of Shader
ID3D10InputLayout* pInputLayout //DX Layout Interface
};


class DX_ShaderManager
{
public:
DX_ShaderManager( ID3D11Device* pDevice );
~DX_ShaderManager(void);

unsigned int Create(D3D11_INPUT_ELEMENT_DESC* pInputDesc, SIZE_T nInput, void* pByteCode, SIZE_T nByteCodeSize )
{
DX_SHADER_ITEM* pShaderItem = new(DX_SHADER);

pDevice->CreateInputLayout( pShaderItem.pInputDesc,
pShaderItem.nInput,
pShaderItem.pByteCode,
pShaderItem.nByteCodeSize,
&pShaderItem.pInputLayout);
//TODO:
//error handling

//Create Storage Mechanism for DX_SHADER_ITEM

return pShaderItem->ID; //If passed error handling
}

bool SetShader(unsigned int ID)
{
// Mechanism to get DX_SHADER_ITEM
pShaderItem = getID(ID);

void IASetInputLayout(pShaderItem.pInputLayout);
}

DX_SHADER_ITEM* getID(unsigned int ID)
{
return DX_SHADER_ITEM*;
}

private:
m_pDevice;
};

}//End namespace dx[/source]

IDK about managing shaders like this.
In general I think if you need a specialization for every type then it's not a good template design, as you will end up with a monolithic factory class that needs to know the details of how to create each resource type in your application.

A better design, in my opinion, would be to create wrapper classes for each of your DX resources and then create them via "new" or a create method, or use a consistent interface and have your DX_ResourceCreator create them with new/create with a non-specialized template method.

Example:

namespace dx
{
class InputLayout
{
public:
struct Descriptor
{
D3D11_INPUT_ELEMENT_DESC* inputElementsDesc_p;
UINT nElements;
void* pShaderSig_p;
SIZE_T iSizeShaderSig_p;
};
public:
InputLayout( ID3D11Device *pDeviceRef_p, Descriptor& desc )
{
pDeviceRef_p->CreateInputLayout( desc.inputElementsDesc_p, desc.nElements, desc.pShaderSig_p, desc.iSizeShaderSig_p, &_layout);
}
ID3DInputLayout* get() { return _layout; }
private:
ID3DInputLayout* _layout;
};


template< class T, int fixedSize >
class DX_Resource_Cache
{
private:
ID3D11Device * m_pDeviceRef; // the one that actually can create stuff
UINT m_iCurrentIndex; // next slot to be allocated, also the ID of the resources
T* m_cache[fixedSize]; // the container per se

public:
//------------------------------------------------------------------------
// Receives a descriptor for the current template type.
//------------------------------------------------------------------------
UINT CreateResource( T** pResource_p, T::Descriptor& resourceDesc )
{
if( m_iCurrentIndex > fixedSize)
{
throw std::exception("resource cache limit achieved");
}
*pResource_p = new T(m_pDeviceRef, resourceDesc );
++m_iCurrentIndex; //points to next element
return (m_iCurrentIndex-1);
}

//etc...
};

}




Or if you really feel you need a factory for whatever reason:


template< class T, int fixedSize >
class DX_Resource_Cache
{
private:
ID3D11Device * m_pDeviceRef; // the one that actually can create stuff
UINT m_iCurrentIndex; // next slot to be allocated, also the ID of the resources
T* m_cache[fixedSize]; // the container per se
public:
//------------------------------------------------------------------------
// Receives a descriptor for the current template type.
//------------------------------------------------------------------------
UINT CreateResource( T** pResource_p, T::Descriptor& resourceDesc )
{
if( m_iCurrentIndex > fixedSize)
{
throw std::exception("resource cache limit achieved");
}
*pResource_p = DX_ResourceCreator::Create<T>(m_pDeviceRef, resourceDesc );
++m_iCurrentIndex; //points to next element
return (m_iCurrentIndex-1);
}

};
struct DX_ResourceCreator
{
template<typename T>
static T* Create( ID3D11Device *pDeviceRef_p, T::Descriptor& resourceDesc_p )
{
return new T(pDeviceRef_p, resourceDesc_p);
}
};


Then you can specialize only if you need to do something special for specific resource types.

These would then become good candidates for variadic templates as well, eliminating the need for the nested Descriptor type.

Personally I find that it's almost always a good idea to create wrappers for the DX objects in all but the simplest applications anyway. Using DX can be kinda messy, so you can make your code cleaner, more clear, and easier to maintain by moving functionality into the wrapper classes.
Thanks for the inputs..I really am just lost on how to do it, I felt I need a centralized way to create and reuse the stuff.
If each class creates its own stuff, at some time they will start create stuff that was already created..

But now I also dont know how would those classes make good use of the resource caches. I was thinking if I should make the classes store the ID for the resources on the cache, or make it transparent asking for the resource with a descriptor and then comparing descriptors traversing the cache..

Before trying that more elaborated thing I had a sprite class that did everything, but each time I needed a different thing I had to create another sprite object witch different parameters, and it would recreate all main stuff again, even recompile the shaders, it worked, but it sucked..

I always try to make stuff simple, but I dont think its possible anymore
I'm not 100% sure what you're looking for. Do you mean that if you create a resource that uses the same descriptor as an existing resource then you want to return a reference to the existing resource rather than create a new one?

If so then I might suggest using a std::map of the resources with a hash of the descriptor as the key. You'll probably want to use some kind of reference-counted wrapper for your resources to make it easier to track when the resources are no longer used anywhere.
"Some kind of reference counted wrapper" could be a shared_ptr with a custom deleter.

This topic is closed to new replies.

Advertisement