PDA

View Full Version : Please double check my object positioning/orienting code



skippyj777
08-23-2000, 09:58 AM
This code is suppose to setup a matrix, that when multiplied using glMultMatrix, will set up the model coordinates for a new model, with the given position as the model's origin, the look up vector as the model's y-axis, and the look at vector as the model's z-axis. How can I improve it?

OOGLE_MATRIXF is a 16 element array. The matrix is as follows:

00 01 02 03
04 05 06 07
08 09 10 11
12 13 14 15

OOGLE_POSITIONF is a record/structure as follows:
OOGLE_POSITIONF = record
vertex, lookat, lookup: OOGLE_VECTORF
end;


// Modified version of Mesa 3.21 gluLookAt function
procedure OoglePositionObject(var outmatrix: OOGLE_MATRIXF; const pos: OOGLE_POSITIONF); overload;
var
m: OOGLE_MATRIXF absolute outmatrix;
x, y, z: array[0..2] of Single;

procedure m2(row, col: Integer; v: Single);
begin
m[col*4+row] := v;
end;

procedure norm(v: array of Single);
var
mag: Single;
begin
mag := sqrt(sqr(v[0]) + sqr(v[1]) + sqr(v[2]));
if mag = 0 then Exit;
v[0] := v[0] / mag;
v[1] := v[1] / mag;
v[2] := v[2] / mag;
end;
begin
// Z vector
z[0] := -pos.lookat.x;
z[1] := -pos.lookat.y;
z[2] := -pos.lookat.z;
norm(z);

// Y vector
y[0] := pos.lookup.x;
y[1] := pos.lookup.y;
y[2] := pos.lookup.z;
norm(y);

// X vector = Y cross Z
x[0] := y[1] * z[2] - y[2] * z[1];
x[1] := -y[0] * z[2] + y[2] * z[0];
x[2] := y[0] * z[1] - y[1] * z[0];

// Recompute Y = Z cross X
y[0] := z[1] * x[2] - z[2] * x[1];
y[1] := -z[0] * x[2] + z[2] * x[0];
y[2] := z[0] * x[1] - z[1] * x[0];

{ Cross product gives area of parallelogram, which
is < 1 for non-perpendicular unit-length vectors,
so normalize x and y here }
norm(x);
norm(y);

// Set matrix values
m2(0, 0, x[0]);
m2(0, 1, x[1]);
m2(0, 2, x[2]);
m2(0, 3, 0);

m2(1, 0, y[0]);
m2(1, 1, y[1]);
m2(1, 2, y[2]);
m2(1, 3, 0);

m2(2, 0, z[0]);
m2(2, 1, z[1]);
m2(2, 2, z[2]);
m2(2, 3, 0);

m2(3, 0, pos.vertex.x);
m2(3, 1, pos.vertex.y);
m2(3, 2, pos.vertex.z);
m2(3, 3, 1);
end;