Generate vertices for a cylinder

This commit is contained in:
Brandon Dyck 2022-10-23 12:36:16 -06:00
parent 07380c8c91
commit a6b3f313e3

View File

@ -1,5 +1,90 @@
"use strict";
(() => {
const makeCylinder = (meridians = 3, parallels = 3) => {
// The number of meridians dividing the sphere's surface.
// Two meridians would make an XZ plane.
if (meridians < 3) {
throw "meridians must be ≥ 3";
}
// The number of parallels, including the poles, dividing the sphere's surface.
// Two parallels would make a vertical line segment.
if (parallels < 3) {
throw "parallels must be ≥ 3";
}
const radius = 1;
const positions = new Float32Array(meridians * parallels * 3);
let positionsIdx = 0;
for (let p = 0; p < parallels; p++) {
const y = -radius + p * 2 * radius / parallels;
for (let m = 0; m < meridians; m++) {
const θ = 2 * Math.PI / meridians;
const x = Math.sin(θ) * radius;
const z = Math.cos(θ) * radius;
const currPosition = [
Math.sin(θ) * radius,
y,
Math.cos(θ) * radius,
];
for (const coord of currPosition) {
positions[positionsIdx++] = coord;
}
}
}
const indices = new Uint16Array(meridians * (parallels - 1) * 6);
const textureCoords = new Float32Array(meridians * (parallels - 1) * 12);
let indicesIdx = 0;
let textureCoordsIdx = 0;
for (let p = 0; p < parallels - 1; p++) {
for (let m = 0; m < meridians; m++) {
const lowerLeft = p * meridians + m;
const lowerRight = p * meridians + (m + 1) % meridians;
const upperLeft = (p + 1) * meridians + m;
const upperRight = (p + 1) * meridians + (m + 1) % meridians;
const currIndices = [
// Lower triangle
lowerLeft, lowerRight, upperRight,
// Upper triangle
lowerLeft, upperRight, upperLeft,
];
for (const index of currIndices) {
indices[indicesIdx++] = index;
}
const currTextureCoords = [
// Lower triangle
m / meridians, p / parallels,
(m + 1) / meridians, p / parallels,
(m + 1) / meridians, (p + 1) / parallels,
// Upper triangle
m / meridians, p / parallels,
(m + 1) / meridians, (p + 1) / parallels,
m / meridians, (p + 1) / parallels,
];
for (const coord of currTextureCoords) {
textureCoords[textureCoordsIdx++] = coord;
}
}
}
for (let p = 0; p < parallels; p++) {
for (let m = 0; m < meridians; m++) {
/*
*/
}
}
return { positions, textureCoords, indices };
}
console.log(makeCylinder());
const initShaderProgram = (gl) => {
const vShaderSrc = `
attribute vec3 position;