2 * Copyright (c) 2023 Samsung Electronics Co., Ltd.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #include "gles-graphics-pipeline-cache.h"
20 #include "egl-graphics-controller.h"
21 #include "gles-graphics-pipeline.h"
22 #include "gles-graphics-program.h"
24 namespace Dali::Graphics::GLES
27 * @brief custom delete function for cached object
30 struct CachedObjectDeleter
32 CachedObjectDeleter() = default;
34 void operator()(T* object)
36 // Discard resource (add it to discard queue)
37 object->DiscardResource();
42 struct CachedObjectDeleter<GLES::Program>
44 CachedObjectDeleter() = default;
46 void operator()(GLES::Program* object)
48 // Program deleter should skip discard queue if controller shutting down
49 if(!object->GetController().IsShuttingDown())
51 object->DiscardResource();
55 // delete object otherwise
62 * @brief The order of states being stored in the cache and mask
64 enum class StateLookupIndex : uint32_t
66 COLOR_BLEND_STATE_BIT = 0,
67 VIEWPORT_STATE_BIT = 1,
68 BASE_PIPELINE_STATE_BIT = 2,
69 DEPTH_STENCIL_STATE_BIT = 3,
70 RASTERIZATION_STATE_BIT = 4,
71 VERTEX_INPUT_STATE_BIT = 5,
72 INPUT_ASSEMBLY_STATE_BIT = 6,
77 * Helper float compare function
79 static bool cmpf(float A, float B, float epsilon = 0.005f)
81 return (fabs(A - B) < epsilon);
87 static bool operator==(const Graphics::Viewport& lhs, const Graphics::Viewport& rhs)
89 return cmpf(lhs.x, rhs.x) &&
91 cmpf(lhs.width, rhs.width) &&
92 cmpf(lhs.height, rhs.height) &&
93 cmpf(lhs.minDepth, rhs.minDepth) &&
94 cmpf(lhs.maxDepth, rhs.maxDepth);
97 static bool operator==(const Graphics::Rect2D& lhs, const Graphics::Rect2D& rhs)
99 return cmpf(lhs.x, rhs.x) &&
100 cmpf(lhs.y, rhs.y) &&
101 cmpf(lhs.width, rhs.width) &&
102 cmpf(lhs.height, rhs.height);
105 static bool operator==(const Graphics::StencilOpState& lhs, const Graphics::StencilOpState& rhs)
107 return lhs.failOp == rhs.failOp &&
108 lhs.passOp == rhs.passOp &&
109 lhs.depthFailOp == rhs.depthFailOp &&
110 lhs.compareOp == rhs.compareOp &&
111 lhs.compareMask == rhs.compareMask &&
112 lhs.writeMask == rhs.writeMask &&
113 lhs.reference == rhs.reference;
117 operator==(const Dali::Graphics::VertexInputState::Attribute& lhs,
118 const Dali::Graphics::VertexInputState::Attribute& rhs)
120 return lhs.location == rhs.location &&
121 lhs.binding == rhs.binding &&
122 lhs.offset == rhs.offset &&
123 lhs.format == rhs.format;
127 operator==(const Dali::Graphics::VertexInputState::Binding& lhs, const Dali::Graphics::VertexInputState::Binding& rhs)
129 return lhs.stride == rhs.stride &&
130 lhs.inputRate == rhs.inputRate;
133 using PipelineStateCompateFunctionType = bool(const Graphics::PipelineCreateInfo*,
134 const Graphics::PipelineCreateInfo*);
136 static std::vector<PipelineStateCompateFunctionType*>& GetStateCompareFuncTable()
138 static std::vector<PipelineStateCompateFunctionType*> stateCompareFuncTable{};
139 return stateCompareFuncTable;
143 * @brief Initialises compare function lookup table
145 void InitialiseStateCompareLookupTable()
147 GetStateCompareFuncTable().clear();
148 GetStateCompareFuncTable().push_back([](const auto* lhs, const auto* rhs) -> bool // colorBlendState
150 const auto& lcb = *lhs->colorBlendState;
151 const auto& rcb = *rhs->colorBlendState;
152 return lcb.logicOpEnable == rcb.logicOpEnable &&
153 lcb.logicOp == rcb.logicOp &&
154 cmpf(lcb.blendConstants[0], rcb.blendConstants[0]) &&
155 cmpf(lcb.blendConstants[1], rcb.blendConstants[1]) &&
156 cmpf(lcb.blendConstants[2], rcb.blendConstants[2]) &&
157 cmpf(lcb.blendConstants[3], rcb.blendConstants[3]) &&
158 lcb.blendEnable == rcb.blendEnable &&
159 lcb.srcColorBlendFactor == rcb.srcColorBlendFactor &&
160 lcb.dstColorBlendFactor == rcb.dstColorBlendFactor &&
161 lcb.colorBlendOp == rcb.colorBlendOp &&
162 lcb.srcAlphaBlendFactor == rcb.srcAlphaBlendFactor &&
163 lcb.dstAlphaBlendFactor == rcb.dstAlphaBlendFactor &&
164 lcb.alphaBlendOp == rcb.alphaBlendOp &&
165 lcb.colorComponentWriteBits == rcb.colorComponentWriteBits;
167 GetStateCompareFuncTable().push_back([](const auto* lhs, const auto* rhs) -> bool // viewport state
169 const auto& lvp = *lhs->viewportState;
170 const auto& rvp = *rhs->viewportState;
171 return lvp.viewport == rvp.viewport &&
172 lvp.scissor == rvp.scissor &&
173 lvp.scissorTestEnable == rvp.scissorTestEnable;
175 GetStateCompareFuncTable().push_back([](const auto* lhs, const auto* rhs) -> bool // basePipeline
177 return lhs->basePipeline == rhs->basePipeline;
179 GetStateCompareFuncTable().push_back([](const auto* lhs, const auto* rhs) -> bool // depthStencilState
181 const auto& lds = *lhs->depthStencilState;
182 const auto& rds = *rhs->depthStencilState;
183 return lds.depthTestEnable == rds.depthTestEnable &&
184 lds.depthWriteEnable == rds.depthWriteEnable &&
185 lds.depthCompareOp == rds.depthCompareOp &&
186 lds.stencilTestEnable == rds.stencilTestEnable &&
187 lds.front == rds.front &&
188 lds.back == rds.back;
190 GetStateCompareFuncTable().push_back([](const auto* lhs, const auto* rhs) -> bool // rasterizationState
192 const auto& lrs = *lhs->rasterizationState;
193 const auto& rrs = *rhs->rasterizationState;
194 return lrs.cullMode == rrs.cullMode &&
195 lrs.polygonMode == rrs.polygonMode &&
196 lrs.frontFace == rrs.frontFace;
198 GetStateCompareFuncTable().push_back([](const auto* lhs, const auto* rhs) -> bool // vertexInputState
200 const auto& lvi = *lhs->vertexInputState;
201 const auto& rvi = *rhs->vertexInputState;
202 return lvi.bufferBindings.size() == rvi.bufferBindings.size() &&
203 lvi.attributes.size() == rvi.attributes.size() &&
204 std::equal(lvi.bufferBindings.begin(), lvi.bufferBindings.end(), rvi.bufferBindings.begin(), [](const auto& lhs, const auto& rhs) {
205 return operator==(lhs, rhs);
207 std::equal(lvi.attributes.begin(), lvi.attributes.end(), rvi.attributes.begin(), [](const auto& lhs, const auto& rhs) {
208 return operator==(lhs, rhs);
211 GetStateCompareFuncTable().push_back([](const auto* lhs, const auto* rhs) -> bool // inputAssemblyState
213 const auto& lia = *lhs->inputAssemblyState;
214 const auto& ria = *rhs->inputAssemblyState;
215 return lia.topology == ria.topology &&
216 lia.primitiveRestartEnable == ria.primitiveRestartEnable;
221 * @brief Helper function calculating the bitmask of set states
223 * @param[in] info Valid PipelineCreateInfo structure
224 * @return bitmask of set states
226 inline uint32_t GetStateBitmask(const PipelineCreateInfo& info)
229 mask |= bool(info.colorBlendState) << int(StateLookupIndex::COLOR_BLEND_STATE_BIT);
230 mask |= bool(info.viewportState) << int(StateLookupIndex::VIEWPORT_STATE_BIT);
231 mask |= bool(info.basePipeline) << int(StateLookupIndex::BASE_PIPELINE_STATE_BIT);
232 mask |= bool(info.depthStencilState) << int(StateLookupIndex::DEPTH_STENCIL_STATE_BIT);
233 mask |= bool(info.rasterizationState) << int(StateLookupIndex::RASTERIZATION_STATE_BIT);
234 mask |= bool(info.vertexInputState) << int(StateLookupIndex::VERTEX_INPUT_STATE_BIT);
235 mask |= bool(info.inputAssemblyState) << int(StateLookupIndex::INPUT_ASSEMBLY_STATE_BIT);
240 * @brief Implementation of cache
242 struct PipelineCache::Impl
247 explicit Impl(EglGraphicsController& _controller)
248 : controller(_controller)
250 // Initialise lookup table
251 InitialiseStateCompareLookupTable();
259 // First destroy pipelines
263 programEntries.clear();
267 * @brief Structure describes a single cache entry
271 CacheEntry() = default;
273 CacheEntry(UniquePtr<PipelineImpl>&& _pipeline, uint32_t _bitmask)
274 : pipeline(std::move(_pipeline)),
275 stateBitmask(_bitmask)
279 ~CacheEntry() = default;
281 CacheEntry(CacheEntry&&) = default;
282 CacheEntry& operator=(CacheEntry&&) = default;
284 UniquePtr<PipelineImpl> pipeline{nullptr};
285 uint32_t stateBitmask{0u};
288 EglGraphicsController& controller;
289 std::vector<CacheEntry> entries;
292 * @brief Sorted array of shaders used to create program
294 struct ProgramCacheEntry
296 // sorted array of shaders
297 std::vector<const Graphics::Shader*> shaders;
298 UniquePtr<ProgramImpl> program{nullptr};
301 std::vector<ProgramCacheEntry> programEntries;
304 PipelineCache::PipelineCache(EglGraphicsController& controller)
306 mImpl = std::make_unique<Impl>(controller);
309 PipelineCache::~PipelineCache() = default;
311 PipelineImpl* PipelineCache::FindPipelineImpl(const PipelineCreateInfo& info)
313 auto bitmask = GetStateBitmask(info);
315 for(auto& entry : mImpl->entries)
317 auto& pipeline = entry.pipeline;
318 auto& cacheInfo = pipeline->GetCreateInfo();
319 if(!info.programState)
324 // Check whether the program is the same
325 if(info.programState->program)
327 const auto& lhsProgram = *static_cast<const GLES::Program*>(info.programState->program);
328 const auto& rhsProgram = *static_cast<const GLES::Program*>(cacheInfo.programState->program);
329 if(lhsProgram != rhsProgram)
334 // Test whether set states bitmask matches
335 if(entry.stateBitmask != bitmask)
340 // Now test only for states that are set
342 for(i = 0; i < int(StateLookupIndex::MAX_STATE); ++i)
344 // Test only set states
345 if((entry.stateBitmask & (1 << i)))
347 if(!(GetStateCompareFuncTable()[i](&info, &cacheInfo)))
354 // TODO: For now ignoring dynamic state mask and allocator
355 // Getting as far as here, we have found our pipeline impl
356 if(i == int(StateLookupIndex::MAX_STATE))
358 return pipeline.get();
365 ProgramImpl* PipelineCache::FindProgramImpl(const ProgramCreateInfo& info)
367 if(mImpl->programEntries.empty())
372 // assert if no shaders given
373 std::vector<const Graphics::Shader*> shaders;
374 shaders.reserve(info.shaderState->size());
376 for(auto& state : *info.shaderState)
378 shaders.push_back(state.shader);
382 std::sort(shaders.begin(), shaders.end());
384 for(auto& item : mImpl->programEntries)
386 if(item.shaders.size() != shaders.size())
391 int k = shaders.size();
392 while(--k >= 0 && item.shaders[k] == shaders[k])
397 return item.program.get();
403 Graphics::UniquePtr<Graphics::Pipeline> PipelineCache::GetPipeline(const PipelineCreateInfo& pipelineCreateInfo,
404 Graphics::UniquePtr<Graphics::Pipeline>&& oldPipeline)
406 auto cachedPipeline = FindPipelineImpl(pipelineCreateInfo);
408 // Return same pointer if nothing changed
409 if(oldPipeline && *static_cast<GLES::Pipeline*>(oldPipeline.get()) == cachedPipeline)
411 return std::move(oldPipeline);
416 // create new pipeline
417 auto pipeline = MakeUnique<GLES::PipelineImpl>(pipelineCreateInfo, mImpl->controller, *this);
419 cachedPipeline = pipeline.get();
422 mImpl->entries.emplace_back(std::move(pipeline), GetStateBitmask(pipelineCreateInfo));
425 auto wrapper = MakeUnique<GLES::Pipeline, CachedObjectDeleter<GLES::Pipeline>>(*cachedPipeline);
426 return std::move(wrapper);
429 Graphics::UniquePtr<Graphics::Program> PipelineCache::GetProgram(const ProgramCreateInfo& programCreateInfo,
430 Graphics::UniquePtr<Graphics::Program>&& oldProgram)
432 ProgramImpl* cachedProgram = FindProgramImpl(programCreateInfo);
434 // Return same pointer if nothing changed
435 if(oldProgram && *static_cast<GLES::Program*>(oldProgram.get()) == cachedProgram)
437 return std::move(oldProgram);
442 // create new pipeline
443 auto program = MakeUnique<GLES::ProgramImpl>(programCreateInfo, mImpl->controller);
447 cachedProgram = program.get();
450 mImpl->programEntries.emplace_back();
451 auto& item = mImpl->programEntries.back();
452 item.program = std::move(program);
453 for(auto& state : *programCreateInfo.shaderState)
455 item.shaders.push_back(state.shader);
458 std::sort(item.shaders.begin(), item.shaders.end());
461 auto wrapper = MakeUnique<GLES::Program, CachedObjectDeleter<GLES::Program>>(cachedProgram);
462 return std::move(wrapper);
465 void PipelineCache::FlushCache()
467 decltype(mImpl->entries) newEntries;
468 newEntries.reserve(mImpl->entries.size());
470 for(auto& entry : mImpl->entries)
472 // Move items which are still in use into the new array
473 if(entry.pipeline->GetRefCount() != 0)
475 newEntries.emplace_back(std::move(entry));
479 // Move temporary array in place of stored cache
480 // Unused pipelines will be deleted automatically
481 mImpl->entries = std::move(newEntries);
483 // TODO: program cache may require similar action. However,
484 // since there is always one wrapper for Program object
485 // kept in the pipeline, then death of pipeline will result
486 // killing the program (if program isn't in use anymore)
489 } // namespace Dali::Graphics::GLES