2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <dali/dali.h>
19 #include <dali-toolkit/dali-toolkit.h>
20 #include "shared/view.h"
30 const char * const APPLICATION_TITLE( "Refraction Effect" );
31 const char * const TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
32 const char * const CHANGE_TEXTURE_ICON( DALI_IMAGE_DIR "icon-change.png" );
33 const char * const CHANGE_MESH_ICON( DALI_IMAGE_DIR "icon-replace.png" );
35 const char* MESH_FILES[] =
37 DALI_MODEL_DIR "surface_pattern_v01.obj",
38 DALI_MODEL_DIR "surface_pattern_v02.obj"
40 const unsigned int NUM_MESH_FILES( sizeof( MESH_FILES ) / sizeof( MESH_FILES[0] ) );
42 const char* TEXTURE_IMAGES[]=
44 DALI_IMAGE_DIR "background-1.jpg",
45 DALI_IMAGE_DIR "background-2.jpg",
46 DALI_IMAGE_DIR "background-3.jpg",
47 DALI_IMAGE_DIR "background-4.jpg"
49 const unsigned int NUM_TEXTURE_IMAGES( sizeof( TEXTURE_IMAGES ) / sizeof( TEXTURE_IMAGES[0] ) );
51 struct LightOffsetConstraint
53 LightOffsetConstraint( float radius )
58 void operator()( Vector2& current, const PropertyInputContainer& inputs )
60 float spinAngle = inputs[0]->GetFloat();
61 current.x = cos( spinAngle );
62 current.y = sin( spinAngle );
71 * @brief Load an image, scaled-down to no more than the stage dimensions.
73 * Uses image scaling mode SCALE_TO_FILL to resize the image at
74 * load time to cover the entire stage with pixels with no borders,
75 * and filter mode BOX_THEN_LINEAR to sample the image with maximum quality.
77 ResourceImage LoadStageFillingImage( const char * const imagePath )
79 Size stageSize = Stage::GetCurrent().GetSize();
80 return ResourceImage::New( imagePath, ImageDimensions( stageSize.x, stageSize.y ), Dali::FittingMode::SCALE_TO_FILL, Dali::SamplingMode::BOX_THEN_LINEAR );
84 * structure of the vertex in the mesh
95 Vertex( const Vector3& position, const Vector3& normal, const Vector2& textureCoord )
96 : position( position ), normal( normal ), textureCoord( textureCoord )
100 /************************************************************************************************
101 *** The shader source is used when the MeshActor is not touched***
102 ************************************************************************************************/
103 const char* VERTEX_SHADER_FLAT = DALI_COMPOSE_SHADER(
104 attribute mediump vec3 aPosition;\n
105 attribute mediump vec3 aNormal;\n
106 attribute highp vec2 aTexCoord;\n
107 uniform mediump mat4 uMvpMatrix;\n
108 varying mediump vec2 vTexCoord;\n
111 gl_Position = uMvpMatrix * vec4( aPosition.xy, 0.0, 1.0 );\n
112 vTexCoord = aTexCoord.xy;\n
116 const char* FRAGMENT_SHADER_FLAT = DALI_COMPOSE_SHADER(
117 uniform lowp vec4 uColor;\n
118 uniform sampler2D sTexture;\n
119 varying mediump vec2 vTexCoord;\n
122 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
126 /************************************************************
127 ** Custom refraction effect shader***************************
128 ************************************************************/
129 const char* VERTEX_SHADER_REFRACTION = DALI_COMPOSE_SHADER(
130 attribute mediump vec3 aPosition;\n
131 attribute mediump vec3 aNormal;\n
132 attribute highp vec2 aTexCoord;\n
133 uniform mediump mat4 uMvpMatrix;\n
134 varying mediump vec4 vVertex;\n
135 varying mediump vec3 vNormal;\n
136 varying mediump vec2 vTexCoord;\n
137 varying mediump vec2 vTextureOffset;\n
140 gl_Position = uMvpMatrix * vec4( aPosition.xy, 0.0, 1.0 );\n
141 vTexCoord = aTexCoord.xy;\n
144 vVertex = vec4( aPosition, 1.0 );\n
145 float length = max(0.01, length(aNormal.xy)) * 40.0;\n
146 vTextureOffset = aNormal.xy / length;\n
150 const char* FRAGMENT_SHADER_REFRACTION = DALI_COMPOSE_SHADER(
151 precision mediump float;\n
152 uniform mediump float uEffectStrength;\n
153 uniform mediump vec3 uLightPosition;\n
154 uniform mediump vec2 uLightXYOffset;\n
155 uniform mediump vec2 uLightSpinOffset;\n
156 uniform mediump float uLightIntensity;\n
157 uniform lowp vec4 uColor;\n
158 uniform sampler2D sTexture;\n
159 varying mediump vec4 vVertex;\n
160 varying mediump vec3 vNormal;\n
161 varying mediump vec2 vTexCoord;\n
162 varying mediump vec2 vTextureOffset;\n
164 vec3 rgb2hsl(vec3 rgb)\n
166 float epsilon = 1.0e-10;\n
167 vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n
168 vec4 P = mix(vec4(rgb.bg, K.wz), vec4(rgb.gb, K.xy), step(rgb.b, rgb.g));\n
169 vec4 Q = mix(vec4(P.xyw, rgb.r), vec4(rgb.r, P.yzx), step(P.x, rgb.r));\n
173 float chroma = Q.x - min(Q.w, Q.y);\n
174 float hue = abs(Q.z + (Q.w-Q.y) / (6.0*chroma+epsilon));\n
176 float lightness = value - chroma*0.5;\n
177 return vec3( hue, chroma/max( 1.0-abs(lightness*2.0-1.0), 1.0e-1 ), lightness );\n
180 vec3 hsl2rgb( vec3 hsl )\n
183 vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n
184 vec3 p = abs(fract(hsl.xxx + K.xyz) * 6.0 - K.www);\n
185 vec3 RGB = clamp(p - K.xxx, 0.0, 1.0);\n
187 float chroma = ( 1.0 - abs( hsl.z*2.0-1.0 ) ) * hsl.y;\n
188 return ( RGB - 0.5 ) * chroma + hsl.z;\n
193 vec3 normal = normalize( vNormal);\n
195 vec3 lightPosition = uLightPosition + vec3(uLightXYOffset+uLightSpinOffset, 0.0);\n
196 mediump vec3 vecToLight = normalize( (lightPosition - vVertex.xyz) * 0.01 );\n
197 mediump float spotEffect = pow( max(0.05, vecToLight.z ) - 0.05, 8.0);\n
199 spotEffect = spotEffect * uEffectStrength;\n
200 mediump float lightDiffuse = ( ( dot( vecToLight, normal )-0.75 ) *uLightIntensity ) * spotEffect;\n
202 lowp vec4 color = texture2D( sTexture, vTexCoord + vTextureOffset * spotEffect );\n
203 vec3 lightedColor = hsl2rgb( rgb2hsl(color.rgb) + vec3(0.0,0.0,lightDiffuse) );\n
205 gl_FragColor = vec4( lightedColor, color.a ) * uColor;\n
212 /*************************************************/
213 /*Demo using RefractionEffect*****************/
214 /*************************************************/
215 class RefractionEffectExample : public ConnectionTracker
218 RefractionEffectExample( Application &application )
219 : mApplication( application ),
220 mCurrentTextureId( 1 ),
223 // Connect to the Application's Init signal
224 application.InitSignal().Connect(this, &RefractionEffectExample::Create);
227 ~RefractionEffectExample()
233 // The Init signal is received once (only) during the Application lifetime
234 void Create(Application& application)
236 Stage stage = Stage::GetCurrent();
237 Vector2 stageSize = stage.GetSize();
239 stage.KeyEventSignal().Connect(this, &RefractionEffectExample::OnKeyEvent);
241 // Creates a default view with a default tool bar.
242 // The view is added to the stage.
243 Toolkit::ToolBar toolBar;
244 Toolkit::Control view;
245 mContent = DemoHelper::CreateView( application,
252 // Add a button to change background. (right of toolbar)
253 mChangeTextureButton = Toolkit::PushButton::New();
254 mChangeTextureButton.SetBackgroundImage( ResourceImage::New( CHANGE_TEXTURE_ICON ) );
255 mChangeTextureButton.ClickedSignal().Connect( this, &RefractionEffectExample::OnChangeTexture );
256 toolBar.AddControl( mChangeTextureButton,
257 DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage,
258 Toolkit::Alignment::HorizontalRight,
259 DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
260 // Add a button to change mesh pattern. ( left of bar )
261 mChangeMeshButton = Toolkit::PushButton::New();
262 mChangeMeshButton.SetBackgroundImage( ResourceImage::New( CHANGE_MESH_ICON ) );
263 mChangeMeshButton.ClickedSignal().Connect( this, &RefractionEffectExample::OnChangeMesh );
264 toolBar.AddControl( mChangeMeshButton,
265 DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage,
266 Toolkit::Alignment::HorizontalLeft,
267 DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
271 // shader used when the screen is not touched, render a flat surface
272 mShaderFlat = Shader::New( VERTEX_SHADER_FLAT, FRAGMENT_SHADER_FLAT );
273 mGeometry = CreateGeometry( MESH_FILES[mCurrentMeshId] );
275 Image texture = LoadStageFillingImage( TEXTURE_IMAGES[mCurrentTextureId] );
276 mSampler = Sampler::New( texture, "sTexture" );
277 mMaterial = Material::New( mShaderFlat );
278 mMaterial.AddSampler( mSampler );
280 mRenderer = Renderer::New( mGeometry, mMaterial );
282 mMeshActor = Actor::New();
283 mMeshActor.AddRenderer( mRenderer );
284 mMeshActor.SetSize( stageSize );
285 mMeshActor.SetParentOrigin(ParentOrigin::CENTER);
286 mContent.Add( mMeshActor );
288 // Connect the callback to the touch signal on the mesh actor
289 mContent.TouchedSignal().Connect( this, &RefractionEffectExample::OnTouch );
291 // shader used when the finger is touching the screen. render refraction effect
292 mShaderRefraction = Shader::New( VERTEX_SHADER_REFRACTION, FRAGMENT_SHADER_REFRACTION );
295 mLightXYOffsetIndex = mMeshActor.RegisterProperty( "uLightXYOffset", Vector2::ZERO );
297 mLightIntensityIndex = mMeshActor.RegisterProperty( "uLightIntensity", 2.5f );
299 mEffectStrengthIndex = mMeshActor.RegisterProperty( "uEffectStrength", 0.f );
301 Vector3 lightPosition( -stageSize.x*0.5f, -stageSize.y*0.5f, stageSize.x*0.5f ); // top_left
302 mMeshActor.RegisterProperty( "uLightPosition", lightPosition );
304 Property::Index lightSpinOffsetIndex = mMeshActor.RegisterProperty( "uLightSpinOffset", Vector2::ZERO );
306 mSpinAngleIndex = mMeshActor.RegisterProperty("uSpinAngle", 0.f );
307 Constraint constraint = Constraint::New<Vector2>( mMeshActor, lightSpinOffsetIndex, LightOffsetConstraint(stageSize.x*0.1f) );
308 constraint.AddSource( LocalSource(mSpinAngleIndex) );
311 // the animation which spin the light around the finger touch position
312 mLightAnimation = Animation::New(2.f);
313 mLightAnimation.AnimateTo( Property( mMeshActor, mSpinAngleIndex ), Math::PI*2.f );
314 mLightAnimation.SetLooping( true );
315 mLightAnimation.Pause();
318 void SetLightXYOffset( const Vector2& offset )
320 mMeshActor.SetProperty( mLightXYOffsetIndex, offset );
324 * Create a mesh actor with different geometry to replace the current one
326 bool OnChangeMesh( Toolkit::Button button )
328 mCurrentMeshId = ( mCurrentMeshId + 1 ) % NUM_MESH_FILES;
329 mGeometry = CreateGeometry( MESH_FILES[mCurrentMeshId] );
330 mRenderer.SetGeometry( mGeometry );
335 bool OnChangeTexture( Toolkit::Button button )
337 mCurrentTextureId = ( mCurrentTextureId + 1 ) % NUM_TEXTURE_IMAGES;
338 Image texture = LoadStageFillingImage( TEXTURE_IMAGES[mCurrentTextureId] );
339 mSampler.SetImage( texture );
343 bool OnTouch( Actor actor , const TouchEvent& event )
345 const TouchPoint &point = event.GetPoint(0);
348 case TouchPoint::Down:
350 mMaterial.SetShader( mShaderRefraction );
352 SetLightXYOffset( point.screen );
354 mLightAnimation.Play();
356 if( mStrenghAnimation )
358 mStrenghAnimation.Clear();
361 mStrenghAnimation= Animation::New(0.5f);
362 mStrenghAnimation.AnimateTo( Property( mMeshActor, mEffectStrengthIndex ), 1.f );
363 mStrenghAnimation.Play();
367 case TouchPoint::Motion:
369 // make the light position following the finger movement
370 SetLightXYOffset( point.screen );
374 case TouchPoint::Leave:
375 case TouchPoint::Interrupted:
377 mLightAnimation.Pause();
379 if( mStrenghAnimation )
381 mStrenghAnimation.Clear();
383 mStrenghAnimation = Animation::New(0.5f);
384 mStrenghAnimation.AnimateTo( Property( mMeshActor, mEffectStrengthIndex ), 0.f );
385 mStrenghAnimation.FinishedSignal().Connect( this, &RefractionEffectExample::OnTouchFinished );
386 mStrenghAnimation.Play();
389 case TouchPoint::Stationary:
390 case TouchPoint::Last:
400 void OnTouchFinished( Animation& source )
402 mMaterial.SetShader( mShaderFlat );
403 SetLightXYOffset( Vector2::ZERO );
406 Geometry CreateGeometry(const std::string& objFileName)
408 std::vector<Vector3> vertexPositions;
409 Vector<unsigned int> faceIndices;
410 Vector<float> boundingBox;
411 // read the vertice and faces from the .obj file, and record the bounding box
412 ReadObjFile( objFileName, boundingBox, vertexPositions, faceIndices );
414 std::vector<Vector2> textureCoordinates;
415 // align the mesh, scale it to fit the screen size, and calculate the texture coordinate for each vertex
416 ShapeResizeAndTexureCoordinateCalculation( boundingBox, vertexPositions, textureCoordinates );
418 // re-organize the mesh, the vertices are duplicated, each vertex only belongs to one triangle.
419 // Without sharing vertex between triangle, so we can manipulate the texture offset on each triangle conveniently.
420 std::vector<Vertex> vertices;
422 std::size_t size = faceIndices.Size();
423 vertices.reserve( size );
425 for( std::size_t i=0; i<size; i=i+3 )
427 Vector3 edge1 = vertexPositions[ faceIndices[i+2] ] - vertexPositions[ faceIndices[i] ];
428 Vector3 edge2 = vertexPositions[ faceIndices[i+1] ] - vertexPositions[ faceIndices[i] ];
429 Vector3 normal = edge1.Cross(edge2);
432 // make sure all the faces are front-facing
435 vertices.push_back( Vertex( vertexPositions[ faceIndices[i] ], normal, textureCoordinates[ faceIndices[i] ] ) );
436 vertices.push_back( Vertex( vertexPositions[ faceIndices[i+1] ], normal, textureCoordinates[ faceIndices[i+1] ] ) );
437 vertices.push_back( Vertex( vertexPositions[ faceIndices[i+2] ], normal, textureCoordinates[ faceIndices[i+2] ] ) );
442 vertices.push_back( Vertex( vertexPositions[ faceIndices[i] ], normal, textureCoordinates[ faceIndices[i] ] ) );
443 vertices.push_back( Vertex( vertexPositions[ faceIndices[i+2] ], normal, textureCoordinates[ faceIndices[i+2] ] ) );
444 vertices.push_back( Vertex( vertexPositions[ faceIndices[i+1] ], normal, textureCoordinates[ faceIndices[i+1] ] ) );
448 Property::Map vertexFormat;
449 vertexFormat["aPosition"] = Property::VECTOR3;
450 vertexFormat["aNormal"] = Property::VECTOR3;
451 vertexFormat["aTexCoord"] = Property::VECTOR2;
452 PropertyBuffer surfaceVertices = PropertyBuffer::New( vertexFormat, vertices.size() );
453 surfaceVertices.SetData( &vertices[0] );
455 Geometry surface = Geometry::New();
456 surface.AddVertexBuffer( surfaceVertices );
461 void ReadObjFile( const std::string& objFileName,
462 Vector<float>& boundingBox,
463 std::vector<Vector3>& vertexPositions,
464 Vector<unsigned int>& faceIndices)
466 std::ifstream ifs( objFileName.c_str(), std::ios::in );
468 boundingBox.Resize( 6 );
469 boundingBox[0]=boundingBox[2]=boundingBox[4] = std::numeric_limits<float>::max();
470 boundingBox[1]=boundingBox[3]=boundingBox[5] = -std::numeric_limits<float>::max();
473 while( std::getline( ifs, line ) )
475 if( line[0] == 'v' && std::isspace(line[1])) // vertex
477 std::istringstream iss(line.substr(2), std::istringstream::in);
480 while( iss >> vertex[i++] && i < 3);
481 if( vertex.x < boundingBox[0] ) boundingBox[0] = vertex.x;
482 if( vertex.x > boundingBox[1] ) boundingBox[1] = vertex.x;
483 if( vertex.y < boundingBox[2] ) boundingBox[2] = vertex.y;
484 if( vertex.y > boundingBox[3] ) boundingBox[3] = vertex.y;
485 if( vertex.z < boundingBox[4] ) boundingBox[4] = vertex.z;
486 if( vertex.z > boundingBox[5] ) boundingBox[5] = vertex.z;
487 vertexPositions.push_back( vertex );
489 else if( line[0] == 'f' ) //face
491 unsigned int numOfInt = 3;
494 std::size_t found = line.find('/');
495 if( found == std::string::npos )
503 std::istringstream iss(line.substr(2), std::istringstream::in);
504 unsigned int indices[ numOfInt ];
506 while( iss >> indices[i++] && i < numOfInt);
507 unsigned int step = (i+1) / 3;
508 faceIndices.PushBack( indices[0]-1 );
509 faceIndices.PushBack( indices[step]-1 );
510 faceIndices.PushBack( indices[2*step]-1 );
517 void ShapeResizeAndTexureCoordinateCalculation( const Vector<float>& boundingBox,
518 std::vector<Vector3>& vertexPositions,
519 std::vector<Vector2>& textureCoordinates)
521 Vector3 bBoxSize( boundingBox[1] - boundingBox[0], boundingBox[3] - boundingBox[2], boundingBox[5] - boundingBox[4]);
522 Vector3 bBoxMinCorner( boundingBox[0], boundingBox[2], boundingBox[4] );
524 Vector2 stageSize = Stage::GetCurrent().GetSize();
525 Vector3 scale( stageSize.x / bBoxSize.x, stageSize.y / bBoxSize.y, 1.f );
526 scale.z = (scale.x + scale.y)/2.f;
528 textureCoordinates.reserve(vertexPositions.size());
530 for( std::vector<Vector3>::iterator iter = vertexPositions.begin(); iter != vertexPositions.end(); iter++ )
532 Vector3 newPosition( (*iter) - bBoxMinCorner ) ;
534 textureCoordinates.push_back( Vector2( newPosition.x / bBoxSize.x, newPosition.y / bBoxSize.y ) );
536 newPosition -= bBoxSize * 0.5f;
537 (*iter) = newPosition * scale;
542 * Main key event handler
544 void OnKeyEvent(const KeyEvent& event)
546 if(event.state == KeyEvent::Down)
548 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
557 Application& mApplication;
567 Shader mShaderRefraction;
569 Animation mLightAnimation;
570 Animation mStrenghAnimation;
572 Property::Index mLightXYOffsetIndex;
573 Property::Index mSpinAngleIndex;
574 Property::Index mLightIntensityIndex;
575 Property::Index mEffectStrengthIndex;
577 Toolkit::PushButton mChangeTextureButton;
578 Toolkit::PushButton mChangeMeshButton;
579 unsigned int mCurrentTextureId;
580 unsigned int mCurrentMeshId;
583 /*****************************************************************************/
586 RunTest(Application& app)
588 RefractionEffectExample theApp(app);
592 /*****************************************************************************/
595 main(int argc, char **argv)
597 Application app = Application::New(&argc, &argv, DALI_DEMO_THEME_PATH);