Merge branch 'tizen' into devel/new_mesh
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / public-api / shader-effects / motion-blur-effect.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-toolkit/public-api/shader-effects/motion-blur-effect.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/animation/active-constraint.h>
23 #include <dali/public-api/animation/constraint.h>
24 #include <dali/public-api/animation/constraints.h>
25 #include <dali/public-api/actors/image-actor.h>
26
27 namespace Dali
28 {
29
30 namespace Toolkit
31 {
32
33 namespace
34 {
35
36 const std::string MOTION_BLUR_TEXCOORD_SCALE_PROPERTY_NAME( "uBlurTexCoordScale" );
37 const std::string MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR_PROPERTY_NAME( "uGeometryStretchFactor" );
38 const std::string MOTION_BLUR_SPEED_SCALING_FACTOR_PROPERTY_NAME( "uSpeedScalingFactor" );
39 const std::string MOTION_BLUR_OBJECT_FADE_START_PROPERTY_NAME( "uObjectFadeStart" );
40 const std::string MOTION_BLUR_OBJECT_FADE_END_PROPERTY_NAME( "uObjectFadeEnd" );
41 const std::string MOTION_BLUR_ALPHA_SCALE_PROPERTY_NAME( "uAlphaScale" );
42 const std::string MOTION_BLUR_NUM_SAMPLES_NAME( "uNumSamples" );
43 const std::string MOTION_BLUR_RECIP_NUM_SAMPLES_NAME( "uRecipNumSamples" );
44 const std::string MOTION_BLUR_RECIP_NUM_SAMPLES_MINUS_ONE_NAME( "uRecipNumSamplesMinusOne" );
45 const std::string MOTION_BLUR_MODEL_LASTFRAME( "uModelLastFrame" );  ///< Matrix
46
47 ////////////////////////////////////////////////////
48 //
49 // Motion blur shader / actor tweaking parameters
50 //
51
52 const unsigned int MOTION_BLUR_NUM_SAMPLES = 8;
53
54 // half width and half height respectively of actor, corresponding to values in vertex attribute stream
55 // TODO: Note that these values work for normal image actor (verts +/- 0.5) but a grid or a nine square seems to have verts in pixel space (e.g. 256,256). Need to fix this somehow,
56 // either in Dali or by passing uniforms which we can use to 'normalise' the verts in the vertex shader
57 const Vector2 MOTION_BLUR_ACTOR_VERTEX( 0.5f, 0.5f );
58
59 const float MOTION_BLUR_TEXCOORD_SCALE = 0.125f;             // stretch texture reads along velocity vector, larger number means reads spaced further apart
60 const float MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR = 0.05f; // scaling factor for how much to stretch actor geom as it moves
61 const float MOTION_BLUR_SPEED_SCALING_FACTOR = 0.5f;         // scales the speed, producing a number affecting how much the actor blurs & fades at the edges
62
63 const Vector2 MOTION_BLUR_OBJECT_FADE_END( MOTION_BLUR_ACTOR_VERTEX );             // distance from center at which actor fully fades to zero alpha
64 const Vector2 MOTION_BLUR_OBJECT_FADE_START( MOTION_BLUR_OBJECT_FADE_END * 0.5f ); // distance from center at which actor start to fade from full alpha
65
66 const float MOTION_BLUR_ALPHA_SCALE = 0.75f; // global scaler applied to actor alpha as it is blurred + moving
67
68 } // namespace
69
70
71 MotionBlurEffect::MotionBlurEffect()
72 {
73 }
74
75 //Call the Parent copy constructor to add reference to the implementation for this object
76 MotionBlurEffect::MotionBlurEffect( ShaderEffect handle )
77 :ShaderEffect( handle )
78 {
79 }
80
81 MotionBlurEffect::~MotionBlurEffect()
82 {
83 }
84
85 MotionBlurEffect MotionBlurEffect::Apply( RenderableActor renderable )
86 {
87   MotionBlurEffect newEffect = New( MOTION_BLUR_NUM_SAMPLES );
88   ImageActor imageActor = ImageActor::DownCast(renderable);
89   if( imageActor )
90   {
91     imageActor.SetShaderEffect( newEffect );
92   }
93
94   Dali::Property::Index uModelProperty = newEffect.GetPropertyIndex( MOTION_BLUR_MODEL_LASTFRAME );
95
96   Constraint constraint = Constraint::New<Matrix>( uModelProperty,
97                                                    Source( renderable, Actor::Property::WORLD_MATRIX ),
98                                                    EqualToConstraint() );
99
100   // and set up constraint.
101   newEffect.ApplyConstraint( constraint );
102   return newEffect;
103 }
104
105 MotionBlurEffect MotionBlurEffect::New()
106 {
107   return New( MOTION_BLUR_NUM_SAMPLES );
108 }
109
110 MotionBlurEffect MotionBlurEffect::New( unsigned int numBlurSamples )
111 {
112   // Dali vertexSource prefix for reference:
113   // precision highp float;
114   // attribute vec3  aPosition;
115   // attribute vec2  aTexCoord;
116   // uniform   mat4  uMvpMatrix;
117   // uniform   mat4  uModelView;
118   // uniform   mat3  uNormalMatrix;
119   // uniform   mat4  uProjection;
120   // uniform   vec4  uColor;
121   // varying   vec2  vTexCoord;
122   std::string vertexSource;
123   vertexSource =
124     "precision mediump float;\n"
125     "uniform mat4 uModelLastFrame;\n"
126     "uniform float uTimeDelta;\n"
127
128     "uniform float uGeometryStretchFactor;\n"
129     "uniform float uSpeedScalingFactor;\n"
130
131     // outputs
132     "varying vec2 vModelSpaceCenterToPos;\n"
133     "varying vec2 vScreenSpaceVelocityVector;\n"
134     "varying float vSpeed;\n"
135
136     "void main()\n"
137     "{\n"
138     // get view space position of vertex this frame and last frame
139     " vec4 vertex = vec4(aPosition, 1.0);\n"
140     " vec4 viewSpaceVertex = uModelView * vertex;\n"
141     " vec4 viewSpaceVertexLastFrame = (uViewMatrix * uModelLastFrame) * vertex;\n"
142     " float reciprocalTimeDelta = 1.0 / ((uTimeDelta > 0.0) ? uTimeDelta : 0.01);\n"
143
144     // work out vertex's last movement in view space
145     " vec3 viewSpacePosDelta = viewSpaceVertex.xyz - viewSpaceVertexLastFrame.xyz;\n"
146
147     // get clip space position of vertex this frame and last frame
148     " vec4 clipSpaceVertex = uMvpMatrix * vertex;\n"
149     " vec4 clipSpaceVertexLastFrame = uProjection * viewSpaceVertexLastFrame;\n"
150
151     // decide how much this vertex is 'trailing', i.e. at the back of the object relative to its direction of motion. We do this
152     // by assuming the objects model space origin is at its center and taking the dot product of the vector from center to vertex with the motion direction
153     " float t = 0.0;\n"
154     " float posDeltaLength = length(viewSpacePosDelta);\n"
155     " if(posDeltaLength > 0.001)\n" // avoid div by 0 if object has barely moved
156     " {\n"
157     "   vec4 viewSpaceCenterToPos = uModelView * vec4(aPosition, 0.0);\n"
158     "   float centerToVertexDist = length(viewSpaceCenterToPos);\n"
159     "   if(centerToVertexDist > 0.001)\n" // avoid div by 0 if object has vertex at model space origin
160     "   {\n"
161     "     vec3 viewSpacePosDeltaNormalised = viewSpacePosDelta / posDeltaLength;\n"
162     "     vec3 viewSpaceCenterToPosNormalised = viewSpaceCenterToPos.xyz / centerToVertexDist;\n"
163     "     t = (dot(viewSpacePosDeltaNormalised, viewSpaceCenterToPosNormalised) * 0.5 ) + 0.5;\n" // scale and bias from [-1..1] to [0..1]
164     "   }\n"
165     " }\n"
166     // output vertex position lerped with its last position, based on how much it is trailing,
167     // this stretches the geom back along where it has just been, giving a warping effect
168     // Note: we must take account of time delta to convert position delta into a velocity, so changes are smooth (take into account frame time correctly)
169     " gl_Position = mix(clipSpaceVertexLastFrame, clipSpaceVertex, t * uGeometryStretchFactor * reciprocalTimeDelta);\n"
170
171     // work out vertex's last movement in normalised device coordinates [-1..1] space, i.e. perspective divide
172     " vec2 ndcVertex = clipSpaceVertex.xy / clipSpaceVertex.w;\n"
173     " vec2 ndcVertexLastFrame = clipSpaceVertexLastFrame.xy / clipSpaceVertexLastFrame.w;\n"
174     // scale and bias so that a value of 1.0 corresponds to screen size (NDC is [-1..1] = 2)
175     " vScreenSpaceVelocityVector = ((ndcVertex - ndcVertexLastFrame) * 0.5 * reciprocalTimeDelta);\n"
176     " vScreenSpaceVelocityVector.y = -vScreenSpaceVelocityVector.y;\n" // TODO negated due to y being inverted in our coordinate system?
177     // calculate a scaling factor proportional to velocity, which we can use to tweak how things look
178     " vSpeed = length(vScreenSpaceVelocityVector) * uSpeedScalingFactor;\n"
179     " vSpeed = clamp(vSpeed, 0.0, 1.0);\n"
180
181     // provide fragment shader with vector from center of object to pixel (assumes the objects model space origin is at its center and verts have same z)
182     " vModelSpaceCenterToPos = aPosition.xy;\n"
183
184     " vTexCoord = aTexCoord;\n"
185     "}\n";
186
187
188   // Dali fragmentSource prefix for reference:
189   // precision highp     float;
190   // uniform   sampler2D sTexture;
191   // uniform   sampler2D sEffect;
192   // uniform   vec4      uColor;
193   // varying   vec2      vTexCoord;
194   std::string fragmentSource;
195   fragmentSource =
196     "precision mediump float;\n"
197     "uniform vec2 uObjectFadeStart;\n"
198     "uniform vec2 uObjectFadeEnd;\n"
199     "uniform float uAlphaScale;\n"
200     "uniform float uBlurTexCoordScale;\n"
201     "uniform float uNumSamples;\n"
202     "uniform float uRecipNumSamples;\n"
203     "uniform float uRecipNumSamplesMinusOne;\n"
204     // inputs
205     "varying vec2 vModelSpaceCenterToPos;\n"
206     "varying vec2 vScreenSpaceVelocityVector;\n"
207     "varying float vSpeed;\n"
208
209     "void main()\n"
210     "{\n"
211     // calculate an alpha value that will fade the object towards its extremities, we need this to avoid an unsightly hard edge between color values of
212     // the blurred object and the unblurred background. Use smoothstep also to hide any hard edges (discontinuities) in rate of change of this alpha gradient
213     " vec2 centerToPixel = abs(vModelSpaceCenterToPos);\n"
214     " vec2 fadeToEdges = smoothstep(0.0, 1.0, 1.0 - ((centerToPixel - uObjectFadeStart) / (uObjectFadeEnd - uObjectFadeStart)));\n"
215     " float fadeToEdgesScale = fadeToEdges.x * fadeToEdges.y * uAlphaScale;\n" // apply global scaler
216     " fadeToEdgesScale = mix(1.0, fadeToEdgesScale, vSpeed);\n" // fade proportional to speed, so opaque when at rest
217
218     // scale velocity vector by user requirements
219     " vec2 velocity = vScreenSpaceVelocityVector * uBlurTexCoordScale;\n"
220
221     // standard actor texel
222     " vec4 colActor = texture2D(sTexture, vTexCoord);\n"
223
224     // blurred actor - gather texture samples from the actor texture in the direction of motion
225     " vec4 col = colActor * uRecipNumSamples;\n"
226     " for(float i = 1.0; i < uNumSamples; i += 1.0)\n"
227     " {\n"
228     "   float t = i * uRecipNumSamplesMinusOne;\n"
229     "   col += texture2D(sTexture, vTexCoord + (velocity * t)) * uRecipNumSamples;\n"
230     " }\n"
231     " gl_FragColor = mix(colActor, col, vSpeed);\n" // lerp blurred and non-blurred actor based on speed of motion
232     " gl_FragColor.a = colActor.a * fadeToEdgesScale;\n" // fade blurred actor to its edges based on speed of motion
233     " gl_FragColor *= uColor;\n"
234     "}\n";
235
236   // NOTE: we must turn on alpha blending for the actor (HINT_BLENDING)
237   ShaderEffect shader = ShaderEffect::New( vertexSource, fragmentSource,
238                                            GEOMETRY_TYPE_IMAGE,
239                                            ShaderEffect::GeometryHints( ShaderEffect::HINT_BLENDING | ShaderEffect::HINT_GRID) );
240
241   MotionBlurEffect handle( shader );
242
243
244   //////////////////////////////////////
245   // Register uniform properties
246   //
247   //
248
249   // factors that scale the look, defaults
250   handle.SetUniform( MOTION_BLUR_TEXCOORD_SCALE_PROPERTY_NAME, MOTION_BLUR_TEXCOORD_SCALE );
251   handle.SetUniform( MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR_PROPERTY_NAME, MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR );
252   handle.SetUniform( MOTION_BLUR_SPEED_SCALING_FACTOR_PROPERTY_NAME, MOTION_BLUR_SPEED_SCALING_FACTOR );
253   handle.SetUniform( MOTION_BLUR_OBJECT_FADE_START_PROPERTY_NAME, MOTION_BLUR_OBJECT_FADE_START );
254   handle.SetUniform( MOTION_BLUR_OBJECT_FADE_END_PROPERTY_NAME, MOTION_BLUR_OBJECT_FADE_END );
255   handle.SetUniform( MOTION_BLUR_ALPHA_SCALE_PROPERTY_NAME, MOTION_BLUR_ALPHA_SCALE );
256   handle.SetUniform( MOTION_BLUR_NUM_SAMPLES_NAME, static_cast<float>( MOTION_BLUR_NUM_SAMPLES ) );
257   handle.SetUniform( MOTION_BLUR_RECIP_NUM_SAMPLES_NAME, 1.0f / static_cast<float>( MOTION_BLUR_NUM_SAMPLES ) );
258   handle.SetUniform( MOTION_BLUR_RECIP_NUM_SAMPLES_MINUS_ONE_NAME, 1.0f / static_cast<float>( MOTION_BLUR_NUM_SAMPLES - 1.0f ) );
259   handle.SetUniform( MOTION_BLUR_MODEL_LASTFRAME, Matrix::IDENTITY );
260
261   return handle;
262 }
263
264 MotionBlurEffect MotionBlurEffect::DownCast( ShaderEffect shaderEffect )
265 {
266   MotionBlurEffect handle = shaderEffect;
267   return handle;
268 }
269
270 void MotionBlurEffect::SetNumSamples( int numSamples )
271 {
272   SetUniform( MOTION_BLUR_NUM_SAMPLES_NAME, static_cast<float>( numSamples ) );
273   SetUniform( MOTION_BLUR_RECIP_NUM_SAMPLES_NAME, 1.0f / static_cast<float>( numSamples ) );
274   SetUniform( MOTION_BLUR_RECIP_NUM_SAMPLES_MINUS_ONE_NAME, 1.0f / static_cast<float>( numSamples - 1.0f ) );
275 }
276
277 void MotionBlurEffect::SetTexcoordScale( float texcoordScale )
278 {
279   SetUniform( MOTION_BLUR_TEXCOORD_SCALE_PROPERTY_NAME, texcoordScale );
280 }
281
282 void MotionBlurEffect::SetGeometryStretchFactor( float scalingFactor )
283 {
284   SetUniform( MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR_PROPERTY_NAME, scalingFactor );
285 }
286
287 void MotionBlurEffect::SetSpeedScalingFactor( float scalingFactor )
288 {
289   SetUniform( MOTION_BLUR_SPEED_SCALING_FACTOR_PROPERTY_NAME, scalingFactor );
290 }
291
292 void MotionBlurEffect::SetObjectFadeStart( Vector2 displacement )
293 {
294   SetUniform( MOTION_BLUR_OBJECT_FADE_START_PROPERTY_NAME, displacement );
295 }
296
297 void MotionBlurEffect::SetObjectFadeEnd( Vector2 displacement )
298 {
299   SetUniform( MOTION_BLUR_OBJECT_FADE_END_PROPERTY_NAME, displacement );
300 }
301
302 void MotionBlurEffect::SetAlphaScale( float alphaScale )
303 {
304   SetUniform( MOTION_BLUR_ALPHA_SCALE_PROPERTY_NAME, alphaScale );
305 }
306
307 const std::string& MotionBlurEffect::GetTexcoordScalePropertyName() const
308 {
309   return MOTION_BLUR_TEXCOORD_SCALE_PROPERTY_NAME;
310 }
311
312 const std::string& MotionBlurEffect::GetGeometryStretchFactorPropertyName() const
313 {
314   return MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR_PROPERTY_NAME;
315 }
316
317 const std::string& MotionBlurEffect::GetSpeedScalingFactorPropertyName() const
318 {
319   return MOTION_BLUR_SPEED_SCALING_FACTOR_PROPERTY_NAME;
320 }
321
322 const std::string& MotionBlurEffect::GetObjectFadeStartPropertyName() const
323 {
324   return MOTION_BLUR_OBJECT_FADE_START_PROPERTY_NAME;
325 }
326
327 const std::string& MotionBlurEffect::GetObjectFadeEndPropertyName() const
328 {
329   return MOTION_BLUR_OBJECT_FADE_END_PROPERTY_NAME;
330 }
331
332 const std::string& MotionBlurEffect::GetAlphaScalePropertyName() const
333 {
334   return MOTION_BLUR_ALPHA_SCALE_PROPERTY_NAME;
335 }
336
337 }
338
339 }