xxxxxxxxxx
103
let ground
let cam
const unused = 0
function half(x) {
return Math.floor(x / 2)
}
function fourth(x) {
return Math.floor(x / 4)
}
function s(x) {
return x * Math.random() - 0.5
}
class Ground {
constructor(size) {
this.size = size
this.elevation = Array(size).fill().map(() => Array(size).fill(unused));
this.generate(this.elevation, 0, 0, size-1, size-1, 0.3)
}
generate(d, x1, y1, x2, y2, rug) {
//console.log(d)
const x3 = half(x1 + x2);
const y3 = half(y1 + y2);
if (y3 < y2) {
if (d[x1][y3] == unused) {
d[x1][y3] = half(d[x1][y1] + d[x1][y2]) + s(rug * (y2 - y1));
}
console.log(x2, y3)
d[x2][y3] = half(d[x2][y1] + d[x2][y2]) + s(rug * (y2 - y1));
}
if (x3 < x2) {
if (d[x3][y1] == unused) {
d[x3][y1] = half(d[x1][y1] + d[x2][y1]) + s(rug * (x2 - x1));
}
d[x3][y2] = half(d[x1][y2] + d[x2][y2]) + s(rug * (x2 - x1));
}
if (x3 < x2 && y3 < y2) {
d[x3][y3] = fourth(d[x1][y1] + d[x2][y1] + d[x1][y2] + d[x2][y2]) +
s(rug * (Math.abs(x2 - x1) + Math.abs(y2 - y1)));
}
if (x3 < x2 - 1 || y3 < y2 - 1) {
this.generate(d, x1, y1, x3, y3, rug);
this.generate(d, x1, y3, x3, y2, rug);
this.generate(d, x3, y1, x2, y3, rug);
this.generate(d, x3, y3, x2, y2, rug);
}
}
draw() {
console.log(this.elevation)
translate(-width/2, 50, 0)
rotateX(radians(90))
let g = 10
for (let row = 0; row < this.size - 1; row += 1) {
beginShape(TRIANGLE_STRIP)
for (let col = 0; col < this.size - 1; col += 1) {
vertex(row * g, col * g, this.elevation[row][col])
vertex((row + 1) * g, col * g, this.elevation[row + 1][col])
}
endShape()
}
}
}
function setup() {
createCanvas(500, 400, WEBGL)
// cam = createCamera()
// cam.camera(0, 100, 300, 0, 0, 0, -1, 0)
ground = new Ground(40)
// for (let row = 0; row < 40; row += 1) {
// for (let col = 0; col < 40; col += 1) {
// ground[row][col] = noise(row*0.03, col*0.03)*150
// }
// }
}
function draw() {
background(220)
ground.draw()
// drawGround()
}
function drawGround() {
const g = 10
push()
rotateX(1.57)
translate(-width / 2, -height / 2)
if (mouseX < width / 2) {
cam.pan(-0.001)
} else if (mouseX > width / 2) {
cam.pan(0.001)
}
if (mouseY < height / 2) {
cam.tilt(0.001)
} else if (mouseY > height / 2) {
cam.tilt(-0.001)
}
cam.move(0, 0, -0.5)
pop()
}