e6b088c5220c46371a46072aa174a7fe82381696
[platform/core/uifw/dali-core.git] / dali / internal / update / render-tasks / scene-graph-camera.cpp
1 /*
2  * Copyright (c) 2017 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/update/render-tasks/scene-graph-camera.h>
20
21 // EXTERNAL INCLUDES
22 #include <stdint.h>
23
24 // INTERNAL INCLUDES
25 #include <dali/integration-api/debug.h>
26 #include <dali/public-api/common/dali-common.h>
27 #include <dali/public-api/math/math-utils.h>
28 #include <dali/internal/update/nodes/node.h>
29
30 namespace // unnamed namespace
31 {
32 const unsigned int UPDATE_COUNT        = 2u;  // Update projection or view matrix this many frames after a change
33 const unsigned int COPY_PREVIOUS_MATRIX = 1u; // Copy view or projection matrix from previous frame
34 }
35
36 namespace Dali
37 {
38
39 namespace Internal
40 {
41
42 namespace SceneGraph
43 {
44
45 namespace
46 {
47
48 void LookAt(Matrix& result, const Vector3& eye, const Vector3& target, const Vector3& up)
49 {
50   Vector3 vZ = target - eye;
51   vZ.Normalize();
52
53   Vector3 vX = up.Cross(vZ);
54   vX.Normalize();
55
56   Vector3 vY = vZ.Cross(vX);
57   vY.Normalize();
58
59   result.SetInverseTransformComponents(vX, vY, vZ, eye);
60 }
61
62
63 void Frustum(Matrix& result, float left, float right, float bottom, float top, float near, float far, bool invertYAxis)
64 {
65   float deltaZ = far - near;
66   if ((near <= 0.0f) || (far <= 0.0f) || Equals(right, left) || Equals(bottom, top) || (deltaZ <= 0.0f))
67   {
68     DALI_LOG_ERROR("Invalid parameters passed into Frustum!\n");
69     DALI_ASSERT_DEBUG("Invalid parameters passed into Frustum!");
70     return;
71   }
72
73   float deltaX = right - left;
74   float deltaY = invertYAxis ? bottom - top : top - bottom;
75
76   result.SetIdentity();
77
78   float* m = result.AsFloat();
79   m[0] = -2.0f * near / deltaX;
80   m[1] = m[2] = m[3] = 0.0f;
81
82   m[5] = -2.0f * near / deltaY;
83   m[4] = m[6] = m[7] = 0.0f;
84
85   m[8] = (right + left) / deltaX;
86   m[9] = (top + bottom) / deltaY;
87   m[10] = (near + far) / deltaZ;
88   m[11] = 1.0f;
89
90   m[14] = -2.0f * near * far / deltaZ;
91   m[12] = m[13] = m[15] = 0.0f;
92 }
93
94 void Perspective(Matrix& result, float fovy, float aspect, float near, float far, bool invertYAxis, const Vector2& stereoBias )
95 {
96   float frustumH = tanf( fovy * 0.5f ) * near;
97   float frustumW = frustumH * aspect;
98   Vector2 bias = stereoBias * 0.5f;
99
100   Frustum(result, -(frustumW + bias.x), frustumW - bias.x, -(frustumH + bias.y), frustumH - bias.y, near, far, invertYAxis);
101 }
102
103 void Orthographic(Matrix& result, float left, float right, float bottom, float top, float near, float far, bool invertYAxis)
104 {
105   if ( Equals(right, left) || Equals(top, bottom) || Equals(far, near) )
106   {
107     DALI_LOG_ERROR( "Cannot create orthographic projection matrix with a zero dimension.\n" );
108     DALI_ASSERT_DEBUG( "Cannot create orthographic projection matrix with a zero dimension." );
109     return;
110   }
111
112   float deltaX = right - left;
113   float deltaY = invertYAxis ? bottom - top : top - bottom;
114   float deltaZ = far - near;
115
116   float *m = result.AsFloat();
117   m[0] = -2.0f / deltaX;
118   m[1] = 0.0f;
119   m[2] = 0.0f;
120   m[3] = 0.0f;
121
122   m[4] = 0.0f;
123   m[5] = -2.0f / deltaY;
124   m[6] = 0.0f;
125   m[7] = 0.0f;
126
127   m[8] = 0.0f;
128   m[9] = 0.0f;
129   m[10] = 2.0f / deltaZ;
130   m[11] = 0.0f;
131   m[12] = -(right + left) / deltaX;
132   m[13] = -(top + bottom) / deltaY;
133   m[14] = -(near + far)   / deltaZ;
134   m[15] = 1.0f;
135 }
136
137 } // unnamed namespace
138
139 const Dali::Camera::Type Camera::DEFAULT_TYPE( Dali::Camera::FREE_LOOK );
140 const Dali::Camera::ProjectionMode Camera::DEFAULT_MODE( Dali::Camera::PERSPECTIVE_PROJECTION );
141 const bool  Camera::DEFAULT_INVERT_Y_AXIS( false );
142 const float Camera::DEFAULT_FIELD_OF_VIEW( 45.0f*(M_PI/180.0f) );
143 const float Camera::DEFAULT_ASPECT_RATIO( 4.0f/3.0f );
144 const float Camera::DEFAULT_LEFT_CLIPPING_PLANE(-240.0f);
145 const float Camera::DEFAULT_RIGHT_CLIPPING_PLANE(240.0f);
146 const float Camera::DEFAULT_TOP_CLIPPING_PLANE(-400.0f);
147 const float Camera::DEFAULT_BOTTOM_CLIPPING_PLANE(400.0f);
148 const float Camera::DEFAULT_NEAR_CLIPPING_PLANE( 800.0f ); // default height of the screen
149 const float Camera::DEFAULT_FAR_CLIPPING_PLANE( DEFAULT_NEAR_CLIPPING_PLANE + 2.f * DEFAULT_NEAR_CLIPPING_PLANE );
150 const Vector2 Camera::DEFAULT_STEREO_BIAS( 0.0f, 0.0f );
151 const Vector3 Camera::DEFAULT_TARGET_POSITION( 0.0f, 0.0f, 0.0f );
152
153
154 Camera::Camera()
155 : mUpdateViewFlag( UPDATE_COUNT ),
156   mUpdateProjectionFlag( UPDATE_COUNT ),
157   mType( DEFAULT_TYPE ),
158   mProjectionMode( DEFAULT_MODE ),
159   mInvertYAxis( DEFAULT_INVERT_Y_AXIS ),
160   mFieldOfView( DEFAULT_FIELD_OF_VIEW ),
161   mAspectRatio( DEFAULT_ASPECT_RATIO ),
162   mLeftClippingPlane( DEFAULT_LEFT_CLIPPING_PLANE ),
163   mRightClippingPlane( DEFAULT_RIGHT_CLIPPING_PLANE ),
164   mTopClippingPlane( DEFAULT_TOP_CLIPPING_PLANE ),
165   mBottomClippingPlane( DEFAULT_BOTTOM_CLIPPING_PLANE ),
166   mNearClippingPlane( DEFAULT_NEAR_CLIPPING_PLANE ),
167   mFarClippingPlane( DEFAULT_FAR_CLIPPING_PLANE ),
168   mStereoBias( DEFAULT_STEREO_BIAS ),
169   mTargetPosition( DEFAULT_TARGET_POSITION ),
170   mViewMatrix(),
171   mProjectionMatrix(),
172   mInverseViewProjection( Matrix::IDENTITY )
173 {
174 }
175
176 Camera* Camera::New()
177 {
178   return new Camera();
179 }
180
181 Camera::~Camera()
182 {
183 }
184
185 void Camera::SetNode( const Node* node )
186 {
187   mNode = node;
188 }
189
190 void Camera::SetType( Dali::Camera::Type type )
191 {
192   mType = type;
193 }
194
195 void Camera::SetProjectionMode( Dali::Camera::ProjectionMode mode )
196 {
197   mProjectionMode = mode;
198   mUpdateProjectionFlag = UPDATE_COUNT;
199 }
200
201 void Camera::SetInvertYAxis( bool invertYAxis )
202 {
203   mInvertYAxis = invertYAxis;
204   mUpdateProjectionFlag = UPDATE_COUNT;
205 }
206
207 void Camera::SetFieldOfView( float fieldOfView )
208 {
209   mFieldOfView = fieldOfView;
210   mUpdateProjectionFlag = UPDATE_COUNT;
211 }
212
213 void Camera::SetAspectRatio( float aspectRatio )
214 {
215   mAspectRatio = aspectRatio;
216   mUpdateProjectionFlag = UPDATE_COUNT;
217 }
218
219 void Camera::SetStereoBias( const Vector2& stereoBias )
220 {
221   mStereoBias = stereoBias;
222   mUpdateProjectionFlag = UPDATE_COUNT;
223 }
224
225 void Camera::SetLeftClippingPlane( float leftClippingPlane )
226 {
227   mLeftClippingPlane = leftClippingPlane;
228   mUpdateProjectionFlag = UPDATE_COUNT;
229 }
230
231 void Camera::SetRightClippingPlane( float rightClippingPlane )
232 {
233   mRightClippingPlane = rightClippingPlane;
234   mUpdateProjectionFlag = UPDATE_COUNT;
235 }
236
237 void Camera::SetTopClippingPlane( float topClippingPlane )
238 {
239   mTopClippingPlane = topClippingPlane;
240   mUpdateProjectionFlag = UPDATE_COUNT;
241 }
242
243 void Camera::SetBottomClippingPlane( float bottomClippingPlane )
244 {
245   mBottomClippingPlane = bottomClippingPlane;
246   mUpdateProjectionFlag = UPDATE_COUNT;
247 }
248
249 void Camera::SetNearClippingPlane( float nearClippingPlane )
250 {
251   mNearClippingPlane = nearClippingPlane;
252   mUpdateProjectionFlag = UPDATE_COUNT;
253 }
254
255 void Camera::SetFarClippingPlane( float farClippingPlane )
256 {
257   mFarClippingPlane = farClippingPlane;
258   mUpdateProjectionFlag = UPDATE_COUNT;
259 }
260
261 void Camera::SetTargetPosition( const Vector3& targetPosition )
262 {
263   mTargetPosition = targetPosition;
264   mUpdateViewFlag = UPDATE_COUNT;
265 }
266
267 const Matrix& Camera::GetProjectionMatrix( BufferIndex bufferIndex ) const
268 {
269   return mProjectionMatrix[ bufferIndex ];
270 }
271
272 const Matrix& Camera::GetViewMatrix( BufferIndex bufferIndex ) const
273 {
274   return mViewMatrix[ bufferIndex ];
275 }
276
277 const Matrix& Camera::GetInverseViewProjectionMatrix( BufferIndex bufferIndex ) const
278 {
279   return mInverseViewProjection[ bufferIndex ];
280 }
281
282 const PropertyInputImpl* Camera::GetProjectionMatrix() const
283 {
284   return &mProjectionMatrix;
285 }
286
287 const PropertyInputImpl* Camera::GetViewMatrix() const
288 {
289   return &mViewMatrix;
290 }
291
292 void Camera::Update( BufferIndex updateBufferIndex )
293 {
294   // if owning node has changes in world position we need to update camera for next 2 frames
295   if( mNode->IsLocalMatrixDirty() )
296   {
297     mUpdateViewFlag = UPDATE_COUNT;
298   }
299   if( mNode->GetDirtyFlags() & VisibleFlag )
300   {
301     // If the visibility changes, the projection matrix needs to be re-calculated.
302     // It may happen the first time an actor is rendered it's rendered only once and becomes invisible,
303     // in the following update the node will be skipped leaving the projection matrix (double buffered)
304     // with the Identity.
305     mUpdateProjectionFlag = UPDATE_COUNT;
306   }
307
308   // if either matrix changed, we need to recalculate the inverse matrix for hit testing to work
309   unsigned int viewUpdateCount = UpdateViewMatrix( updateBufferIndex );
310   unsigned int projectionUpdateCount = UpdateProjection( updateBufferIndex );
311
312   // if model or view matrix changed we need to either recalculate the inverse VP or copy previous
313   if( viewUpdateCount > COPY_PREVIOUS_MATRIX || projectionUpdateCount > COPY_PREVIOUS_MATRIX )
314   {
315     // either has actually changed so recalculate
316     Matrix::Multiply( mInverseViewProjection[ updateBufferIndex ], mViewMatrix[ updateBufferIndex ], mProjectionMatrix[ updateBufferIndex ] );
317     UpdateFrustum( updateBufferIndex );
318
319     // ignore the error, if the view projection is incorrect (non inversible) then you will have tough times anyways
320     static_cast< void >( mInverseViewProjection[ updateBufferIndex ].Invert() );
321   }
322   else if( viewUpdateCount == COPY_PREVIOUS_MATRIX || projectionUpdateCount == COPY_PREVIOUS_MATRIX )
323   {
324     // neither has actually changed, but we might copied previous frames value so need to
325     // copy the previous inverse and frustum as well
326     mInverseViewProjection[updateBufferIndex] = mInverseViewProjection[updateBufferIndex ? 0 : 1];
327     mFrustum[ updateBufferIndex ] = mFrustum[ updateBufferIndex ? 0 : 1 ];
328   }
329 }
330
331 bool Camera::ViewMatrixUpdated()
332 {
333   return 0u != mUpdateViewFlag;
334 }
335
336 unsigned int Camera::UpdateViewMatrix( BufferIndex updateBufferIndex )
337 {
338   unsigned int retval( mUpdateViewFlag );
339   if( 0u != mUpdateViewFlag )
340   {
341     if( COPY_PREVIOUS_MATRIX == mUpdateViewFlag )
342     {
343       // The projection matrix was updated in the previous frame; copy it
344       mViewMatrix.CopyPrevious( updateBufferIndex );
345     }
346     else // UPDATE_COUNT == mUpdateViewFlag
347     {
348       switch( mType )
349       {
350         // camera orientation taken from node - i.e. look in abitrary, unconstrained direction
351         case Dali::Camera::FREE_LOOK:
352         {
353           Matrix& viewMatrix = mViewMatrix.Get( updateBufferIndex );
354           viewMatrix = mNode->GetWorldMatrix( updateBufferIndex );
355           viewMatrix.Invert();
356           mViewMatrix.SetDirty( updateBufferIndex );
357           break;
358         }
359           // camera orientation constrained to look at a target
360         case Dali::Camera::LOOK_AT_TARGET:
361         {
362           const Matrix& owningNodeMatrix( mNode->GetWorldMatrix( updateBufferIndex ) );
363           Vector3 position, scale;
364           Quaternion orientation;
365           owningNodeMatrix.GetTransformComponents( position, orientation, scale );
366           Matrix& viewMatrix = mViewMatrix.Get( updateBufferIndex );
367           LookAt( viewMatrix, position, mTargetPosition, orientation.Rotate( Vector3::YAXIS ) );
368           mViewMatrix.SetDirty( updateBufferIndex );
369           break;
370         }
371       }
372     }
373     --mUpdateViewFlag;
374   }
375   return retval;
376 }
377
378 void Camera::UpdateFrustum( BufferIndex updateBufferIndex, bool normalize )
379 {
380
381   // Extract the clip matrix planes
382   Matrix clipMatrix;
383   Matrix::Multiply( clipMatrix, mViewMatrix[ updateBufferIndex ], mProjectionMatrix[ updateBufferIndex ] );
384
385   const float* cm = clipMatrix.AsFloat();
386   FrustumPlanes& planes = mFrustum[ updateBufferIndex ];
387
388   // Left
389   planes.mPlanes[ 0 ].mNormal.x = cm[ 3 ]  + cm[ 0 ]; // column 4 + column 1
390   planes.mPlanes[ 0 ].mNormal.y = cm[ 7 ]  + cm[ 4 ];
391   planes.mPlanes[ 0 ].mNormal.z = cm[ 11 ] + cm[ 8 ];
392   planes.mPlanes[ 0 ].mDistance = cm[ 15 ] + cm[ 12 ];
393
394   // Right
395   planes.mPlanes[ 1 ].mNormal.x = cm[ 3 ]  - cm[ 0 ]; // column 4 - column 1
396   planes.mPlanes[ 1 ].mNormal.y = cm[ 7 ]  - cm[ 4 ];
397   planes.mPlanes[ 1 ].mNormal.z = cm[ 11 ] - cm[ 8 ];
398   planes.mPlanes[ 1 ].mDistance = cm[ 15 ] - cm[ 12 ];
399
400   // Bottom
401   planes.mPlanes[ 2 ].mNormal.x = cm[ 3 ]  + cm[ 1 ]; // column 4 + column 2
402   planes.mPlanes[ 2 ].mNormal.y = cm[ 7 ]  + cm[ 5 ];
403   planes.mPlanes[ 2 ].mNormal.z = cm[ 11 ] + cm[ 9 ];
404   planes.mPlanes[ 2 ].mDistance = cm[ 15 ] + cm[ 13 ];
405
406   // Top
407   planes.mPlanes[ 3 ].mNormal.x = cm[ 3 ]  - cm[ 1 ]; // column 4 - column 2
408   planes.mPlanes[ 3 ].mNormal.y = cm[ 7 ]  - cm[ 5 ];
409   planes.mPlanes[ 3 ].mNormal.z = cm[ 11 ] - cm[ 9 ];
410   planes.mPlanes[ 3 ].mDistance = cm[ 15 ] - cm[ 13 ];
411
412   // Near
413   planes.mPlanes[ 4 ].mNormal.x = cm[ 3 ]  + cm[ 2 ]; // column 4 + column 3
414   planes.mPlanes[ 4 ].mNormal.y = cm[ 7 ]  + cm[ 6 ];
415   planes.mPlanes[ 4 ].mNormal.z = cm[ 11 ] + cm[ 10 ];
416   planes.mPlanes[ 4 ].mDistance = cm[ 15 ] + cm[ 14 ];
417
418   // Far
419   planes.mPlanes[ 5 ].mNormal.x = cm[ 3 ]  - cm[ 2 ]; // column 4 - column 3
420   planes.mPlanes[ 5 ].mNormal.y = cm[ 7 ]  - cm[ 6 ];
421   planes.mPlanes[ 5 ].mNormal.z = cm[ 11 ] - cm[ 10 ];
422   planes.mPlanes[ 5 ].mDistance = cm[ 15 ] - cm[ 14 ];
423
424   if ( normalize )
425   {
426     for ( unsigned int i = 0; i < 6; ++i )
427     {
428       // Normalize planes to ensure correct bounding distance checking
429       Plane& plane = planes.mPlanes[ i ];
430       float l = 1.0f / plane.mNormal.Length();
431       plane.mNormal *= l;
432       plane.mDistance *= l;
433
434       planes.mSign[i] = Vector3( Sign(plane.mNormal.x), Sign(plane.mNormal.y), Sign(plane.mNormal.z) );
435     }
436   }
437   else
438   {
439     for ( unsigned int i = 0; i < 6; ++i )
440     {
441       planes.mSign[i] = Vector3( Sign(planes.mPlanes[ i ].mNormal.x), Sign(planes.mPlanes[ i ].mNormal.y), Sign(planes.mPlanes[ i ].mNormal.z) );
442     }
443   }
444   mFrustum[ updateBufferIndex ? 0 : 1 ] = planes;
445 }
446
447 bool Camera::CheckSphereInFrustum( BufferIndex bufferIndex, const Vector3& origin, float radius )
448 {
449   const FrustumPlanes& planes = mFrustum[ bufferIndex ];
450   for ( uint32_t i = 0; i < 6; ++i )
451   {
452     if ( ( planes.mPlanes[ i ].mDistance + planes.mPlanes[ i ].mNormal.Dot( origin ) ) < -radius )
453     {
454       return false;
455     }
456   }
457   return true;
458 }
459
460 bool Camera::CheckAABBInFrustum( BufferIndex bufferIndex, const Vector3& origin, const Vector3& halfExtents )
461 {
462   const FrustumPlanes& planes = mFrustum[ bufferIndex ];
463   for ( uint32_t i = 0; i < 6; ++i )
464   {
465     if( planes.mPlanes[ i ].mNormal.Dot( origin + (halfExtents * planes.mSign[i]) ) > -(planes.mPlanes[ i ].mDistance) )
466     {
467       continue;
468     }
469
470     return false;
471   }
472   return true;
473 }
474
475 unsigned int Camera::UpdateProjection( BufferIndex updateBufferIndex )
476 {
477   unsigned int retval( mUpdateProjectionFlag );
478   // Early-exit if no update required
479   if ( 0u != mUpdateProjectionFlag )
480   {
481     if ( COPY_PREVIOUS_MATRIX == mUpdateProjectionFlag )
482     {
483       // The projection matrix was updated in the previous frame; copy it
484       mProjectionMatrix.CopyPrevious( updateBufferIndex );
485     }
486     else // UPDATE_COUNT == mUpdateProjectionFlag
487     {
488       switch( mProjectionMode )
489       {
490         case Dali::Camera::PERSPECTIVE_PROJECTION:
491         {
492           Matrix &projectionMatrix = mProjectionMatrix.Get( updateBufferIndex );
493           Perspective( projectionMatrix,
494                        mFieldOfView,
495                        mAspectRatio,
496                        mNearClippingPlane,
497                        mFarClippingPlane,
498                        mInvertYAxis,
499                        mStereoBias );
500           break;
501         }
502         case Dali::Camera::ORTHOGRAPHIC_PROJECTION:
503         {
504           Matrix &projectionMatrix = mProjectionMatrix.Get( updateBufferIndex );
505           Orthographic( projectionMatrix,
506                         mLeftClippingPlane,   mRightClippingPlane,
507                         mBottomClippingPlane, mTopClippingPlane,
508                         mNearClippingPlane,   mFarClippingPlane,
509                         mInvertYAxis );
510           break;
511         }
512       }
513
514       mProjectionMatrix.SetDirty( updateBufferIndex );
515     }
516     --mUpdateProjectionFlag;
517   }
518   return retval;
519 }
520
521 } // namespace SceneGraph
522
523 } // namespace Internal
524
525 } // namespace Dali