summaryrefslogtreecommitdiff
path: root/src/Terrain.js
blob: 291a4fc6d97055acbd0c69041cf6a20c6b4ba992 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
'use strict';

import Voronoi from './3rdparty/rhill-voronoi-core.js';

import { lerp, clamp, useAverage } from './modules/Util.js';
import { dist, AABB, QuadTree } from './modules/Geometry.js';


/* from here on up, we always assume that points live in the range [(0,0), (1,1)) */

function lloydRelax(point_set, density) {
	/* setup quadtree and averages */
	let tree = new QuadTree(1,1);
	let averages = {};
	for (let i=0; i<point_set.length; i++) {
		const point = point_set[i];
		point.index = i;
		tree.insert(point);

		let [avg, append] = useAverage();
		const cent_x = { avg, append };
		[avg, append] = useAverage();
		const cent_y = { avg, append };
		averages[i] = { cent_x, cent_y };
	}

	/* compute average centroids */
	for (let x=0; x<1; x += 1/density) {
		for (let y=0; y<1; y += 1/density) {
			const point = { x, y };
			const closest = tree.closest(point);
			const { cent_x, cent_y } = averages[closest.index];
			cent_x.append(point.x);
			cent_y.append(point.y);
		}
	}

	/* return centroid points */
	const result = [];
	for (let i=0; i<point_set.length; i++) {
		const point = { x: averages[i].cent_x.avg(), y: averages[i].cent_y.avg() };
		result.push(point);
	}
	return result;
}


class Terrain {
	constructor() {
		const N_SEED_POINTS = 2**12;
		const N_RELAX_ITERATIONS = 1;
		const RELAX_DENSITY = 400;
		const randomPoint = () => ({x: Math.random(), y: Math.random()});

		this.min_height = 0;
		this.max_height = 0;

		let seed_points = [];
		for (let i=0; i<N_SEED_POINTS; i++) seed_points.push(randomPoint());

	for (let i=0; i<N_RELAX_ITERATIONS; i++)
			lloydRelax(seed_points, RELAX_DENSITY);

		const v = new Voronoi();
		this.voronoi = v.compute(seed_points, {xl: 0, xr: 1, yt: 0, yb: 1});

		this.tree = new QuadTree(1,1);
		let index = 0;
		for (let v of this.voronoi.vertices) {
			v.height = v.y;
			v.index = index;
			index += 1;
			this.tree.insert(v);
		}

		this.graph = {}; 
		for (let e of this.voronoi.edges) {
			if (!this.graph[e.va.index]) this.graph[e.va.index] = new Set();
			if (!this.graph[e.vb.index]) this.graph[e.vb.index] = new Set();

			this.graph[e.va.index].add(e.vb.index);
			this.graph[e.vb.index].add(e.va.index);
		}
	}


	applyBrush(x, y, f, strength, radius) {
		const region = new AABB(x-radius, y-radius, 2*radius, 2*radius);
		const points = this.tree.root.getPointsInRegion(region);
		
		const dist2 = (a, b) => (a.x - b.x)**2 + (a.y - b.y)**2;

		const sigma = radius/3;
		const beta = 1/(2*sigma*sigma);
		const center = { x, y };
		const power = pt => Math.exp(-beta * dist2(pt, center));
		
		for (let pt of points) f(pt, strength * power(pt));
	}


	getNeighbors(point) {
		const indices = Array.from(this.graph[point.index]);
		return indices.map( index => this.voronoi.vertices[index] );
	}


	renderGrid(ct) {
		ct.save();
		ct.lineWidth = 0.001;
		for (let edge of this.voronoi.edges) {
			ct.fillStyle = `hsl(${edge.va.height}, 100%, 50%)`;
			ct.beginPath();
			ct.arc(edge.va.x, edge.va.y, 0.0005, 0, 2*Math.PI);
			ct.closePath();
			ct.fill();

			/*ct.beginPath();
			ct.moveTo(edge.va.x, edge.va.y);
			ct.lineTo(edge.vb.x, edge.vb.y);
			ct.closePath();
			ct.stroke();
			*/
		}
		ct.restore();
	}

	render(ct) {
		function rgb(r, g, b) {
			this.r = r; this.g = g; this.b = b;
		}
		const renderRgb = rgb => `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`;
		const lerpColors = (a, b, alpha) => new rgb(
			lerp(a.r, b.r, alpha),
			lerp(a.g, b.g, alpha),
			lerp(a.b, b.b, alpha)
		);
		const getBucket = (value, min, max, numBuckets) => {
			const delta = max - min;
			const step = delta/numBuckets;
			return clamp(Math.floor((value-min)/step), 0, numBuckets-1);
		}
		const getColor = (value, min, max, colors) => {
			if (value < min) return colors[0];
			if (value >= max) return colors[colors.length-1];

			const step = (max - min)/(colors.length - 1);

			const index = getBucket(value, min, max, colors.length-1);
			const alpha = (value - (index*step) - min)/step;
			const color = lerpColors(
				colors[index], colors[index+1], 
				alpha
			);
			if (color.r <= 0)
				console.log(value, index, alpha, color);
			return color;
		}

		const colors = [
			/* ocean */
			new rgb(31, 59, 68),
			new rgb(68, 130, 149),
			
			/* land */
			new rgb(229, 199, 169),
			new rgb(198, 133, 67),
			new rgb(117, 89, 61),

			/* mountain */
			new rgb(82, 74, 64),
			new rgb(82, 74, 64),
			new rgb(255, 255, 255),
		];
		ct.save();

		for (let cell of this.voronoi.cells) {
			ct.beginPath();

			let height = 0;
			let count = 1;
			for (let edge of cell.halfedges) {
				const p0 = edge.getStartpoint();
				const p1 = edge.getEndpoint();
				height += p0.height;
				count += 1;
				ct.lineTo(p0.x, p0.y);
				ct.lineTo(p1.x, p1.y);
			}
			ct.closePath();
			height /= count;
			height = 10 * Math.floor(height/10);
			const color = getColor(height, 0, 100, colors);
			if (color.r <=0) console.log(color);
			ct.fillStyle = renderRgb(color);
			ct.strokeStyle = renderRgb(color);
			ct.stroke();
			ct.fill();
		}

		ct.restore();
	}
}

export { lloydRelax };
export default Terrain;