Property enum name changes in dali-core: Core changes
[platform/core/uifw/dali-core.git] / dali / internal / event / effects / shader-effect-impl.cpp
1 /*
2  * Copyright (c) 2014 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali/internal/event/effects/shader-effect-impl.h>
20
21 // INTERNAL INCLUDES
22 #include <dali/public-api/math/matrix.h>
23 #include <dali/public-api/math/matrix3.h>
24 #include <dali/public-api/math/vector2.h>
25 #include <dali/public-api/object/type-registry.h>
26 #include <dali/public-api/scripting/scripting.h>
27 #include <dali/public-api/shader-effects/shader-effect.h>
28 #include <dali/internal/event/common/property-helper.h>
29 #include <dali/internal/event/common/stage-impl.h>
30 #include <dali/internal/event/common/thread-local-storage.h>
31 #include <dali/internal/event/effects/shader-declarations.h>
32 #include <dali/internal/event/effects/shader-factory.h>
33 #include <dali/internal/event/images/image-impl.h>
34 #include <dali/internal/render/shaders/shader.h>
35 #include <dali/internal/render/shaders/uniform-meta.h>
36 #include <dali/internal/update/animation/scene-graph-constraint-base.h>
37 #include <dali/internal/update/common/animatable-property.h>
38 #include <dali/internal/update/manager/update-manager.h>
39 #include "dali-shaders.h"
40
41 using Dali::Internal::SceneGraph::UpdateManager;
42 using Dali::Internal::SceneGraph::UniformMeta;
43 using Dali::Internal::SceneGraph::Shader;
44 using Dali::Internal::SceneGraph::AnimatableProperty;
45 using Dali::Internal::SceneGraph::PropertyBase;
46 using Dali::Internal::SceneGraph::RenderQueue;
47 using std::string;
48
49 namespace Dali
50 {
51
52 namespace Internal
53 {
54
55 namespace
56 {
57
58 // Properties
59
60 //              Name             Type   writable animatable constraint-input  enum for index-checking
61 DALI_PROPERTY_TABLE_BEGIN
62 DALI_PROPERTY( "grid-density",   FLOAT,   true,    false,   false,   Dali::ShaderEffect::Property::GRID_DENSITY   )
63 DALI_PROPERTY( "image",          MAP,     true,    false,   false,   Dali::ShaderEffect::Property::IMAGE          )
64 DALI_PROPERTY( "program",        MAP,     true,    false,   false,   Dali::ShaderEffect::Property::PROGRAM        )
65 DALI_PROPERTY( "geometry-hints", INTEGER, true,    false,   false,   Dali::ShaderEffect::Property::GEOMETRY_HINTS )
66 DALI_PROPERTY_TABLE_END( DEFAULT_ACTOR_PROPERTY_START_INDEX )
67
68 BaseHandle Create()
69 {
70   Internal::ShaderEffectPtr internal = Internal::ShaderEffect::New();
71
72   return Dali::ShaderEffect(internal.Get());
73 }
74
75 TypeRegistration mType( typeid(Dali::ShaderEffect), typeid(Dali::Handle), Create );
76
77 struct WrapperStrings
78 {
79   const char* vertexShaderPrefix;
80   const char* fragmentShaderPrefix;
81   const char* vertexShaderPostfix;
82   const char* fragmentShaderPostfix;
83 };
84
85 WrapperStrings customShaderWrappers [] =
86 {
87   {
88     CustomImagePrefixVertex, CustomImagePrefixFragment,
89     CustomImagePostfixVertex, CustomImagePostfixFragment
90   },
91   {
92     CustomTextDistanceFieldPrefixVertex, CustomTextDistanceFieldPrefixFragment,
93     CustomTextDistanceFieldPostfixVertex, CustomTextDistanceFieldPostfixFragment
94   },
95   {
96     CustomUntexturedMeshPrefixVertex, CustomUntexturedMeshPrefixFragment,
97     CustomUntexturedMeshPostfixVertex, CustomUntexturedMeshPostfixFragment
98   },
99   {
100     CustomTexturedMeshPrefixVertex, CustomTexturedMeshPrefixFragment,
101     CustomTexturedMeshPostfixVertex, CustomTexturedMeshPostfixFragment
102   }
103 };
104
105 /**
106  * Helper to wrap the program with our default pre and postfix if needed and then send it to update/render thread
107  * @param[in] effect of the shader
108  * @param[in] actualGeometryType of the shader
109  * @param[in] expectedGeometryType of the shader
110  * @param[in] vertexPrefix from application
111  * @param[in] fragmentPrefix from application
112  * @param[in] vertexBody from application
113  * @param[in] fragmentBody from application
114  * @param[in] modifiesGeometry based on flags and vertex shader
115  */
116 void WrapAndSetProgram( Internal::ShaderEffect& effect,
117                         GeometryType actualGeometryType, GeometryType expectedGeometryType,
118                         const std::string& vertexPrefix, const std::string& fragmentPrefix,
119                         const std::string& vertexBody, const std::string& fragmentBody,
120                         bool modifiesGeometry )
121 {
122   // if geometry type matches and there is some real data in the strings
123   if( ( actualGeometryType & expectedGeometryType )&&
124       ( ( vertexPrefix.length() > 0   )||
125         ( fragmentPrefix.length() > 0 )||
126         ( vertexBody.length() > 0     )||
127         ( fragmentBody.length() > 0   ) ) )
128   {
129     std::string vertexSource = vertexPrefix;
130     std::string fragmentSource = fragmentPrefix;
131
132     // create complete shader program strings for the given geometry type
133     unsigned int index = 0;
134     switch( expectedGeometryType )
135     {
136       case GEOMETRY_TYPE_IMAGE:
137       {
138         index = 0;
139         break;
140       }
141       case GEOMETRY_TYPE_TEXT:
142       {
143         index = 1;
144         break;
145       }
146       case GEOMETRY_TYPE_UNTEXTURED_MESH:
147       {
148         index = 2;
149         break;
150       }
151       case GEOMETRY_TYPE_TEXTURED_MESH:
152       {
153         index = 3;
154         break;
155       }
156       case GEOMETRY_TYPE_LAST:
157       {
158         DALI_ASSERT_DEBUG(0 && "Wrong geometry type");
159         break;
160       }
161     }
162
163     vertexSource += customShaderWrappers[index].vertexShaderPrefix;
164     // Append the custom vertex shader code if supplied, otherwise append the default
165     if ( vertexBody.length() > 0 )
166     {
167       vertexSource.append( vertexBody );
168     }
169     else
170     {
171       vertexSource.append( customShaderWrappers[index].vertexShaderPostfix );
172     }
173
174     fragmentSource += customShaderWrappers[index].fragmentShaderPrefix;
175     // Append the custom fragment shader code if supplied, otherwise append the default
176     if ( fragmentBody.length() > 0 )
177     {
178       fragmentSource.append( fragmentBody );
179     }
180     else
181     {
182       fragmentSource.append( customShaderWrappers[index].fragmentShaderPostfix );
183     }
184
185     effect.SendProgramMessage( expectedGeometryType, SHADER_SUBTYPE_ALL, vertexSource, fragmentSource, modifiesGeometry );
186   }
187 }
188
189 std::string GetShader(const std::string& field, const Property::Value& property)
190 {
191   std::string value;
192   if( property.HasKey(field) )
193   {
194     DALI_ASSERT_ALWAYS(property.GetValue(field).GetType() == Property::STRING && "Shader property is not a string" );
195
196     // we could also check here for an array of strings as convenience for json not having multi line strings
197     value = property.GetValue(field).Get<std::string>();
198   }
199
200   return value;
201 }
202
203 } // unnamed namespace
204
205 ShaderEffectPtr ShaderEffect::New( Dali::ShaderEffect::GeometryHints hints )
206 {
207   ThreadLocalStorage& tls = ThreadLocalStorage::Get();
208   UpdateManager& updateManager = tls.GetUpdateManager();
209
210   ShaderEffectPtr shaderEffect( new ShaderEffect( updateManager, hints ) );
211   shaderEffect->RegisterObject();
212
213   return shaderEffect;
214 }
215
216 ShaderEffect::ShaderEffect( UpdateManager& updateManager, Dali::ShaderEffect::GeometryHints hints )
217 : mUpdateManager( updateManager ),
218   mConnectionCount (0),
219   mGeometryHints( hints )
220 {
221   mSceneObject = new Shader( hints );
222   DALI_ASSERT_DEBUG( NULL != mSceneObject );
223
224   // Transfer shader ownership to a scene message
225   AddShaderMessage( mUpdateManager, *mSceneObject );
226 }
227
228 ShaderEffect::~ShaderEffect()
229 {
230   // Guard to allow handle destruction after Core has been destroyed
231   if ( Stage::IsInstalled() )
232   {
233     // Remove scene-object using a message to the UpdateManager
234     if( mSceneObject )
235     {
236       RemoveShaderMessage( mUpdateManager, *mSceneObject );
237     }
238     UnregisterObject();
239   }
240 }
241
242 void ShaderEffect::SetEffectImage( Dali::Image image )
243 {
244   // if images are the same, do nothing
245   if (mImage == image)
246   {
247     return;
248   }
249
250   if (mImage && mConnectionCount > 0)
251   {
252     // unset previous image
253     GetImplementation(mImage).Disconnect();
254   }
255
256   // in case image is empty this will reset our image handle
257   mImage = image;
258
259   if (!image)
260   {
261     // mSceneShader can be in a separate thread; queue a setter message
262     SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, 0 );
263   }
264   else
265   {
266     // tell image that we're using it
267     if (mConnectionCount > 0)
268     {
269       GetImplementation(mImage).Connect();
270     }
271     // mSceneShader can be in a separate thread; queue a setter message
272     SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, GetImplementation(mImage).GetResourceId() );
273   }
274 }
275
276 void ShaderEffect::SetUniform( const std::string& name, Property::Value value, UniformCoordinateType uniformCoordinateType )
277 {
278   // Register the property if it does not exist
279   Property::Index index = GetPropertyIndex( name );
280   if ( Property::INVALID_INDEX == index )
281   {
282     index = RegisterProperty( name, value );
283   }
284
285   SetProperty( index, value );
286
287   // RegisterProperty guarantees a positive value as index
288   DALI_ASSERT_DEBUG( static_cast<unsigned int>(index) >= CustomPropertyStartIndex() );
289   unsigned int metaIndex = index - CustomPropertyStartIndex();
290   // check if there's space in cache
291   if( mCoordinateTypes.Count() < (metaIndex + 1) )
292   {
293     mCoordinateTypes.Resize( metaIndex + 1 );
294   }
295   // only send message if the value is different than current, initial value is COORDINATE_TYPE_DEFAULT (0)
296   if( uniformCoordinateType != mCoordinateTypes[ metaIndex ] )
297   {
298     mCoordinateTypes[ metaIndex ] = uniformCoordinateType;
299     SetCoordinateTypeMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, metaIndex, uniformCoordinateType );
300   }
301 }
302
303 void ShaderEffect::AttachExtension( Dali::ShaderEffect::Extension *extension )
304 {
305   DALI_ASSERT_ALWAYS( extension != NULL && "Attaching uninitialized extension" );
306   mExtension = IntrusivePtr<Dali::ShaderEffect::Extension>( extension );
307 }
308
309 Dali::ShaderEffect::Extension& ShaderEffect::GetExtension()
310 {
311   DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
312   return *mExtension;
313 }
314
315 const Dali::ShaderEffect::Extension& ShaderEffect::GetExtension() const
316 {
317   DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
318   return *mExtension;
319 }
320
321 void ShaderEffect::SetPrograms( GeometryType geometryType, const string& vertexSource, const string& fragmentSource )
322 {
323   SetPrograms( geometryType, "", "", vertexSource, fragmentSource );
324 }
325
326 void ShaderEffect::SetPrograms( GeometryType geometryType,
327                                 const std::string& vertexPrefix, const std::string& fragmentPrefix,
328                                 const std::string& vertexSource, const std::string& fragmentSource )
329 {
330   bool modifiesGeometry = true;
331   // check if the vertex shader is empty (means it cannot modify geometry)
332   if( (vertexPrefix.length() == 0 )&&( vertexSource.length() == 0 ) )
333   {
334     modifiesGeometry = false;
335   }
336   // check the hint second
337   if( (mGeometryHints & Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY ) != 0 )
338   {
339     modifiesGeometry = false;
340   }
341
342   WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_IMAGE, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
343   WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXT, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
344   WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
345   WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_UNTEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
346 }
347
348 void ShaderEffect::SendProgramMessage( GeometryType geometryType, ShaderSubTypes subType,
349                                        const string& vertexSource, const string& fragmentSource,
350                                        bool modifiesGeometry )
351 {
352   ThreadLocalStorage& tls = ThreadLocalStorage::Get();
353   ShaderFactory& shaderFactory = tls.GetShaderFactory();
354   size_t shaderHash;
355
356   ResourceTicketPtr ticket( shaderFactory.Load(vertexSource, fragmentSource, shaderHash) );
357
358   DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "ShaderEffect: SetProgram(geometryType %d subType:%d ticket.id:%d)\n", geometryType, subType, ticket->GetId() );
359
360   // Add shader program to scene-object using a message to the UpdateManager
361   SetShaderProgramMessage( mUpdateManager, *mSceneObject, geometryType, subType, ticket->GetId(), shaderHash, modifiesGeometry );
362
363   mTickets.push_back(ticket);       // add ticket to collection to keep it alive.
364 }
365
366 void ShaderEffect::Connect()
367 {
368   ++mConnectionCount;
369
370   if (mImage && mConnectionCount == 1)
371   {
372     GetImplementation(mImage).Connect();
373
374     // Image may have changed resource due to load/release policy. Ensure correct texture ID is set on scene graph object
375     SetTextureIdMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, GetImplementation(mImage).GetResourceId() );
376   }
377 }
378
379 void ShaderEffect::Disconnect()
380 {
381   DALI_ASSERT_DEBUG(mConnectionCount > 0);
382   --mConnectionCount;
383
384   if (mImage && mConnectionCount == 0)
385   {
386      GetImplementation(mImage).Disconnect();
387   }
388 }
389
390 unsigned int ShaderEffect::GetDefaultPropertyCount() const
391 {
392   return DEFAULT_PROPERTY_COUNT;
393 }
394
395 void ShaderEffect::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const
396 {
397   indices.reserve( DEFAULT_PROPERTY_COUNT );
398
399   for ( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
400   {
401     indices.push_back( i );
402   }
403 }
404
405 const char* ShaderEffect::GetDefaultPropertyName(Property::Index index) const
406 {
407   if( index < DEFAULT_PROPERTY_COUNT )
408   {
409     return DEFAULT_PROPERTY_DETAILS[index].name;
410   }
411
412   return NULL;
413 }
414
415 Property::Index ShaderEffect::GetDefaultPropertyIndex(const std::string& name) const
416 {
417   Property::Index index = Property::INVALID_INDEX;
418
419   // Look for name in default properties
420   for( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
421   {
422     const Internal::PropertyDetails* property = &DEFAULT_PROPERTY_DETAILS[ i ];
423     if( 0 == strcmp( name.c_str(), property->name ) ) // dont want to convert rhs to string
424     {
425       index = i;
426       break;
427     }
428   }
429
430   return index;
431 }
432
433 bool ShaderEffect::IsDefaultPropertyWritable(Property::Index index) const
434 {
435   return DEFAULT_PROPERTY_DETAILS[ index ].writable;
436 }
437
438 bool ShaderEffect::IsDefaultPropertyAnimatable(Property::Index index) const
439 {
440   return DEFAULT_PROPERTY_DETAILS[ index ].animatable;
441 }
442
443 bool ShaderEffect::IsDefaultPropertyAConstraintInput( Property::Index index ) const
444 {
445   return DEFAULT_PROPERTY_DETAILS[ index ].constraintInput;
446 }
447
448 Property::Type ShaderEffect::GetDefaultPropertyType(Property::Index index) const
449 {
450   if( index < DEFAULT_PROPERTY_COUNT )
451   {
452     return DEFAULT_PROPERTY_DETAILS[index].type;
453   }
454
455   // index out of range...return Property::NONE
456   return Property::NONE;
457 }
458
459 void ShaderEffect::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )
460 {
461   switch ( index )
462   {
463     case Dali::ShaderEffect::Property::GRID_DENSITY:
464     {
465       SetGridDensityMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, propertyValue.Get<float>() );
466       break;
467     }
468
469     case Dali::ShaderEffect::Property::IMAGE:
470     {
471       Dali::Image img(Scripting::NewImage( propertyValue ));
472       if(img)
473       {
474         SetEffectImage( img );
475       }
476       else
477       {
478         DALI_LOG_WARNING("Cannot create image from property value for ShaderEffect image\n");
479       }
480       break;
481     }
482
483     case Dali::ShaderEffect::Property::PROGRAM:
484     {
485       std::string vertexPrefix   = GetShader("vertex-prefix", propertyValue);
486       std::string fragmentPrefix = GetShader("fragment-prefix", propertyValue);
487       std::string vertex         = GetShader("vertex", propertyValue);
488       std::string fragment       = GetShader("fragment", propertyValue);
489
490       GeometryType geometryType      = GEOMETRY_TYPE_IMAGE;
491
492       if( propertyValue.HasKey("geometry-type") )
493       {
494         Property::Value geometryValue  = propertyValue.GetValue("geometry-type");
495         DALI_ASSERT_ALWAYS(geometryValue.GetType() == Property::STRING && "Geometry type is not a string" );
496
497         std::string s = geometryValue.Get<std::string>();
498         if(s == "GEOMETRY_TYPE_IMAGE")
499         {
500           geometryType  = GEOMETRY_TYPE_IMAGE;
501         }
502         else if (s == "GEOMETRY_TYPE_TEXT")
503         {
504           geometryType  = GEOMETRY_TYPE_TEXT;
505         }
506         else if( s == "GEOMETRY_TYPE_UNTEXTURED_MESH")
507         {
508           geometryType  = GEOMETRY_TYPE_UNTEXTURED_MESH;
509         }
510         else if( s == "GEOMETRY_TYPE_TEXTURED_MESH")
511         {
512           geometryType  = GEOMETRY_TYPE_TEXTURED_MESH;
513         }
514         else
515         {
516           DALI_ASSERT_ALWAYS(!"Geometry type unknown" );
517         }
518       }
519       SetPrograms( geometryType, vertexPrefix, fragmentPrefix, vertex, fragment );
520       break;
521     }
522
523     case Dali::ShaderEffect::Property::GEOMETRY_HINTS:
524     {
525       Dali::ShaderEffect::GeometryHints hint = Dali::ShaderEffect::HINT_NONE;
526       Property::Value geometryHintsValue   = propertyValue.GetValue("geometry-hints");
527
528       std::string s = geometryHintsValue.Get<std::string>();
529       if(s == "HINT_NONE")
530       {
531         hint = Dali::ShaderEffect::HINT_NONE;
532       }
533       else if(s == "HINT_GRID_X")
534       {
535         hint = Dali::ShaderEffect::HINT_GRID_X;
536       }
537       else if(s == "HINT_GRID_Y")
538       {
539         hint = Dali::ShaderEffect::HINT_GRID_Y;
540       }
541       else if(s == "HINT_GRID")
542       {
543         hint = Dali::ShaderEffect::HINT_GRID;
544       }
545       else if(s == "HINT_DEPTH_BUFFER")
546       {
547         hint = Dali::ShaderEffect::HINT_DEPTH_BUFFER;
548       }
549       else if(s == "HINT_BLENDING")
550       {
551         hint = Dali::ShaderEffect::HINT_BLENDING;
552       }
553       else if(s == "HINT_DOESNT_MODIFY_GEOMETRY")
554       {
555         hint = Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY;
556       }
557       else
558       {
559         DALI_ASSERT_ALWAYS(!"Geometry hint unknown" );
560       }
561
562       SetHintsMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, hint );
563
564       break;
565     }
566
567     default:
568     {
569       // nothing to do
570       break;
571     }
572   }
573 }
574
575 Property::Value ShaderEffect::GetDefaultProperty(Property::Index /*index*/) const
576 {
577   // none of our properties are readable so return empty
578   return Property::Value();
579 }
580
581 void ShaderEffect::NotifyScenePropertyInstalled( const SceneGraph::PropertyBase& newProperty, const std::string& name, unsigned int index )
582 {
583   // Warning - the property is added to the Shader object in the Update thread and the meta-data is added in the Render thread (through a secondary message)
584
585   // mSceneObject requires metadata for each custom property (uniform)
586   UniformMeta* meta = UniformMeta::New( name, newProperty, Dali::ShaderEffect::COORDINATE_TYPE_DEFAULT );
587   // mSceneObject is being used in a separate thread; queue a message to add the property
588   InstallUniformMetaMessage( mUpdateManager.GetEventToUpdate(), *mSceneObject, *meta ); // Message takes ownership
589 }
590
591 const SceneGraph::PropertyOwner* ShaderEffect::GetSceneObject() const
592 {
593   return mSceneObject;
594 }
595
596 const PropertyBase* ShaderEffect::GetSceneObjectAnimatableProperty( Property::Index index ) const
597 {
598   CustomProperty* custom = FindCustomProperty( index );
599   DALI_ASSERT_ALWAYS( custom && "Property index is invalid" );
600   return custom->GetSceneGraphProperty();
601 }
602
603 const PropertyInputImpl* ShaderEffect::GetSceneObjectInputProperty( Property::Index index ) const
604 {
605   return GetSceneObjectAnimatableProperty( index );
606 }
607
608 } // namespace Internal
609
610 } // namespace Dali