4230-hw-1/Pendulum/ShapedObject.js

76 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

2022-07-01 08:45:53 +00:00
// PendulumComponents.js
// John Breaux 2022-06-30
// Super-class for simple, flat-color drawn primitives
2022-07-01 08:49:08 +00:00
"use strict";
2022-07-01 08:45:53 +00:00
//
// Classes
//
// ShapedObject: Super-class for simple drawn primitives
class ShapedObject {
constructor({ color = { r: 1, g: 1, b: 1, a: 0.5 } } = {}) {
// Set object color
this.color = [color.r, color.g, color.b, color.a];
}
// Convert to Float32Array [x, y]
vertex_array() {
// allocate space for center.xy + vertices.xy
var ret = new Float32Array((this.vertices.length) * 2);
// save the vertices
for (var i = 0; i < this.vertices.length; i++) {
var j = 2 * i;
ret[j] = this.vertices[i].x;
ret[j + 1] = this.vertices[i].y;
}
return ret;
}
// Generate the index_array for the shape
index_array() {
var ret = new Uint8Array(this.vertices.length + 1);
for (var i = 0; i < this.vertices.length; i++) {
ret[i] = i
}
ret[this.vertices.length] = 0;
return ret;
}
// Initialize the object's drawing parameters
init(gl) {
// Make the buffers
this.vertexBuffer = acquire_buffer(gl);
this.indexBuffer = acquire_buffer(gl);
// Bind the buffers
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
// Write date into the buffers
gl.bufferData(gl.ARRAY_BUFFER, this.vertex_array(), gl.STATIC_DRAW);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.index_array(), gl.STATIC_DRAW);
}
// Draw the object
draw(gl, modelMatrix, u_ModelMatrix) {
// Bind the buffers
gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
// Set the object's color
var u_Color = acquire_uniform(gl, 'u_Color');
gl.uniform4fv(u_Color, this.color);
// get a_Position
enable_attribute(gl, 'a_Position', 2, gl.FLOAT);
// Pass the rotation matrix to the vertex shader
gl.uniformMatrix4fv(u_ModelMatrix, false, modelMatrix.elements);
// Draw the Anchor
gl.drawElements(this.draw_primitive, this.vertices.length, gl.UNSIGNED_BYTE, 0);
}
}
// Give me your [HeartShapedObject]