computer-graphics-study/index.ts
2021-09-05 15:46:06 +09:00

81 lines
2.4 KiB
TypeScript

/// <reference path="node_modules/webgl-strict-types/index.d.ts" />
import {createProgramFromSource, ProgramError, ShaderError} from "./src/gl_util";
/// <reference path="./src/glsl.d.ts" />
import vert_src from "./src/vertex";
import frag_src from "./src/fragment";
function findCanvas(){
const canvas = document.querySelector("canvas");
if(canvas === null){
console.error("couldn't find canvas");
throw new Error("canvas is null");
}
return canvas;
}
function getGLContext(canvas : HTMLCanvasElement){
const gl = canvas.getContext("webgl2") as any as WebGL2RenderingContextStrict|null;
if(gl === null){
console.error("webgl2 is not supported!");
throw new Error("webgl2 not supported");
}
return gl;
}
class Renderer{
gl : WebGL2RenderingContextStrict;
constructor(gl: WebGL2RenderingContextStrict){
this.gl = gl;
try{
const program = createProgramFromSource(gl,vert_src,frag_src);
gl.useProgram(program);
}
catch(e){
if(e instanceof ShaderError){
console.log(e.message,"\n",e.info);
}
else if(e instanceof ProgramError){
console.log(e.message,"\n",e.info);
}
else throw e;
}
}
draw(){
const gl = this.gl;
gl.viewport(0,0,gl.canvas.width,gl.canvas.height);
const position = [
-0.5,-0.5,
0.0,0.5,
0.5,-0.5
];
let positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER,positionBuffer);
gl.enableVertexAttribArray(0);
gl.vertexAttribPointer(0,2,gl.FLOAT,false,0,0);
const floatPosition = new Float32Array(position);
gl.bufferData(gl.ARRAY_BUFFER,floatPosition,gl.STATIC_DRAW);
gl.drawArrays(gl.TRIANGLES,0,3);
gl.deleteBuffer(positionBuffer);
}
}
function main(){
const canvas = findCanvas();
const gl = getGLContext(canvas);
const renderer = new Renderer(gl);
window.addEventListener("resize",(e)=>{
e.preventDefault();
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
renderer.draw();
});
canvas.width = document.body.clientWidth;
canvas.height = document.body.clientHeight;
renderer.draw();
}
main();