Solved

3d zoom fit (directX, perspective) implementation needs direction

Posted on 2006-10-25
5
3,550 Views
Last Modified: 2013-12-26
I am creating a zoom fit function for a 3d model.  Using DirectX 9, VB.NET (C# and C++ OK), right hand coord system, and perspective view.  I have reviewed
http://www4.experts-exchange.com/Programming/Game_Development/Game_Graphics/OpenGL/Q_21903389.html
but still have some problems.

Basically, I need some direction (psuedocode) on an overall approach.  The above post was for ortho projections, and did not seem to work completely in my case.  Currently, I can transform all my world space vertices to screen space using Vector3.TransformCoordinate(vertex(i),matView*matProj).  This gives me a cloud of screen points, some of which are outside the current screen display (-1 to 1 in x and y directions).  Next, I calculate the world space coordinate of the center of a 2D screen bounding box (bb) containing all the transformed points using Vector3.TransformCoordinate(bb_center,Inverse(matView*matProj)), and move my camera target to that world space location, while also moving the camera position the same relative amount to preserve the camera look direction.  The effectivly "centers" the model, but I still need to determine how to adjust distance between camera position and camera target to effectivly zoom in/out such that the bound box of transformed points fills the viewable screen area.

Some issues are:  
1.  first, the camera centering I described works great in ortho mode, after which I can manually zoom in/out as necessary until the model is completely within the screen. In perspective mode, manually zooming does not end up with a model that fits the screen edge to edge.  Probably because as the camera position changes, so does the matView matrix, which would change all my transformed screen verticies.

2.  how to move the camera to do the zoom in/out automatically such that the model fits the screen

I would prefer not to have to do an itterative method for camera fitting which some have suggested.
There is little to no examples of this on the web, but if you find one, let me know!

    Public Const FOV As Single = Math.PI / 4
    Public Const NEARCLIP As Single = 1
    Public Const FARCLIP As Single = 100000
    matProj = Matrix.PerspectiveFieldOfViewRightHanded(FOV, AspectRatio, NEARCLIP, FARCLIP)
    matView = Matrix.LookAtRightHanded(CameraPosition, CameraTarget, CameraUp)









0
Comment
Question by:grknight
  • 3
  • 2
5 Comments
 
LVL 18

Expert Comment

by:JoseParrot
ID: 17815694
Hi,

Zoom implics in fixed camera. Just the focal lens changes.
If the camera moves, it is a travelling (move) or panning (rotating around a vertical axis) or tilting (rotation around the viewing ray).

I understand you need to inverse calculate the perspective projection size to make its zoom to fit the screen.

Is it your understanding too?

Jose
0
 

Author Comment

by:grknight
ID: 17815760
I don't believe the perspective matrix needs to change, as that would basically change the viewing fustrum.  I need to know how to calculate the new camera position and target (effectivly the view matrix) to fit the model to the screen.
0
 
LVL 18

Accepted Solution

by:
JoseParrot earned 500 total points
ID: 17824349
Hi,

So, what you are looking for is a moving camera, not zooming.
The zoom effect is obtained by changing the frustum angles, with the camera in the same position, not moved. Or simply by calculating the projection plane distance to the camera such that the perspective size equal to the screen size.

If you want to move the camera, by making it closer or farer to the target object, then we need a solver to find the camera position.

The entries are:
- camera initial position x0,y0,z0
- object dimensions and position
- target xt,yt,zt (which point the camera looks to) Suggestion: middle point of the object

The constraints are
- algorithm for object perspective width and height calculation
- maintain the new camera position in the line (x0,y0,z0) - (xt,yt,zt)
- screen width and height

The output is:
- camera x,y,z

The algorithm consists in moving the camera closer or farer to the object by smaller and smaller moves until the error (object perspective size - screen size) is less than the maximum acceptable error. This is needed because the perspective calculation is not a simple formula, but a sequence of matrices operations.

By zoming (no camera moving), we can simply:
  calculate the perspective
  find perspective size
  factor = screen size / perspective size
  find new camera position such that
      new camera position is in the line (x0,y0,z0) - (xt,yt,zt)
      new projection plane distance = factor * projection plane distance

I think this second approach is the best one.

Jose
0
 

Author Comment

by:grknight
ID: 17842794
I did some testing and here are the results.  First, moving the projection plane (near clip) distance does not cause any zooming effect, although changing the FOV in the projection matrix does.  However, I don't want to change the projection matrix since that would cause problems as the user continued to rotate/pan the model after the zoom fit operation.  Kinda like using the zoom on your camera,and then trying to navigate around your subject by just looking through the lens of a zoomed camera.  Tunnel vision.

Ultimately, I went with an iterative method that consists of calculating the bounding box of the model, transforming the box's corners to screen space and comparing with the current screen extents.  If they were outside the screen extents, I move the camera away from the model some fraction and then (because of perspective view) transform the box points again, move the camera in/out, etc... via a loop.  See the code below.

        Dim boundingPoints As New System.Collections.Generic.List(Of Vector3)
        Dim ProjBounds As New Bounds
        Dim BoundingBox As New BoundingBox

        BoundingBox.CreateFromVisibleObjects()   'create the bounding box from the model
        BoundingBox.BoxPoints(boundingPoints)     'get the box corner points (world space) and load into the array boundingPoints

        'Itterative Fit Procedure
        Dim ScreenBounds As New Bounds
        ScreenBounds.minX = -1
        ScreenBounds.maxX = 1
        ScreenBounds.minY = -1
        ScreenBounds.maxY = 1

        Dim relaxationFactor As Single = 0.25
        Dim Itt As Integer = 0
        Dim dx As Single = 0
        Dim dy As Single = 0

        Do While Not ApproxEqual(Math.Max(dx, dy), 1, 0.01) AndAlso Itt < 50
            '//CAMERA POSITION
            Canvas.UpdateViewProjMatrices(TrackBall.CamPosition, TrackBall.CamTarget)
            Canvas.TransformAllCoordinates(boundingPoints, ProjBounds)  'projBounds is a 2D rectangle in screen space around our transformed boundingPoints

            Dim ProjCenterInWorldSpace As Vector3 = Vector3.TransformCoordinate(ProjBounds.CenterPoint, _
                                                    Matrix.Invert(Matrix.Multiply(Canvas.matView, Canvas.matProj)))
            'move the camera target toward this point
            Dim CamTargettoProjCenterWS As Vector3 = Vector3.Subtract(ProjCenterInWorldSpace, TrackBall.CamTarget)
            TrackBall.CamPosition += CamTargettoProjCenterWS * relaxationFactor
            TrackBall.CamTarget += CamTargettoProjCenterWS * relaxationFactor
            '//===============================================

            '//CAMERA ZOOM====================================
            Canvas.UpdateViewProjMatrices(TrackBall.CamPosition, TrackBall.CamTarget)
            Canvas.TransformAllCoordinates(boundingPoints, ProjBounds)

            'adjust camera zoom
            dx = ProjBounds.deltaX / ScreenBounds.deltaX
            dy = ProjBounds.deltaY / ScreenBounds.deltaY

            If dx < 1 AndAlso dy < 1 Then
                'camera must move toward model
                'CamDirection is the un-normalized vector from cam position to cam target
                TrackBall.CamPosition += TrackBall.CamDirection * (1 - Math.Max(dx, dy)) * relaxationFactor
            ElseIf dx > 1 OrElse dy > 1 Then
                'camera must move away from model
                TrackBall.CamPosition += TrackBall.CamDirection * (1 - Math.Max(dx, dy)) * relaxationFactor
            End If
            '//===============================================

#If DEBUG Then
            frmMain.cfbCommandLine.AddMessage("Fit: " & Math.Max(dx, dy).ToString("F4") & "  Itt: " & Itt.ToString)
            Application.DoEvents()
            'TrackBall.Update()
            'System.Threading.Thread.Sleep(50)
#End If
            Itt += 1
        Loop
        Canvas.ReDraw()

0
 
LVL 18

Expert Comment

by:JoseParrot
ID: 17871702
Congratulations.
And thanks for sharing your result with all of us.
Jose
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

What is RenderMan: RenderMan is a not any particular piece of software. RenderMan is an industry standard, defining set of rules that any rendering software should use, to be RenderMan-compliant. Pixar's RenderMan is a flagship implementation of …
As game developers, we quickly learn that Artificial Intelligence (AI) doesn’t need to be so tough.  To reference Space Ghost: “Moltar, I have a giant brain that is able to reduce any complex machine into a simple yes or no answer. (http://www.youtu…
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now