// ----------------------------------------------------------------------------------------------
// this function must *always* return a valid Resource, even for 'missing' resources.
Resource* ResourceManager::LoadAsync(const WCHAR* filename, Resource* def)
{
    AutoSync sync(&m_criticalSection); // CRITICAL SECTION  - ENTIRE FUNCTION
    Resource * res = NULL;
    // check cache, use if already there.
    if(NULL == res)
    {
        auto it = m_loaded.find(filename);
        if(it != m_loaded.end() ) res = it->second;
    }

    // check pending, use if already there.
    if(NULL == res)
    {
        auto it = m_pending.find(filename);
        if(it != m_pending.end() ) res = it->second;
    }

    // create new info and add it to pending list to be loaded.
    if(NULL == res)
    {
        ResourceFactory * factory = GetFactory(filename);
        if (!factory)
        {
            return NULL;
        }

        res = factory->CreateResource(def);
        m_pending[filename] = res;
        BOOL success = SetEvent(m_EventHandle);
        #ifdef  NDEBUG
        UNREFERENCED_VARIABLE(success);
        #endif
        assert(success);
    }
    assert(res);
    res->AddRef();
    return res;
}
// ----------------------------------------------------------------------------------------------
Resource* ResourceManager::LoadImmediate(const WCHAR* filename, Resource* def)
{
    AutoSync sync(&m_criticalSection); // CRITICAL SECTION - ENTIRE FUNCTION
    Resource * res = NULL;
    // check cache, use if already there.
    if(NULL == res)
    {
        auto it = m_loaded.find(filename);
        if(it != m_loaded.end() ) res = it->second;
    }

    // check pending, use if already there.
    if(NULL == res)
    {
        auto it = m_pending.find(filename);
        if(it != m_pending.end() ) res = it->second;
    }

    // create new info and add load it immediatelly.
    if(NULL == res)
    {
        ResourceFactory * factory = GetFactory(filename);
        res = factory->CreateResource(def);
        bool loaded = LoadResource(res, filename);
        if(!loaded)
        {
            Logger::Log(OutputMessageType::Error, L"failed to load %s\n",filename);
            SAFE_DELETE(res);
            return NULL;
        }
        else
        {
            m_loaded[filename] = res;
        }
    }
    res->AddRef();
    return res;
}