Viewing Pipeline Draw

by Trevor Dixon

HTML

<script src="https://rawgit.com/mrdoob/three.js/master/src/Three.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/src/math/Quaternion.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/src/math/Vector3.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/src/math/Matrix4.js"></script>
<script src="https://rawgit.com/mrdoob/three.js/master/src/math/Vector4.js"></script>
<canvas id="canvas" width="640" height="480"></canvas>

JavaScript

function V3(init) { return new THREE.Vector3().fromArray(init || Array(3)); }
function V4(init) { return new THREE.Vector4().fromArray(init || Array(4)); }
function M4(init) { return new THREE.Matrix4().fromArray(init || Array(4)); }

function getTransformMatrix(camera, screen) {
    var e = V3(camera.position),
        g = V3(camera.gaze),
        up = V3(camera.up),
        n = camera.near,
        f = camera.far,
        fov = camera.fov,
        nx = screen.width,
        ny = screen.height
        distanceToN = Math.abs(n - e.z),
        vSpan = distanceToN / (Math.tan((Math.PI-fov)/2)),
        hSpan = nx/ny * vSpan,
        t = vSpan,
        b = -vSpan,
        l = -hSpan,
        r = hSpan;

    var w = g.clone().normalize().multiplyScalar(-1),
        u = up.clone().cross(w).normalize(),
        v = w.clone().cross(u);
    
    var Mvp = new THREE.Matrix4(
        nx/2,    0 ,   0,  (nx - 1)/2,
        0   ,  ny/2,   0,  (ny - 1)/2,
        0   ,    0 ,   1,      0     ,
        0   ,    0 ,   0,      1
    ),
    
    Morth = new THREE.Matrix4(
        2/(r - l),  0      ,  0      ,  (-r-l)/(r-l),
        0        ,  2/(t-b),  0      ,  (-t-b)/(t-b),
        0        ,  0      ,  2/(n-f),  (-n-f)/(n-f),
        0        ,  0      ,  0      ,  1
    ),
        
    P = new THREE.Matrix4(
        n,  0,  0    ,     0  ,
        0,  n,  0    ,     0  ,
        0,  0,  n + f,  -f * n,
        0,  0,  1    ,     0
    ),
        
    Mcam = new THREE.Matrix4(
        u.x, u.y, u.z, 0,
        v.x, v.y, v.z, 0,
        w.x, w.y, w.z, 0,
        0  ,  0 ,  0 , 1
    ).multiply(new THREE.Matrix4(
        1, 0, 0, -e.x,
        0, 1, 0, -e.y,
        0, 0, 1, -e.z,
        0, 0, 0,   1
    ));
    
    return (new THREE.Matrix4())
        .copy(Mvp)
        .multiply(Morth)
        .multiply(P)
        .multiply(Mcam);

    pixel.applyMatrix4(T).divideScalar(pixel.w);
    
    return [pixel.x, pixel.y];
}


var canvas = document.getElementById('canvas'),
   ...