1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
| function picking() {
var vx, vy, vz, i, j;
var rval = false;
// Viewport Space to NDC to Clip Space
vx = lastMouseX;
vy = lastMouseY;
vz = 0.0; // By setting vz to 0 we will compute a ray passing through v
// NDC coordinates
var nx = 2.0*vx/(gl.viewportWidth) - 1.0;
var ny = 1.0 - 2.0*vy/(gl.viewportHeight);
var nz = 2*vz - 1.0;
var nw = 1.0;
var c = Vector.create([nx, ny, nz, nw]); // Clip coordinates same as NDC coordinates
// Clipping Space to View Space
var v = pMatrixInv.x(c);
// Rescale
v.elements[0] = v.elements[0] / v.elements[3];
v.elements[1] = v.elements[1] / v.elements[3];
v.elements[2] = v.elements[2] / v.elements[3];
v.elements[3] = 1.0;
// View Space to Model Space
var R = mvPickMatrix.minor(1,1,3,3);
var Rt = R.transpose();
var tc = mvPickMatrix.col(4);
var t = Vector.create([ tc.e(1), tc.e(2), tc.e(3) ]);
var tp = Rt.x(t);
var mvPickMatrixInv = Matrix.I(4);
for (i=0; i < 3; i++) {
for (j=0; j < 3; j++) {
mvPickMatrixInv.elements[i][j] = Rt.elements[i][j];
}
mvPickMatrixInv.elements[i][3] = -1.0 * tp.elements[i];
}
var ray_start_point = Vector.create([ 0.0, 0.0, 0.0, 1.0 ]); // camera position in Viewspace
// v = point in view space
// w = point in world space
v.elements[3] = 0; // Make v a ray in view coordinates
var w = mvPickMatrixInv.x(v); // w is now a ray in world coordinates
var a = mvPickMatrixInv.x(ray_start_point);
var anchor = Vector.create([ a.e(1), a.e(2), a.e(3) ]);
var direction = Vector.create([ w.e(1), w.e(2), w.e(3) ]);
// Perform intersection test between ray l and world geometry (cube)
var l = Line.create(anchor, direction.toUnitVector());
// Geometry in our case is a front plane of cube at z = 1;
anchor = Vector.create([ 0, 0, 1 ]); // Point on the front face of cube
var normal = Vector.create([0, 0, 1 ]); // Normal of front face of cube
var p = Plane.create(anchor, normal); // Plane representing a cubes front face
// Check if line l and plane p intersect
if (l.intersects(p)) {
var intersectionPt = l.intersectionWith(p);
if ((intersectionPt.e(1) >= -1.0) && (intersectionPt.e(1) <= 1.0) &&
(intersectionPt.e(2) >= -1.0) && (intersectionPt.e(2) <= 1.0) ) {
rval = true; // intersection point is on the cubes front face
}
}
return rval;
} |
Partager