Remove dali-any from Property::Value - reimplement multivalue using more efficient...
[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/devel-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", STRING,  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     CustomUntexturedMeshPrefixVertex, CustomUntexturedMeshPrefixFragment,
93     CustomUntexturedMeshPostfixVertex, CustomUntexturedMeshPostfixFragment
94   },
95   {
96     CustomTexturedMeshPrefixVertex, CustomTexturedMeshPrefixFragment,
97     CustomTexturedMeshPostfixVertex, CustomTexturedMeshPostfixFragment
98   }
99 };
100
101 /**
102  * Helper to wrap the program with our default pre and postfix if needed and then send it to update/render thread
103  * @param[in] effect of the shader
104  * @param[in] actualGeometryType of the shader
105  * @param[in] expectedGeometryType of the shader
106  * @param[in] vertexPrefix from application
107  * @param[in] fragmentPrefix from application
108  * @param[in] vertexBody from application
109  * @param[in] fragmentBody from application
110  * @param[in] modifiesGeometry based on flags and vertex shader
111  */
112 void WrapAndSetProgram( Internal::ShaderEffect& effect,
113                         GeometryType actualGeometryType, GeometryType expectedGeometryType,
114                         const std::string& vertexPrefix, const std::string& fragmentPrefix,
115                         const std::string& vertexBody, const std::string& fragmentBody,
116                         bool modifiesGeometry )
117 {
118   // if geometry type matches and there is some real data in the strings
119   if( ( actualGeometryType & expectedGeometryType )&&
120       ( ( vertexPrefix.length() > 0   )||
121         ( fragmentPrefix.length() > 0 )||
122         ( vertexBody.length() > 0     )||
123         ( fragmentBody.length() > 0   ) ) )
124   {
125     std::string vertexSource = vertexPrefix;
126     std::string fragmentSource = fragmentPrefix;
127
128     // create complete shader program strings for the given geometry type
129     unsigned int index = 0;
130     switch( expectedGeometryType )
131     {
132       case GEOMETRY_TYPE_IMAGE:
133       {
134         index = 0;
135         break;
136       }
137       case GEOMETRY_TYPE_UNTEXTURED_MESH:
138       {
139         index = 1;
140         break;
141       }
142       case GEOMETRY_TYPE_TEXTURED_MESH:
143       {
144         index = 2;
145         break;
146       }
147       case GEOMETRY_TYPE_LAST:
148       {
149         DALI_ASSERT_DEBUG(0 && "Wrong geometry type");
150         break;
151       }
152     }
153
154     vertexSource += customShaderWrappers[index].vertexShaderPrefix;
155     // Append the custom vertex shader code if supplied, otherwise append the default
156     if ( vertexBody.length() > 0 )
157     {
158       vertexSource.append( vertexBody );
159     }
160     else
161     {
162       vertexSource.append( customShaderWrappers[index].vertexShaderPostfix );
163     }
164
165     fragmentSource += customShaderWrappers[index].fragmentShaderPrefix;
166     // Append the custom fragment shader code if supplied, otherwise append the default
167     if ( fragmentBody.length() > 0 )
168     {
169       fragmentSource.append( fragmentBody );
170     }
171     else
172     {
173       fragmentSource.append( customShaderWrappers[index].fragmentShaderPostfix );
174     }
175
176     effect.SendProgramMessage( expectedGeometryType, SHADER_SUBTYPE_ALL, vertexSource, fragmentSource, modifiesGeometry );
177   }
178 }
179
180 std::string GetShader(const std::string& field, const Property::Value& property)
181 {
182   std::string retval;
183   const Property::Map* map = property.GetMap();
184   if( map )
185   {
186     const Property::Value* value = map->Find( field );
187     if( value )
188     {
189       value->Get( retval );
190     }
191   }
192
193   return retval;
194 }
195
196 } // unnamed namespace
197
198 ShaderEffectPtr ShaderEffect::New( Dali::ShaderEffect::GeometryHints hints )
199 {
200   Stage* stage = Stage::GetCurrent();
201
202   ShaderEffectPtr shaderEffect( new ShaderEffect( *stage, hints ) );
203   shaderEffect->RegisterObject();
204
205   return shaderEffect;
206 }
207
208 ShaderEffect::ShaderEffect( EventThreadServices& eventThreadServices, Dali::ShaderEffect::GeometryHints hints )
209 : mEventThreadServices( eventThreadServices ),
210   mConnectionCount (0),
211   mGeometryHints( hints )
212 {
213   mSceneObject = new Shader( hints );
214   DALI_ASSERT_DEBUG( NULL != mSceneObject );
215
216   // Transfer shader ownership to a scene message
217   AddShaderMessage( eventThreadServices.GetUpdateManager(), *mSceneObject );
218 }
219
220 ShaderEffect::~ShaderEffect()
221 {
222   // Guard to allow handle destruction after Core has been destroyed
223   if ( Stage::IsInstalled() )
224   {
225     // Remove scene-object using a message to the UpdateManager
226     if( mSceneObject )
227     {
228       RemoveShaderMessage( mEventThreadServices.GetUpdateManager(), *mSceneObject );
229     }
230     UnregisterObject();
231   }
232 }
233
234 void ShaderEffect::SetEffectImage( Dali::Image image )
235 {
236   // if images are the same, do nothing
237   if (mImage == image)
238   {
239     return;
240   }
241
242   if (mImage && mConnectionCount > 0)
243   {
244     // unset previous image
245     GetImplementation(mImage).Disconnect();
246   }
247
248   // in case image is empty this will reset our image handle
249   mImage = image;
250
251   if (!image)
252   {
253     // mSceneShader can be in a separate thread; queue a setter message
254     SetTextureIdMessage( mEventThreadServices, *mSceneObject, 0 );
255   }
256   else
257   {
258     // tell image that we're using it
259     if (mConnectionCount > 0)
260     {
261       GetImplementation(mImage).Connect();
262     }
263     // mSceneShader can be in a separate thread; queue a setter message
264     SetTextureIdMessage( mEventThreadServices, *mSceneObject, GetImplementation(mImage).GetResourceId() );
265   }
266 }
267
268 void ShaderEffect::SetUniform( const std::string& name, Property::Value value, UniformCoordinateType uniformCoordinateType )
269 {
270   // Register the property if it does not exist
271   Property::Index index = GetPropertyIndex( name );
272   if ( Property::INVALID_INDEX == index )
273   {
274     index = RegisterProperty( name, value );
275   }
276
277   SetProperty( index, value );
278
279   // RegisterProperty guarantees a positive value as index
280   DALI_ASSERT_DEBUG( static_cast<unsigned int>(index) >= CustomPropertyStartIndex() );
281   unsigned int metaIndex = index - CustomPropertyStartIndex();
282   // check if there's space in cache
283   if( mCoordinateTypes.Count() < (metaIndex + 1) )
284   {
285     mCoordinateTypes.Resize( metaIndex + 1 );
286   }
287   // only send message if the value is different than current, initial value is COORDINATE_TYPE_DEFAULT (0)
288   if( uniformCoordinateType != mCoordinateTypes[ metaIndex ] )
289   {
290     mCoordinateTypes[ metaIndex ] = uniformCoordinateType;
291     SetCoordinateTypeMessage( mEventThreadServices, *mSceneObject, metaIndex, uniformCoordinateType );
292   }
293 }
294
295 void ShaderEffect::AttachExtension( Dali::ShaderEffect::Extension *extension )
296 {
297   DALI_ASSERT_ALWAYS( extension != NULL && "Attaching uninitialized extension" );
298   mExtension = IntrusivePtr<Dali::ShaderEffect::Extension>( extension );
299 }
300
301 Dali::ShaderEffect::Extension& ShaderEffect::GetExtension()
302 {
303   DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
304   return *mExtension;
305 }
306
307 const Dali::ShaderEffect::Extension& ShaderEffect::GetExtension() const
308 {
309   DALI_ASSERT_ALWAYS( mExtension && "Getting uninitialized extension" );
310   return *mExtension;
311 }
312
313 void ShaderEffect::SetPrograms( GeometryType geometryType, const string& vertexSource, const string& fragmentSource )
314 {
315   SetPrograms( geometryType, "", "", vertexSource, fragmentSource );
316 }
317
318 void ShaderEffect::SetPrograms( GeometryType geometryType,
319                                 const std::string& vertexPrefix, const std::string& fragmentPrefix,
320                                 const std::string& vertexSource, const std::string& fragmentSource )
321 {
322   bool modifiesGeometry = true;
323   // check if the vertex shader is empty (means it cannot modify geometry)
324   if( (vertexPrefix.length() == 0 )&&( vertexSource.length() == 0 ) )
325   {
326     modifiesGeometry = false;
327   }
328   // check the hint second
329   if( (mGeometryHints & Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY ) != 0 )
330   {
331     modifiesGeometry = false;
332   }
333
334   WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_IMAGE, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
335   WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_TEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
336   WrapAndSetProgram( *this, geometryType, GEOMETRY_TYPE_UNTEXTURED_MESH, vertexPrefix, fragmentPrefix, vertexSource, fragmentSource, modifiesGeometry );
337 }
338
339 void ShaderEffect::SendProgramMessage( GeometryType geometryType, ShaderSubTypes subType,
340                                        const string& vertexSource, const string& fragmentSource,
341                                        bool modifiesGeometry )
342 {
343   ThreadLocalStorage& tls = ThreadLocalStorage::Get();
344   ShaderFactory& shaderFactory = tls.GetShaderFactory();
345   size_t shaderHash;
346
347   ResourceTicketPtr ticket( shaderFactory.Load(vertexSource, fragmentSource, shaderHash) );
348
349   DALI_LOG_INFO( Debug::Filter::gShader, Debug::General, "ShaderEffect: SetProgram(geometryType %d subType:%d ticket.id:%d)\n", geometryType, subType, ticket->GetId() );
350
351   // Add shader program to scene-object using a message to the UpdateManager
352   SetShaderProgramMessage( mEventThreadServices.GetUpdateManager(), *mSceneObject, geometryType, subType, ticket->GetId(), shaderHash, modifiesGeometry );
353
354   mTickets.push_back(ticket);       // add ticket to collection to keep it alive.
355 }
356
357 void ShaderEffect::Connect()
358 {
359   ++mConnectionCount;
360
361   if (mImage && mConnectionCount == 1)
362   {
363     GetImplementation(mImage).Connect();
364
365     // Image may have changed resource due to load/release policy. Ensure correct texture ID is set on scene graph object
366     SetTextureIdMessage( mEventThreadServices, *mSceneObject, GetImplementation(mImage).GetResourceId() );
367   }
368 }
369
370 void ShaderEffect::Disconnect()
371 {
372   DALI_ASSERT_DEBUG(mConnectionCount > 0);
373   --mConnectionCount;
374
375   if (mImage && mConnectionCount == 0)
376   {
377      GetImplementation(mImage).Disconnect();
378   }
379 }
380
381 unsigned int ShaderEffect::GetDefaultPropertyCount() const
382 {
383   return DEFAULT_PROPERTY_COUNT;
384 }
385
386 void ShaderEffect::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const
387 {
388   indices.Reserve( DEFAULT_PROPERTY_COUNT );
389
390   for ( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
391   {
392     indices.PushBack( i );
393   }
394 }
395
396 const char* ShaderEffect::GetDefaultPropertyName(Property::Index index) const
397 {
398   if( index < DEFAULT_PROPERTY_COUNT )
399   {
400     return DEFAULT_PROPERTY_DETAILS[index].name;
401   }
402
403   return NULL;
404 }
405
406 Property::Index ShaderEffect::GetDefaultPropertyIndex(const std::string& name) const
407 {
408   Property::Index index = Property::INVALID_INDEX;
409
410   // Look for name in default properties
411   for( int i = 0; i < DEFAULT_PROPERTY_COUNT; ++i )
412   {
413     const Internal::PropertyDetails* property = &DEFAULT_PROPERTY_DETAILS[ i ];
414     if( 0 == strcmp( name.c_str(), property->name ) ) // dont want to convert rhs to string
415     {
416       index = i;
417       break;
418     }
419   }
420
421   return index;
422 }
423
424 bool ShaderEffect::IsDefaultPropertyWritable(Property::Index index) const
425 {
426   return DEFAULT_PROPERTY_DETAILS[ index ].writable;
427 }
428
429 bool ShaderEffect::IsDefaultPropertyAnimatable(Property::Index index) const
430 {
431   return DEFAULT_PROPERTY_DETAILS[ index ].animatable;
432 }
433
434 bool ShaderEffect::IsDefaultPropertyAConstraintInput( Property::Index index ) const
435 {
436   return DEFAULT_PROPERTY_DETAILS[ index ].constraintInput;
437 }
438
439 Property::Type ShaderEffect::GetDefaultPropertyType(Property::Index index) const
440 {
441   if( index < DEFAULT_PROPERTY_COUNT )
442   {
443     return DEFAULT_PROPERTY_DETAILS[index].type;
444   }
445
446   // index out of range...return Property::NONE
447   return Property::NONE;
448 }
449
450 void ShaderEffect::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue )
451 {
452   switch ( index )
453   {
454     case Dali::ShaderEffect::Property::GRID_DENSITY:
455     {
456       SetGridDensityMessage( mEventThreadServices, *mSceneObject, propertyValue.Get<float>() );
457       break;
458     }
459
460     case Dali::ShaderEffect::Property::IMAGE:
461     {
462       Dali::Image img(Scripting::NewImage( propertyValue ));
463       if(img)
464       {
465         SetEffectImage( img );
466       }
467       else
468       {
469         DALI_LOG_WARNING("Cannot create image from property value for ShaderEffect image\n");
470       }
471       break;
472     }
473
474     case Dali::ShaderEffect::Property::PROGRAM:
475     {
476       std::string vertexPrefix   = GetShader("vertex-prefix", propertyValue);
477       std::string fragmentPrefix = GetShader("fragment-prefix", propertyValue);
478       std::string vertex         = GetShader("vertex", propertyValue);
479       std::string fragment       = GetShader("fragment", propertyValue);
480
481       GeometryType geometryType      = GEOMETRY_TYPE_IMAGE; // only images are supported
482       SetPrograms( geometryType, vertexPrefix, fragmentPrefix, vertex, fragment );
483       break;
484     }
485
486     case Dali::ShaderEffect::Property::GEOMETRY_HINTS:
487     {
488       Dali::ShaderEffect::GeometryHints hint = Dali::ShaderEffect::HINT_NONE;
489       std::string s = propertyValue.Get<std::string>();
490       if(s == "HINT_NONE")
491       {
492         hint = Dali::ShaderEffect::HINT_NONE;
493       }
494       else if(s == "HINT_GRID_X")
495       {
496         hint = Dali::ShaderEffect::HINT_GRID_X;
497       }
498       else if(s == "HINT_GRID_Y")
499       {
500         hint = Dali::ShaderEffect::HINT_GRID_Y;
501       }
502       else if(s == "HINT_GRID")
503       {
504         hint = Dali::ShaderEffect::HINT_GRID;
505       }
506       else if(s == "HINT_DEPTH_BUFFER")
507       {
508         hint = Dali::ShaderEffect::HINT_DEPTH_BUFFER;
509       }
510       else if(s == "HINT_BLENDING")
511       {
512         hint = Dali::ShaderEffect::HINT_BLENDING;
513       }
514       else if(s == "HINT_DOESNT_MODIFY_GEOMETRY")
515       {
516         hint = Dali::ShaderEffect::HINT_DOESNT_MODIFY_GEOMETRY;
517       }
518       else
519       {
520         DALI_ASSERT_ALWAYS(!"Geometry hint unknown" );
521       }
522
523       SetHintsMessage( mEventThreadServices, *mSceneObject, hint );
524
525       break;
526     }
527
528     default:
529     {
530       // nothing to do
531       break;
532     }
533   }
534 }
535
536 Property::Value ShaderEffect::GetDefaultProperty(Property::Index /*index*/) const
537 {
538   // none of our properties are readable so return empty
539   return Property::Value();
540 }
541
542 void ShaderEffect::NotifyScenePropertyInstalled( const SceneGraph::PropertyBase& newProperty, const std::string& name, unsigned int index ) const
543 {
544   // 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)
545
546   // mSceneObject requires metadata for each custom property (uniform)
547   UniformMeta* meta = UniformMeta::New( name, newProperty, Dali::ShaderEffect::COORDINATE_TYPE_DEFAULT );
548   // mSceneObject is being used in a separate thread; queue a message to add the property
549   InstallUniformMetaMessage( mEventThreadServices, *mSceneObject, *meta ); // Message takes ownership
550 }
551
552 const SceneGraph::PropertyOwner* ShaderEffect::GetSceneObject() const
553 {
554   return mSceneObject;
555 }
556
557 const PropertyBase* ShaderEffect::GetSceneObjectAnimatableProperty( Property::Index index ) const
558 {
559   PropertyMetadata* property = index >= PROPERTY_CUSTOM_START_INDEX ? static_cast<PropertyMetadata*>(FindCustomProperty( index )) : static_cast<PropertyMetadata*>(FindAnimatableProperty( index ));
560   DALI_ASSERT_ALWAYS( property && "Property index is invalid" );
561   return property->GetSceneGraphProperty();
562 }
563
564 const PropertyInputImpl* ShaderEffect::GetSceneObjectInputProperty( Property::Index index ) const
565 {
566   return GetSceneObjectAnimatableProperty( index );
567 }
568
569 } // namespace Internal
570
571 } // namespace Dali