510 likes | 515 Views
CS 352: Computer Graphics. Chapter 4: Geometric Objects and Transformations. Sensational Solar System Simulator. Perspective. How is it that mathematics can model the (ideal) world so well?. Overview. Scalars and Vectors Coordinates and frames Homogeneous coordinates
E N D
CS 352: Computer Graphics Chapter 4: Geometric Objects andTransformations
Perspective • How is it that mathematics can model the (ideal) world so well?
Overview • Scalars and Vectors • Coordinates and frames • Homogeneous coordinates • Rotation, translation, and scaling • Concatenating transformations • Transformations in Canvas • Projections • A virtual trackball
Background: linear algebra • Quick review of important concepts • Point: location (x, y) or (x, y, z) • Vector: direction and magnitude<x, y, z>
Vectors • Magnitude of a vector: |v| • Direction of a vector, unit vector: v • Affine sum: P = (1-a) Q + a R • MV.js: mix( u, v, s ) ^
Dot Product • Def: u • v = uxvx + uyvy+ uzvz • u • v = |u| |v| cos θ • Uses: • Angle between two vectors? • Are two vectors perpendicular? • Do two vectors formacute or obtuse angle? • Is a face visible?(backface culling) • MV.js: dot
Cross Product • u v = <uyvz- uzvy, uzvx- uxvz, uxvy- uyvx> • Direction: normal to plane containing u, v (using right-hand rule in right-handed coordinate system) • Magnitude: |u||v| sin θ • Uses: • Angle between vectors? • Face outward normal? • MV.js: cross
Face outward normals • Why might I need face normals? • How to find the outward normal of a face? • Assume that vertices are listed in a standard order when viewed from the outside -- counter-clockwise • Cross product of the first two edges is outward normal vector • Note that first corner must be convex
Ouch! • How can I tell if I have run into a wall? • Walls, motion segments, intersection tests • How to tell if two line segments (p1, p2) and (p3, p4) intersect? • Looking from p1 to p2, check that p3 and p4 are on opposite sides • Looking from p3 to p4, check that p1 and p2 are on opposite sides • Sylvester.js
Sensational Solar System Simulator • How do you get the earth to go around the sun? • How do you get the moon to do that fancy motion?
Coordinate systems and frames • A graphics program uses many coordinate systems, e.g. model, world, screen • Frame: origin + basis vectors (axes) • Need to transform between frames
Transformations • Changes in coordinate systems usually involve • Translation • Rotation • Scale • 3-D Rotation and scale can be represented as 3x3 matrices, but not translation • We're also interested in a 3-D to 2-D projection • We use 3-D "homogeneous coordinates" with four components per point • 2-D homogeneous coordinates have three components
Homogeneous Coordinates • A point: (x, y, z, w) where w is a "scale factor" • Converting a 3D point to homogeneous coordinates: (x, y, z) (x, y, z, 1) • Transforming back to 3-space: divide by w • (x, y, z, w) (x/w, y/w, z/w) • (3, 2, 1): same as (3, 2, 1, 1) = (6, 4, 2, 2) = (1.5, 1, 0.5, 0.5) • Where is the point (3, 2, 1, 0)? • Point at infinity or "pure direction." • Used for vectors (vs. points)
Homogeneous transformations • Most important reason for using homogeneous coordinates: • All affine transformations (line-preserving: translation, rotation, scale, perspective, skew) can be represented as a matrix multiplication • You can concatenate several such transformations by multiplying the matrices together. Just as fast as a single transform! • Modern graphics cards implement homogeneous transformations in hardware (or used to)
2D Homogeneous transformations • HTML canvas setTransform: void ctx.setTransform( x_scale, x_skew, y_scale, y_skew, dx, dy);
Scaling • Note that the scaling fixed point is the origin
Rotation • General rotation: about anaxis v by angle u with fixed point p • With origin as fixed point, about x, y, or z-axis:
Rotating about another point • How can I rotate around another fixed point, e.g. [1, 2, 3]? • Translate [1, 2, 3] -> 0, 0, 0 (T) • Rotate (R) • Translate back (T-1) • T-1 R T P = P'
Rotating about another axis • How can I rotate about an arbitrary axis? • Can combine rotationsabout z, y, and x:Rx RyRz P = P' • Math library usually hasa function…
Concatenating transformations • Many transformations can be concatenated into one matrix for efficiency • Canvas: transformations concatenate • Set the transformation to the identity to reset • Or, push/pop matrices (save/restore state)
Example: Orbiting the Sun • How to make the earth move 5 degrees? • Set appropriate modeling matrix before drawing image • Rotate 5 degrees, then translate • What Canvas code to use? • How to animate a continuous rotation? • Every few ms, modify modeling matrix and redisplay • Reset to original and concatenate rotation and translation • How to make it spin on its own axis too? • rotate, translate, rotate, draw
Earth & Moon solar.cx.save(); solar.cx.rotate(timefrac/365); // earth around the sun solar.cx.translate(250,0); solar.cx.save(); solar.cx.rotate(timefrac); solar.cx.drawImage(earth, -earth.width/2, –earth.height/2); solar.cx.restore(); solar.cx.save(); // moon around earth solar.cx.rotate(timefrac/28); solar.cx.translate(56, 0); solar.cx.drawImage(moon, -moon.width/2, -moon.height/2); solar.cx.restore();
Moon River, wider than a mile… • How to make the moon follow that crazy path? • Try it…
Project 4: Wonderfully Wiggly Working Widget • Write a program to animate something that has moving parts that have moving parts • Use both translation and rotation • It should save/restore state • Examples: • Walking robot • Giraffe pedaling a unicycle • Person waving in a moving convertible • Spirograph
Accelerometer events • Many browsers now support the DeviceOrientation API (W3C draft) • [demo] • window.ondevicemotion = function(event) {varaccelerationX = event.accelerationIncludingGravity.xvaraccelerationY = event.accelerationIncludingGravity.yvaraccelerationZ = event.accelerationIncludingGravity.z}
How to display a complex object? • You don't want to put all those teapot triangles in your source code…
A JSON object format • Object description with vertex positions and faces { "vertices" : [ 40,40,40, 60,0,60, 20,0,60, 40,0,20], "indices" : [ 0,1,2, 0,2,3, 0,3,1, 1,3,2] } ________________________________ x = data.vertices[0];
Loading an object via AJAX • What do you think of this code? trackball.load = function() { var objectURL = $('#object1').val(); $.getJSON(objectURL, function(data) { trackball.loadObject(data); }); trackball.display(); } • Remember the first 'A' in AJAX! • Wait for the object to load before displaying it $.getJSON(objectURL, function(data) { trackball.loadObject(data); trackball.display(); });
Question • How to move object into the sphere centered at the origin with radius 1?
Point normalization • Find min and max values of X, Y, Z • Find center point, Xc, Yc, Zc • Translate center to origin (T) • Scale (S) • P' = S T P • Modeling matrix M = S T • Note apparent reversed order of matrices
Question • How to draw a 3-D object on a 2-D screen?
Orthographic projection • Zeroing the z coordinate with a matrix multiplication is easy… • Or, just ignore the Z value when drawing
Perspective projection • Can also be done with a single matrix multiply using homogeneous coordinates • Uses the divide-by-w step • We'll see in next chapter
Transformations in the Pipeline • Three coordinate frames: • World coordinates (e.g. unit cube) • Eye (projection) coordinates (from viewpoint) • Window coordinates (after projection) • Two transformations convert between them • Modeling xform * world coords -> eye coords • Projection xform * eye coords -> window coords
Transformations in Canvas • Maintain separate 3-D model and project matrices • Multiply vertices by these matrices before drawing polygons • Vertices are transformed as they flow through the pipeline
Transformations 2 • If p is a vertex, pipeline produces Cp (post-multiplication only) • Can concatenate transforms in CTM: C I C T(4, 5, 6) C R(45, 1, 2, 3) C T(-4, -5, -6) [C = T-1 S T] • Note that last transform defined is first applied
Putting it all together • Load vertices and faces of object. • Normalize: put them in (-1, 1, -1, 1, -1, 1) cube • Put primitives into a display list • Set up viewing transform to display that cube • Set modeling transform to identity • To spin the object, every 1/60 second do: • Add 5 degrees to current rotation amount • Set up modeling transform to rotate by current amount
Virtual Trackball • Imagine a trackball embedded in the screen • If I click on the screen, what point on the trackball am I touching?
Trackball Rotation Axis • If I move the mouse from p1 to p2, what rotation does that correspond to?
Virtual Trackball Rotations • Rotation about the axis n = p1xp2 • Fixed point: if you use the [-1, 1] cube, it is the origin • Angle of rotation: use cross product |uv| = |u||v| sin θ (or use Sylvester's built-in function) n = p1.cross(p2); theta = p1.angleFrom(p2); modelMat = oldModelMat.multiply(1); // restore old matrix modelMat = Matrix.Rotation(theta,n).multiply(modelMat);
Hidden surface removal • What's wrong with this picture? • How can weprevent hiddensurfaces frombeing displayed?
Hidden surface removal • How can we prevent hidden surfaces from being displayed? • Painter's algorithm: paint from back to front. • How can we do thisby computer, whenpolygons come in arbitrary order?
Poor-man's HSR • Transform points for current viewpoint • Sort back to front by the face's average Z • Does this always work?
HSR Example • Which polygon should be drawn first? • We'll study other algorithms later
A better HSR algorithm • Depth buffer algorithm
A fast HSR algorithm • Depth buffer algorithm • Render each point in polygon with screen coordinates and distance from viewer • Only place it in the frame buffer if it is closer than the point already there
Data structures needed • An array of vertices, oldVertices • An array of normalized vertices, vertices[n][3], in the [-1, 1] cube • An array for vertices in world coordinates • An array of faces containing vertex indexes, int faces[n][max_sides]. Use faces[n][0] to store the number of sides. Set max_sides to 12 or so.