apatrick@chromium.org | 3cfd722 | 2012-07-13 22:36:58 +0000 | [diff] [blame^] | 1 | // |
| 2 | // Copyright (c) 2012 The ANGLE Project Authors. All rights reserved. |
| 3 | // Use of this source code is governed by a BSD-style license that can be |
| 4 | // found in the LICENSE file. |
| 5 | // |
| 6 | |
| 7 | // Display.h: Defines egl::ShaderCache, a cache of Direct3D shader objects |
| 8 | // keyed by their byte code. |
| 9 | |
| 10 | #ifndef LIBEGL_SHADER_CACHE_H_ |
| 11 | #define LIBEGL_SHADER_CACHE_H_ |
| 12 | |
| 13 | #include <d3d9.h> |
| 14 | #include <hash_map> |
| 15 | |
| 16 | namespace egl |
| 17 | { |
| 18 | template <typename ShaderObject> |
| 19 | class ShaderCache |
| 20 | { |
| 21 | public: |
| 22 | ShaderCache() : mDevice(NULL) |
| 23 | { |
| 24 | } |
| 25 | |
| 26 | ~ShaderCache() |
| 27 | { |
| 28 | // Call clear while the device is still valid. |
| 29 | ASSERT(mMap.empty()); |
| 30 | } |
| 31 | |
| 32 | void initialize(IDirect3DDevice9* device) |
| 33 | { |
| 34 | mDevice = device; |
| 35 | } |
| 36 | |
| 37 | ShaderObject *create(const DWORD *function, size_t length) |
| 38 | { |
| 39 | std::string key(reinterpret_cast<const char*>(function), length); |
| 40 | Map::iterator it = mMap.find(key); |
| 41 | if (it != mMap.end()) |
| 42 | { |
| 43 | it->second->AddRef(); |
| 44 | return it->second; |
| 45 | } |
| 46 | |
| 47 | ShaderObject *shader; |
| 48 | HRESULT result = createShader(function, &shader); |
| 49 | if (FAILED(result)) |
| 50 | { |
| 51 | return NULL; |
| 52 | } |
| 53 | |
| 54 | // Random eviction policy. |
| 55 | if (mMap.size() >= kMaxMapSize) |
| 56 | { |
| 57 | mMap.begin()->second->Release(); |
| 58 | mMap.erase(mMap.begin()); |
| 59 | } |
| 60 | |
| 61 | shader->AddRef(); |
| 62 | mMap[key] = shader; |
| 63 | |
| 64 | return shader; |
| 65 | } |
| 66 | |
| 67 | void clear() |
| 68 | { |
| 69 | for (Map::iterator it = mMap.begin(); it != mMap.end(); ++it) |
| 70 | { |
| 71 | it->second->Release(); |
| 72 | } |
| 73 | |
| 74 | mMap.clear(); |
| 75 | } |
| 76 | |
| 77 | private: |
| 78 | DISALLOW_COPY_AND_ASSIGN(ShaderCache); |
| 79 | |
| 80 | const static size_t kMaxMapSize = 100; |
| 81 | |
| 82 | HRESULT createShader(const DWORD *function, IDirect3DVertexShader9 **shader) |
| 83 | { |
| 84 | return mDevice->CreateVertexShader(function, shader); |
| 85 | } |
| 86 | |
| 87 | HRESULT createShader(const DWORD *function, IDirect3DPixelShader9 **shader) |
| 88 | { |
| 89 | return mDevice->CreatePixelShader(function, shader); |
| 90 | } |
| 91 | |
| 92 | typedef stdext::hash_map<std::string, ShaderObject*> Map; |
| 93 | Map mMap; |
| 94 | |
| 95 | IDirect3DDevice9 *mDevice; |
| 96 | }; |
| 97 | |
| 98 | typedef ShaderCache<IDirect3DVertexShader9> VertexShaderCache; |
| 99 | typedef ShaderCache<IDirect3DPixelShader9> PixelShaderCache; |
| 100 | |
| 101 | } |
| 102 | |
| 103 | #endif // LIBEGL_SHADER_CACHE_H_ |