panorama-viewer/panorama-viewer.js

113 lines
2.9 KiB
JavaScript

"use strict";
(() => {
const initShaderProgram = (gl) => {
const vShaderSrc = `
attribute vec3 position;
uniform mat4 viewMatrix;
void main() {
gl_Position = viewMatrix * vec4(position, 1);
}
`;
const fShaderSrc = `
void main() {
gl_FragColor = vec4(0.5, 0.5, 0, 1);
}
`;
const compileShader = (src, type) => {
let shader = gl.createShader(type);
gl.shaderSource(shader, src);
gl.compileShader(shader);
let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!success) {
throw gl.getShaderInfoLog(vShader);
}
return shader;
}
let vShader = compileShader(vShaderSrc, gl.VERTEX_SHADER);
let fShader = compileShader(fShaderSrc, gl.FRAGMENT_SHADER);
let program = gl.createProgram();
gl.attachShader(program, vShader);
gl.attachShader(program, fShader);
gl.linkProgram(program);
let success = gl.getProgramParameter(program, gl.LINK_STATUS);
if (!success) {
throw gl.getProgramInfoLog(program);
}
return program;
};
let viewer = document.getElementById("viewer");
let gl = viewer.getContext("webgl2");
let program = initShaderProgram(gl);
let viewMatrixLocation = gl.getUniformLocation(program, "viewMatrix");
// Set up mouse-panning state machine.
let θy = 0;
let θx = 0.25;
const PanState = Object.freeze({
idle: (event) => {
if (event.type === "mousedown") {
return PanState.panning;
}
return PanState.idle;
},
panning: (event) => {
switch (event.type) {
case "mouseup":
return PanState.idle;
case "mouseover":
if ((event.buttons & 1) == 0) {
return PanState.idle;
}
break;
case "mousemove":
θy += event.movementX * 0.025;
θx += event.movementY * 0.025;
break
}
return PanState.panning;
},
});
const runPanState = (mouseEvent) => {
panState = panState(mouseEvent);
}
var panState = PanState.idle;
viewer.addEventListener("mousedown", runPanState);
viewer.addEventListener("mouseup", runPanState);
viewer.addEventListener("mouseover", runPanState);
viewer.addEventListener("mousemove", runPanState);
const render = () => {
gl.useProgram(program);
let vertexBuffer = gl.createBuffer();
let vertices = new Float32Array([
0, 0, 0,
1, 0, 0,
1, 1, 0,
]);
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
// Create the transformation matrix.
let viewMatrix = mat4.create();
mat4.rotateX(viewMatrix, viewMatrix, θx);
mat4.rotateY(viewMatrix, viewMatrix, θy);
gl.uniformMatrix4fv(viewMatrixLocation, false, viewMatrix);
let positionLocation = gl.getAttribLocation(program, "position");
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 3, gl.FLOAT, false, 4 * 3, 0);
gl.drawArrays(gl.TRIANGLES, 0, 3);
requestAnimationFrame(render);
};
requestAnimationFrame(render);
})();