2 * Copyright (c) 2014 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"
29 const char * const APPLICATION_TITLE( "Refraction Effect" );
30 const char * const TOOLBAR_IMAGE( DALI_IMAGE_DIR "top-bar.png" );
31 const char * const CHANGE_TEXTURE_ICON( DALI_IMAGE_DIR "icon-change.png" );
32 const char * const CHANGE_MESH_ICON( DALI_IMAGE_DIR "icon-replace.png" );
34 const char* MESH_FILES[] =
36 DALI_MODEL_DIR "surface_pattern_v01.obj",
37 DALI_MODEL_DIR "surface_pattern_v02.obj"
39 const unsigned int NUM_MESH_FILES( sizeof( MESH_FILES ) / sizeof( MESH_FILES[0] ) );
41 const char* TEXTURE_IMAGES[]=
43 DALI_IMAGE_DIR "background-1.jpg",
44 DALI_IMAGE_DIR "background-2.jpg",
45 DALI_IMAGE_DIR "background-3.jpg",
46 DALI_IMAGE_DIR "background-4.jpg"
48 const unsigned int NUM_TEXTURE_IMAGES( sizeof( TEXTURE_IMAGES ) / sizeof( TEXTURE_IMAGES[0] ) );
50 #define MAKE_SHADER(A)#A
52 struct LightOffsetConstraint
54 LightOffsetConstraint( float radius )
59 Vector2 operator()( const Vector2& current, const PropertyInput& spinAngleProperty)
61 float spinAngle = spinAngleProperty.GetFloat();
62 return Vector2( cos(spinAngle ), sin( spinAngle ) ) * mRadius;
69 * @brief Load an image, scaled-down to no more than the stage dimensions.
71 * Uses image scaling mode ImageAttributes::ScaleToFill to resize the image at
72 * load time to cover the entire stage with pixels with no borders,
73 * and filter mode ImageAttributes::BoxThenLinear to sample the image with
76 ResourceImage LoadStageFillingImage( const char * const imagePath )
78 Size stageSize = Stage::GetCurrent().GetSize();
79 ImageAttributes attributes;
80 attributes.SetSize( stageSize.x, stageSize.y );
81 attributes.SetFilterMode( ImageAttributes::BoxThenLinear );
82 attributes.SetScalingMode( ImageAttributes::ScaleToFill );
83 return ResourceImage::New( imagePath, attributes );
88 /************************************************************************************************
89 *** This shader is used when the MeshActor is not touched***
90 ************************************************************************************************/
91 class NoEffect : public ShaderEffect
95 * Create an empty handle.
109 * Create a NoEffect object.
110 * @return A handle to a newly allocated NoEffect
112 static NoEffect New()
114 std::string vertexShader = MAKE_SHADER(
115 precision mediump float;\n
116 uniform mediump vec4 uTextureRect;\n
119 gl_Position = uMvpMatrix * vec4( aPosition.xy, 0.0, 1.0 );\n
120 vTexCoord = aTexCoord.xy;\n
123 std::string fragmentShader = MAKE_SHADER(
124 precision mediump float;\n
127 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
130 ShaderEffect shaderEffect = ShaderEffect::New( vertexShader, fragmentShader,
131 GeometryType( GEOMETRY_TYPE_TEXTURED_MESH),
132 ShaderEffect::GeometryHints( ShaderEffect::HINT_NONE ) );
133 NoEffect handle( shaderEffect );
141 NoEffect( ShaderEffect handle )
142 : ShaderEffect( handle )
147 /************************************************************/
148 /* Custom refraction effect shader******************************/
149 /************************************************************/
151 class RefractionEffect : public ShaderEffect
156 * Create an empty RefractionEffect handle.
165 virtual ~RefractionEffect()
170 * Create a RefractionEffect object.
171 * @return A handle to a newly allocated RefractionEffect
173 static RefractionEffect New()
175 std::string vertexShader = MAKE_SHADER(
176 precision mediump float;\n
177 varying mediump vec2 vTextureOffset;\n
180 gl_Position = uMvpMatrix * vec4( aPosition.xy, 0.0, 1.0 );\n
181 vTexCoord = aTexCoord.xy;\n
184 vVertex = vec4( aPosition, 1.0 );\n
185 float length = max(0.01, length(aNormal.xy)) * 40.0;\n
186 vTextureOffset = aNormal.xy / length;\n
190 std::string fragmentShader = MAKE_SHADER(
191 precision mediump float;\n
192 uniform mediump float uEffectStrength;\n
193 uniform mediump vec3 uLightPosition;\n
194 uniform mediump vec2 uLightXYOffset;\n
195 uniform mediump vec2 uLightSpinOffset;\n
196 uniform mediump float uLightIntensity;\n
197 varying mediump vec2 vTextureOffset;\n
199 vec3 rgb2hsl(vec3 rgb)\n
201 float epsilon = 1.0e-10;\n
202 vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n
203 vec4 P = mix(vec4(rgb.bg, K.wz), vec4(rgb.gb, K.xy), step(rgb.b, rgb.g));\n
204 vec4 Q = mix(vec4(P.xyw, rgb.r), vec4(rgb.r, P.yzx), step(P.x, rgb.r));\n
208 float chroma = Q.x - min(Q.w, Q.y);\n
209 float hue = abs(Q.z + (Q.w-Q.y) / (6.0*chroma+epsilon));\n
211 float lightness = value - chroma*0.5;\n
212 return vec3( hue, chroma/max( 1.0-abs(lightness*2.0-1.0), 1.0e-1 ), lightness );\n
215 vec3 hsl2rgb( vec3 hsl )
218 vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n
219 vec3 p = abs(fract(hsl.xxx + K.xyz) * 6.0 - K.www);\n
220 vec3 RGB = clamp(p - K.xxx, 0.0, 1.0);\n
222 float chroma = ( 1.0 - abs( hsl.z*2.0-1.0 ) ) * hsl.y;\n
223 return ( RGB - 0.5 ) * chroma + hsl.z;
228 vec3 normal = normalize( vNormal);\n
230 vec3 lightPosition = uLightPosition + vec3(uLightXYOffset+uLightSpinOffset, 0.0);\n
231 mediump vec3 vecToLight = normalize( (lightPosition - vVertex.xyz) * 0.01 );\n
232 mediump float spotEffect = pow( max(0.05, vecToLight.z ) - 0.05, 8.0);\n
234 spotEffect = spotEffect * uEffectStrength;\n
235 mediump float lightDiffuse = ( ( dot( vecToLight, normal )-0.75 ) *uLightIntensity ) * spotEffect;\n
237 lowp vec4 color = texture2D( sTexture, vTexCoord + vTextureOffset * spotEffect );\n
238 vec3 lightedColor = hsl2rgb( rgb2hsl(color.rgb) + vec3(0.0,0.0,lightDiffuse) );\n
240 gl_FragColor = vec4( lightedColor, color.a ) * uColor;\n
244 ShaderEffect shaderEffect = ShaderEffect::New( vertexShader, fragmentShader,
245 GeometryType( GEOMETRY_TYPE_TEXTURED_MESH),
246 ShaderEffect::GeometryHints( ShaderEffect::HINT_BLENDING ) );
247 RefractionEffect handle( shaderEffect );
249 Vector2 stageSize = Stage::GetCurrent().GetSize();
250 handle.SetLightPosition( Vector2(stageSize.x, 0.f) );
251 handle.SetUniform( "uLightXYOffset", Vector2::ZERO );
252 handle.SetUniform( "uLightSpinOffset", Vector2::ZERO );
253 handle.SetUniform( "uEffectStrength", 0.f );
254 handle.SetUniform( "uLightIntensity", 2.5f );
256 Dali::Property::Index index = handle.RegisterProperty( "uSpinAngle", 0.f );
257 Constraint constraint = Constraint::New<Vector2>( handle.GetPropertyIndex("uLightSpinOffset"),
259 LightOffsetConstraint(stageSize.x*0.1f));
260 handle.ApplyConstraint( constraint );
265 void SetLightPosition( const Vector2& position )
267 Vector2 stageHalfSize = Stage::GetCurrent().GetSize() * 0.5f;
268 SetUniform( "uLightPosition", Vector3( position.x - stageHalfSize.x, position.y - stageHalfSize.y, stageHalfSize.x ) );
271 void SetLightXYOffset( const Vector2& offset )
273 SetUniform( "uLightXYOffset", offset );
276 void SetEffectStrength( float strength )
278 SetUniform( "uEffectStrength", strength );
281 void SetLightIntensity( float intensity )
283 SetUniform( "uLightIntensity", intensity );
290 RefractionEffect( ShaderEffect handle )
291 : ShaderEffect( handle )
296 /*************************************************/
297 /*Demo using RefractionEffect*****************/
298 /*************************************************/
299 class RefractionEffectExample : public ConnectionTracker
302 RefractionEffectExample( Application &application )
303 : mApplication( application ),
305 mCurrentTextureId( 1 ),
308 // Connect to the Application's Init signal
309 application.InitSignal().Connect(this, &RefractionEffectExample::Create);
312 ~RefractionEffectExample()
318 // The Init signal is received once (only) during the Application lifetime
319 void Create(Application& application)
321 Stage stage = Stage::GetCurrent();
322 mStageHalfSize = stage.GetSize() * 0.5f;
324 stage.KeyEventSignal().Connect(this, &RefractionEffectExample::OnKeyEvent);
326 // Creates a default view with a default tool bar.
327 // The view is added to the stage.
328 Toolkit::ToolBar toolBar;
330 mContent = DemoHelper::CreateView( application,
337 // Add a button to change background. (right of toolbar)
338 mChangeTextureButton = Toolkit::PushButton::New();
339 mChangeTextureButton.SetBackgroundImage( ResourceImage::New( CHANGE_TEXTURE_ICON ) );
340 mChangeTextureButton.ClickedSignal().Connect( this, &RefractionEffectExample::OnChangeTexture );
341 toolBar.AddControl( mChangeTextureButton,
342 DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage,
343 Toolkit::Alignment::HorizontalRight,
344 DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
345 // Add a button to change mesh pattern. ( left of bar )
346 mChangeMeshButton = Toolkit::PushButton::New();
347 mChangeMeshButton.SetBackgroundImage( ResourceImage::New( CHANGE_MESH_ICON ) );
348 mChangeMeshButton.ClickedSignal().Connect( this, &RefractionEffectExample::OnChangeMesh );
349 toolBar.AddControl( mChangeMeshButton,
350 DemoHelper::DEFAULT_VIEW_STYLE.mToolBarButtonPercentage,
351 Toolkit::Alignment::HorizontalLeft,
352 DemoHelper::DEFAULT_MODE_SWITCH_PADDING );
354 // creates the shader effects applied on the mesh actor
355 mRefractionEffect = RefractionEffect::New(); // used when the finger is touching the screen
356 mNoEffect = NoEffect::New(); // used in the other situations, basic render shader
357 // Create the mesh from the obj file and add to stage
358 mMaterial = Material::New( "Material" ) ;
359 mMaterial.SetDiffuseTexture( LoadStageFillingImage( TEXTURE_IMAGES[mCurrentTextureId] ) );
360 CreateSurface( MESH_FILES[mCurrentMeshId] );
362 // Connect the callback to the touch signal on the mesh actor
363 mContent.TouchedSignal().Connect( this, &RefractionEffectExample::OnTouch );
365 // the animation which spin the light around the finger touch position
366 mLightPosition = Vector2( mStageHalfSize.x*2.f, 0.f);
367 mLightAnimation = Animation::New(2.f);
368 mLightAnimation.AnimateTo( Property( mRefractionEffect, "uSpinAngle" ), Math::PI*2.f );
369 mLightAnimation.SetLooping( true );
370 mLightAnimation.Pause();
374 * Create a mesh actor with different geometry to replace the current one
376 bool OnChangeMesh( Toolkit::Button button )
380 UnparentAndReset( mMeshActor );
383 mCurrentMeshId = ( mCurrentMeshId + 1 ) % NUM_MESH_FILES;
384 CreateSurface( MESH_FILES[mCurrentMeshId] );
389 bool OnChangeTexture( Toolkit::Button button )
391 mCurrentTextureId = ( mCurrentTextureId + 1 ) % NUM_TEXTURE_IMAGES;
392 mMaterial.SetDiffuseTexture( LoadStageFillingImage( TEXTURE_IMAGES[mCurrentTextureId] ) );
397 bool OnTouch( Actor actor , const TouchEvent& event )
399 const TouchPoint &point = event.GetPoint(0);
403 case TouchPoint::Down:
406 mDownPosition = point.screen;
408 mLightAnimation.Play();
410 if( mStrenghAnimation )
412 mStrenghAnimation.Clear();
415 mRefractionEffect.SetLightXYOffset( point.screen - mLightPosition );
416 mMeshActor.SetShaderEffect( mRefractionEffect );
417 mStrenghAnimation= Animation::New(0.5f);
418 mStrenghAnimation.AnimateTo( Property( mRefractionEffect, "uEffectStrength" ), 1.f );
419 mStrenghAnimation.Play();
423 case TouchPoint::Motion:
427 // make the light position following the finger movement
428 mRefractionEffect.SetLightXYOffset( point.screen - mLightPosition );
433 case TouchPoint::Leave:
434 case TouchPoint::Interrupted:
438 mLightAnimation.Pause();
440 if( mStrenghAnimation )
442 mStrenghAnimation.Clear();
444 mStrenghAnimation = Animation::New(0.5f);
445 mStrenghAnimation.AnimateTo( Property( mRefractionEffect, "uEffectStrength" ), 0.f );
446 mStrenghAnimation.FinishedSignal().Connect( this, &RefractionEffectExample::OnTouchFinished );
447 mStrenghAnimation.Play();
453 case TouchPoint::Stationary:
454 case TouchPoint::Last:
463 void OnTouchFinished( Animation& source )
465 mMeshActor.SetShaderEffect( mNoEffect );
466 mRefractionEffect.SetLightXYOffset( Vector2::ZERO );
469 void CreateSurface( const std::string& objFileName )
471 MeshData::VertexContainer vertices;
472 MeshData::FaceIndices faces;
475 std::vector<float> boundingBox;
476 std::vector<Vector3> vertexPositions;
477 std::vector<int> faceIndices;
478 // read the vertice and faces from the .obj file, and record the bounding box
479 ReadObjFile( objFileName, boundingBox, vertexPositions, faceIndices );
481 std::vector<Vector2> textureCoordinates;
482 // align the mesh, scale it to fit the screen size, and calculate the texture coordinate for each vertex
483 ShapeResizeAndTexureCoordinateCalculation( boundingBox, vertexPositions, textureCoordinates );
485 // re-organize the mesh, the vertices are duplicated, each vertex only belongs to one triangle.
486 // Without sharing vertex between triangle, so we can manipulate the texture offset on each triangle conveniently.
487 for( std::size_t i=0; i<faceIndices.size(); i=i+3 )
489 Vector3 edge1 = vertexPositions[ faceIndices[i+2] ] - vertexPositions[ faceIndices[i] ];
490 Vector3 edge2 = vertexPositions[ faceIndices[i+1] ] - vertexPositions[ faceIndices[i] ];
491 Vector3 normal = edge1.Cross(edge2);
496 faces.push_back( i );
497 faces.push_back( i+1 );
498 faces.push_back( i+2 );
503 faces.push_back( i );
504 faces.push_back( i+2 );
505 faces.push_back( i+1 );
508 vertices.push_back( MeshData::Vertex( vertexPositions[ faceIndices[i] ], textureCoordinates[ faceIndices[i] ], normal ) );
509 vertices.push_back( MeshData::Vertex( vertexPositions[ faceIndices[i+1] ], textureCoordinates[ faceIndices[i+1] ], normal ) );
510 vertices.push_back( MeshData::Vertex( vertexPositions[ faceIndices[i+2] ], textureCoordinates[ faceIndices[i+2] ], normal ) );
514 // Now ready to construct the mesh actor
515 meshData.SetMaterial( mMaterial );
516 meshData.SetVertices( vertices );
517 meshData.SetFaceIndices( faces );
518 meshData.SetHasTextureCoords(true);
519 meshData.SetHasNormals(true);
520 mMeshActor = MeshActor::New( Mesh::New( meshData ) );
521 mMeshActor.SetParentOrigin(ParentOrigin::CENTER);
522 mMeshActor.SetShaderEffect( mNoEffect );
523 mContent.Add( mMeshActor );
526 void ReadObjFile( const std::string& objFileName,
527 std::vector<float>& boundingBox,
528 std::vector<Vector3>& vertexPositions,
529 std::vector<int>& faceIndices)
531 std::ifstream ifs( objFileName.c_str(), std::ios::in );
533 boundingBox.resize( 6 );
534 boundingBox[0]=boundingBox[2]=boundingBox[4] = std::numeric_limits<float>::max();
535 boundingBox[1]=boundingBox[3]=boundingBox[5] = -std::numeric_limits<float>::max();
538 while( std::getline( ifs, line ) )
540 if( line[0] == 'v' && std::isspace(line[1])) // vertex
542 std::istringstream iss(line.substr(2), std::istringstream::in);
545 while( iss >> vertex[i++] && i < 3);
546 if( vertex.x < boundingBox[0] ) boundingBox[0] = vertex.x;
547 if( vertex.x > boundingBox[1] ) boundingBox[1] = vertex.x;
548 if( vertex.y < boundingBox[2] ) boundingBox[2] = vertex.y;
549 if( vertex.y > boundingBox[3] ) boundingBox[3] = vertex.y;
550 if( vertex.z < boundingBox[4] ) boundingBox[4] = vertex.z;
551 if( vertex.z > boundingBox[5] ) boundingBox[5] = vertex.z;
552 vertexPositions.push_back( vertex );
554 else if( line[0] == 'f' ) //face
556 unsigned int numOfInt = 3;
559 std::size_t found = line.find('/');
560 if( found == std::string::npos )
568 std::istringstream iss(line.substr(2), std::istringstream::in);
569 int indices[ numOfInt ];
571 while( iss >> indices[i++] && i < numOfInt);
572 unsigned int step = (i+1) / 3;
573 faceIndices.push_back( indices[0]-1 );
574 faceIndices.push_back( indices[step]-1 );
575 faceIndices.push_back( indices[2*step]-1 );
582 void ShapeResizeAndTexureCoordinateCalculation( const std::vector<float>& boundingBox,
583 std::vector<Vector3>& vertexPositions,
584 std::vector<Vector2>& textureCoordinates)
586 Vector3 bBoxSize( boundingBox[1] - boundingBox[0], boundingBox[3] - boundingBox[2], boundingBox[5] - boundingBox[4]);
587 Vector3 bBoxMinCorner( boundingBox[0], boundingBox[2], boundingBox[4] );
589 Vector2 stageSize = Stage::GetCurrent().GetSize();
590 Vector3 scale( stageSize.x / bBoxSize.x, stageSize.y / bBoxSize.y, 1.f );
591 scale.z = (scale.x + scale.y)/2.f;
593 for( std::vector<Vector3>::iterator iter = vertexPositions.begin(); iter != vertexPositions.end(); iter++ )
595 Vector3 newPosition( (*iter) - bBoxMinCorner ) ;
597 Vector2 textureCoord( newPosition.x / bBoxSize.x, newPosition.y / bBoxSize.y );
598 textureCoordinates.push_back( textureCoord );
600 newPosition -= bBoxSize * 0.5f;
601 (*iter) = newPosition * scale;
606 * Main key event handler
608 void OnKeyEvent(const KeyEvent& event)
610 if(event.state == KeyEvent::Down)
612 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
621 Application& mApplication;
625 Vector2 mDownPosition;
626 Vector2 mLightPosition;
627 Vector2 mStageHalfSize;
630 MeshActor mMeshActor;
632 RefractionEffect mRefractionEffect;
634 Animation mLightAnimation;
635 Animation mStrenghAnimation;
637 Toolkit::PushButton mChangeTextureButton;
638 Toolkit::PushButton mChangeMeshButton;
639 unsigned int mCurrentTextureId;
640 unsigned int mCurrentMeshId;
643 /*****************************************************************************/
646 RunTest(Application& app)
648 RefractionEffectExample theApp(app);
652 /*****************************************************************************/
655 main(int argc, char **argv)
657 Application app = Application::New(&argc, &argv);