Upload
rodd
View
45
Download
0
Embed Size (px)
DESCRIPTION
Transformaciones geométricas. 2D y 3D. ¿ Cómo usamos las transformaciones geométricas ?. Los objetos de una escena son colecciones de puntos … Estos objetos tiene posición , orientación , tamaño - PowerPoint PPT Presentation
Citation preview
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Computación Gráfica
Semestre 201321CRN
Septiembre 2012 – Febrero 2013
Ciro DuránIngeniero en Computación
[email protected]://www.ciroduran.com
@chiguire
Transformaciones geométricas
2D y 3D
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
¿Cómo usamos las transformaciones geométricas?
• Los objetos de una escena son colecciones de puntos…
• Estos objetos tiene posición, orientación, tamaño• Corresponde a las transformaciones, Translación
(), Rotación (), y Escalamiento ()
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
¿Cómo usamos las transformaciones geométricas? (2/2)
• Una escena tiene una cámara/punto de vista desde el cual se renderiza la escena.
• La cámara tiene una posición y orientación en el espacio 3D…
• Éstos corresponden a las transformaciones de Traslación y Rotación
• Se necesitan otros tipos de transformaciones de vista también – las veremos ahora
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Algunos conceptos de álgebra lineal…
• Geometría de coordenadas 3D• Vectores en espacios 2D y 3D• Producto punto y producto cruz – definiciones y usos• Notación y álgebra vectorial y matricial• Matriz identidad• Asociatividad multiplicativa
– Ej. A(BC) = (AB)C
• Traspuesta e inversa de matriz – definición, uso y cálculo• Coordenadas homogéneas ()
• ¡Necesitarán entender estos conceptos!• Una “ayudaíta” (en inglés) ->
http://cs.brown.edu/courses/cs123/resources/Linear_Algebra.pdf
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Transformaciones lineales (1/3)
• Representamos los vectores como letras en bold-itálica () y escalares como letras en itálica solamente (c)
• Cualquier vector en el plano puede ser definido como la suma de dos vectores base no co-lineares en el plano– Recordemos que una base es un conjunto
de vectores que cumplen dos propiedades:– Los vectores son linealmente
independientes– Cualquier vector en el espacio vectorial
puede ser generado por una combinación lineal de la base
• Las constantes escalares pueden ser usadas para ajustar magnitud y dirección del vector resultante
a b = a + b
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Transformaciones lineales (2/3)
• Definición de una función lineal, f:– fdonde el dominio y co-dominio de f son idénticos
• La función de una adición de vectores es equivalente a la adición de la función aplicada a cada uno de los vectores
–
• La función de una multiplicación escalar con un vector es un escalar multiplicado por la función aplicada al vector
• Ambas de estas propiedades deben ser satisfechas para que f sea un operador lineal
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
– Uso gráfico: transformaciones de puntos alrededor del origen (dejando invariante al origen)• Esto incluye al escalamiento y
a las rotaciones (pero no a la translación),
• La translación no es una función lineal (mueve el origen)
• Cualquier transformación lineal de un punto resultará en otro punto en el mismo sistema de coordenadas, transformado sobre el origen
Transformaciones lineales (3/3)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Las Transformaciones Lineales pueden ser representadas como matrices no singulares (invertibles)
• Comencemos con las transformaciones 2D: =
• La matriz puede ser también escrita como: , donde = , =
• Donde y son los vectores unitarios estandar sobre los vectores x e y:
= = • ¿Por qué es importante esto? Esto significa que podemos
computar las columnas de la matriz de transformación una por una determinando como nuestra transformación afecta cada uno de los vectores unitarios estándar. Por lo que “ manda a = “
• Use esta estrategia para derivar las matrices de transformación
Transformaciones lineales como matrices (1/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Una transformación de un vector columna arbitrario tiene la forma:
=
• Sustituyamos por = – La transformación aplicada a es la primera
columna de
• Ahora sustituyamos por = – La transformación aplicacada a es la segunda
columna de
Transformaciones lineales como matrices (2/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Escalemos por 3, por 2 (Sx = 3, Sy = 2)– = (vértice original); =
(nuevo vértice)
• Derivemos determinando cómo y deberían ser transformadas
– = * = (Escalar en X por ) , la primera columna de
– = * = (Escalar en Y por), la segunda columna de
• Por lo tanto obtenemos :
Escalando en 2D (1/2)Efecto lateral: la casa cambia su posición relativa al origen
2
6
2
9
1
2
1
3
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• es una matriz diagonal – se puede confirmar la derivación simplemente mirando las propiedades de las matrices diagonales:
• = – En donde es una matriz
diagonal
• La posición de = ( posición sobre la diagonal de posición de )
• multiplica cada coordenada de una por los factores de escalamiento () especificados por las posiciones sobre la diagonal, como se espera
– = , =
Escalando en 2D (2/2) Otras propiedades del
escalamiento: No conserva longitudes en los
objetos No conserva los ángulos entre
partes de los objetos, a menos que el escalamiento sea uniforme, )
Si el objeto no está en su origen, traslada la casa relativa al origen – algo comúnmente no deseado…
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Rotar por alrededor del origen • donde
– = (vértice original)
– = (vértice nuevo)
– Derivemos determinando cómo y deberían transformarse
• = , primera columna de • = , segunda columna de
– Y así obtenemos :
Rotación en 2D (1/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Intentemos multiplicar las matrices
• = = ’
• Otras propiedades de la rotación:– Conserva longitudes y ángulos entre partes de los objetos– La rotación es de cuerpo rígido– Para objetos que no están en el origen, nuevamente una traslación puede no
ser deseada (i.e. esto rota alrededor del origen, no alrededor del centro de rotación de la casa)
Rotación en 2D (2/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• La traslación no es una transformación linea (no centrada alrededor del origen)
• No puede ser representada como una matriz 2x2 invertible…
• Pregunta: ¿Hay alguna otra solución?
• Respuesta: Sí, , donde • Sumar para trasladar, esto
es inconsistente.
¿Qué hay sobre la traslación? Si tratamos todas las
transformaciones de una manera consistente, es decir, con representación de matrices, entonces podríamos combinar las trnasformaciones al componer sus matrices
Usemos nuevamente una matriz ¿Cómo? Con coordenadas
homogéneas: agrega una dimensión adicional, el eje w, y una coordenada extra, el componente w. Y así 2D -> 3D (efectivamente el
hiperespacio para colocar el espacio 2D)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Permite la expresión de todas las transformaciones 2D como matrices 3x3
– Comenzamos con el punto en el plano y aplicamos un mapeo para llevarlo al plano-w en el hiperespacio
• Las coordenadas resultantes (’, ’) en nuestro nuevo punto son diferentes del original (, ) , donde ’ = , ’ =
Coordenadas homogéneas (1/3)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Una vez que tenemos este punto podemos aplicar una versión homogeneizada de nuestras matrices de transformación (próximas láminas) para llevarlo a un nuevo punto en el hiperespacio
• Finalmente, queremos obtener el punto resultante en el espacio 2D nuevamente, así que hacemos un reverso del mapeo anterior (dividimos todas las entradas por )
• Esto convierte nuestro punto en el hiperespacio al punto correspondiente en el epsacio 2D
• El vértice ahora es representado como
Coordenadas homogéneas (2/3)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Hacer que las transformaciones mapeen puntos en el hiperplano a otro punto en el hiperplano. Las transformaciones aplicadas a un punto en el hiperplano siempre sacar un resultado también en el mismo hiperplano (clausura matemática)
• La transformación aplicada a se corresponde con • ¿Cómo aplicamos esto a nuestras matrices de transformación?• Para transformaciones lineales, mantenemos una sub-matriz
2x2, expandimos la matriz como aparece a continuación, donde para las transformaciones 2D, la submatriz superior izquierda es la que incluye el escalamiento o la matriz de rotación derivada anteriormente:
Coordenadas homogéneas (3/3)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Nuestra matriz de traslación () puede ahora ser representada al incluir el vector de traslación en la columna derecha en el tope como:
• • Pruébalo, multiplícalo por el vértice
homogenizado • = = = ’• Las coordenadas trasladadas, ’
siguen homogéneas
De vuelta a la traslación
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• La traslación usa una matriz 3x3, pero el escalamiento y la rotación son matrices 2x2
• ¡Homogenicemos! Esto no afecta la propiedad lineal del escalamiento y la rotación
• Nuetras nuevas matrices de transformación se verán así…
• Nota: estas 3 transformaciones se le llaman transformaciones afines.
Transformaciones homogenizadas
Transformación Matriz
Escalado
Rotación
Traslación
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Escalado: Escalar por 15 en la dirección , 17 en la
• Rotación: Rotar por 1
• Traslación: Trasladar por -16 en el eje , +18 en el
Ejemplos
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Hasta ahora, sólo hemos usar la noción de un punto en nuestro espacio 2D.• Ahora debemos presentar una distinción entre vectores y puntos.
• Usamos las coordenadas homogéneas para representar más convenientemente la traslación; luego los puntos se representan como (x, y, 1)T
• Un vector puede ser rotado o escalado, pero no trasladado (porque siempre comienza en el origen), no uses la coordenada homogénea (x, y, 0)T
• Por ahora, enfoquémonos solamente en los puntos (típicamente vértices)
¡Antes de continuar! Vectores vs. Puntos
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• How do we find the inverse of a transformation?• Take the inverse of the transformation matrix
(thanks to homogenization, they’re all invertible!):
Inversas
Transformation Matrix Inverse Does it make sense?
Scaling If you scale something by factor X, the inverse is scaling by 1/X
Rotation Not so obvious, but can use math! Rotation Matrix is orthonormal, so inverse should just be the transpose, (proof on slide 23)
Translation If you translate by X, the inverse is translating by -X
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Some uses we’ll be seeing later• Placing sub-objects in parent’s coordinate system to construct
hierarchical scene graph
– transforming primitives their own coordinate systems
• View volume normalization
– mapping arbitrary view volume into canonical view volume along -axis
• Parallel (orthographic, oblique) and perspective projection
• Perspective transformation (turn viewing pyramid into a cuboid to turn perspective projection into parallel projection)
More with Homogeneous Coordinates
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• The inverse of a rotation matrix is just its transpose, That’s really convenient, so let’s understand how it works…
• Take a rotation matrix = • First note these properties of
– Columns are orthogonal to each other: vi • vj = 0 (i j)
– Columns represent unit length vectors: ||vi|| = 1
• Let’s see what happens when we multiply
• =
• Using the properties we defined we can see that the result is the identity matrix , thus , and by definition of matrix inverse, matrix must be inverse of
A moment of appreciation for linear algebra
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• We now have a number of tools at our disposal, we can combine them!
• An object in a scene uses many transformations in sequence, how do we represent this in terms of functions?
• Transformation is a function; by associativity we can compose functions: (
• This is the same as first applying to some input and then applying : (
• Consider our functions as matrices ( and respectively) and our input as a vector ()
• Our composition is equivalent to
Composition of Transformations (2D) (1/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• We can now form compositions of transformation matrices to form a more complex transformation
• For example,, which scales point, then rotates, then translates:
•
• Note that we apply the matrices in sequence right to left, but practically, given associativity, we can compose them and apply the composite to all the vertices in, say, a mesh.
• Important: Order Matters!• Matrix Multiplication is not commutative. • Be sure to check out the Transformation Game at
http://www.cs.brown.edu/exploratories/freeSoftware/repository/edu/brown/cs/exploratories/applets/transformationGame/transformation_game_guide.html
• Let’s see an example…
Composition of Transformations (2D) (2/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Not commutativeTranslate by =6, =0 then rotate by 45º
Rotate by 45º then translate by =6, =0
0 1
1
2
2
3 4 5 6 7 8 9 10
3
4
5
6
Y
X 0
1
1
2
2
3 4 5 6 7 8 9 10
3
4
5
6
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Start: Goal:
• Important concept: Make the problem simpler
• Translate object to origin first, scale , rotate, and translate back:–
• Apply to all vertices
Composition (an example) (2D) (1/2)
Rotate 90Uniform Scale 3xBoth around object’s center,not the origin
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• But what if we mixed up the order? Let’s try
• Oops! We managed to scale it properly but when we rotated it we rotated the object about the origin, not its own center, shifting its position…Order Matters!
Composition (an example) (2D) (2/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Aside: Skewing/shearing “Skew” an object to the side, like
shearing a card deck by displacing each card relative to the previous one What physical situations mirror this behavior?!?
Squares become parallelograms - coordinates skew to right, stays same
Notice that base of house (at =1) remains horizontal, but shifts right - why?
Y
X 0
1
1
2
2
3 4 5 6 7 8 9 10
3
4
5
6
4
10tan
11
Skew
2D non-Homogeneous
100
010
0tan
11
Skew
2D Homogeneous
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• What is the inverse of a sequence of transformations?
• Inverse of a sequence of transformations is the composition of the inverses of each transformation in reverse order
• Say we want to do the opposite transform of the example on Slide 27, what will our sequence look like?
• We still translate to origin first, then translate back at the end!
Inverses Revisited
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Windowing transformation maps contents of a 2D clip rectangle ("window") to a rectangle on the screen, e.g., interior canvas of a window manager's window ("viewport"), so also known as window-to-viewport transformation
• Sends rectangle with bounding coordinatesto
Aside: Windowing Transformations
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Aside: Transforming Coordinate Axes
Rotation Scaling Translation
• We understand linear transformations as changing the position of vertices relative to the standard axes
• Can also think of transforming the coordinate axes themselves
• Just as in matrix composition, be careful of which order you modify your coordinate system
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• How should we treat geometric transformations in 3D?
• Just add one more coordinate/axis!
• A point is represented as • A matrix for a linear transformation can be
represented as where corresponds to the z-coordinate,
• But remember to use homogeneous coordinates! Thus embed the scale and rotation matrices upper left submatrix, translation vector upper right column
Dimension++ (3D!)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
Transformation Matrix Comments
ScalingLooks just like the 2D version right? We just added an term.
Rotation See next slide
This one’s more complicated. In 2D there is only one axis of rotation. In 3D there are infinitely many, thus the matrix has to take into account all possible axes.See next slide…
TranslationSimilar to the 2D version, we just have one more term, , representing change in theaxis
35/45
Transformations in 3D
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Rotation by angle around v =
• Here’s a not so friendly rotation matrix:
• This is called the coordinate form of Rodrigues’s formula• Let’s try a different way…
36/45
Rodrigues’s Formula…
Note: This is an arbitrary unit vector in space
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Every rotation can be represented as the composition of 3 different angles of counter-clockwise rotation around 3 axes, namely– -axis in the plane by – -axis in the plane by – -axis in the plane by
• Also known as Euler angles, makes problem of rotation much easier
• : rotation around axis, : rotation about axis, : rotation about axis• Note these differ only in where the 3x3 submatrix is embedded in
the homogeneous matrix• You can compose these matrices to form a composite rotation
matrix 37/45
Rotating axis by axis (1/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• It would still be difficult to find the 3 angles to rotate by, given arbitrary axis and specified angle
• Solution? Make the problem easier by mapping u to one of the principal axes
• Step 1: Find a to rotate around axis to put in the plane
•Step 2: Then find a to rotate around the axis to align with the axis
• Step 3: Rotate by around axis = coincident axis
• Step 4: Finally, undo the alignment rotations (inverse)
• Rotation Matrix:
38/45
Rotating axis by axis (2/2)
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Inverses are once again parallel to their 2D versions…
• Composition works exactly the same way…
39/45
Inverses and Composition in 3D!
Transformation Matrix Inverse
Scaling
Rotation
Translation
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Let’s take some 3D object, say a cube, centered at (2,2,2)• Rotate in object’s space by 30 around axis, 60 around and
90around • Scale in object space by 1 in the , 2 in the , 3 in the • Translate by (2,2,4) in world space• Transformation Sequence: , where translates to
•
40/45
Example in 3D!
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Objects can be complex:
• 3D scenes are often stored in a directed acyclic graph (DAG) called a scene graph– WPF – Open Scene Graph (used in the Cave)– Sun’s Java3D™– X3D ™ (VRML ™ was a precursor to X3D)
• Typical scene graph format:– objects (cubes, sphere, cone, polyhedra etc.): stored as nodes (default: unit size at
origin)– attributes (color, texture map, etc.) stored as separate nodes– transformations are also nodes
41/45
Transformations and the scene graph (1/4)
ROBOT
upper body lower body
headbase
Scene Graph
stanchiontrunk arm arm
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán42/45
Transformations and the scene graph (2/4)
Step 1: Various transformations are applied to each of the leaves (object primitives—head, base, etc.)Step 2: Transformations are then applied to groups of these objects as a whole (upper body, lower body)
Together this hierarchy of transformations forms the “robot” scene as a whole
Represents a transformation
For your assignments use simplified format: Attributes stored as a components of each object node (no separate
attribute node) Transform node affects its subtree Only leaf nodes are graphical objects All internal nodes that are not transform nodes are group nodes
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• Notion of a cumulative transformation matrix that builds as you move up the tree (), appending higher level transformation matrices to the front of your sequence
• Example:– For o1, – For o2, – For o3,
– For a vertex v in o3, position in world (root) coordinate system is:
43/45
Transformations and the scene graph (3/4)
object nodes (geometry)
transformation nodes
group nodes
𝑴𝟏
𝑴𝟑
𝑴𝟐
𝑴 𝟒
𝑴𝟓
Universidad Católica Andrés Bello » Computación Gráfica » Ciro Durán
• You can reuse groups of objects (sub-trees) if they have been defined
• Group 3 has been used twice here
• Transformations defined within group 3 itself are the same
• Different s for each use of group 3 as a whole
44/45
Transformations and the scene graph (4/4)
group3
obj3 obj4
𝑻 𝟓𝑻 𝟔
𝑻 𝟒
root
group1
𝑻 𝟏𝑻 𝟐
obj1 group3
𝑻 𝟑
group2
group3obj2