Merge branch 'devel/master' into devel/graphics
[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) 2021 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
26 #include <dali/graphics-api/graphics-controller.h>
27 #include <dali/integration-api/debug.h>
28 #include <dali/internal/common/blending-options.h>
29 #include <dali/internal/common/const-string.h>
30 #include <dali/internal/common/message.h>
31 #include <dali/internal/common/type-abstraction-enums.h>
32 #include <dali/internal/event/common/property-input-impl.h>
33 #include <dali/internal/render/data-providers/render-data-provider.h>
34 #include <dali/internal/render/gl-resources/gl-resource-owner.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 Context;
45 class Texture;
46 class ProgramCache;
47
48 namespace SceneGraph
49 {
50 class SceneController;
51 class Shader;
52 class NodeDataProvider;
53
54 class RenderInstruction; //for relfection effect
55 } // namespace SceneGraph
56
57 namespace Render
58 {
59 struct ShaderCache;
60 class UniformBufferManager;
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 : public GlResourceOwner
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    * @copydoc Dali::Internal::GlResourceOwner::GlContextDestroyed()
99    */
100   void GlContextDestroyed() override;
101
102   /**
103    * @copydoc Dali::Internal::GlResourceOwner::GlCleanup()
104    */
105   void GlCleanup() override;
106
107   /**
108    * Create a new renderer instance
109    * @param[in] dataProviders The data providers for the renderer
110    * @param[in] geometry The geometry for the renderer
111    * @param[in] blendingBitmask A bitmask of blending options.
112    * @param[in] blendColor The blend color to pass to GL
113    * @param[in] faceCullingMode The face-culling mode.
114    * @param[in] preMultipliedAlphaEnabled whether alpha is pre-multiplied.
115    * @param[in] depthWriteMode Depth buffer write mode
116    * @param[in] depthTestMode Depth buffer test mode
117    * @param[in] depthFunction Depth function
118    * @param[in] stencilParameters Struct containing all stencil related options
119    */
120   static Renderer* New(SceneGraph::RenderDataProvider* dataProviders,
121                        Render::Geometry*               geometry,
122                        uint32_t                        blendingBitmask,
123                        const Vector4&                  blendColor,
124                        FaceCullingMode::Type           faceCullingMode,
125                        bool                            preMultipliedAlphaEnabled,
126                        DepthWriteMode::Type            depthWriteMode,
127                        DepthTestMode::Type             depthTestMode,
128                        DepthFunction::Type             depthFunction,
129                        StencilParameters&              stencilParameters);
130
131   /**
132    * Constructor.
133    * @param[in] dataProviders The data providers for the renderer
134    * @param[in] geometry The geometry for the renderer
135    * @param[in] blendingBitmask A bitmask of blending options.
136    * @param[in] blendColor The blend color to pass to GL
137    * @param[in] faceCullingMode The face-culling mode.
138    * @param[in] preMultipliedAlphaEnabled whether alpha is pre-multiplied.
139    * @param[in] depthWriteMode Depth buffer write mode
140    * @param[in] depthTestMode Depth buffer test mode
141    * @param[in] depthFunction Depth function
142    * @param[in] stencilParameters Struct containing all stencil related options
143    */
144   Renderer(SceneGraph::RenderDataProvider* dataProviders,
145            Render::Geometry*               geometry,
146            uint32_t                        blendingBitmask,
147            const Vector4&                  blendColor,
148            FaceCullingMode::Type           faceCullingMode,
149            bool                            preMultipliedAlphaEnabled,
150            DepthWriteMode::Type            depthWriteMode,
151            DepthTestMode::Type             depthTestMode,
152            DepthFunction::Type             depthFunction,
153            StencilParameters&              stencilParameters);
154
155   /**
156    * Change the geometry used by the renderer
157    * @param[in] geometry The new geometry
158    */
159   void SetGeometry(Render::Geometry* geometry);
160
161   void SetDrawCommands(Dali::DevelRenderer::DrawCommand* pDrawCommands, uint32_t size);
162
163   /**
164    * @brief Returns a reference to an array of draw commands
165    * @return Valid array of draw commands (may be empty)
166    */
167   const std::vector<Dali::DevelRenderer::DrawCommand>& GetDrawCommands() const
168   {
169     return mDrawCommands;
170   }
171
172   /**
173    * Second-phase construction.
174    * This is called when the renderer is inside render thread
175    * @param[in] context Context used by the renderer (To be removed)
176    * @param[in] graphicsController The graphics controller to use
177    * @param[in] programCache Cache of program objects
178    * @param[in] shaderCache Cache of shaders
179    * @param[in] uniformBufferManager Uniform buffer manager
180    */
181   void Initialize(Context& context, Graphics::Controller& graphicsController, ProgramCache& programCache, Render::ShaderCache& shaderCache, Render::UniformBufferManager& uniformBufferManager);
182
183   /**
184    * Destructor
185    */
186   ~Renderer() override;
187
188   /**
189    * Set the face-culling mode.
190    * @param[in] mode The face-culling mode.
191    */
192   void SetFaceCullingMode(FaceCullingMode::Type mode);
193
194   /**
195    * Set the bitmask for blending options
196    * @param[in] bitmask A bitmask of blending options.
197    */
198   void SetBlendingBitMask(uint32_t bitmask);
199
200   /**
201    * Set the blend color for blending options
202    * @param[in] blendColor The blend color to pass to GL
203    */
204   void SetBlendColor(const Vector4& color);
205
206   /**
207    * Set the first element index to draw by the indexed draw
208    * @param[in] firstElement index of first element to draw
209    */
210   void SetIndexedDrawFirstElement(uint32_t firstElement);
211
212   /**
213    * Set the number of elements to draw by the indexed draw
214    * @param[in] elementsCount number of elements to draw
215    */
216   void SetIndexedDrawElementsCount(uint32_t elementsCount);
217
218   /**
219    * @brief Set whether the Pre-multiplied Alpha Blending is required
220    *
221    * @param[in] preMultipled whether alpha is pre-multiplied.
222    */
223   void EnablePreMultipliedAlpha(bool preMultipled);
224
225   /**
226    * Sets the depth write mode
227    * @param[in] depthWriteMode The depth write mode
228    */
229   void SetDepthWriteMode(DepthWriteMode::Type depthWriteMode);
230
231   /**
232    * Query the Renderer's depth write mode
233    * @return The renderer depth write mode
234    */
235   DepthWriteMode::Type GetDepthWriteMode() const;
236
237   /**
238    * Sets the depth test mode
239    * @param[in] depthTestMode The depth test mode
240    */
241   void SetDepthTestMode(DepthTestMode::Type depthTestMode);
242
243   /**
244    * Query the Renderer's depth test mode
245    * @return The renderer depth test mode
246    */
247   DepthTestMode::Type GetDepthTestMode() const;
248
249   /**
250    * Sets the depth function
251    * @param[in] depthFunction The depth function
252    */
253   void SetDepthFunction(DepthFunction::Type depthFunction);
254
255   /**
256    * Query the Renderer's depth function
257    * @return The renderer depth function
258    */
259   DepthFunction::Type GetDepthFunction() const;
260
261   /**
262    * Sets the render mode
263    * @param[in] renderMode The render mode
264    */
265   void SetRenderMode(RenderMode::Type mode);
266
267   /**
268    * Gets the render mode
269    * @return The render mode
270    */
271   RenderMode::Type GetRenderMode() const;
272
273   /**
274    * Sets the stencil function
275    * @param[in] stencilFunction The stencil function
276    */
277   void SetStencilFunction(StencilFunction::Type stencilFunction);
278
279   /**
280    * Gets the stencil function
281    * @return The stencil function
282    */
283   StencilFunction::Type GetStencilFunction() const;
284
285   /**
286    * Sets the stencil function mask
287    * @param[in] stencilFunctionMask The stencil function mask
288    */
289   void SetStencilFunctionMask(int stencilFunctionMask);
290
291   /**
292    * Gets the stencil function mask
293    * @return The stencil function mask
294    */
295   int GetStencilFunctionMask() const;
296
297   /**
298    * Sets the stencil function reference
299    * @param[in] stencilFunctionReference The stencil function reference
300    */
301   void SetStencilFunctionReference(int stencilFunctionReference);
302
303   /**
304    * Gets the stencil function reference
305    * @return The stencil function reference
306    */
307   int GetStencilFunctionReference() const;
308
309   /**
310    * Sets the stencil mask
311    * @param[in] stencilMask The stencil mask
312    */
313   void SetStencilMask(int stencilMask);
314
315   /**
316    * Gets the stencil mask
317    * @return The stencil mask
318    */
319   int GetStencilMask() const;
320
321   /**
322    * Sets the stencil operation for when the stencil test fails
323    * @param[in] stencilOperationOnFail The stencil operation
324    */
325   void SetStencilOperationOnFail(StencilOperation::Type stencilOperationOnFail);
326
327   /**
328    * Gets the stencil operation for when the stencil test fails
329    * @return The stencil operation
330    */
331   StencilOperation::Type GetStencilOperationOnFail() const;
332
333   /**
334    * Sets the stencil operation for when the depth test fails
335    * @param[in] stencilOperationOnZFail The stencil operation
336    */
337   void SetStencilOperationOnZFail(StencilOperation::Type stencilOperationOnZFail);
338
339   /**
340    * Gets the stencil operation for when the depth test fails
341    * @return The stencil operation
342    */
343   StencilOperation::Type GetStencilOperationOnZFail() const;
344
345   /**
346    * Sets the stencil operation for when the depth test passes
347    * @param[in] stencilOperationOnZPass The stencil operation
348    */
349   void SetStencilOperationOnZPass(StencilOperation::Type stencilOperationOnZPass);
350
351   /**
352    * Gets the stencil operation for when the depth test passes
353    * @return The stencil operation
354    */
355   StencilOperation::Type GetStencilOperationOnZPass() const;
356
357   /**
358    * Called to upload during RenderManager::Render().
359    */
360   void Upload();
361
362   /**
363    * Called to render during RenderManager::Render().
364    * @param[in] context The context used for rendering
365    * @param[in] bufferIndex The index of the previous update buffer.
366    * @param[in] node The node using this renderer
367    * @param[in] modelViewMatrix The model-view matrix.
368    * @param[in] viewMatrix The view matrix.
369    * @param[in] projectionMatrix The projection matrix.
370    * @param[in] size Size of the render item
371    * @param[in] blend If true, blending is enabled
372    * @param[in] boundTextures The textures bound for rendering
373    * @param[in] instruction. for use case like reflection where CullFace needs to be adjusted
374
375    */
376   void Render(Context&                                             context,
377               BufferIndex                                          bufferIndex,
378               const SceneGraph::NodeDataProvider&                  node,
379               const Matrix&                                        modelMatrix,
380               const Matrix&                                        modelViewMatrix,
381               const Matrix&                                        viewMatrix,
382               const Matrix&                                        projectionMatrix,
383               const Vector3&                                       size,
384               bool                                                 blend,
385               Vector<Graphics::Texture*>&                          boundTextures,
386               const Dali::Internal::SceneGraph::RenderInstruction& instruction,
387               uint32_t                                             queueIndex);
388
389   /**
390    * Write the renderer's sort attributes to the passed in reference
391    *
392    * @param[in] bufferIndex The current update buffer index.
393    * @param[out] sortAttributes
394    */
395   void SetSortAttributes(BufferIndex bufferIndex, SceneGraph::RenderInstructionProcessor::SortAttributes& sortAttributes) const;
396
397   /**
398    * Sets the flag indicating whether shader changed.
399    *
400    * @param[in] value True if shader changed
401    */
402   void SetShaderChanged(bool value);
403
404   /**
405    * Check if the renderer attributes/uniforms are updated and returns the flag
406    *
407    * @param[in] bufferIndex The current update buffer index.
408    * @param[in] node The node using this renderer
409    */
410   bool Updated(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider* node);
411
412   template<class T>
413   bool WriteDefaultUniform(const Graphics::UniformInfo* uniformInfo, Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const T& data);
414
415   template<class T>
416   void WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const T& data);
417
418   void WriteUniform(Render::UniformBuffer& ubo, const std::vector<Graphics::UniformBufferBinding>& bindings, const Graphics::UniformInfo& uniformInfo, const void* data, uint32_t size);
419
420 private:
421   struct UniformIndexMap;
422
423   // Undefined
424   Renderer(const Renderer&);
425
426   // Undefined
427   Renderer& operator=(const Renderer& rhs);
428
429   /**
430    * Sets blending options
431    * @param context to use
432    * @param blend Wheter blending should be enabled or not
433    */
434   void SetBlending(Context& context, bool blend);
435
436   /**
437    * Builds a uniform map based on the index of the cached location in the Program.
438    * @param[in] bufferIndex The index of the previous update buffer.
439    * @param[in] node The node using the renderer
440    * @param[in] size The size of the renderer
441    * @param[in] program The shader program on which to set the uniforms.
442    */
443   void BuildUniformIndexMap(BufferIndex bufferIndex, const SceneGraph::NodeDataProvider& node, const Vector3& size, Program& program);
444
445   /**
446    * Set the program uniform in the map from the mapped property
447    * @param[in] bufferIndex The index of the previous update buffer.
448    * @param[in] program The shader program
449    * @param[in] map The uniform
450    */
451   void SetUniformFromProperty(BufferIndex bufferIndex, Program& program, UniformIndexMap& map);
452
453   /**
454    * Bind the textures and setup the samplers
455    * @param[in] context The GL context
456    * @param[in] program The shader program
457    * @param[in] boundTextures The textures bound for rendering
458    * @return False if create or bind failed, true if success.
459    */
460   bool BindTextures(Program& program, Graphics::CommandBuffer& commandBuffer, Vector<Graphics::Texture*>& boundTextures);
461
462   /**
463    * Prepare a pipeline for this renderer
464    */
465   Graphics::UniquePtr<Graphics::Pipeline> PrepareGraphicsPipeline(
466     Program&                                             program,
467     const Dali::Internal::SceneGraph::RenderInstruction& instruction,
468     bool                                                 blend,
469     Graphics::UniquePtr<Graphics::Pipeline>&&            oldPipeline);
470
471   /**
472    * @brief Fill uniform buffer at index. Writes uniforms into given memory address
473    *
474    * @param[in] instruction The render instruction
475    * @param[in,out] ubo Target uniform buffer object
476    * @param[out] outBindings output bindings vector
477    * @param[out] offset output offset of the next uniform buffer memory address
478    * @param[in] updateBufferIndex update buffer index
479    */
480   void FillUniformBuffers(Program&                                      program,
481                           const SceneGraph::RenderInstruction&          instruction,
482                           Render::UniformBuffer&                        ubo,
483                           std::vector<Graphics::UniformBufferBinding>*& outBindings,
484                           uint32_t&                                     offset,
485                           BufferIndex                                   updateBufferIndex);
486
487 private:
488   Graphics::Controller*                        mGraphicsController;
489   OwnerPointer<SceneGraph::RenderDataProvider> mRenderDataProvider;
490
491   Context*          mContext;
492   Render::Geometry* mGeometry;
493
494   Graphics::UniquePtr<Graphics::CommandBuffer> mGraphicsCommandBuffer{};
495
496   ProgramCache*        mProgramCache{nullptr};
497   Render::ShaderCache* mShaderCache{nullptr};
498
499   Render::UniformBufferManager*               mUniformBufferManager{};
500   std::vector<Graphics::UniformBufferBinding> mUniformBufferBindings{};
501
502   Graphics::UniquePtr<Graphics::Pipeline> mGraphicsPipeline{}; ///< The graphics pipeline. (Cached implementation)
503   std::vector<Graphics::ShaderState>      mShaderStates{};
504
505   using Hash = unsigned long;
506   struct UniformIndexMap
507   {
508     uint32_t                 uniformIndex;  ///< The index of the cached location in the Program
509     ConstString              uniformName;   ///< The uniform name
510     const PropertyInputImpl* propertyValue; ///< The property value
511     Hash                     uniformNameHash{0u};
512     Hash                     uniformNameHashNoArray{0u};
513     int32_t                  arrayIndex; ///< The array index
514   };
515
516   using UniformIndexMappings = Dali::Vector<UniformIndexMap>;
517
518   UniformIndexMappings mUniformIndexMap;
519   Vector<int32_t>      mAttributeLocations;
520
521   uint64_t mUniformsHash;
522
523   StencilParameters mStencilParameters; ///< Struct containing all stencil related options
524   BlendingOptions   mBlendingOptions;   ///< Blending options including blend color, blend func and blend equation
525
526   uint32_t mIndexedDrawFirstElement;  ///< Offset of first element to draw
527   uint32_t mIndexedDrawElementsCount; ///< Number of elements to draw
528
529   DepthFunction::Type   mDepthFunction : 4;            ///< The depth function
530   FaceCullingMode::Type mFaceCullingMode : 3;          ///< The mode of face culling
531   DepthWriteMode::Type  mDepthWriteMode : 3;           ///< The depth write mode
532   DepthTestMode::Type   mDepthTestMode : 3;            ///< The depth test mode
533   bool                  mUpdateAttributeLocations : 1; ///< Indicates attribute locations have changed
534   bool                  mPremultipledAlphaEnabled : 1; ///< Flag indicating whether the Pre-multiplied Alpha Blending is required
535   bool                  mShaderChanged : 1;            ///< Flag indicating the shader changed and uniform maps have to be updated
536   bool                  mUpdated : 1;
537
538   std::vector<Dali::DevelRenderer::DrawCommand> mDrawCommands; // Devel stuff
539
540   struct LegacyProgram : Graphics::ExtensionCreateInfo
541   {
542     uint32_t programId{0};
543   };
544
545   LegacyProgram mLegacyProgram; ///< The structure to pass the program ID into Graphics::PipelineCreateInfo
546
547   Graphics::UniquePtr<Render::UniformBuffer> mUniformBuffer[2]{nullptr, nullptr}; ///< The double-buffered uniform buffer
548 };
549
550 } // namespace Render
551
552 } // namespace Internal
553
554 } // namespace Dali
555
556 #endif // DALI_INTERNAL_RENDER_RENDERER_H