mirror of
https://github.com/Azgaar/Fantasy-Map-Generator.git
synced 2025-12-17 09:41:24 +01:00
v1.5.32 - resolve conflicts
This commit is contained in:
parent
79584fffac
commit
67ec838160
7 changed files with 465 additions and 361 deletions
32
main.js
32
main.js
|
|
@ -545,7 +545,6 @@ function generate() {
|
||||||
reGraph();
|
reGraph();
|
||||||
drawCoastline();
|
drawCoastline();
|
||||||
|
|
||||||
elevateLakes();
|
|
||||||
Rivers.generate();
|
Rivers.generate();
|
||||||
defineBiomes();
|
defineBiomes();
|
||||||
|
|
||||||
|
|
@ -626,7 +625,7 @@ function calculateVoronoi(graph, points) {
|
||||||
TIME && console.timeEnd("calculateDelaunay");
|
TIME && console.timeEnd("calculateDelaunay");
|
||||||
|
|
||||||
TIME && console.time("calculateVoronoi");
|
TIME && console.time("calculateVoronoi");
|
||||||
const voronoi = Voronoi(delaunay, allPoints, n);
|
const voronoi = new Voronoi(delaunay, allPoints, n);
|
||||||
graph.cells = voronoi.cells;
|
graph.cells = voronoi.cells;
|
||||||
graph.cells.i = n < 65535 ? Uint16Array.from(d3.range(n)) : Uint32Array.from(d3.range(n)); // array of indexes
|
graph.cells.i = n < 65535 ? Uint16Array.from(d3.range(n)) : Uint32Array.from(d3.range(n)); // array of indexes
|
||||||
graph.vertices = voronoi.vertices;
|
graph.vertices = voronoi.vertices;
|
||||||
|
|
@ -1137,22 +1136,6 @@ function reMarkFeatures() {
|
||||||
TIME && console.timeEnd("reMarkFeatures");
|
TIME && console.timeEnd("reMarkFeatures");
|
||||||
}
|
}
|
||||||
|
|
||||||
// temporary elevate some lakes to resolve depressions and flux the water to form an open (exorheic) lake
|
|
||||||
function elevateLakes() {
|
|
||||||
if (templateInput.value === "Atoll") return; // no need for Atolls
|
|
||||||
TIME && console.time('elevateLakes');
|
|
||||||
const cells = pack.cells, features = pack.features;
|
|
||||||
const maxCells = cells.i.length / 100; // size limit; let big lakes be closed (endorheic)
|
|
||||||
cells.i.forEach(i => {
|
|
||||||
if (cells.h[i] >= 20) return;
|
|
||||||
if (features[cells.f[i]].group !== "freshwater" || features[cells.f[i]].cells > maxCells) return;
|
|
||||||
cells.h[i] = 20;
|
|
||||||
//debug.append("circle").attr("cx", cells.p[i][0]).attr("cy", cells.p[i][1]).attr("r", .5).attr("fill", "blue");
|
|
||||||
});
|
|
||||||
|
|
||||||
TIME && console.timeEnd('elevateLakes');
|
|
||||||
}
|
|
||||||
|
|
||||||
// assign biome id for each cell
|
// assign biome id for each cell
|
||||||
function defineBiomes() {
|
function defineBiomes() {
|
||||||
TIME && console.time("defineBiomes");
|
TIME && console.time("defineBiomes");
|
||||||
|
|
@ -1160,7 +1143,6 @@ function defineBiomes() {
|
||||||
cells.biome = new Uint8Array(cells.i.length); // biomes array
|
cells.biome = new Uint8Array(cells.i.length); // biomes array
|
||||||
|
|
||||||
for (const i of cells.i) {
|
for (const i of cells.i) {
|
||||||
if (f[cells.f[i]].group === "freshwater") cells.h[i] = 19; // de-elevate lakes; here to save some resources
|
|
||||||
const t = temp[cells.g[i]]; // cell temperature
|
const t = temp[cells.g[i]]; // cell temperature
|
||||||
const h = cells.h[i]; // cell height
|
const h = cells.h[i]; // cell height
|
||||||
const m = h < 20 ? 0 : calculateMoisture(i); // cell moisture
|
const m = h < 20 ? 0 : calculateMoisture(i); // cell moisture
|
||||||
|
|
@ -1718,11 +1700,7 @@ function addZones(number = 1) {
|
||||||
function showStatistics() {
|
function showStatistics() {
|
||||||
const template = templateInput.value;
|
const template = templateInput.value;
|
||||||
const templateRandom = locked("template") ? "" : "(random)";
|
const templateRandom = locked("template") ? "" : "(random)";
|
||||||
|
const stats = ` Seed: ${seed}
|
||||||
mapId = Date.now(); // unique map id is it's creation date number
|
|
||||||
mapHistory.push({seed, width:graphWidth, height:graphHeight, template, created:mapId});
|
|
||||||
console.log(`
|
|
||||||
Seed: ${seed}
|
|
||||||
Canvas size: ${graphWidth}x${graphHeight}
|
Canvas size: ${graphWidth}x${graphHeight}
|
||||||
Template: ${template} ${templateRandom}
|
Template: ${template} ${templateRandom}
|
||||||
Points: ${grid.points.length}
|
Points: ${grid.points.length}
|
||||||
|
|
@ -1733,7 +1711,11 @@ function showStatistics() {
|
||||||
Burgs: ${pack.burgs.length-1}
|
Burgs: ${pack.burgs.length-1}
|
||||||
Religions: ${pack.religions.length-1}
|
Religions: ${pack.religions.length-1}
|
||||||
Culture set: ${culturesSet.selectedOptions[0].innerText}
|
Culture set: ${culturesSet.selectedOptions[0].innerText}
|
||||||
Cultures: ${pack.cultures.length-1}`);
|
Cultures: ${pack.cultures.length-1}`;
|
||||||
|
|
||||||
|
mapId = Date.now(); // unique map id is it's creation date number
|
||||||
|
mapHistory.push({seed, width:graphWidth, height:graphHeight, template, created:mapId});
|
||||||
|
INFO && console.log(stats);
|
||||||
}
|
}
|
||||||
|
|
||||||
const regenerateMap = debounce(function() {
|
const regenerateMap = debounce(function() {
|
||||||
|
|
|
||||||
|
|
@ -419,7 +419,7 @@
|
||||||
const hull = getHull(start, s.i, s.cells / 10);
|
const hull = getHull(start, s.i, s.cells / 10);
|
||||||
const points = [...hull].map(v => pack.vertices.p[v]);
|
const points = [...hull].map(v => pack.vertices.p[v]);
|
||||||
const delaunay = Delaunator.from(points);
|
const delaunay = Delaunator.from(points);
|
||||||
const voronoi = Voronoi(delaunay, points, points.length);
|
const voronoi = new Voronoi(delaunay, points, points.length);
|
||||||
const chain = connectCenters(voronoi.vertices, s.pole[1]);
|
const chain = connectCenters(voronoi.vertices, s.pole[1]);
|
||||||
const relaxed = chain.map(i => voronoi.vertices.p[i]).filter((p, i) => i%15 === 0 || i+1 === chain.length);
|
const relaxed = chain.map(i => voronoi.vertices.p[i]).filter((p, i) => i%15 === 0 || i+1 === chain.length);
|
||||||
paths.push([s.i, relaxed]);
|
paths.push([s.i, relaxed]);
|
||||||
|
|
|
||||||
|
|
@ -1,296 +1,376 @@
|
||||||
(function (global, factory) {
|
(function (global, factory) {
|
||||||
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
||||||
typeof define === 'function' && define.amd ? define(factory) :
|
typeof define === 'function' && define.amd ? define(factory) :
|
||||||
(global.Rivers = factory());
|
(global.Rivers = factory());
|
||||||
}(this, (function () {'use strict';
|
}(this, (function () {'use strict';
|
||||||
|
|
||||||
const generate = function(changeHeights = true) {
|
const generate = function(changeHeights = true) {
|
||||||
TIME && console.time('generateRivers');
|
TIME && console.time('generateRivers');
|
||||||
Math.random = aleaPRNG(seed);
|
Math.random = aleaPRNG(seed);
|
||||||
const cells = pack.cells, p = cells.p, features = pack.features;
|
const cells = pack.cells, p = cells.p, features = pack.features;
|
||||||
|
|
||||||
// build distance field in cells from water (cells.t)
|
// build distance field in cells from water (cells.t)
|
||||||
void function markupLand() {
|
void function markupLand() {
|
||||||
const q = t => cells.i.filter(i => cells.t[i] === t);
|
const q = t => cells.i.filter(i => cells.t[i] === t);
|
||||||
for (let t = 2, queue = q(t); queue.length; t++, queue = q(t)) {
|
for (let t = 2, queue = q(t); queue.length; t++, queue = q(t)) {
|
||||||
queue.forEach(i => cells.c[i].forEach(c => {
|
queue.forEach(i => cells.c[i].forEach(c => {
|
||||||
if (!cells.t[c]) cells.t[c] = t+1;
|
if (!cells.t[c]) cells.t[c] = t+1;
|
||||||
}));
|
}));
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// height with added t value to make map less depressed
|
||||||
|
const h = Array.from(cells.h)
|
||||||
|
.map((h, i) => h < 20 || cells.t[i] < 1 ? h : h + cells.t[i] / 100)
|
||||||
|
.map((h, i) => h < 20 || cells.t[i] < 1 ? h : h + d3.mean(cells.c[i].map(c => cells.t[c])) / 10000);
|
||||||
|
|
||||||
|
resolveDepressions(h);
|
||||||
|
features.forEach(f => {delete f.river; delete f.flux; delete f.inlets});
|
||||||
|
|
||||||
|
const riversData = []; // rivers data
|
||||||
|
cells.fl = new Uint16Array(cells.i.length); // water flux array
|
||||||
|
cells.r = new Uint16Array(cells.i.length); // rivers array
|
||||||
|
cells.conf = new Uint8Array(cells.i.length); // confluences array
|
||||||
|
let riverNext = 1; // first river id is 1, not 0
|
||||||
|
|
||||||
|
void function drainWater() {
|
||||||
|
const land = cells.i.filter(i => h[i] >= 20).sort((a,b) => h[b] - h[a]);
|
||||||
|
const outlets = new Uint32Array(features.length);
|
||||||
|
// enumerate lake outlet positions
|
||||||
|
features.filter(f => f.type === "lake" && (f.group === "freshwater" || f.group === "frozen")).forEach(l => {
|
||||||
|
let outlet = 0;
|
||||||
|
if (l.shoreline) {
|
||||||
|
outlet = l.shoreline[d3.scan(l.shoreline, (a,b) => h[a] - h[b])];
|
||||||
|
} else { // in case it got missed or deleted
|
||||||
|
WARN && console.warn('Re-scanning shoreline of a lake');
|
||||||
|
const shallows = cells.i.filter(j => cells.t[j] === -1 && cells.f[j] === l.i);
|
||||||
|
let shoreline = [];
|
||||||
|
shallows.map(w => cells.c[w]).forEach(cList => cList.forEach(s => shoreline.push(s)));
|
||||||
|
outlet = shoreline[d3.scan(shoreline, (a,b) => h[a] - h[b])];
|
||||||
}
|
}
|
||||||
}()
|
outlets[l.i] = outlet;
|
||||||
|
delete l.shoreline // cleanup temp data once used
|
||||||
|
});
|
||||||
|
|
||||||
// height with added t value to make map less depressed
|
const flowDown = function(min, mFlux, iFlux, ri, i = 0){
|
||||||
const h = Array.from(cells.h)
|
if (cells.r[min]) { // downhill cell already has river assigned
|
||||||
.map((h, i) => h < 20 || cells.t[i] < 1 ? h : h + cells.t[i] / 100)
|
if (mFlux < iFlux) {
|
||||||
.map((h, i) => h < 20 || cells.t[i] < 1 ? h : h + d3.mean(cells.c[i].map(c => cells.t[c])) / 10000);
|
cells.conf[min] = cells.fl[min]; // mark confluence
|
||||||
|
if (h[min] >= 20) riversData.find(r => r.river === cells.r[min]).parent = ri; // min river is a tributary of current river
|
||||||
resolveDepressions(h);
|
cells.r[min] = ri; // re-assign river if downhill part has less flux
|
||||||
features.forEach(f => {delete f.river; delete f.flux;});
|
|
||||||
|
|
||||||
const riversData = []; // rivers data
|
|
||||||
cells.fl = new Uint16Array(cells.i.length); // water flux array
|
|
||||||
cells.r = new Uint16Array(cells.i.length); // rivers array
|
|
||||||
cells.conf = new Uint8Array(cells.i.length); // confluences array
|
|
||||||
let riverNext = 1; // first river id is 1, not 0
|
|
||||||
|
|
||||||
void function drainWater() {
|
|
||||||
const land = cells.i.filter(i => h[i] >= 20).sort((a,b) => h[b] - h[a]);
|
|
||||||
land.forEach(function(i) {
|
|
||||||
cells.fl[i] += grid.cells.prec[cells.g[i]]; // flux from precipitation
|
|
||||||
const x = p[i][0], y = p[i][1];
|
|
||||||
|
|
||||||
// near-border cell: pour out of the screen
|
|
||||||
if (cells.b[i]) {
|
|
||||||
if (cells.r[i]) {
|
|
||||||
const to = [];
|
|
||||||
const min = Math.min(y, graphHeight - y, x, graphWidth - x);
|
|
||||||
if (min === y) {to[0] = x; to[1] = 0;} else
|
|
||||||
if (min === graphHeight - y) {to[0] = x; to[1] = graphHeight;} else
|
|
||||||
if (min === x) {to[0] = 0; to[1] = y;} else
|
|
||||||
if (min === graphWidth - x) {to[0] = graphWidth; to[1] = y;}
|
|
||||||
riversData.push({river: cells.r[i], cell: i, x: to[0], y: to[1]});
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
//const min = cells.c[i][d3.scan(cells.c[i], (a, b) => h[a] - h[b])]; // downhill cell
|
|
||||||
let min = cells.c[i][d3.scan(cells.c[i], (a, b) => h[a] - h[b])]; // downhill cell
|
|
||||||
|
|
||||||
// allow only one river can flow through a lake
|
|
||||||
const cf = features[cells.f[i]]; // current cell feature
|
|
||||||
if (cf.river && cf.river !== cells.r[i]) {
|
|
||||||
cells.fl[i] = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cells.fl[i] < 30) {
|
|
||||||
if (h[min] >= 20) cells.fl[min] += cells.fl[i];
|
|
||||||
return; // flux is too small to operate as river
|
|
||||||
}
|
|
||||||
|
|
||||||
// Proclaim a new river
|
|
||||||
if (!cells.r[i]) {
|
|
||||||
cells.r[i] = riverNext;
|
|
||||||
riversData.push({river: riverNext, cell: i, x, y});
|
|
||||||
riverNext++;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cells.r[min]) { // downhill cell already has river assigned
|
|
||||||
if (cells.fl[min] < cells.fl[i]) {
|
|
||||||
cells.conf[min] = cells.fl[min]; // mark confluence
|
|
||||||
if (h[min] >= 20) riversData.find(r => r.river === cells.r[min]).parent = cells.r[i]; // min river is a tributary of current river
|
|
||||||
cells.r[min] = cells.r[i]; // re-assign river if downhill part has less flux
|
|
||||||
} else {
|
|
||||||
cells.conf[min] += cells.fl[i]; // mark confluence
|
|
||||||
if (h[min] >= 20) riversData.find(r => r.river === cells.r[i]).parent = cells.r[min]; // current river is a tributary of min river
|
|
||||||
}
|
|
||||||
} else cells.r[min] = cells.r[i]; // assign the river to the downhill cell
|
|
||||||
|
|
||||||
const nx = p[min][0], ny = p[min][1];
|
|
||||||
if (h[min] < 20) {
|
|
||||||
// pour water to the sea haven
|
|
||||||
riversData.push({river: cells.r[i], cell: cells.haven[i], x: nx, y: ny});
|
|
||||||
} else {
|
} else {
|
||||||
const mf = features[cells.f[min]]; // feature of min cell
|
cells.conf[min] += iFlux; // mark confluence
|
||||||
if (mf.type === "lake") {
|
if (h[min] >= 20) riversData.find(r => r.river === ri).parent = cells.r[min]; // current river is a tributary of min river
|
||||||
if (!mf.river || cells.fl[i] > mf.flux) {
|
}
|
||||||
mf.river = cells.r[i]; // pour water to temporaly elevated lake
|
} else cells.r[min] = ri; // assign the river to the downhill cell
|
||||||
mf.flux = cells.fl[i]; // entering flux
|
|
||||||
|
if (h[min] < 20) {
|
||||||
|
// pour water to the sea haven
|
||||||
|
const oh = i ? cells.haven[i] : min;
|
||||||
|
riversData.push({river: ri, cell: oh, x: p[min][0], y: p[min][1]});
|
||||||
|
const mf = features[cells.f[min]]; // feature of min cell
|
||||||
|
if (mf.type === "lake") {
|
||||||
|
if (!mf.river || iFlux > mf.flux) {
|
||||||
|
mf.river = ri; // pour water to temporaly elevated lake
|
||||||
|
mf.flux = iFlux; // entering flux
|
||||||
|
}
|
||||||
|
mf.totalFlux += iFlux;
|
||||||
|
if (mf.inlets) {
|
||||||
|
mf.inlets.push(ri);
|
||||||
|
} else {
|
||||||
|
mf.inlets = [ri];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
cells.fl[min] += iFlux; // propagate flux
|
||||||
|
riversData.push({river: ri, cell: min, x: p[min][0], y: p[min][1]}); // add next River segment
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
land.forEach(function(i) {
|
||||||
|
cells.fl[i] += grid.cells.prec[cells.g[i]]; // flux from precipitation
|
||||||
|
const x = p[i][0], y = p[i][1];
|
||||||
|
|
||||||
|
// lake outlets draw from lake
|
||||||
|
let n = -1, out2 = 0;
|
||||||
|
while (outlets.includes(i, n+1)) {
|
||||||
|
n = outlets.indexOf(i, n+1);
|
||||||
|
const l = features[n];
|
||||||
|
if ( ! l ) {continue;}
|
||||||
|
const j = cells.haven[i];
|
||||||
|
// allow chain lakes to retain identity
|
||||||
|
if(cells.r[j] !== l.river) {
|
||||||
|
let touch = false;
|
||||||
|
for (const c of cells.c[j]){
|
||||||
|
if (cells.r[c] === l.river) {
|
||||||
|
touch = true;
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
cells.fl[min] += cells.fl[i]; // propagate flux
|
if (touch) {
|
||||||
riversData.push({river: cells.r[i], cell: min, x: nx, y: ny}); // add next River segment
|
cells.r[j] = l.river;
|
||||||
}
|
riversData.push({river: l.river, cell: j, x: p[j][0], y: p[j][1]});
|
||||||
|
} else {
|
||||||
});
|
cells.r[j] = riverNext;
|
||||||
}()
|
riversData.push({river: riverNext, cell: j, x: p[j][0], y: p[j][1]});
|
||||||
|
riverNext++;
|
||||||
void function defineRivers() {
|
}
|
||||||
pack.rivers = []; // rivers data
|
|
||||||
const riverPaths = []; // temporary data for all rivers
|
|
||||||
|
|
||||||
for (let r = 1; r <= riverNext; r++) {
|
|
||||||
const riverSegments = riversData.filter(d => d.river === r);
|
|
||||||
|
|
||||||
if (riverSegments.length > 2) {
|
|
||||||
const riverEnhanced = addMeandring(riverSegments);
|
|
||||||
const width = rn(.8 + Math.random() * .4, 1); // river width modifier
|
|
||||||
const increment = rn(.8 + Math.random() * .6, 1); // river bed widening modifier
|
|
||||||
const [path, length] = getPath(riverEnhanced, width, increment);
|
|
||||||
riverPaths.push([r, path, width, increment]);
|
|
||||||
const source = riverSegments[0], mouth = riverSegments[riverSegments.length-2];
|
|
||||||
const parent = source.parent || 0;
|
|
||||||
pack.rivers.push({i:r, parent, length, source:source.cell, mouth:mouth.cell});
|
|
||||||
} else {
|
|
||||||
// remove too short rivers
|
|
||||||
riverSegments.filter(s => cells.r[s.cell] === r).forEach(s => cells.r[s.cell] = 0);
|
|
||||||
}
|
}
|
||||||
|
cells.fl[j] = l.totalFlux; // signpost river size
|
||||||
|
flowDown(i, cells.fl[i], l.totalFlux, cells.r[j]);
|
||||||
|
// prevent dropping imediately back into the lake
|
||||||
|
out2 = cells.c[i].filter(c => (h[c] >= 20 || cells.f[c] !== cells.f[j])).sort((a,b) => h[a] - h[b])[0]; // downhill cell not in the source lake
|
||||||
|
// assign all to outlet basin
|
||||||
|
if (l.inlets) l.inlets.forEach(fork => riversData.find(r => r.river === fork).parent = cells.r[j]);
|
||||||
}
|
}
|
||||||
|
|
||||||
const html = riverPaths.map(r =>`<path id="river${r[0]}" d="${r[1]}" data-width="${r[2]}" data-increment="${r[3]}"/>`).join("");
|
// near-border cell: pour out of the screen
|
||||||
rivers.html(html);
|
if (cells.b[i]) {
|
||||||
}()
|
if (cells.r[i]) {
|
||||||
|
const to = [];
|
||||||
// apply change heights as basic one
|
const min = Math.min(y, graphHeight - y, x, graphWidth - x);
|
||||||
if (changeHeights) cells.h = Uint8Array.from(h);
|
if (min === y) {to[0] = x; to[1] = 0;} else
|
||||||
|
if (min === graphHeight - y) {to[0] = x; to[1] = graphHeight;} else
|
||||||
TIME && console.timeEnd('generateRivers');
|
if (min === x) {to[0] = 0; to[1] = y;} else
|
||||||
}
|
if (min === graphWidth - x) {to[0] = graphWidth; to[1] = y;}
|
||||||
|
riversData.push({river: cells.r[i], cell: i, x: to[0], y: to[1]});
|
||||||
// depression filling algorithm (for a correct water flux modeling)
|
|
||||||
const resolveDepressions = function(h) {
|
|
||||||
const cells = pack.cells;
|
|
||||||
const land = cells.i.filter(i => h[i] >= 20 && h[i] < 100 && !cells.b[i]); // exclude near-border cells
|
|
||||||
land.sort((a,b) => h[b] - h[a]); // highest cells go first
|
|
||||||
let depressed = false;
|
|
||||||
|
|
||||||
for (let l = 0, depression = Infinity; depression && l < 100; l++) {
|
|
||||||
depression = 0;
|
|
||||||
for (const i of land) {
|
|
||||||
const minHeight = d3.min(cells.c[i].map(c => h[c]));
|
|
||||||
if (minHeight === 100) continue; // already max height
|
|
||||||
if (h[i] <= minHeight) {
|
|
||||||
h[i] = Math.min(minHeight + 1, 100);
|
|
||||||
depression++;
|
|
||||||
depressed = true;
|
|
||||||
}
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const min = out2 ? out2 : cells.c[i][d3.scan(cells.c[i], (a, b) => h[a] - h[b])]; // downhill cell
|
||||||
|
|
||||||
|
if (cells.fl[i] < 30) {
|
||||||
|
if (h[min] >= 20) cells.fl[min] += cells.fl[i];
|
||||||
|
return; // flux is too small to operate as river
|
||||||
|
}
|
||||||
|
|
||||||
|
// Proclaim a new river
|
||||||
|
if (!cells.r[i]) {
|
||||||
|
cells.r[i] = riverNext;
|
||||||
|
riversData.push({river: riverNext, cell: i, x, y});
|
||||||
|
riverNext++;
|
||||||
|
}
|
||||||
|
|
||||||
|
flowDown(min, cells.fl[min], cells.fl[i], cells.r[i], i);
|
||||||
|
|
||||||
|
});
|
||||||
|
}()
|
||||||
|
|
||||||
|
void function defineRivers() {
|
||||||
|
pack.rivers = []; // rivers data
|
||||||
|
const riverPaths = []; // temporary data for all rivers
|
||||||
|
|
||||||
|
for (let r = 1; r <= riverNext; r++) {
|
||||||
|
const riverSegments = riversData.filter(d => d.river === r);
|
||||||
|
|
||||||
|
if (riverSegments.length > 2) {
|
||||||
|
const source = riverSegments[0], mouth = riverSegments[riverSegments.length-2];
|
||||||
|
const riverEnhanced = addMeandring(riverSegments);
|
||||||
|
let width = rn(.8 + Math.random() * .4, 1); // river width modifier [.2, 10]
|
||||||
|
let increment = rn(.8 + Math.random() * .6, 1); // river bed widening modifier [.01, 3]
|
||||||
|
const [path, length] = getPath(riverEnhanced, width, increment, cells.h[source.cell] >= 20 ? .1 : .6);
|
||||||
|
riverPaths.push([r, path, width, increment]);
|
||||||
|
const parent = source.parent || 0;
|
||||||
|
pack.rivers.push({i:r, parent, length, source:source.cell, mouth:mouth.cell});
|
||||||
|
} else {
|
||||||
|
// remove too short rivers
|
||||||
|
riverSegments.filter(s => cells.r[s.cell] === r).forEach(s => cells.r[s.cell] = 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return depressed;
|
// drawRivers
|
||||||
}
|
rivers.selectAll("path").remove();
|
||||||
|
rivers.selectAll("path").data(riverPaths).enter()
|
||||||
|
.append("path").attr("d", d => d[1]).attr("id", d => "river"+d[0])
|
||||||
|
.attr("data-width", d => d[2]).attr("data-increment", d => d[3]);
|
||||||
|
}()
|
||||||
|
|
||||||
// add more river points on 1/3 and 2/3 of length
|
// apply change heights as basic one
|
||||||
const addMeandring = function(segments, rndFactor = 0.3) {
|
if (changeHeights) cells.h = Uint8Array.from(h);
|
||||||
const riverEnhanced = []; // to store enhanced segments
|
|
||||||
let side = 1; // to control meandring direction
|
|
||||||
|
|
||||||
for (let s = 0; s < segments.length; s++) {
|
TIME && console.timeEnd('generateRivers');
|
||||||
const sX = segments[s].x, sY = segments[s].y; // segment start coordinates
|
}
|
||||||
const c = pack.cells.conf[segments[s].cell] || 0; // if segment is river confluence
|
|
||||||
riverEnhanced.push([sX, sY, c]);
|
|
||||||
|
|
||||||
if (s+1 === segments.length) break; // do not enhance last segment
|
// depression filling algorithm (for a correct water flux modeling)
|
||||||
|
const resolveDepressions = function(h) {
|
||||||
const eX = segments[s+1].x, eY = segments[s+1].y; // segment end coordinates
|
const cells = pack.cells;
|
||||||
const angle = Math.atan2(eY - sY, eX - sX);
|
const land = cells.i.filter(i => h[i] >= 20 && h[i] < 100 && !cells.b[i]); // exclude near-border cells
|
||||||
const sin = Math.sin(angle), cos = Math.cos(angle);
|
const lakes = pack.features.filter(f => f.type === "lake" && (f.group === "freshwater" || f.group === "frozen")); // to keep lakes flat
|
||||||
const serpentine = 1 / (s + 1) + 0.3;
|
lakes.forEach(l => {
|
||||||
const meandr = serpentine + Math.random() * rndFactor;
|
l.shoreline = [];
|
||||||
if (P(.5)) side *= -1; // change meandring direction in 50%
|
l.height = 21;
|
||||||
const dist2 = (eX - sX) ** 2 + (eY - sY) ** 2;
|
l.totalFlux = grid.cells.prec[cells.g[l.firstCell]];
|
||||||
// if dist2 is big or river is small add extra points at 1/3 and 2/3 of segment
|
});
|
||||||
if (dist2 > 64 || (dist2 > 16 && segments.length < 6)) {
|
for (let i of land.filter(i => cells.t[i] === 1)) { // select shoreline cells
|
||||||
const p1x = (sX * 2 + eX) / 3 + side * -sin * meandr;
|
cells.c[i].map(c => pack.features[cells.f[c]]).forEach(cf => {
|
||||||
const p1y = (sY * 2 + eY) / 3 + side * cos * meandr;
|
if (lakes.includes(cf) && !cf.shoreline.includes(i)) {
|
||||||
if (P(.2)) side *= -1; // change 2nd extra point meandring direction in 20%
|
cf.shoreline.push(i);
|
||||||
const p2x = (sX + eX * 2) / 3 + side * sin * meandr;
|
|
||||||
const p2y = (sY + eY * 2) / 3 + side * cos * meandr;
|
|
||||||
riverEnhanced.push([p1x, p1y], [p2x, p2y]);
|
|
||||||
// if dist is medium or river is small add 1 extra middlepoint
|
|
||||||
} else if (dist2 > 16 || segments.length < 6) {
|
|
||||||
const p1x = (sX + eX) / 2 + side * -sin * meandr;
|
|
||||||
const p1y = (sY + eY) / 2 + side * cos * meandr;
|
|
||||||
riverEnhanced.push([p1x, p1y]);
|
|
||||||
}
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
land.sort((a,b) => h[b] - h[a]); // highest cells go first
|
||||||
|
let depressed = false;
|
||||||
|
|
||||||
|
for (let l = 0, depression = Infinity; depression && l < 100; l++) {
|
||||||
|
depression = 0;
|
||||||
|
for (const l of lakes) {
|
||||||
|
const minHeight = d3.min(l.shoreline.map(s => h[s]));
|
||||||
|
if (minHeight === 100) continue; // already max height
|
||||||
|
if (l.height <= minHeight) {
|
||||||
|
l.height = Math.min(minHeight + 1, 100);
|
||||||
|
depression++;
|
||||||
|
depressed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const i of land) {
|
||||||
|
const minHeight = d3.min(cells.c[i].map(c => cells.t[c] > 0 ? h[c] :
|
||||||
|
pack.features[cells.f[c]].height || h[c] // NB undefined is falsy (a || b is short for a ? a : b)
|
||||||
|
));
|
||||||
|
if (minHeight === 100) continue; // already max height
|
||||||
|
if (h[i] <= minHeight) {
|
||||||
|
h[i] = Math.min(minHeight + 1, 100);
|
||||||
|
depression++;
|
||||||
|
depressed = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return riverEnhanced;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const getPath = function(points, width = 1, increment = 1) {
|
return depressed;
|
||||||
let offset, extraOffset = .1; // starting river width (to make river source visible)
|
}
|
||||||
const riverLength = points.reduce((s, v, i, p) => s + (i ? Math.hypot(v[0] - p[i-1][0], v[1] - p[i-1][1]) : 0), 0); // summ of segments length
|
|
||||||
const widening = rn((1000 + (riverLength * 30)) * increment);
|
|
||||||
const riverPointsLeft = [], riverPointsRight = []; // store points on both sides to build a valid polygon
|
|
||||||
const last = points.length - 1;
|
|
||||||
const factor = riverLength / points.length;
|
|
||||||
|
|
||||||
// first point
|
// add more river points on 1/3 and 2/3 of length
|
||||||
let x = points[0][0], y = points[0][1], c;
|
const addMeandring = function(segments, rndFactor = 0.3) {
|
||||||
let angle = Math.atan2(y - points[1][1], x - points[1][0]);
|
const riverEnhanced = []; // to store enhanced segments
|
||||||
let sin = Math.sin(angle), cos = Math.cos(angle);
|
let side = 1; // to control meandring direction
|
||||||
let xLeft = x + -sin * extraOffset, yLeft = y + cos * extraOffset;
|
|
||||||
riverPointsLeft.push([xLeft, yLeft]);
|
|
||||||
let xRight = x + sin * extraOffset, yRight = y + -cos * extraOffset;
|
|
||||||
riverPointsRight.unshift([xRight, yRight]);
|
|
||||||
|
|
||||||
// middle points
|
for (let s = 0; s < segments.length; s++) {
|
||||||
for (let p = 1; p < last; p++) {
|
const sX = segments[s].x, sY = segments[s].y; // segment start coordinates
|
||||||
x = points[p][0], y = points[p][1], c = points[p][2] || 0;
|
const c = pack.cells.conf[segments[s].cell] || 0; // if segment is river confluence
|
||||||
const xPrev = points[p-1][0], yPrev = points[p - 1][1];
|
riverEnhanced.push([sX, sY, c]);
|
||||||
const xNext = points[p+1][0], yNext = points[p + 1][1];
|
|
||||||
angle = Math.atan2(yPrev - yNext, xPrev - xNext);
|
if (s+1 === segments.length) break; // do not enhance last segment
|
||||||
sin = Math.sin(angle), cos = Math.cos(angle);
|
|
||||||
offset = (Math.atan(Math.pow(p * factor, 2) / widening) / 2 * width) + extraOffset;
|
const eX = segments[s+1].x, eY = segments[s+1].y; // segment end coordinates
|
||||||
const confOffset = Math.atan(c * 5 / widening);
|
const angle = Math.atan2(eY - sY, eX - sX);
|
||||||
extraOffset += confOffset;
|
const sin = Math.sin(angle), cos = Math.cos(angle);
|
||||||
xLeft = x + -sin * offset, yLeft = y + cos * (offset + confOffset);
|
const serpentine = 1 / (s + 1) + 0.3;
|
||||||
riverPointsLeft.push([xLeft, yLeft]);
|
const meandr = serpentine + Math.random() * rndFactor;
|
||||||
xRight = x + sin * offset, yRight = y + -cos * offset;
|
if (P(.5)) side *= -1; // change meandring direction in 50%
|
||||||
riverPointsRight.unshift([xRight, yRight]);
|
const dist2 = (eX - sX) ** 2 + (eY - sY) ** 2;
|
||||||
|
// if dist2 is big or river is small add extra points at 1/3 and 2/3 of segment
|
||||||
|
if (dist2 > 64 || (dist2 > 16 && segments.length < 6)) {
|
||||||
|
const p1x = (sX * 2 + eX) / 3 + side * -sin * meandr;
|
||||||
|
const p1y = (sY * 2 + eY) / 3 + side * cos * meandr;
|
||||||
|
if (P(.2)) side *= -1; // change 2nd extra point meandring direction in 20%
|
||||||
|
const p2x = (sX + eX * 2) / 3 + side * sin * meandr;
|
||||||
|
const p2y = (sY + eY * 2) / 3 + side * cos * meandr;
|
||||||
|
riverEnhanced.push([p1x, p1y], [p2x, p2y]);
|
||||||
|
// if dist is medium or river is small add 1 extra middlepoint
|
||||||
|
} else if (dist2 > 16 || segments.length < 6) {
|
||||||
|
const p1x = (sX + eX) / 2 + side * -sin * meandr;
|
||||||
|
const p1y = (sY + eY) / 2 + side * cos * meandr;
|
||||||
|
riverEnhanced.push([p1x, p1y]);
|
||||||
}
|
}
|
||||||
|
|
||||||
// end point
|
}
|
||||||
x = points[last][0], y = points[last][1], c = points[last][2];
|
return riverEnhanced;
|
||||||
if (c) extraOffset += Math.atan(c * 10 / widening); // add extra width on river confluence
|
}
|
||||||
angle = Math.atan2(points[last-1][1] - y, points[last-1][0] - x);
|
|
||||||
|
const getPath = function(points, width = 1, increment = 1, starting = .1) {
|
||||||
|
let offset, extraOffset = starting; // starting river width (to make river source visible)
|
||||||
|
const riverLength = points.reduce((s, v, i, p) => s + (i ? Math.hypot(v[0] - p[i-1][0], v[1] - p[i-1][1]) : 0), 0); // summ of segments length
|
||||||
|
const widening = rn((1000 + (riverLength * 30)) * increment);
|
||||||
|
const riverPointsLeft = [], riverPointsRight = []; // store points on both sides to build a valid polygon
|
||||||
|
const last = points.length - 1;
|
||||||
|
const factor = riverLength / points.length;
|
||||||
|
|
||||||
|
// first point
|
||||||
|
let x = points[0][0], y = points[0][1], c;
|
||||||
|
let angle = Math.atan2(y - points[1][1], x - points[1][0]);
|
||||||
|
let sin = Math.sin(angle), cos = Math.cos(angle);
|
||||||
|
let xLeft = x + -sin * extraOffset, yLeft = y + cos * extraOffset;
|
||||||
|
riverPointsLeft.push([xLeft, yLeft]);
|
||||||
|
let xRight = x + sin * extraOffset, yRight = y + -cos * extraOffset;
|
||||||
|
riverPointsRight.unshift([xRight, yRight]);
|
||||||
|
|
||||||
|
// middle points
|
||||||
|
for (let p = 1; p < last; p++) {
|
||||||
|
x = points[p][0], y = points[p][1], c = points[p][2] || 0;
|
||||||
|
const xPrev = points[p-1][0], yPrev = points[p - 1][1];
|
||||||
|
const xNext = points[p+1][0], yNext = points[p + 1][1];
|
||||||
|
angle = Math.atan2(yPrev - yNext, xPrev - xNext);
|
||||||
sin = Math.sin(angle), cos = Math.cos(angle);
|
sin = Math.sin(angle), cos = Math.cos(angle);
|
||||||
xLeft = x + -sin * offset, yLeft = y + cos * offset;
|
offset = (Math.atan(Math.pow(p * factor, 2) / widening) / 2 * width) + extraOffset;
|
||||||
|
const confOffset = Math.atan(c * 5 / widening);
|
||||||
|
extraOffset += confOffset;
|
||||||
|
xLeft = x + -sin * offset, yLeft = y + cos * (offset + confOffset);
|
||||||
riverPointsLeft.push([xLeft, yLeft]);
|
riverPointsLeft.push([xLeft, yLeft]);
|
||||||
xRight = x + sin * offset, yRight = y + -cos * offset;
|
xRight = x + sin * offset, yRight = y + -cos * offset;
|
||||||
riverPointsRight.unshift([xRight, yRight]);
|
riverPointsRight.unshift([xRight, yRight]);
|
||||||
|
|
||||||
// generate polygon path and return
|
|
||||||
lineGen.curve(d3.curveCatmullRom.alpha(0.1));
|
|
||||||
const right = lineGen(riverPointsRight);
|
|
||||||
let left = lineGen(riverPointsLeft);
|
|
||||||
left = left.substring(left.indexOf("C"));
|
|
||||||
return [round(right + left, 2), rn(riverLength, 2)];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const specify = function() {
|
// end point
|
||||||
if (!pack.rivers.length) return;
|
x = points[last][0], y = points[last][1], c = points[last][2];
|
||||||
Math.random = aleaPRNG(seed);
|
if (c) extraOffset += Math.atan(c * 10 / widening); // add extra width on river confluence
|
||||||
const smallLength = pack.rivers.map(r => r.length||0).sort((a,b) => a-b)[Math.ceil(pack.rivers.length * .15)];
|
angle = Math.atan2(points[last-1][1] - y, points[last-1][0] - x);
|
||||||
const smallType = {"Creek":9, "River":3, "Brook":3, "Stream":1}; // weighted small river types
|
sin = Math.sin(angle), cos = Math.cos(angle);
|
||||||
|
xLeft = x + -sin * offset, yLeft = y + cos * offset;
|
||||||
|
riverPointsLeft.push([xLeft, yLeft]);
|
||||||
|
xRight = x + sin * offset, yRight = y + -cos * offset;
|
||||||
|
riverPointsRight.unshift([xRight, yRight]);
|
||||||
|
|
||||||
for (const r of pack.rivers) {
|
// generate polygon path and return
|
||||||
r.basin = getBasin(r.i, r.parent);
|
lineGen.curve(d3.curveCatmullRom.alpha(0.1));
|
||||||
r.name = getName(r.mouth);
|
const right = lineGen(riverPointsRight);
|
||||||
//debug.append("circle").attr("cx", pack.cells.p[r.mouth][0]).attr("cy", pack.cells.p[r.mouth][1]).attr("r", 2);
|
let left = lineGen(riverPointsLeft);
|
||||||
const small = r.length < smallLength;
|
left = left.substring(left.indexOf("C"));
|
||||||
r.type = r.parent && !(r.i%6) ? small ? "Branch" : "Fork" : small ? rw(smallType) : "River";
|
return [round(right + left, 2), rn(riverLength, 2)];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const specify = function() {
|
||||||
|
if (!pack.rivers.length) return;
|
||||||
|
Math.random = aleaPRNG(seed);
|
||||||
|
const smallLength = pack.rivers.map(r => r.length||0).sort((a,b) => a-b)[Math.ceil(pack.rivers.length * .15)];
|
||||||
|
const smallType = {"Creek":9, "River":3, "Brook":3, "Stream":1}; // weighted small river types
|
||||||
|
|
||||||
|
for (const r of pack.rivers) {
|
||||||
|
r.basin = getBasin(r.i, r.parent);
|
||||||
|
r.name = getName(r.mouth);
|
||||||
|
//debug.append("circle").attr("cx", pack.cells.p[r.mouth][0]).attr("cy", pack.cells.p[r.mouth][1]).attr("r", 2);
|
||||||
|
const small = r.length < smallLength;
|
||||||
|
r.type = r.parent && !(r.i%6) ? small ? "Branch" : "Fork" : small ? rw(smallType) : "River";
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const getName = function(cell) {
|
const getName = function(cell) {
|
||||||
return Names.getCulture(pack.cells.culture[cell]);
|
return Names.getCulture(pack.cells.culture[cell]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove river and all its tributaries
|
||||||
|
const remove = function(id) {
|
||||||
|
const cells = pack.cells;
|
||||||
|
const riversToRemove = pack.rivers.filter(r => r.i === id || getBasin(r.i, r.parent, id) === id).map(r => r.i);
|
||||||
|
riversToRemove.forEach(r => rivers.select("#river"+r).remove());
|
||||||
|
cells.r.forEach((r, i) => {
|
||||||
|
if (!r || !riversToRemove.includes(r)) return;
|
||||||
|
cells.r[i] = 0;
|
||||||
|
cells.fl[i] = grid.cells.prec[cells.g[i]];
|
||||||
|
cells.conf[i] = 0;
|
||||||
|
});
|
||||||
|
pack.rivers = pack.rivers.filter(r => !riversToRemove.includes(r.i));
|
||||||
|
}
|
||||||
|
|
||||||
|
const getBasin = function(r, p, e) {
|
||||||
|
while (p && r !== p && r !== e) {
|
||||||
|
const parent = pack.rivers.find(r => r.i === p);
|
||||||
|
if (!parent) return r;
|
||||||
|
r = parent.i;
|
||||||
|
p = parent.parent;
|
||||||
}
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
// remove river and all its tributaries
|
return {generate, resolveDepressions, addMeandring, getPath, specify, getName, getBasin, remove};
|
||||||
const remove = function(id) {
|
|
||||||
const cells = pack.cells;
|
|
||||||
const riversToRemove = pack.rivers.filter(r => r.i === id || getBasin(r.i, r.parent, id) === id).map(r => r.i);
|
|
||||||
riversToRemove.forEach(r => rivers.select("#river"+r).remove());
|
|
||||||
cells.r.forEach((r, i) => {
|
|
||||||
if (!r || !riversToRemove.includes(r)) return;
|
|
||||||
cells.r[i] = 0;
|
|
||||||
cells.fl[i] = grid.cells.prec[cells.g[i]];
|
|
||||||
cells.conf[i] = 0;
|
|
||||||
});
|
|
||||||
pack.rivers = pack.rivers.filter(r => !riversToRemove.includes(r.i));
|
|
||||||
}
|
|
||||||
|
|
||||||
const getBasin = function(r, p, e) {
|
})));
|
||||||
while (p && r !== p && r !== e) {
|
|
||||||
const parent = pack.rivers.find(r => r.i === p);
|
|
||||||
if (!parent) return r;
|
|
||||||
r = parent.i;
|
|
||||||
p = parent.parent;
|
|
||||||
}
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
||||||
return {generate, resolveDepressions, addMeandring, getPath, specify, getName, getBasin, remove};
|
|
||||||
|
|
||||||
})));
|
|
||||||
|
|
@ -176,7 +176,6 @@ function editHeightmap() {
|
||||||
reGraph();
|
reGraph();
|
||||||
drawCoastline();
|
drawCoastline();
|
||||||
|
|
||||||
elevateLakes();
|
|
||||||
Rivers.generate(change);
|
Rivers.generate(change);
|
||||||
|
|
||||||
if (!change) {
|
if (!change) {
|
||||||
|
|
@ -288,10 +287,7 @@ function editHeightmap() {
|
||||||
reGraph();
|
reGraph();
|
||||||
drawCoastline();
|
drawCoastline();
|
||||||
|
|
||||||
if (changeHeights.checked) {
|
if (changeHeights.checked) Rivers.generate(changeHeights.checked);
|
||||||
elevateLakes();
|
|
||||||
Rivers.generate(changeHeights.checked);
|
|
||||||
}
|
|
||||||
|
|
||||||
// assign saved pack data from grid back to pack
|
// assign saved pack data from grid back to pack
|
||||||
const n = pack.cells.i.length;
|
const n = pack.cells.i.length;
|
||||||
|
|
@ -314,7 +310,6 @@ function editHeightmap() {
|
||||||
|
|
||||||
for (const i of pack.cells.i) {
|
for (const i of pack.cells.i) {
|
||||||
const g = pack.cells.g[i];
|
const g = pack.cells.g[i];
|
||||||
if (pack.features[pack.cells.f[i]].group === "freshwater") pack.cells.h[i] = 19; // de-elevate lakes
|
|
||||||
const land = pack.cells.h[i] >= 20;
|
const land = pack.cells.h[i] >= 20;
|
||||||
|
|
||||||
// check biome
|
// check biome
|
||||||
|
|
|
||||||
|
|
@ -73,12 +73,7 @@ function processFeatureRegeneration(event, button) {
|
||||||
}
|
}
|
||||||
|
|
||||||
function regenerateRivers() {
|
function regenerateRivers() {
|
||||||
elevateLakes();
|
|
||||||
Rivers.generate();
|
Rivers.generate();
|
||||||
for (const i of pack.cells.i) {
|
|
||||||
const f = pack.features[pack.cells.f[i]]; // feature
|
|
||||||
if (f.group === "freshwater") pack.cells.h[i] = 19; // de-elevate lakes
|
|
||||||
}
|
|
||||||
Rivers.specify();
|
Rivers.specify();
|
||||||
if (!layerIsOn("toggleRivers")) toggleRivers();
|
if (!layerIsOn("toggleRivers")) toggleRivers();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -45,7 +45,6 @@ function editWorld() {
|
||||||
updateGlobePosition();
|
updateGlobePosition();
|
||||||
calculateTemperatures();
|
calculateTemperatures();
|
||||||
generatePrecipitation();
|
generatePrecipitation();
|
||||||
elevateLakes();
|
|
||||||
const heights = new Uint8Array(pack.cells.h);
|
const heights = new Uint8Array(pack.cells.h);
|
||||||
Rivers.generate();
|
Rivers.generate();
|
||||||
Rivers.specify();
|
Rivers.specify();
|
||||||
|
|
|
||||||
|
|
@ -1,82 +1,135 @@
|
||||||
(function (global, factory) {
|
class Voronoi {
|
||||||
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
/**
|
||||||
typeof define === 'function' && define.amd ? define(factory) :
|
* Creates a Voronoi diagram from the given Delaunator, a list of points, and the number of points. The Voronoi diagram is constructed using (I think) the {@link https://en.wikipedia.org/wiki/Bowyer%E2%80%93Watson_algorithm |Bowyer-Watson Algorithm}
|
||||||
(global.Voronoi = factory());
|
* The {@link https://github.com/mapbox/delaunator/ |Delaunator} library uses {@link https://en.wikipedia.org/wiki/Doubly_connected_edge_list |half-edges} to represent the relationship between points and triangles.
|
||||||
}(this, (function () { 'use strict';
|
* @param {{triangles: Uint32Array, halfedges: Int32Array}} delaunay A {@link https://github.com/mapbox/delaunator/blob/master/index.js |Delaunator} instance.
|
||||||
|
* @param {[number, number][]} points A list of coordinates.
|
||||||
|
* @param {number} pointsN The number of points.
|
||||||
|
*/
|
||||||
|
constructor(delaunay, points, pointsN) {
|
||||||
|
this.delaunay = delaunay;
|
||||||
|
this.points = points;
|
||||||
|
this.pointsN = pointsN;
|
||||||
|
this.cells = { v: [], c: [], b: [] }; // voronoi cells: v = cell vertices, c = adjacent cells, b = near-border cell
|
||||||
|
this.vertices = { p: [], v: [], c: [] }; // cells vertices: p = vertex coordinates, v = neighboring vertices, c = adjacent cells
|
||||||
|
|
||||||
var Voronoi = function Voronoi(delaunay, points, pointsN) {
|
// Half-edges are the indices into the delaunator outputs:
|
||||||
const cells = {v: [], c: [], b: []}; // voronoi cells: v = cell vertices, c = adjacent cells, b = near-border cell
|
// delaunay.triangles[e] gives the point ID where the half-edge starts
|
||||||
const vertices = {p: [], v: [], c: []}; // cells vertices: p = vertex coordinates, v = neighboring vertices, c = adjacent cells
|
// delaunay.triangles[e] returns either the opposite half-edge in the adjacent triangle, or -1 if there's not an adjacent triangle.
|
||||||
|
for (let e = 0; e < this.delaunay.triangles.length; e++) {
|
||||||
|
|
||||||
for (let e=0; e < delaunay.triangles.length; e++) {
|
const p = this.delaunay.triangles[this.nextHalfedge(e)];
|
||||||
|
if (p < this.pointsN && !this.cells.c[p]) {
|
||||||
const p = delaunay.triangles[nextHalfedge(e)];
|
const edges = this.edgesAroundPoint(e);
|
||||||
if (p < pointsN && !cells.c[p]) {
|
this.cells.v[p] = edges.map(e => this.triangleOfEdge(e)); // cell: adjacent vertex
|
||||||
const edges = edgesAroundPoint(e);
|
this.cells.c[p] = edges.map(e => this.delaunay.triangles[e]).filter(c => c < this.pointsN); // cell: adjacent valid cells
|
||||||
cells.v[p] = edges.map(e => triangleOfEdge(e)); // cell: adjacent vertex
|
this.cells.b[p] = edges.length > this.cells.c[p].length ? 1 : 0; // cell: is border
|
||||||
cells.c[p] = edges.map(e => delaunay.triangles[e]).filter(c => c < pointsN); // cell: adjacent valid cells
|
|
||||||
cells.b[p] = edges.length > cells.c[p].length ? 1 : 0; // cell: is border
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const t = triangleOfEdge(e);
|
const t = this.triangleOfEdge(e);
|
||||||
if (!vertices.p[t]) {
|
if (!this.vertices.p[t]) {
|
||||||
vertices.p[t] = triangleCenter(t); // vertex: coordinates
|
this.vertices.p[t] = this.triangleCenter(t); // vertex: coordinates
|
||||||
vertices.v[t] = trianglesAdjacentToTriangle(t); // vertex: adjacent vertices
|
this.vertices.v[t] = this.trianglesAdjacentToTriangle(t); // vertex: adjacent vertices
|
||||||
vertices.c[t] = pointsOfTriangle(t); // vertex: adjacent cells
|
this.vertices.c[t] = this.pointsOfTriangle(t); // vertex: adjacent cells
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function pointsOfTriangle(t) {
|
|
||||||
return edgesOfTriangle(t).map(e => delaunay.triangles[e]);
|
|
||||||
}
|
|
||||||
|
|
||||||
function trianglesAdjacentToTriangle(t) {
|
|
||||||
let triangles = [];
|
|
||||||
for (let e of edgesOfTriangle(t)) {
|
|
||||||
let opposite = delaunay.halfedges[e];
|
|
||||||
triangles.push(triangleOfEdge(opposite));
|
|
||||||
}
|
|
||||||
return triangles;
|
|
||||||
}
|
|
||||||
|
|
||||||
function edgesAroundPoint(start) {
|
|
||||||
let result = [], incoming = start;
|
|
||||||
do {
|
|
||||||
result.push(incoming);
|
|
||||||
const outgoing = nextHalfedge(incoming);
|
|
||||||
incoming = delaunay.halfedges[outgoing];
|
|
||||||
} while (incoming !== -1 && incoming !== start && result.length < 20);
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
function triangleCenter(t) {
|
|
||||||
let vertices = pointsOfTriangle(t).map(p => points[p]);
|
|
||||||
return circumcenter(vertices[0], vertices[1], vertices[2]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {cells, vertices}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function edgesOfTriangle(t) {return [3*t, 3*t+1, 3*t+2];}
|
/**
|
||||||
|
* Gets the IDs of the points comprising the given triangle. Taken from {@link https://mapbox.github.io/delaunator/#triangle-to-points| the Delaunator docs.}
|
||||||
|
* @param {number} t The index of the triangle
|
||||||
|
* @returns {[number, number, number]} The IDs of the points comprising the given triangle.
|
||||||
|
*/
|
||||||
|
pointsOfTriangle(t) {
|
||||||
|
return this.edgesOfTriangle(t).map(edge => this.delaunay.triangles[edge]);
|
||||||
|
}
|
||||||
|
|
||||||
function triangleOfEdge(e) {return Math.floor(e/3);}
|
/**
|
||||||
|
* Identifies what triangles are adjacent to the given triangle. Taken from {@link https://mapbox.github.io/delaunator/#triangle-to-triangles| the Delaunator docs.}
|
||||||
|
* @param {number} t The index of the triangle
|
||||||
|
* @returns {number[]} The indices of the triangles that share half-edges with this triangle.
|
||||||
|
*/
|
||||||
|
trianglesAdjacentToTriangle(t) {
|
||||||
|
let triangles = [];
|
||||||
|
for (let edge of this.edgesOfTriangle(t)) {
|
||||||
|
let opposite = this.delaunay.halfedges[edge];
|
||||||
|
triangles.push(this.triangleOfEdge(opposite));
|
||||||
|
}
|
||||||
|
return triangles;
|
||||||
|
}
|
||||||
|
|
||||||
function nextHalfedge(e) {return (e % 3 === 2) ? e-2 : e+1;}
|
/**
|
||||||
|
* Gets the indices of all the incoming and outgoing half-edges that touch the given point. Taken from {@link https://mapbox.github.io/delaunator/#point-to-edges| the Delaunator docs.}
|
||||||
|
* @param {number} start The index of an incoming half-edge that leads to the desired point
|
||||||
|
* @returns {number[]} The indices of all half-edges (incoming or outgoing) that touch the point.
|
||||||
|
*/
|
||||||
|
edgesAroundPoint(start) {
|
||||||
|
const result = [];
|
||||||
|
let incoming = start;
|
||||||
|
do {
|
||||||
|
result.push(incoming);
|
||||||
|
const outgoing = this.nextHalfedge(incoming);
|
||||||
|
incoming = this.delaunay.halfedges[outgoing];
|
||||||
|
} while (incoming !== -1 && incoming !== start && result.length < 20);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
function prevHalfedge(e) {return (e % 3 === 0) ? e+2 : e-1;}
|
/**
|
||||||
|
* Returns the center of the triangle located at the given index.
|
||||||
|
* @param {number} t The index of the triangle
|
||||||
|
* @returns {[number, number]}
|
||||||
|
*/
|
||||||
|
triangleCenter(t) {
|
||||||
|
let vertices = this.pointsOfTriangle(t).map(p => this.points[p]);
|
||||||
|
return this.circumcenter(vertices[0], vertices[1], vertices[2]);
|
||||||
|
}
|
||||||
|
|
||||||
function circumcenter(a, b, c) {
|
/**
|
||||||
let ad = a[0]*a[0] + a[1]*a[1],
|
* Retrieves all of the half-edges for a specific triangle `t`. Taken from {@link https://mapbox.github.io/delaunator/#edge-and-triangle| the Delaunator docs.}
|
||||||
bd = b[0]*b[0] + b[1]*b[1],
|
* @param {number} t The index of the triangle
|
||||||
cd = c[0]*c[0] + c[1]*c[1];
|
* @returns {[number, number, number]} The edges of the triangle.
|
||||||
let D = 2 * (a[0] * (b[1] - c[1]) + b[0] * (c[1] - a[1]) + c[0] * (a[1] - b[1]));
|
*/
|
||||||
|
edgesOfTriangle(t) { return [3 * t, 3 * t + 1, 3 * t + 2]; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enables lookup of a triangle, given one of the half-edges of that triangle. Taken from {@link https://mapbox.github.io/delaunator/#edge-and-triangle| the Delaunator docs.}
|
||||||
|
* @param {number} e The index of the edge
|
||||||
|
* @returns {number} The index of the triangle
|
||||||
|
*/
|
||||||
|
triangleOfEdge(e) { return Math.floor(e / 3); }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves to the next half-edge of a triangle, given the current half-edge's index. Taken from {@link https://mapbox.github.io/delaunator/#edge-to-edges| the Delaunator docs.}
|
||||||
|
* @param {number} e The index of the current half edge
|
||||||
|
* @returns {number} The index of the next half edge
|
||||||
|
*/
|
||||||
|
nextHalfedge(e) { return (e % 3 === 2) ? e - 2 : e + 1; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Moves to the previous half-edge of a triangle, given the current half-edge's index. Taken from {@link https://mapbox.github.io/delaunator/#edge-to-edges| the Delaunator docs.}
|
||||||
|
* @param {number} e The index of the current half edge
|
||||||
|
* @returns {number} The index of the previous half edge
|
||||||
|
*/
|
||||||
|
prevHalfedge(e) { return (e % 3 === 0) ? e + 2 : e - 1; }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the circumcenter of the triangle identified by points a, b, and c. Taken from {@link https://en.wikipedia.org/wiki/Circumscribed_circle#Circumcenter_coordinates| Wikipedia}
|
||||||
|
* @param {[number, number]} a The coordinates of the first point of the triangle
|
||||||
|
* @param {[number, number]} b The coordinates of the second point of the triangle
|
||||||
|
* @param {[number, number]} c The coordinates of the third point of the triangle
|
||||||
|
* @return {[number, number]} The coordinates of the circumcenter of the triangle.
|
||||||
|
*/
|
||||||
|
circumcenter(a, b, c) {
|
||||||
|
const [ax, ay] = a;
|
||||||
|
const [bx, by] = b;
|
||||||
|
const [cx, cy] = c;
|
||||||
|
const ad = ax * ax + ay * ay;
|
||||||
|
const bd = bx * bx + by * by;
|
||||||
|
const cd = cx * cx + cy * cy;
|
||||||
|
const D = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
|
||||||
return [
|
return [
|
||||||
Math.floor(1/D * (ad * (b[1] - c[1]) + bd * (c[1] - a[1]) + cd * (a[1] - b[1]))),
|
Math.floor(1 / D * (ad * (by - cy) + bd * (cy - ay) + cd * (ay - by))),
|
||||||
Math.floor(1/D * (ad * (c[0] - b[0]) + bd * (a[0] - c[0]) + cd * (b[0] - a[0])))
|
Math.floor(1 / D * (ad * (cx - bx) + bd * (ax - cx) + cd * (bx - ax)))
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
}
|
||||||
return Voronoi;
|
|
||||||
|
|
||||||
})));
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue