9f25651f6aad31ba275ede2ad4d3f05251a24151
[platform/core/uifw/dali-core.git] / dali / internal / render / renderers / render-renderer.h
1 #ifndef DALI_INTERNAL_RENDER_RENDERER_H
2 #define DALI_INTERNAL_RENDER_RENDERER_H
3
4 /*
5  * Copyright (c) 2023 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // INTERNAL INCLUDES
22 #include <dali/public-api/common/vector-wrapper.h>
23 #include <dali/public-api/math/matrix.h>
24 #include <dali/public-api/math/vector4.h>
25 #include <dali/public-api/rendering/texture-set.h>
26 #include <dali/public-api/signals/render-callback.h>
27
28 #include <dali/graphics-api/graphics-controller.h>
29 #include <dali/integration-api/debug.h>
30 #include <dali/internal/common/blending-options.h>
31 #include <dali/internal/common/const-string.h>
32 #include <dali/internal/common/message.h>
33 #include <dali/internal/common/type-abstraction-enums.h>
34 #include <dali/internal/event/common/property-input-impl.h>
35 #include <dali/internal/render/data-providers/render-data-provider.h>
36 #include <dali/internal/render/renderers/render-geometry.h>
37 #include <dali/internal/render/renderers/uniform-buffer-manager.h>
38 #include <dali/internal/render/shaders/program.h>
39 #include <dali/internal/update/manager/render-instruction-processor.h>
40
41 namespace Dali
42 {
43 namespace Internal
44 {
45 class Texture;
46 class ProgramCache;
47
48 namespace SceneGraph
49 {
50 class SceneController;
51 class Shader;
52 class NodeDataProvider;
53 class RenderInstruction; //for reflection effect
54 } // namespace SceneGraph
55
56 namespace Render
57 {
58 struct ShaderCache;
59 class PipelineCache;
60 class UniformBufferManager;
61 class PipelineCache;
62 class Renderer;
63
64 using RendererKey = MemoryPoolKey<Render::Renderer>;
65 } //namespace Render
66 } //namespace Internal
67
68 // Ensure RendererKey can be used in Dali::Vector
69 template<>
70 struct TypeTraits<Internal::Render::RendererKey> : public BasicTypes<Internal::Render::RendererKey>
71 {
72   enum
73   {
74     IS_TRIVIAL_TYPE = true
75   };
76 };
77
78 namespace Internal
79 {
80 namespace Render
81 {
82 /**
83  * Renderers are used to render meshes
84  * These objects are used during RenderManager::Render(), so properties modified during
85  * the Update must either be double-buffered, or set via a message added to the RenderQueue.
86  */
87 class Renderer
88 {
89 public:
90   /**
91    * @brief Struct to encapsulate stencil parameters required for control of the stencil buffer.
92    */
93   struct StencilParameters
94   {
95     StencilParameters(RenderMode::Type renderMode, StencilFunction::Type stencilFunction, int stencilFunctionMask, int stencilFunctionReference, int stencilMask, StencilOperation::Type stencilOperationOnFail, StencilOperation::Type stencilOperationOnZFail, StencilOperation::Type stencilOperationOnZPass)
96     : stencilFunctionMask(stencilFunctionMask),
97       stencilFunctionReference(stencilFunctionReference),
98       stencilMask(stencilMask),
99       renderMode(renderMode),
100       stencilFunction(stencilFunction),
101       stencilOperationOnFail(stencilOperationOnFail),
102       stencilOperationOnZFail(stencilOperationOnZFail),
103       stencilOperationOnZPass(stencilOperationOnZPass)
104     {
105     }
106
107     int                    stencilFunctionMask;         ///< The stencil function mask
108     int                    stencilFunctionReference;    ///< The stencil function reference
109     int                    stencilMask;                 ///< The stencil mask
110     RenderMode::Type       renderMode : 4;              ///< The render mode
111     StencilFunction::Type  stencilFunction : 4;         ///< The stencil function
112     StencilOperation::Type stencilOperationOnFail : 4;  ///< The stencil operation for stencil test fail
113     StencilOperation::Type stencilOperationOnZFail : 4; ///< The stencil operation for depth test fail
114     StencilOperation::Type stencilOperationOnZPass : 4; ///< The stencil operation for depth test pass
115   };
116
117   /**
118    * Create a new renderer instance
119    * @param[in] dataProviders The data providers for the renderer
120    * @param[in] geometry The geometry for the renderer
121    * @param[in] blendingBitmask A bitmask of blending options.
122    * @param[in] blendColor The blend color
123    * @param[in] faceCullingMode The face-culling mode.
124    * @param[in] preMultipliedAlphaEnabled whether alpha is pre-multiplied.
125    * @param[in] depthWriteMode Depth buffer write mode
126    * @param[in] depthTestMode Depth buffer test mode
127    * @param[in] depthFunction Depth function
128    * @param[in] stencilParameters Struct containing all stencil related options
129    */
130   static RendererKey NewKey(SceneGraph::RenderDataProvider* dataProviders,
131                             Render::Geometry*               geometry,
132                             uint32_t                        blendingBitmask,
133                             const Vector4&                  blendColor,
134                             FaceCullingMode::Type           faceCullingMode,
135                             bool                            preMultipliedAlphaEnabled,
136                             DepthWriteMode::Type            depthWriteMode,
137                             DepthTestMode::Type             depthTestMode,
138                             DepthFunction::Type             depthFunction,
139                             StencilParameters&              stencilParameters);
140
141   /**
142    * Constructor.
143    * @param[in] dataProviders The data providers for the renderer
144    * @param[in] geometry The geometry for the renderer
145    * @param[in] blendingBitmask A bitmask of blending options.
146    * @param[in] blendColor The blend color
147    * @param[in] faceCullingMode The face-culling mode.
148    * @param[in] preMultipliedAlphaEnabled whether alpha is pre-multiplied.
149    * @param[in] depthWriteMode Depth buffer write mode
150    * @param[in] depthTestMode Depth buffer test mode
151    * @param[in] depthFunction Depth function
152    * @param[in] stencilParameters Struct containing all stencil related options
153    */
154   Renderer(SceneGraph::RenderDataProvider* dataProviders,
155            Render::Geometry*               geometry,
156            uint32_t                        blendingBitmask,
157            const Vector4&                  blendColor,
158            FaceCullingMode::Type           faceCullingMode,
159            bool                            preMultipliedAlphaEnabled,
160            DepthWriteMode::Type            depthWriteMode,
161            DepthTestMode::Type             depthTestMode,
162            DepthFunction::Type             depthFunction,
163            StencilParameters&              stencilParameters);
164
165   /**
166    * Second-phase construction.
167    * This is called when the renderer is inside render thread
168    * @param[in] graphicsController The graphics controller to use
169    * @param[in] programCache Cache of program objects
170    * @param[in] shaderCache Cache of shaders
171    * @param[in] uniformBufferManager Uniform buffer manager
172    * @param[in] pipelineCache Cache of pipelines
173    */
174   void Initialize(Graphics::Controller&         graphicsController,
175                   ProgramCache&                 programCache,
176                   Render::ShaderCache&          shaderCache,
177                   Render::UniformBufferManager& uniformBufferManager,
178                   Render::PipelineCache&        pipelineCache);
179
180   /**
181    * Destructor
182    */
183   ~Renderer();
184
185   /**
186    * Overriden delete operator
187    * Deletes the renderer from its global memory pool
188    */
189   void operator delete(void* ptr);
190
191   /**
192    * Get a pointer to the object from the given key.
193    * Used by MemoryPoolKey to provide pointer semantics.
194    */
195   static Renderer* Get(RendererKey::KeyType rendererKey);
196
197   /**
198    * Change the geometry used by the renderer
199    * @param[in] geometry The new geometry
200    */
201   void SetGeometry(Render::Geometry* geometry);
202
203   void SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size);
204
205   /**
206    * @brief Returns a reference to an array of draw commands
207    * @return Valid array of draw commands (may be empty)
208    */
209   [[nodiscard]] const std::vector<Dali::DevelRenderer::DrawCommand>& GetDrawCommands() const
210   {
211     return mDrawCommands;
212   }
213
214   /**
215    * Set the face-culling mode.
216    * @param[in] mode The face-culling mode.
217    */
218   void SetFaceCullingMode(FaceCullingMode::Type mode);
219
220   /**
221    * Set the bitmask for blending options
222    * @param[in] bitmask A bitmask of blending options.
223    */
224   void SetBlendingBitMask(uint32_t bitmask);
225
226   /**
227    * Set the blend color for blending options
228    * @param[in] blendColor The blend color
229    */
230   void SetBlendColor(const Vector4& color);
231
232   /**
233    * Set the first element index to draw by the indexed draw
234    * @param[in] firstElement index of first element to draw
235    */
236   void SetIndexedDrawFirstElement(uint32_t firstElement);
237
238   /**
239    * Set the number of elements to draw by the indexed draw
240    * @param[in] elementsCount number of elements to draw
241    */
242   void SetIndexedDrawElementsCount(uint32_t elementsCount);
243
244   /**
245    * @brief Set whether the Pre-multiplied Alpha Blending is required
246    *
247    * @param[in] preMultipled whether alpha is pre-multiplied.
248    */
249   void EnablePreMultipliedAlpha(bool preMultipled);
250
251   /**
252    * Sets the depth write mode
253    * @param[in] depthWriteMode The depth write mode
254    */
255   void SetDepthWriteMode(DepthWriteMode::Type depthWriteMode);
256
257   /**
258    * Query the Renderer's depth write mode
259    * @return The renderer depth write mode
260    */
261   [[nodiscard]] DepthWriteMode::Type GetDepthWriteMode() const;
262
263   /**
264    * Sets the depth test mode
265    * @param[in] depthTestMode The depth test mode
266    */
267   void SetDepthTestMode(DepthTestMode::Type depthTestMode);
268
269   /**
270    * Query the Renderer's depth test mode
271    * @return The renderer depth test mode
272    */
273   [[nodiscard]] DepthTestMode::Type GetDepthTestMode() const;
274
275   /**
276    * Sets the depth function
277    * @param[in] depthFunction The depth function
278    */
279   void SetDepthFunction(DepthFunction::Type depthFunction);
280
281   /**
282    * Query the Renderer's depth function
283    * @return The renderer depth function
284    */
285   [[nodiscard]] DepthFunction::Type GetDepthFunction() const;
286
287   /**
288    * Sets the render mode
289    * @param[in] renderMode The render mode
290    */
291   void SetRenderMode(RenderMode::Type mode);
292
293   /**
294    * Gets the render mode
295    * @return The render mode
296    */
297   [[nodiscard]] RenderMode::Type GetRenderMode() const;
298
299   /**
300    * Sets the stencil function
301    * @param[in] stencilFunction The stencil function
302    */
303   void SetStencilFunction(StencilFunction::Type stencilFunction);
304
305   /**
306    * Gets the stencil function
307    * @return The stencil function
308    */
309   [[nodiscard]] StencilFunction::Type GetStencilFunction() const;
310
311   /**
312    * Sets the stencil function mask
313    * @param[in] stencilFunctionMask The stencil function mask
314    */
315   void SetStencilFunctionMask(int stencilFunctionMask);
316
317   /**
318    * Gets the stencil function mask
319    * @return The stencil function mask
320    */
321   [[nodiscard]] int GetStencilFunctionMask() const;
322
323   /**
324    * Sets the stencil function reference
325    * @param[in] stencilFunctionReference The stencil function reference
326    */
327   void SetStencilFunctionReference(int stencilFunctionReference);
328
329   /**
330    * Gets the stencil function reference
331    * @return The stencil function reference
332    */
333   [[nodiscard]] int GetStencilFunctionReference() const;
334
335   /**
336    * Sets the stencil mask
337    * @param[in] stencilMask The stencil mask
338    */
339   void SetStencilMask(int stencilMask);
340
341   /**
342    * Gets the stencil mask
343    * @return The stencil mask
344    */
345   [[nodiscard]] int GetStencilMask() const;
346
347   /**
348    * Sets the stencil operation for when the stencil test fails
349    * @param[in] stencilOperationOnFail The stencil operation
350    */
351   void SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail);
352
353   /**
354    * Gets the stencil operation for when the stencil test fails
355    * @return The stencil operation
356    */
357   [[nodiscard]] StencilOperation::Type GetStencilOperationOnFail() const;
358
359   /**
360    * Sets the stencil operation for when the depth test fails
361    * @param[in] stencilOperationOnZFail The stencil operation
362    */
363   void SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail);
364
365   /**
366    * Gets the stencil operation for when the depth test fails
367    * @return The stencil operation
368    */
369   [[nodiscard]] StencilOperation::Type GetStencilOperationOnZFail() const;
370
371   /**
372    * Sets the stencil operation for when the depth test passes
373    * @param[in] stencilOperationOnZPass The stencil operation
374    */
375   void SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass);
376
377   /**
378    * Gets the stencil operation for when the depth test passes
379    * @return The stencil operation
380    */
381   [[nodiscard]] StencilOperation::Type GetStencilOperationOnZPass() const;
382
383   /**
384    * Called to upload during RenderManager::Render().
385    */
386   void Upload();
387
388   /**
389    * Called to render during RenderManager::Render().
390    * @param[in,out] commandBuffer The command buffer to write into
391    * @param[in] bufferIndex The index of the previous update buffer.
392    * @param[in] node The node using this renderer
393    * @param[in] modelViewMatrix The model-view matrix.
394    * @param[in] viewMatrix The view matrix.
395    * @param[in] projectionMatrix The projection matrix.
396    * @param[in] size Size of the render item
397    * @param[in] blend If true, blending is enabled
398    * @param[in] boundTextures The textures bound for rendering
399    * @param[in] instruction. for use case like reflection where CullFace needs to be adjusted
400    *
401    * @return True if commands have been added to the command buffer
402    */
403   bool Render(Graphics::CommandBuffer&                             commandBuffer,
404               BufferIndex                                          bufferIndex,
405               const SceneGraph::NodeDataProvider&                  node,
406               const Matrix&                                        modelMatrix,
407               const Matrix&                                        modelViewMatrix,
408               const Matrix&                                        viewMatrix,
409               const Matrix&                                        projectionMatrix,
410               const Vector3&                                       size,
411               bool                                                 blend,
412               Vector<Graphics::Texture*>&                          boundTextures,
413               const Dali::Internal::SceneGraph::RenderInstruction& instruction,
414               uint32_t                                             queueIndex);
415
416   /**
417    * Sets RenderCallback object
418    *
419    * @param[in] callback Valid pointer to RenderCallback object
420    */
421   void SetRenderCallback(RenderCallback* callback);
422
423   /**
424    * Returns currently set RenderCallback object
425    *
426    * @return Valid pointer to RenderCallback object or nullptr
427    */
428   RenderCallback* GetRenderCallback()
429   {
430     return mRenderCallback;
431   }
432
433   /**
434    * Returns internal RenderCallbackInput structure
435    * @return Valid reference to the RenderCallbackInput
436    */
437   RenderCallbackInput& GetRenderCallbackInput()
438   {
439     if(!mRenderCallbackInput)
440     {
441       mRenderCallbackInput = std::unique_ptr<RenderCallbackInput>(new RenderCallbackInput);
442     }
443     return *mRenderCallbackInput;
444   }
445
446   /**
447    * Write the renderer's sort attributes to the passed in reference
448    *
449    * @param[out] sortAttributes
450    */
451   void SetSortAttributes(SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const;
452
453   /**
454    * Sets the flag indicating whether shader changed.
455    *
456    * @param[in] value True if shader changed
457    */
458   void SetShaderChanged(bool value);
459
460   /**
461    * Check if the renderer attributes/uniforms are updated and returns the flag
462    *
463    * @param[in] bufferIndex The current update buffer index.
464    */
465   bool Updated(BufferIndex bufferIndex);
466
467   template<class T>
468   bool WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo,
469                            Render::UniformBufferView&   ubo,
470                            const T&                     data);
471
472   template<class T>
473   void WriteUniform(Render::UniformBufferView&   ubo,
474                     const Graphics::UniformInfo& uniformInfo,
475                     const T&                     data);
476
477   void WriteUniform(Render::UniformBufferView&   ubo,
478                     const Graphics::UniformInfo& uniformInfo,
479                     const void*                  data,
480                     uint32_t                     size);
481
482   [[nodiscard]] FaceCullingMode::Type GetFaceCullMode() const
483   {
484     return mFaceCullingMode;
485   }
486
487   /**
488    * @brief Gets update area after visual properties applied.
489    *
490    * @param[in] bufferIndex The index of the previous update buffer.
491    * @param[in] originalUpdateArea The original update area before apply the visual properties.
492    *
493    * @return The recalculated update area after visual properties applied.
494    */
495   Vector4 GetVisualTransformedUpdateArea(BufferIndex bufferIndex, const Vector4& originalUpdateArea) const noexcept;
496
497 private:
498   struct UniformIndexMap;
499
500   // Undefined
501   Renderer(const Renderer&);
502
503   // Undefined
504   Renderer& operator=(const Renderer& rhs);
505
506   /**
507    * Builds a uniform map based on the index of the cached location in the Program.
508    * @param[in] bufferIndex The index of the previous update buffer.
509    * @param[in] node The node using the renderer
510    * @param[in] size The size of the renderer
511    * @param[in] program The shader program on which to set the uniforms.
512    *
513    * @return the index of the node in change counters store / uniform maps store.
514    */
515   std::size_t BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program);
516
517   /**
518    * Bind the textures and setup the samplers
519    * @param[in] commandBuffer The command buffer to record binding into
520    * @param[in] boundTextures The textures bound for rendering
521    */
522   void BindTextures(Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures);
523
524   /**
525    * Prepare a pipeline for this renderer.
526    *
527    * As a renderer can be re-used in a single frame (e.g. being used by multiple nodes, or
528    * by non-exclusive render tasks), we store a pipeline per node/instruction.
529    * In practice, the implementation will cached pipelines, so we normally only have
530    * multiple handles.
531    */
532   Graphics::Pipeline& PrepareGraphicsPipeline(
533     Program&                                             program,
534     const Dali::Internal::SceneGraph::RenderInstruction& instruction,
535     const SceneGraph::NodeDataProvider&                  node,
536     bool                                                 blend);
537
538   /**
539    * Setup and write data to the uniform buffer
540    *
541    * @param[in] bufferIndex The current buffer index
542    * @param[in] commandBuffer The command buffer to bind the uniform buffer to
543    * @param[in] node The node using this renderer
544    * @param[in] modelViewMatrix The model-view matrix.
545    * @param[in] viewMatrix The view matrix.
546    * @param[in] projectionMatrix The projection matrix.
547    * @param[in] size Size of the render item
548    * @param[in] blend If true, blending is enabled
549    * @param[in] instruction The render instruction
550    * @param[in] The node index
551    */
552   void WriteUniformBuffer(BufferIndex                          bufferIndex,
553                           Graphics::CommandBuffer&             commandBuffer,
554                           Program*                             program,
555                           const SceneGraph::RenderInstruction& instruction,
556                           const SceneGraph::NodeDataProvider&  node,
557                           const Matrix&                        modelMatrix,
558                           const Matrix&                        modelViewMatrix,
559                           const Matrix&                        viewMatrix,
560                           const Matrix&                        projectionMatrix,
561                           const Vector3&                       size,
562                           std::size_t                          nodeIndex);
563
564   /**
565    * @brief Fill uniform buffer at index. Writes uniforms into given memory address
566    *
567    * @param[in] instruction The render instruction
568    * @param[in,out] ubo Target uniform buffer object
569    * @param[out] outBindings output bindings vector
570    * @param[out] offset output offset of the next uniform buffer memory address
571    * @param[in] updateBufferIndex update buffer index
572    */
573   void FillUniformBuffer(Program&                                      program,
574                          const SceneGraph::RenderInstruction&          instruction,
575                          Render::UniformBufferView&                    ubo,
576                          std::vector<Graphics::UniformBufferBinding>*& outBindings,
577                          uint32_t&                                     offset,
578                          BufferIndex                                   updateBufferIndex,
579                          std::size_t                                   nodeIndex);
580
581 private:
582   Graphics::Controller*           mGraphicsController;
583   SceneGraph::RenderDataProvider* mRenderDataProvider;
584
585   Render::Geometry* mGeometry;
586
587   ProgramCache*        mProgramCache{nullptr};
588   Render::ShaderCache* mShaderCache{nullptr};
589
590   Render::UniformBufferManager*               mUniformBufferManager{};
591   std::vector<Graphics::UniformBufferBinding> mUniformBufferBindings{};
592
593   Render::PipelineCache* mPipelineCache{nullptr};
594
595   using Hash = std::size_t;
596
597   typedef const float& (PropertyInputImpl::*FuncGetter)(BufferIndex) const;
598
599   struct UniformIndexMap
600   {
601     ConstString              uniformName;            ///< The uniform name
602     const PropertyInputImpl* propertyValue{nullptr}; ///< The property value
603     Hash                     uniformNameHash{0u};
604     Hash                     uniformNameHashNoArray{0u};
605     int32_t                  arrayIndex{-1}; ///< The array index
606
607     int16_t    uniformLocation{0u};
608     uint16_t   uniformOffset{0u};
609     uint16_t   uniformSize{0u};
610     FuncGetter uniformFunc{0};
611   };
612
613   StencilParameters mStencilParameters; ///< Struct containing all stencil related options
614   BlendingOptions   mBlendingOptions;   ///< Blending options including blend color, blend func and blend equation
615
616   uint32_t mIndexedDrawFirstElement;  ///< Offset of first element to draw
617   uint32_t mIndexedDrawElementsCount; ///< Number of elements to draw
618
619   /** Struct to map node to index into mNodeMapCounters and mUniformIndexMaps */
620   struct RenderItemLookup
621   {
622     const SceneGraph::NodeDataProvider* node{nullptr}; ///<Node key. It can be nullptr if this NodeIndex don't need node uniform
623
624     std::size_t index{0};                       ///<Index into mUniformIndexMap
625     std::size_t nodeChangeCounter{0};           ///<The last known change counter for this node's uniform map
626     std::size_t renderItemMapChangeCounter{0u}; ///< Change counter of the renderer & shader collected uniform map for this render item (node/renderer pair)
627   };
628   std::vector<RenderItemLookup> mNodeIndexMap; ///< usually only 1 element.
629   using UniformIndexMappings = std::vector<UniformIndexMap>;
630   std::vector<UniformIndexMappings> mUniformIndexMaps; ///< Cached map per node/renderer/shader.
631
632   DepthFunction::Type   mDepthFunction : 4;             ///< The depth function
633   FaceCullingMode::Type mFaceCullingMode : 3;           ///< The mode of face culling
634   DepthWriteMode::Type  mDepthWriteMode : 3;            ///< The depth write mode
635   DepthTestMode::Type   mDepthTestMode : 3;             ///< The depth test mode
636   bool                  mPremultipliedAlphaEnabled : 1; ///< Flag indicating whether the Pre-multiplied Alpha Blending is required
637   bool                  mShaderChanged : 1;             ///< Flag indicating the shader changed and uniform maps have to be updated
638
639   std::vector<Dali::DevelRenderer::DrawCommand> mDrawCommands; // Devel stuff
640   RenderCallback*                               mRenderCallback{nullptr};
641   std::unique_ptr<RenderCallbackInput>          mRenderCallbackInput{nullptr};
642   std::vector<Graphics::Texture*>               mRenderCallbackTextureBindings{};
643 };
644
645 } // namespace Render
646
647 } // namespace Internal
648
649 } // namespace Dali
650
651 #endif // DALI_INTERNAL_RENDER_RENDERER_H