xxxxxxxxxx
128
// Keyboard arrows for rotating view
class Voxel { // 3D pixel
constructor(size) {
this.size = size;
// this.color = [255,255,255,0];
this.color = [255,255,255,255]; // test performance when showing all
}
shouldDisplay() {
if (this.color[3]==0) {
return false;
}
return true;
}
show() {
if (!this.shouldDisplay()) {return;}
push();
fill(this.color);
scale(this.size,this.size,this.size);
box(1);
pop();
}
}
class Cube {
constructor() {
this.d = 15; // dimention (how many voxels in a row)
this.voxelSize = 10;
this.voxels = [];
this.viewAngleX = 0;
this.viewAngleY = 0;
this.controlled = false;
this.initialize();
}
initialize() {
for (let i=0;i<pow(this.d,3);i++) {
append(this.voxels, new Voxel(this.voxelSize));
}
}
control() {
if (!this.controlled) {
return;
}
if (keyIsDown(UP_ARROW)) {
this.viewAngleY += 0.1;
}
if (keyIsDown(DOWN_ARROW)) {
this.viewAngleY -= 0.1;
}
if (keyIsDown(LEFT_ARROW)) {
this.viewAngleX -= 0.1;
}
if (keyIsDown(RIGHT_ARROW)) {
this.viewAngleX += 0.1;
}
}
update() {
this.control();
}
show() {
let fd = this.voxelSize*this.d; // used to go to next row
let cd = fd/2+this.voxelSize/2; // used to center voxel display
translate(-cd,-cd,-cd);
for (let i=0;i<this.d;i++) {
translate(this.voxelSize,0,0);
for (let j=0;j<this.d;j++) {
translate(0,this.voxelSize,0);
for (let k=0;k<this.d;k++) {
translate(0,0,this.voxelSize);
this.voxels[pow(this.d,2)*i+this.d*j+k].show();
}
translate(0,0,-fd);
}
translate(0,-fd,0);
}
}
}
let fps;
let c;
function setup() {
let cvs = createCanvas(350, 250, WEBGL); // Sets default size and ratio.
cvs.canvas.style.width = "100%"; // 100% width of available space
cvs.canvas.style.height = "auto";
fps = document.getElementById('fps');
frameRate(55);
// normalMaterial();
// noStroke();
c = new Cube();
}
function draw() {
background(220);
c.update();
rotateX(c.viewAngleY);
rotateY(c.viewAngleX);
c.show();
// if (frameCount%55==0) {
c.voxels[int(random(pow(c.d,3)))].color = [int(random(255)),int(random(255)),int(random(255)),255];
// }
displayfps();
}
function keyPressed() {
if (!c) {return;}
c.controlled = true;
}
function keyReleased() {
if (!c) {return;}
if (!keyIsPressed) {
// In case two keys were pressed and one released
c.controlled = false;
}
}
function displayfps() {
fps.innerText = ''+round(frameRate())
}