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