2 * Copyright (c) 2018 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.
19 #include <dali/internal/update/render-tasks/scene-graph-camera.h>
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>
30 namespace // unnamed namespace
32 const uint32_t UPDATE_COUNT = 2u; // Update projection or view matrix this many frames after a change
33 const uint32_t COPY_PREVIOUS_MATRIX = 1u; // Copy view or projection matrix from previous frame
35 //For reflection and clipping plane
36 const float REFLECTION_NORMALIZED_DEVICE_COORDINATE_PARAMETER_A = 2.0f;
37 const float REFLECTION_NORMALIZED_DEVICE_COORDINATE_PARAMETER_D = 1.0f;
52 template< typename T >
55 return T( T(0) < value ) - T( value < T(0) );
58 void LookAt(Matrix& result, const Vector3& eye, const Vector3& target, const Vector3& up)
60 Vector3 vZ = target - eye;
63 Vector3 vX = up.Cross(vZ);
66 Vector3 vY = vZ.Cross(vX);
69 result.SetInverseTransformComponents(vX, vY, vZ, eye);
72 void Frustum(Matrix& result, float left, float right, float bottom, float top, float near, float far, bool invertYAxis)
74 float deltaZ = far - near;
75 if ((near <= 0.0f) || (far <= 0.0f) || Equals(right, left) || Equals(bottom, top) || (deltaZ <= 0.0f))
77 DALI_LOG_ERROR("Invalid parameters passed into Frustum!\n");
78 DALI_ASSERT_DEBUG("Invalid parameters passed into Frustum!");
82 float deltaX = right - left;
83 float deltaY = invertYAxis ? bottom - top : top - bottom;
87 float* m = result.AsFloat();
88 m[0] = -2.0f * near / deltaX;
89 m[1] = m[2] = m[3] = 0.0f;
91 m[5] = -2.0f * near / deltaY;
92 m[4] = m[6] = m[7] = 0.0f;
94 m[8] = (right + left) / deltaX;
95 m[9] = (top + bottom) / deltaY;
96 m[10] = (near + far) / deltaZ;
99 m[14] = -2.0f * near * far / deltaZ;
100 m[12] = m[13] = m[15] = 0.0f;
103 void Perspective(Matrix& result, float fovy, float aspect, float near, float far, bool invertYAxis )
105 float frustumH = tanf( fovy * 0.5f ) * near;
106 float frustumW = frustumH * aspect;
108 Frustum(result, -frustumW, frustumW, -frustumH, frustumH, near, far, invertYAxis);
111 void Orthographic(Matrix& result, float left, float right, float bottom, float top, float near, float far, bool invertYAxis)
113 if ( Equals(right, left) || Equals(top, bottom) || Equals(far, near) )
115 DALI_LOG_ERROR( "Cannot create orthographic projection matrix with a zero dimension.\n" );
116 DALI_ASSERT_DEBUG( "Cannot create orthographic projection matrix with a zero dimension." );
120 float deltaX = right - left;
121 float deltaY = invertYAxis ? bottom - top : top - bottom;
122 float deltaZ = far - near;
124 float *m = result.AsFloat();
125 m[0] = -2.0f / deltaX;
131 m[5] = -2.0f / deltaY;
137 m[10] = 2.0f / deltaZ;
139 m[12] = -(right + left) / deltaX;
140 m[13] = -(top + bottom) / deltaY;
141 m[14] = -(near + far) / deltaZ;
145 } // unnamed namespace
147 const Dali::Camera::Type Camera::DEFAULT_TYPE( Dali::Camera::FREE_LOOK );
148 const Dali::Camera::ProjectionMode Camera::DEFAULT_MODE( Dali::Camera::PERSPECTIVE_PROJECTION );
149 const bool Camera::DEFAULT_INVERT_Y_AXIS( false );
150 const float Camera::DEFAULT_FIELD_OF_VIEW( 45.0f*(Math::PI/180.0f) );
151 const float Camera::DEFAULT_ASPECT_RATIO( 4.0f/3.0f );
152 const float Camera::DEFAULT_LEFT_CLIPPING_PLANE(-240.0f);
153 const float Camera::DEFAULT_RIGHT_CLIPPING_PLANE(240.0f);
154 const float Camera::DEFAULT_TOP_CLIPPING_PLANE(-400.0f);
155 const float Camera::DEFAULT_BOTTOM_CLIPPING_PLANE(400.0f);
156 const float Camera::DEFAULT_NEAR_CLIPPING_PLANE( 800.0f ); // default height of the screen
157 const float Camera::DEFAULT_FAR_CLIPPING_PLANE( DEFAULT_NEAR_CLIPPING_PLANE + 2.f * DEFAULT_NEAR_CLIPPING_PLANE );
158 const Vector3 Camera::DEFAULT_TARGET_POSITION( 0.0f, 0.0f, 0.0f );
162 : mUpdateViewFlag( UPDATE_COUNT ),
163 mUpdateProjectionFlag( UPDATE_COUNT ),
164 mProjectionRotation( 0 ),
166 mType( DEFAULT_TYPE ),
167 mProjectionMode( DEFAULT_MODE ),
168 mInvertYAxis( DEFAULT_INVERT_Y_AXIS ),
169 mFieldOfView( DEFAULT_FIELD_OF_VIEW ),
170 mAspectRatio( DEFAULT_ASPECT_RATIO ),
171 mLeftClippingPlane( DEFAULT_LEFT_CLIPPING_PLANE ),
172 mRightClippingPlane( DEFAULT_RIGHT_CLIPPING_PLANE ),
173 mTopClippingPlane( DEFAULT_TOP_CLIPPING_PLANE ),
174 mBottomClippingPlane( DEFAULT_BOTTOM_CLIPPING_PLANE ),
175 mNearClippingPlane( DEFAULT_NEAR_CLIPPING_PLANE ),
176 mFarClippingPlane( DEFAULT_FAR_CLIPPING_PLANE ),
177 mTargetPosition( DEFAULT_TARGET_POSITION ),
180 mInverseViewProjection( Matrix::IDENTITY ),
181 mFinalProjection( Matrix::IDENTITY )
185 Camera* Camera::New()
190 Camera::~Camera() = default;
192 void Camera::SetNode( const Node* node )
197 const Node* Camera::GetNode() const
202 void Camera::SetType( Dali::Camera::Type type )
207 void Camera::SetProjectionMode( Dali::Camera::ProjectionMode mode )
209 mProjectionMode = mode;
210 mUpdateProjectionFlag = UPDATE_COUNT;
213 void Camera::SetInvertYAxis( bool invertYAxis )
215 mInvertYAxis = invertYAxis;
216 mUpdateProjectionFlag = UPDATE_COUNT;
219 void Camera::SetFieldOfView( float fieldOfView )
221 mFieldOfView = fieldOfView;
222 mUpdateProjectionFlag = UPDATE_COUNT;
225 void Camera::SetAspectRatio( float aspectRatio )
227 mAspectRatio = aspectRatio;
228 mUpdateProjectionFlag = UPDATE_COUNT;
231 void Camera::SetLeftClippingPlane( float leftClippingPlane )
233 mLeftClippingPlane = leftClippingPlane;
234 mUpdateProjectionFlag = UPDATE_COUNT;
237 void Camera::SetRightClippingPlane( float rightClippingPlane )
239 mRightClippingPlane = rightClippingPlane;
240 mUpdateProjectionFlag = UPDATE_COUNT;
243 void Camera::SetTopClippingPlane( float topClippingPlane )
245 mTopClippingPlane = topClippingPlane;
246 mUpdateProjectionFlag = UPDATE_COUNT;
249 void Camera::SetBottomClippingPlane( float bottomClippingPlane )
251 mBottomClippingPlane = bottomClippingPlane;
252 mUpdateProjectionFlag = UPDATE_COUNT;
255 void Camera::SetNearClippingPlane( float nearClippingPlane )
257 mNearClippingPlane = nearClippingPlane;
258 mUpdateProjectionFlag = UPDATE_COUNT;
261 void Camera::SetFarClippingPlane( float farClippingPlane )
263 mFarClippingPlane = farClippingPlane;
264 mUpdateProjectionFlag = UPDATE_COUNT;
267 void Camera::SetTargetPosition( const Vector3& targetPosition )
269 mTargetPosition = targetPosition;
270 mUpdateViewFlag = UPDATE_COUNT;
273 void VectorReflectedByPlane(Vector4 &out, Vector4 &in, Vector4 &plane)
275 float d = float(2.0) * plane.Dot(in);
276 out.x = static_cast<float>(in.x - plane.x*d);
277 out.y = static_cast<float>(in.y - plane.y*d);
278 out.z = static_cast<float>(in.z - plane.z*d);
279 out.w = static_cast<float>(in.w - plane.w*d);
282 void Camera::AdjustNearPlaneForPerspective( Matrix& perspective, const Vector4& clipPlane )
285 float* v = perspective.AsFloat();
287 q.x = (Sign(clipPlane.x) + v[8]) / v[0];
288 q.y = (Sign(clipPlane.y) + v[9]) / v[5];
290 q.w = (1.0f + v[10]) / v[14];
292 // Calculate the scaled plane vector
293 Vector4 c = clipPlane * (REFLECTION_NORMALIZED_DEVICE_COORDINATE_PARAMETER_A / q.Dot( clipPlane));
295 // Replace the third row of the projection v
298 v[10] = c.z + REFLECTION_NORMALIZED_DEVICE_COORDINATE_PARAMETER_D;
302 void Camera::SetReflectByPlane( const Vector4& plane )
304 float* v = mReflectionMtx.AsFloat();
305 float _2ab = -2.0f * plane.x * plane.y;
306 float _2ac = -2.0f * plane.x * plane.z;
307 float _2bc = -2.0f * plane.y * plane.z;
309 v[0] = 1.0f - 2.0f * plane.x * plane.x;
315 v[5] = 1.0f - 2.0f * plane.y * plane.y;
321 v[10] = 1.0f - 2.0f * plane.z * plane.z;
324 v[12] = - 2 * plane.x * plane.w;
325 v[13] = - 2 * plane.y * plane.w;
326 v[14] = - 2 * plane.z * plane.w;
329 mUseReflection = true;
330 mReflectionPlane = plane;
331 mUpdateViewFlag = UPDATE_COUNT;
334 void Camera::RotateProjection( int rotationAngle )
336 mProjectionRotation = rotationAngle;
337 mUpdateViewFlag = UPDATE_COUNT;
340 const Matrix& Camera::GetProjectionMatrix( BufferIndex bufferIndex ) const
342 return mProjectionMatrix[ bufferIndex ];
345 const Matrix& Camera::GetViewMatrix( BufferIndex bufferIndex ) const
347 return mViewMatrix[ bufferIndex ];
350 const Matrix& Camera::GetInverseViewProjectionMatrix( BufferIndex bufferIndex ) const
352 return mInverseViewProjection[ bufferIndex ];
355 const Matrix& Camera::GetFinalProjectionMatrix( BufferIndex bufferIndex ) const
357 return mFinalProjection[ bufferIndex ];
360 const PropertyInputImpl* Camera::GetProjectionMatrix() const
362 return &mProjectionMatrix;
365 const PropertyInputImpl* Camera::GetViewMatrix() const
370 void Camera::Update( BufferIndex updateBufferIndex )
372 // if owning node has changes in world position we need to update camera for next 2 frames
373 if( mNode->IsLocalMatrixDirty() )
375 mUpdateViewFlag = UPDATE_COUNT;
377 if( mNode->GetDirtyFlags() & NodePropertyFlags::VISIBLE )
379 // If the visibility changes, the projection matrix needs to be re-calculated.
380 // It may happen the first time an actor is rendered it's rendered only once and becomes invisible,
381 // in the following update the node will be skipped leaving the projection matrix (double buffered)
382 // with the Identity.
383 mUpdateProjectionFlag = UPDATE_COUNT;
386 // if either matrix changed, we need to recalculate the inverse matrix for hit testing to work
387 uint32_t viewUpdateCount = UpdateViewMatrix( updateBufferIndex );
388 uint32_t projectionUpdateCount = UpdateProjection( updateBufferIndex );
390 // if model or view matrix changed we need to either recalculate the inverse VP or copy previous
391 if( viewUpdateCount > COPY_PREVIOUS_MATRIX || projectionUpdateCount > COPY_PREVIOUS_MATRIX )
393 // either has actually changed so recalculate
394 Matrix::Multiply( mInverseViewProjection[ updateBufferIndex ], mViewMatrix[ updateBufferIndex ], mProjectionMatrix[ updateBufferIndex ] );
395 UpdateFrustum( updateBufferIndex );
397 // ignore the error, if the view projection is incorrect (non inversible) then you will have tough times anyways
398 static_cast< void >( mInverseViewProjection[ updateBufferIndex ].Invert() );
400 else if( viewUpdateCount == COPY_PREVIOUS_MATRIX || projectionUpdateCount == COPY_PREVIOUS_MATRIX )
402 // neither has actually changed, but we might copied previous frames value so need to
403 // copy the previous inverse and frustum as well
404 mInverseViewProjection[updateBufferIndex] = mInverseViewProjection[updateBufferIndex ? 0 : 1];
405 mFrustum[ updateBufferIndex ] = mFrustum[ updateBufferIndex ? 0 : 1 ];
409 bool Camera::ViewMatrixUpdated()
411 return 0u != mUpdateViewFlag;
414 uint32_t Camera::UpdateViewMatrix( BufferIndex updateBufferIndex )
416 uint32_t retval( mUpdateViewFlag );
417 if( 0u != mUpdateViewFlag )
419 if( COPY_PREVIOUS_MATRIX == mUpdateViewFlag )
421 // The projection matrix was updated in the previous frame; copy it
422 mViewMatrix.CopyPrevious( updateBufferIndex );
424 else // UPDATE_COUNT == mUpdateViewFlag
428 // camera orientation taken from node - i.e. look in abitrary, unconstrained direction
429 case Dali::Camera::FREE_LOOK:
431 Matrix& viewMatrix = mViewMatrix.Get( updateBufferIndex );
432 viewMatrix = mNode->GetWorldMatrix( updateBufferIndex );
436 const Matrix& owningNodeMatrix( mNode->GetWorldMatrix( updateBufferIndex ) );
437 Vector3 position{}, scale{};
438 Quaternion orientation{};
439 owningNodeMatrix.GetTransformComponents( position, orientation, scale );
440 mReflectionEye = position;
441 mUseReflectionClip = true;
443 Matrix& viewMatrix = mViewMatrix.Get( updateBufferIndex );
444 Matrix oldViewMatrix( viewMatrix );
445 Matrix::Multiply(viewMatrix, oldViewMatrix, mReflectionMtx);
449 mViewMatrix.SetDirty( updateBufferIndex );
453 // camera orientation constrained to look at a target
454 case Dali::Camera::LOOK_AT_TARGET:
456 const Matrix& owningNodeMatrix( mNode->GetWorldMatrix( updateBufferIndex ) );
457 Vector3 position, scale;
458 Quaternion orientation;
459 owningNodeMatrix.GetTransformComponents( position, orientation, scale );
460 Matrix& viewMatrix = mViewMatrix.Get( updateBufferIndex );
464 Vector3 up = orientation.Rotate( Vector3::YAXIS );
465 Vector4 position4 = Vector4(position);
466 Vector4 target4 = Vector4(mTargetPosition);
467 Vector4 up4 = Vector4(up);
471 Vector3 positionNew3;
472 Vector3 targetNewVector3;
476 VectorReflectedByPlane(positionNew, position4, mReflectionPlane);
477 VectorReflectedByPlane(targetNew, target4, mReflectionPlane);
478 VectorReflectedByPlane(upNew, up4, mReflectionPlane);
480 positionNew3 = Vector3(positionNew);
481 targetNewVector3 = Vector3(targetNew);
482 upNew3 = Vector3(upNew);
483 LookAt(viewMatrix, positionNew3, targetNewVector3, upNew3 );
485 Matrix oldViewMatrix( viewMatrix );
487 tmp.SetIdentityAndScale(Vector3(-1.0, 1.0,1.0));
488 Matrix::Multiply(viewMatrix, oldViewMatrix, tmp);
490 mReflectionEye = positionNew;
491 mUseReflectionClip = true;
495 LookAt( viewMatrix, position, mTargetPosition, orientation.Rotate( Vector3::YAXIS ) );
497 mViewMatrix.SetDirty( updateBufferIndex );
507 void Camera::UpdateFrustum( BufferIndex updateBufferIndex, bool normalize )
510 // Extract the clip matrix planes
512 Matrix::Multiply( clipMatrix, mViewMatrix[ updateBufferIndex ], mProjectionMatrix[ updateBufferIndex ] );
514 const float* cm = clipMatrix.AsFloat();
515 FrustumPlanes& planes = mFrustum[ updateBufferIndex ];
518 planes.mPlanes[ 0 ].mNormal.x = cm[ 3 ] + cm[ 0 ]; // column 4 + column 1
519 planes.mPlanes[ 0 ].mNormal.y = cm[ 7 ] + cm[ 4 ];
520 planes.mPlanes[ 0 ].mNormal.z = cm[ 11 ] + cm[ 8 ];
521 planes.mPlanes[ 0 ].mDistance = cm[ 15 ] + cm[ 12 ];
524 planes.mPlanes[ 1 ].mNormal.x = cm[ 3 ] - cm[ 0 ]; // column 4 - column 1
525 planes.mPlanes[ 1 ].mNormal.y = cm[ 7 ] - cm[ 4 ];
526 planes.mPlanes[ 1 ].mNormal.z = cm[ 11 ] - cm[ 8 ];
527 planes.mPlanes[ 1 ].mDistance = cm[ 15 ] - cm[ 12 ];
530 planes.mPlanes[ 2 ].mNormal.x = cm[ 3 ] + cm[ 1 ]; // column 4 + column 2
531 planes.mPlanes[ 2 ].mNormal.y = cm[ 7 ] + cm[ 5 ];
532 planes.mPlanes[ 2 ].mNormal.z = cm[ 11 ] + cm[ 9 ];
533 planes.mPlanes[ 2 ].mDistance = cm[ 15 ] + cm[ 13 ];
536 planes.mPlanes[ 3 ].mNormal.x = cm[ 3 ] - cm[ 1 ]; // column 4 - column 2
537 planes.mPlanes[ 3 ].mNormal.y = cm[ 7 ] - cm[ 5 ];
538 planes.mPlanes[ 3 ].mNormal.z = cm[ 11 ] - cm[ 9 ];
539 planes.mPlanes[ 3 ].mDistance = cm[ 15 ] - cm[ 13 ];
542 planes.mPlanes[ 4 ].mNormal.x = cm[ 3 ] + cm[ 2 ]; // column 4 + column 3
543 planes.mPlanes[ 4 ].mNormal.y = cm[ 7 ] + cm[ 6 ];
544 planes.mPlanes[ 4 ].mNormal.z = cm[ 11 ] + cm[ 10 ];
545 planes.mPlanes[ 4 ].mDistance = cm[ 15 ] + cm[ 14 ];
548 planes.mPlanes[ 5 ].mNormal.x = cm[ 3 ] - cm[ 2 ]; // column 4 - column 3
549 planes.mPlanes[ 5 ].mNormal.y = cm[ 7 ] - cm[ 6 ];
550 planes.mPlanes[ 5 ].mNormal.z = cm[ 11 ] - cm[ 10 ];
551 planes.mPlanes[ 5 ].mDistance = cm[ 15 ] - cm[ 14 ];
555 for ( uint32_t i = 0; i < 6; ++i )
557 // Normalize planes to ensure correct bounding distance checking
558 Plane& plane = planes.mPlanes[ i ];
559 float l = 1.0f / plane.mNormal.Length();
561 plane.mDistance *= l;
563 planes.mSign[i] = Vector3( Sign(plane.mNormal.x), Sign(plane.mNormal.y), Sign(plane.mNormal.z) );
568 for ( uint32_t i = 0; i < 6; ++i )
570 planes.mSign[i] = Vector3( Sign(planes.mPlanes[ i ].mNormal.x), Sign(planes.mPlanes[ i ].mNormal.y), Sign(planes.mPlanes[ i ].mNormal.z) );
573 mFrustum[ updateBufferIndex ? 0 : 1 ] = planes;
576 bool Camera::CheckSphereInFrustum( BufferIndex bufferIndex, const Vector3& origin, float radius )
578 const FrustumPlanes& planes = mFrustum[ bufferIndex ];
579 for ( uint32_t i = 0; i < 6; ++i )
581 if ( ( planes.mPlanes[ i ].mDistance + planes.mPlanes[ i ].mNormal.Dot( origin ) ) < -radius )
589 bool Camera::CheckAABBInFrustum( BufferIndex bufferIndex, const Vector3& origin, const Vector3& halfExtents )
591 const FrustumPlanes& planes = mFrustum[ bufferIndex ];
592 for ( uint32_t i = 0; i < 6; ++i )
594 if( planes.mPlanes[ i ].mNormal.Dot( origin + (halfExtents * planes.mSign[i]) ) > -(planes.mPlanes[ i ].mDistance) )
604 uint32_t Camera::UpdateProjection( BufferIndex updateBufferIndex )
606 uint32_t retval( mUpdateProjectionFlag );
607 // Early-exit if no update required
608 if ( 0u != mUpdateProjectionFlag )
610 if ( COPY_PREVIOUS_MATRIX == mUpdateProjectionFlag )
612 // The projection matrix was updated in the previous frame; copy it
613 mProjectionMatrix.CopyPrevious( updateBufferIndex );
615 else // UPDATE_COUNT == mUpdateProjectionFlag
617 switch( mProjectionMode )
619 case Dali::Camera::PERSPECTIVE_PROJECTION:
621 Matrix &projectionMatrix = mProjectionMatrix.Get( updateBufferIndex );
622 Perspective( projectionMatrix,
629 //need to apply custom clipping plane
630 if (mUseReflectionClip)
632 Matrix& viewMatrix = mViewMatrix.Get( updateBufferIndex );
633 Matrix viewInv = viewMatrix;
637 Dali::Vector4 adjReflectPlane = mReflectionPlane;
638 float d = mReflectionPlane.Dot(mReflectionEye);
641 adjReflectPlane.w = -adjReflectPlane.w;
644 Vector4 customClipping = viewInv * adjReflectPlane;
645 AdjustNearPlaneForPerspective(projectionMatrix, customClipping);
650 float* vZ = matZ.AsFloat();
652 Matrix::Multiply(projectionMatrix, projectionMatrix , matZ);
656 case Dali::Camera::ORTHOGRAPHIC_PROJECTION:
658 Matrix &projectionMatrix = mProjectionMatrix.Get( updateBufferIndex );
659 Orthographic( projectionMatrix,
660 mLeftClippingPlane, mRightClippingPlane,
661 mBottomClippingPlane, mTopClippingPlane,
662 mNearClippingPlane, mFarClippingPlane,
668 mProjectionMatrix.SetDirty( updateBufferIndex );
670 Matrix &finalProjection = mFinalProjection[ updateBufferIndex ];
671 finalProjection.SetIdentity();
673 Quaternion rotationAngle;
674 switch( mProjectionRotation )
678 rotationAngle = Quaternion( Dali::ANGLE_90, Vector3::ZAXIS );
683 rotationAngle = Quaternion( Dali::ANGLE_180, Vector3::ZAXIS );
688 rotationAngle = Quaternion( Dali::ANGLE_270, Vector3::ZAXIS );
692 rotationAngle = Quaternion( Dali::ANGLE_0, Vector3::ZAXIS );
697 rotation.SetIdentity();
698 rotation.SetTransformComponents( Vector3( 1.0f, 1.0f, 1.0f ), rotationAngle, Vector3( 0.0f, 0.0f, 0.0f ) );
700 Matrix::Multiply( finalProjection, mProjectionMatrix.Get( updateBufferIndex ), rotation );
702 --mUpdateProjectionFlag;
707 } // namespace SceneGraph
709 } // namespace Internal