Mirror in Metal

↑ I tried to express a mirror in Metal and this is the result.

I don’t know the proper way to express a mirror, so there might be a better other way.

At first you have to show an object in a mirror. So I made the matrix. The concept is here :
Before translate and rotate
↑You can see a mirror and an object. The mirror object have a center point and a normal vector.

Just before flip
↑You can make a mirrored object easily with just flipping after the object translates and rotates as mirror’s center exists at origin and mirror’s normal vector is the same direction with y axis.

So step by step...

(1) translate At first the mirror should go to the origin of the coordinate. The matrix is here :
    GLKMatrix4 matrix1 = GLKMatrix4Identity;
    matrix1 = GLKMatrix4Translate(matrix1, -mirror.position.x, -mirror.position.y, -mirror.position.z);
‘mirror' is an object of the mirror and it has a property ‘position’.

(2) rotate
Next the mirror should rotate as its normal is the same direction with y axis.
Well, this process is a little bit annoying but not difficult. You can get the angle between normal and y axis with their dot product and cross product like this :
equation 1
And now you already know two vector and its angle, then you can get the matrix to do it with this :

equation 2

This matrix is to rotate θ around a unit vector (nx,ny,nz). This unit vector can be got by cross product.

(3) flip
Now you can flip object data against x-z plane and it can be done with just changing plus or minus sign of y axis, and its matrix is like this :
    GLKMatrix4 matrix3 = GLKMatrix4Identity;
    matrix3.m11 = -1.0;

(4) rotate inversely
Next you have to go back, so data should be rotated inversely with inverse matrix of (2)
And there is a method ‘GLKMatrix4Invert’ in GLKit.

(5) transpose to first position
That’s all!

Now there are 5 matrices, so you have to make one matrix from those matrices with multiplying.
    mirrorMatrix = GLKMatrix4Multiply(matrix5 , matrix4);
    mirrorMatrix = GLKMatrix4Multiply(mirrorMatrix , matrix3);
    mirrorMatrix = GLKMatrix4Multiply(mirrorMatrix , matrix2);
    mirrorMatrix = GLKMatrix4Multiply(mirrorMatrix , matrix1);
The mirrored robot appears with this one matrix. And it should be masked using stencil buffer like :
Mask with stencil buffer in Metal / iPhone App Development Memo
Develop | Comments(0) | Trackback(0)