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