make depressions resolve elevation change not that big

This commit is contained in:
Azgaar 2021-06-06 01:29:58 +03:00
parent ab065da5d2
commit 67235bc41e
8 changed files with 1765 additions and 1264 deletions

View file

@ -1,90 +1,110 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Lakes = factory());
}(this, (function () {'use strict';
typeof exports === "object" && typeof module !== "undefined" ? (module.exports = factory()) : typeof define === "function" && define.amd ? define(factory) : (global.Lakes = factory());
})(this, function () {
"use strict";
const setClimateData = function(h) {
const cells = pack.cells;
const lakeOutCells = new Uint16Array(cells.i.length);
const setClimateData = function (h) {
const cells = pack.cells;
const lakeOutCells = new Uint16Array(cells.i.length);
pack.features.forEach(f => {
if (f.type !== "lake") return;
pack.features.forEach(f => {
if (f.type !== "lake") return;
// default flux: sum of precipition around lake first cell
f.flux = rn(d3.sum(f.shoreline.map(c => grid.cells.prec[cells.g[c]])) / 2);
// temperature and evaporation to detect closed lakes
f.temp = f.cells < 6 ? grid.cells.temp[cells.g[f.firstCell]] : rn(d3.mean(f.shoreline.map(c => grid.cells.temp[cells.g[c]])), 1);
const height = (f.height - 18) ** heightExponentInput.value; // height in meters
const evaporation = (700 * (f.temp + .006 * height) / 50 + 75) / (80 - f.temp); // based on Penman formula, [1-11]
f.evaporation = rn(evaporation * f.cells);
// default flux: sum of precipition around lake first cell
f.flux = rn(d3.sum(f.shoreline.map(c => grid.cells.prec[cells.g[c]])) / 2);
// lake outlet cell
f.outCell = f.shoreline[d3.scan(f.shoreline, (a,b) => h[a] - h[b])];
lakeOutCells[f.outCell] = f.i;
});
// temperature and evaporation to detect closed lakes
f.temp = f.cells < 6 ? grid.cells.temp[cells.g[f.firstCell]] : rn(d3.mean(f.shoreline.map(c => grid.cells.temp[cells.g[c]])), 1);
const height = (f.height - 18) ** heightExponentInput.value; // height in meters
const evaporation = ((700 * (f.temp + 0.006 * height)) / 50 + 75) / (80 - f.temp); // based on Penman formula, [1-11]
f.evaporation = rn(evaporation * f.cells);
return lakeOutCells;
}
// no outlet for lakes in depressed areas
if (f.closed) return;
const cleanupLakeData = function() {
for (const feature of pack.features) {
if (feature.type !== "lake") continue;
delete feature.river;
delete feature.enteringFlux;
delete feature.shoreline;
delete feature.outCell;
feature.height = rn(feature.height);
// lake outlet cell
f.outCell = f.shoreline[d3.scan(f.shoreline, (a, b) => h[a] - h[b])];
lakeOutCells[f.outCell] = f.i;
});
const inlets = feature.inlets?.filter(r => pack.rivers.find(river => river.i === r));
if (!inlets || !inlets.length) delete feature.inlets;
else feature.inlets = inlets;
return lakeOutCells;
};
const outlet = feature.outlet && pack.rivers.find(river => river.i === feature.outlet);
if (!outlet) delete feature.outlet;
}
}
// get array of land cells aroound lake
const getShoreline = function (lake) {
const queue = [lake.firstCell];
const used = [queue[0]];
const landCellsAround = [];
while (queue.length) {
const q = queue.pop();
for (const c of pack.cells.c[q]) {
if (used[c]) continue;
used[c] = true;
if (pack.cells.f[c] === lake.i) queue.push(c);
if (pack.cells.h[c] >= 20) landCellsAround.push(c);
}
}
const defineGroup = function() {
for (const feature of pack.features) {
if (feature.type !== "lake") continue;
const lakeEl = lakes.select(`[data-f="${feature.i}"]`).node();
if (!lakeEl) continue;
lake.shoreline = landCellsAround;
};
feature.group = getGroup(feature);
document.getElementById(feature.group).appendChild(lakeEl);
}
}
const cleanupLakeData = function () {
for (const feature of pack.features) {
if (feature.type !== "lake") continue;
delete feature.river;
delete feature.enteringFlux;
delete feature.shoreline;
delete feature.outCell;
delete feature.closed;
feature.height = rn(feature.height);
const generateName = function() {
Math.random = aleaPRNG(seed);
for (const feature of pack.features) {
if (feature.type !== "lake") continue;
feature.name = getName(feature);
}
}
const inlets = feature.inlets?.filter(r => pack.rivers.find(river => river.i === r));
if (!inlets || !inlets.length) delete feature.inlets;
else feature.inlets = inlets;
const getName = function(feature) {
const landCell = pack.cells.c[feature.firstCell].find(c => pack.cells.h[c] >= 20);
const culture = pack.cells.culture[landCell];
return Names.getCulture(culture);
}
const outlet = feature.outlet && pack.rivers.find(river => river.i === feature.outlet);
if (!outlet) delete feature.outlet;
}
};
function getGroup(feature) {
if (feature.temp < -3) return "frozen";
if (feature.height > 60 && feature.cells < 10 && feature.firstCell % 5 === 0) return "lava";
const defineGroup = function () {
for (const feature of pack.features) {
if (feature.type !== "lake") continue;
const lakeEl = lakes.select(`[data-f="${feature.i}"]`).node();
if (!lakeEl) continue;
if (!feature.inlets && !feature.outlet) {
if (feature.evaporation / 2 > feature.flux) return "dry";
if (feature.cells < 3 && feature.firstCell % 5 === 0) return "sinkhole";
feature.group = getGroup(feature);
document.getElementById(feature.group).appendChild(lakeEl);
}
};
const generateName = function () {
Math.random = aleaPRNG(seed);
for (const feature of pack.features) {
if (feature.type !== "lake") continue;
feature.name = getName(feature);
}
};
const getName = function (feature) {
const landCell = pack.cells.c[feature.firstCell].find(c => pack.cells.h[c] >= 20);
const culture = pack.cells.culture[landCell];
return Names.getCulture(culture);
};
function getGroup(feature) {
if (feature.temp < -3) return "frozen";
if (feature.height > 60 && feature.cells < 10 && feature.firstCell % 5 === 0) return "lava";
if (!feature.inlets && !feature.outlet) {
if (feature.evaporation / 2 > feature.flux) return "dry";
if (feature.cells < 3 && feature.firstCell % 5 === 0) return "sinkhole";
}
if (!feature.outlet && feature.evaporation > feature.flux) return "salt";
return "freshwater";
}
if (!feature.outlet && feature.evaporation > feature.flux) return "salt";
return "freshwater";
}
return {setClimateData, cleanupLakeData, defineGroup, generateName, getName};
})));
return {setClimateData, cleanupLakeData, defineGroup, generateName, getName, getShoreline};
});

View file

@ -1,355 +1,389 @@
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.Rivers = factory());
}(this, (function () {'use strict';
typeof exports === "object" && typeof module !== "undefined" ? (module.exports = factory()) : typeof define === "function" && define.amd ? define(factory) : (global.Rivers = factory());
})(this, function () {
"use strict";
const generate = function(changeHeights = true) {
TIME && console.time('generateRivers');
Math.random = aleaPRNG(seed);
const cells = pack.cells, p = cells.p, features = pack.features;
const generate = function (changeHeights = true) {
TIME && console.time("generateRivers");
Math.random = aleaPRNG(seed);
const cells = pack.cells,
p = cells.p,
features = pack.features;
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
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
const h = alterHeights();
removeStoredLakeData();
resolveDepressions(h);
drainWater();
defineRivers();
Lakes.cleanupLakeData();
const h = alterHeights();
prepareLakeData();
resolveDepressions(h, 200);
drainWater();
defineRivers();
Lakes.cleanupLakeData();
if (changeHeights) cells.h = Uint8Array.from(h); // apply changed heights as basic one
if (changeHeights) cells.h = Uint8Array.from(h); // apply changed heights as basic one
TIME && console.timeEnd('generateRivers');
TIME && console.timeEnd("generateRivers");
// height with added t value to make map less depressed
function alterHeights() {
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);
return h;
}
function prepareLakeData() {
features.forEach(f => {
if (f.type !== "lake") return;
delete f.flux;
delete f.inlets;
delete f.outlet;
delete f.height;
!f.shoreline && Lakes.getShoreline(f);
});
}
function removeStoredLakeData() {
features.forEach(f => {
delete f.flux;
delete f.inlets;
delete f.outlet;
delete f.height;
});
}
function drainWater() {
const MIN_FLUX_TO_FORM_RIVER = 30;
const land = cells.i.filter(i => h[i] >= 20).sort((a, b) => h[b] - h[a]);
const lakeOutCells = Lakes.setClimateData(h);
function drainWater() {
const MIN_FLUX_TO_FORM_RIVER = 30;
const land = cells.i.filter(i => h[i] >= 20).sort((a,b) => h[b] - h[a]);
const lakeOutCells = Lakes.setClimateData(h);
land.forEach(function (i) {
cells.fl[i] += grid.cells.prec[cells.g[i]]; // flux from precipitation
const [x, y] = p[i];
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];
// create lake outlet if lake is not in deep depression and flux > evaporation
const lakes = lakeOutCells[i] ? features.filter(feature => i === feature.outCell && feature.flux > feature.evaporation) : [];
for (const lake of lakes) {
const lakeCell = cells.c[i].find(c => h[c] < 20 && cells.f[c] === lake.i);
// create lake outlet if flux > evaporation
const lakes = !lakeOutCells[i] ? [] : features.filter(feature => i === feature.outCell && feature.flux > feature.evaporation);
for (const lake of lakes) {
const lakeCell = cells.c[i].find(c => h[c] < 20 && cells.f[c] === lake.i);
cells.fl[lakeCell] += Math.max(lake.flux - lake.evaporation, 0); // not evaporated lake water drains to outlet
cells.fl[lakeCell] += Math.max(lake.flux - lake.evaporation, 0); // not evaporated lake water drains to outlet
// allow chain lakes to retain identity
if (cells.r[lakeCell] !== lake.river) {
const sameRiver = cells.c[lakeCell].some(c => cells.r[c] === lake.river);
if (sameRiver) {
cells.r[lakeCell] = lake.river;
riversData.push({river: lake.river, cell: lakeCell, x: p[lakeCell][0], y: p[lakeCell][1], flux: cells.fl[lakeCell]});
} else {
cells.r[lakeCell] = riverNext;
riversData.push({river: riverNext, cell: lakeCell, x: p[lakeCell][0], y: p[lakeCell][1], flux: cells.fl[lakeCell]});
riverNext++;
// allow chain lakes to retain identity
if (cells.r[lakeCell] !== lake.river) {
const sameRiver = cells.c[lakeCell].some(c => cells.r[c] === lake.river);
if (sameRiver) {
cells.r[lakeCell] = lake.river;
riversData.push({river: lake.river, cell: lakeCell, x: p[lakeCell][0], y: p[lakeCell][1], flux: cells.fl[lakeCell]});
} else {
cells.r[lakeCell] = riverNext;
riversData.push({river: riverNext, cell: lakeCell, x: p[lakeCell][0], y: p[lakeCell][1], flux: cells.fl[lakeCell]});
riverNext++;
}
}
lake.outlet = cells.r[lakeCell];
flowDown(i, cells.fl[i], cells.fl[lakeCell], lake.outlet);
}
lake.outlet = cells.r[lakeCell];
flowDown(i, cells.fl[i], cells.fl[lakeCell], lake.outlet);
// assign all tributary rivers to outlet basin
for (let outlet = lakes[0]?.outlet, l = 0; l < lakes.length; l++) {
lakes[l].inlets?.forEach(fork => (riversData.find(r => r.river === fork).parent = outlet));
}
// near-border cell: pour water out of the screen
if (cells.b[i] && cells.r[i]) {
let to = [];
const min = Math.min(y, graphHeight - y, x, graphWidth - x);
if (min === y) to = [x, 0];
else if (min === graphHeight - y) to = [x, graphHeight];
else if (min === x) to = [0, y];
else if (min === graphWidth - x) to = [graphWidth, y];
riversData.push({river: cells.r[i], cell: i, x: to[0], y: to[1], flux: cells.fl[i]});
return;
}
// downhill cell (make sure it's not in the source lake)
const min = lakeOutCells[i] ? cells.c[i].filter(c => !lakes.map(lake => lake.i).includes(cells.f[c])).sort((a, b) => h[a] - h[b])[0] : cells.c[i].sort((a, b) => h[a] - h[b])[0];
if (cells.fl[i] < MIN_FLUX_TO_FORM_RIVER) {
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, flux: cells.fl[i]});
riverNext++;
}
flowDown(min, cells.fl[min], cells.fl[i], cells.r[i], i);
});
}
function flowDown(toCell, toFlux, fromFlux, river, fromCell = 0) {
if (cells.r[toCell]) {
// downhill cell already has river assigned
if (toFlux < fromFlux) {
cells.conf[toCell] = cells.fl[toCell]; // mark confluence
if (h[toCell] >= 20) riversData.find(r => r.river === cells.r[toCell]).parent = river; // min river is a tributary of current river
cells.r[toCell] = river; // re-assign river if downhill part has less flux
} else {
cells.conf[toCell] += fromFlux; // mark confluence
if (h[toCell] >= 20) riversData.find(r => r.river === river).parent = cells.r[toCell]; // current river is a tributary of min river
}
} else cells.r[toCell] = river; // assign the river to the downhill cell
if (h[toCell] < 20) {
// pour water to the water body
const haven = fromCell ? cells.haven[fromCell] : toCell;
riversData.push({river, cell: haven, x: p[toCell][0], y: p[toCell][1], flux: fromFlux});
const waterBody = features[cells.f[toCell]];
if (waterBody.type === "lake") {
if (!waterBody.river || fromFlux > waterBody.enteringFlux) {
waterBody.river = river;
waterBody.enteringFlux = fromFlux;
}
waterBody.flux = waterBody.flux + fromFlux;
waterBody.inlets ? waterBody.inlets.push(river) : (waterBody.inlets = [river]);
}
} else {
// propagate flux and add next river segment
cells.fl[toCell] += fromFlux;
riversData.push({river, cell: toCell, x: p[toCell][0], y: p[toCell][1], flux: fromFlux});
}
}
function defineRivers() {
cells.r = new Uint16Array(cells.i.length); // re-initiate rivers array
pack.rivers = []; // rivers data
const riverPaths = [];
for (let r = 1; r <= riverNext; r++) {
const riverSegments = riversData.filter(d => d.river === r);
if (riverSegments.length < 3) continue;
for (const segment of riverSegments) {
const i = segment.cell;
if (cells.r[i]) continue;
if (cells.h[i] < 20) continue;
cells.r[i] = r;
}
const source = riverSegments[0].cell;
const mouth = riverSegments[riverSegments.length - 2].cell;
const widthFactor = rn(0.8 + Math.random() * 0.4, 1); // river width modifier [.8, 1.2]
const sourceWidth = cells.h[source] >= 20 ? 0.1 : rn(Math.min(Math.max((cells.fl[source] / 500) ** 0.4, 0.5), 1.7), 2);
const riverMeandered = addMeandering(riverSegments, sourceWidth * 10, 0.5);
const [path, length, offset] = getPath(riverMeandered, widthFactor, sourceWidth);
riverPaths.push([path, r]);
const parent = riverSegments[0].parent || 0;
const width = rn(offset ** 2, 2); // mounth width in km
const discharge = last(riverSegments).flux; // in m3/s
pack.rivers.push({i: r, source, mouth, discharge, length, width, widthFactor, sourceWidth, parent});
}
// assign all tributary rivers to outlet basin
for (let outlet = lakes[0]?.outlet, l = 0; l < lakes.length; l++) {
lakes[l].inlets?.forEach(fork => riversData.find(r => r.river === fork).parent = outlet);
}
// draw rivers
rivers.html(riverPaths.map(d => `<path id="river${d[1]}" d="${d[0]}"/>`).join(""));
}
};
// near-border cell: pour water out of the screen
if (cells.b[i] && 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], flux: cells.fl[i]});
return;
}
// downhill cell (make sure it's not in the source lake)
const min = lakeOutCells[i]
? cells.c[i].filter(c => !lakes.map(lake => lake.i).includes(cells.f[c])).sort((a, b) => h[a] - h[b])[0]
: cells.c[i].sort((a, b) => h[a] - h[b])[0];
if (cells.fl[i] < MIN_FLUX_TO_FORM_RIVER) {
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, flux: cells.fl[i]});
riverNext++;
}
flowDown(min, cells.fl[min], cells.fl[i], cells.r[i], i);
// add distance to water value to land cells to make map less depressed
function alterHeights() {
const cells = pack.cells;
return Array.from(cells.h).map((h, i) => {
if (h < 20 || cells.t[i] < 1) return h;
return h + cells.t[i] / 100 + d3.mean(cells.c[i].map(c => cells.t[c])) / 10000;
});
}
function flowDown(toCell, toFlux, fromFlux, river, fromCell = 0) {
if (cells.r[toCell]) {
// downhill cell already has river assigned
if (toFlux < fromFlux) {
cells.conf[toCell] = cells.fl[toCell]; // mark confluence
if (h[toCell] >= 20) riversData.find(r => r.river === cells.r[toCell]).parent = river; // min river is a tributary of current river
cells.r[toCell] = river; // re-assign river if downhill part has less flux
} else {
cells.conf[toCell] += fromFlux; // mark confluence
if (h[toCell] >= 20) riversData.find(r => r.river === river).parent = cells.r[toCell]; // current river is a tributary of min river
// depression filling algorithm (for a correct water flux modeling)
const resolveDepressions = function (h, maxIterations) {
const {cells, features} = pack;
const height = i => features[cells.f[i]].height || h[i]; // height of lake or specific cell
const lakes = features.filter(f => f.type === "lake");
const land = cells.i.filter(i => h[i] >= 20 && !cells.b[i]); // exclude near-border cells
land.sort((a, b) => h[b] - h[a]); // highest cells go first
const progress = [];
let depressions = Infinity;
let prevDepressions = null;
for (let iteration = 0; depressions && iteration < maxIterations; iteration++) {
if (progress.length > 5 && d3.sum(progress) > 0) {
// bad progress, abort and set heights back
h = alterHeights();
depressions = progress[0];
break;
}
} else cells.r[toCell] = river; // assign the river to the downhill cell
if (h[toCell] < 20) {
// pour water to the water body
const haven = fromCell ? cells.haven[fromCell] : toCell;
riversData.push({river, cell: haven, x: p[toCell][0], y: p[toCell][1], flux: fromFlux});
depressions = 0;
const waterBody = features[cells.f[toCell]];
if (waterBody.type === "lake") {
if (!waterBody.river || fromFlux > waterBody.enteringFlux) {
waterBody.river = river;
waterBody.enteringFlux = fromFlux;
if (iteration < 180) {
for (const l of lakes) {
if (l.closed) continue;
const minHeight = d3.min(l.shoreline.map(s => h[s]));
if (minHeight >= 100 || l.height > minHeight) continue;
if (iteration > 150) {
l.shoreline.forEach(i => (h[i] = cells.h[i]));
l.height = d3.min(l.shoreline.map(s => h[s])) - 1;
l.closed = true;
continue;
}
depressions++;
l.height = minHeight + 0.2;
}
waterBody.flux = waterBody.flux + fromFlux;
waterBody.inlets ? waterBody.inlets.push(river) : waterBody.inlets = [river];
}
} else {
// propagate flux and add next river segment
cells.fl[toCell] += fromFlux;
riversData.push({river, cell: toCell, x: p[toCell][0], y: p[toCell][1], flux: fromFlux});
}
}
function defineRivers() {
cells.r = new Uint16Array(cells.i.length); // re-initiate rivers array
pack.rivers = []; // rivers data
const riverPaths = [];
for (let r = 1; r <= riverNext; r++) {
const riverSegments = riversData.filter(d => d.river === r);
if (riverSegments.length < 3) continue;
for (const segment of riverSegments) {
const i = segment.cell;
if (cells.r[i]) continue;
if (cells.h[i] < 20) continue;
cells.r[i] = r;
}
const source = riverSegments[0].cell;
const mouth = riverSegments[riverSegments.length-2].cell;
for (const i of land) {
const minHeight = d3.min(cells.c[i].map(c => height(c)));
if (minHeight >= 100 || h[i] > minHeight) continue;
const widthFactor = rn(.8 + Math.random() * .4, 1); // river width modifier [.8, 1.2]
const sourceWidth = cells.h[source] >= 20 ? .1 : rn(Math.min(Math.max((cells.fl[source] / 500) ** .4, .5), 1.7), 2);
depressions++;
h[i] = minHeight + 0.1;
}
const riverMeandered = addMeandering(riverSegments, sourceWidth * 10, .5);
const [path, length, offset] = getPath(riverMeandered, widthFactor, sourceWidth);
riverPaths.push([path, r]);
const parent = riverSegments[0].parent || 0;
const width = rn(offset ** 2, 2); // mounth width in km
const discharge = last(riverSegments).flux; // in m3/s
pack.rivers.push({i:r, source, mouth, discharge, length, width, widthFactor, sourceWidth, parent});
prevDepressions !== null && progress.push(depressions - prevDepressions);
prevDepressions = depressions;
}
// draw rivers
rivers.html(riverPaths.map(d => `<path id="river${d[1]}" d="${d[0]}"/>`).join(""));
}
}
if (!depressions) return;
WARN && console.warn(`Unresolved depressions: ${depressions}. Edit heightmap to fix`);
//const flow = cells.i.length < 65535 ? new Uint16Array(cells.i.length) : new Uint32Array(cells.i.length);
//flow[i] = min;
//debug.append("path").attr("class", "arrow").attr("d", `M${cells.p[i][0]},${cells.p[i][1]}L${cells.p[min][0]},${cells.p[min][1]}`);
};
// depression filling algorithm (for a correct water flux modeling)
const resolveDepressions = function(h) {
const {cells, features} = pack;
const ITERATIONS = 150;
// add more river points on 1/3 and 2/3 of length
const addMeandering = function (segments, width = 1, meandering = 0.5) {
const riverMeandered = []; // to store enhanced segments
const lakes = features.filter(f => f.type === "lake");
lakes.forEach(l => {
const uniqueCells = new Set();
l.vertices.forEach(v => pack.vertices.c[v].forEach(c => cells.h[c] >= 20 && uniqueCells.add(c)));
l.shoreline = [...uniqueCells];
});
for (let s = 0; s < segments.length; s++, width++) {
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
riverMeandered.push([sX, sY, c]);
const land = cells.i.filter(i => h[i] >= 20 && !cells.b[i]); // exclude near-border cells
land.sort((a,b) => h[b] - h[a]); // highest cells go first
if (s + 1 === segments.length) break; // do not meander last segment
let depressions = Infinity;
for (let l = 0; depressions && l < ITERATIONS; l++) {
depressions = 0;
const eX = segments[s + 1].x,
eY = segments[s + 1].y; // segment end coordinates
const angle = Math.atan2(eY - sY, eX - sX);
const sin = Math.sin(angle),
cos = Math.cos(angle);
for (const l of lakes) {
const minHeight = d3.min(l.shoreline.map(s => h[s]));
if (minHeight >= 100 || l.height > minHeight) continue;
l.height = minHeight + 1;
depressions++;
const meander = meandering + 1 / width + Math.random() * Math.max(meandering - width / 100, 0);
const dist2 = (eX - sX) ** 2 + (eY - sY) ** 2; // square distance between segment start and end
if (width < 10 && (dist2 > 64 || (dist2 > 36 && segments.length < 6))) {
// if dist2 is big or river is small add extra points at 1/3 and 2/3 of segment
const p1x = (sX * 2 + eX) / 3 + -sin * meander;
const p1y = (sY * 2 + eY) / 3 + cos * meander;
const p2x = (sX + eX * 2) / 3 + sin * meander;
const p2y = (sY + eY * 2) / 3 + cos * meander;
riverMeandered.push([p1x, p1y], [p2x, p2y]);
} else if (dist2 > 25 || segments.length < 6) {
// if dist is medium or river is small add 1 extra middlepoint
const p1x = (sX + eX) / 2 + -sin * meander;
const p1y = (sY + eY) / 2 + cos * meander;
riverMeandered.push([p1x, p1y]);
}
}
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]));
if (minHeight >= 100 || h[i] > minHeight) continue;
h[i] = minHeight + 1;
depressions++;
}
}
return riverMeandered;
};
depressions && ERROR && console.error("Heightmap is depressed. Issues with rivers expected. Remove depressed areas to resolve");
}
const getPath = function (points, widthFactor = 1, sourceWidth = 0.1) {
let offset,
extraOffset = sourceWidth; // 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 = 1000 + riverLength * 30;
const riverPointsLeft = [],
riverPointsRight = []; // store points on both sides to build a valid polygon
const last = points.length - 1;
const factor = riverLength / points.length;
// add more river points on 1/3 and 2/3 of length
const addMeandering = function(segments, width = 1, meandering = .5) {
const riverMeandered = []; // to store enhanced segments
for (let s = 0; s < segments.length; s++, width++) {
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
riverMeandered.push([sX, sY, c]);
if (s+1 === segments.length) break; // do not meander last segment
const eX = segments[s+1].x, eY = segments[s+1].y; // segment end coordinates
const angle = Math.atan2(eY - sY, eX - sX);
const sin = Math.sin(angle), cos = Math.cos(angle);
const meander = meandering + 1 / width + Math.random() * Math.max(meandering - width / 100, 0);
const dist2 = (eX - sX) ** 2 + (eY - sY) ** 2; // square distance between segment start and end
if (width < 10 && (dist2 > 64 || (dist2 > 36 && segments.length < 6))) {
// if dist2 is big or river is small add extra points at 1/3 and 2/3 of segment
const p1x = (sX * 2 + eX) / 3 + -sin * meander;
const p1y = (sY * 2 + eY) / 3 + cos * meander;
const p2x = (sX + eX * 2) / 3 + sin * meander;
const p2y = (sY + eY * 2) / 3 + cos * meander;
riverMeandered.push([p1x, p1y], [p2x, p2y]);
} else if (dist2 > 25 || segments.length < 6) {
// if dist is medium or river is small add 1 extra middlepoint
const p1x = (sX + eX) / 2 + -sin * meander;
const p1y = (sY + eY) / 2 + cos * meander;
riverMeandered.push([p1x, p1y]);
}
}
return riverMeandered;
}
const getPath = function(points, widthFactor = 1, sourceWidth = .1) {
let offset, extraOffset = sourceWidth; // 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 = 1000 + riverLength * 30;
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);
offset = (Math.atan(Math.pow(p * factor, 2) / widening) / 2 * widthFactor) + extraOffset;
const confOffset = Math.atan(c * 5 / widening);
extraOffset += confOffset;
xLeft = x + -sin * offset, yLeft = y + cos * (offset + confOffset);
// 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]);
xRight = x + sin * offset, yRight = y + -cos * offset;
let xRight = x + sin * extraOffset,
yRight = y + -cos * extraOffset;
riverPointsRight.unshift([xRight, yRight]);
}
// end point
x = points[last][0], y = points[last][1], c = points[last][2];
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);
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]);
// 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));
offset = (Math.atan(Math.pow(p * factor, 2) / widening) / 2) * widthFactor + extraOffset;
const confOffset = Math.atan((c * 5) / widening);
extraOffset += confOffset;
(xLeft = x + -sin * offset), (yLeft = y + cos * (offset + confOffset));
riverPointsLeft.push([xLeft, yLeft]);
(xRight = x + sin * offset), (yRight = y + -cos * offset);
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), offset];
}
// end point
(x = points[last][0]), (y = points[last][1]), (c = points[last][2]);
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);
(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]);
const specify = function() {
const rivers = pack.rivers;
if (!rivers.length) return;
Math.random = aleaPRNG(seed);
const tresholdElement = Math.ceil(rivers.length * .15);
const smallLength = rivers.map(r => r.length || 0).sort((a, b) => a-b)[tresholdElement];
const smallType = {"Creek":9, "River":3, "Brook":3, "Stream":1}; // weighted small river types
// 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), offset];
};
for (const r of rivers) {
r.basin = getBasin(r.i);
r.name = getName(r.mouth);
const small = r.length < smallLength;
r.type = r.parent && !(r.i%6) ? small ? "Branch" : "Fork" : small ? rw(smallType) : "River";
}
}
const specify = function () {
const rivers = pack.rivers;
if (!rivers.length) return;
Math.random = aleaPRNG(seed);
const tresholdElement = Math.ceil(rivers.length * 0.15);
const smallLength = rivers.map(r => r.length || 0).sort((a, b) => a - b)[tresholdElement];
const smallType = {Creek: 9, River: 3, Brook: 3, Stream: 1}; // weighted small river types
const getName = function(cell) {
return Names.getCulture(pack.cells.culture[cell]);
}
for (const r of rivers) {
r.basin = getBasin(r.i);
r.name = getName(r.mouth);
const small = r.length < smallLength;
r.type = r.parent && !(r.i % 6) ? (small ? "Branch" : "Fork") : small ? rw(smallType) : "River";
}
};
// remove river and all its tributaries
const remove = function(id) {
const cells = pack.cells;
const riversToRemove = pack.rivers.filter(r => r.i === id || r.parent === id || r.basin === 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 getName = function (cell) {
return Names.getCulture(pack.cells.culture[cell]);
};
const getBasin = function(r) {
const parent = pack.rivers.find(river => river.i === r)?.parent;
if (!parent || r === parent) return r;
return getBasin(parent);
}
// remove river and all its tributaries
const remove = function (id) {
const cells = pack.cells;
const riversToRemove = pack.rivers.filter(r => r.i === id || r.parent === id || r.basin === 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));
};
return {generate, resolveDepressions, addMeandering, getPath, specify, getName, getBasin, remove};
const getBasin = function (r) {
const parent = pack.rivers.find(river => river.i === r)?.parent;
if (!parent || r === parent) return r;
return getBasin(parent);
};
})));
return {generate, resolveDepressions, addMeandering, getPath, specify, getName, getBasin, remove};
});

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,44 +1,57 @@
// module to control the Tools options (click to edit, to re-geenerate, tp add)
"use strict";
toolsContent.addEventListener("click", function(event) {
if (customization) {tip("Please exit the customization mode first", false, "warning"); return;}
toolsContent.addEventListener("click", function (event) {
if (customization) {
tip("Please exit the customization mode first", false, "warning");
return;
}
if (event.target.tagName !== "BUTTON") return;
const button = event.target.id;
// Click to open Editor buttons
if (button === "editHeightmapButton") editHeightmap(); else
if (button === "editBiomesButton") editBiomes(); else
if (button === "editStatesButton") editStates(); else
if (button === "editProvincesButton") editProvinces(); else
if (button === "editDiplomacyButton") editDiplomacy(); else
if (button === "editCulturesButton") editCultures(); else
if (button === "editReligions") editReligions(); else
if (button === "editEmblemButton") openEmblemEditor(); else
if (button === "editNamesBaseButton") editNamesbase(); else
if (button === "editUnitsButton") editUnits(); else
if (button === "editNotesButton") editNotes(); else
if (button === "editZonesButton") editZones(); else
if (button === "overviewBurgsButton") overviewBurgs(); else
if (button === "overviewRiversButton") overviewRivers(); else
if (button === "overviewMilitaryButton") overviewMilitary(); else
if (button === "overviewCellsButton") viewCellDetails();
if (button === "editHeightmapButton") editHeightmap();
else if (button === "editBiomesButton") editBiomes();
else if (button === "editStatesButton") editStates();
else if (button === "editProvincesButton") editProvinces();
else if (button === "editDiplomacyButton") editDiplomacy();
else if (button === "editCulturesButton") editCultures();
else if (button === "editReligions") editReligions();
else if (button === "editEmblemButton") openEmblemEditor();
else if (button === "editNamesBaseButton") editNamesbase();
else if (button === "editUnitsButton") editUnits();
else if (button === "editNotesButton") editNotes();
else if (button === "editZonesButton") editZones();
else if (button === "overviewBurgsButton") overviewBurgs();
else if (button === "overviewRiversButton") overviewRivers();
else if (button === "overviewMilitaryButton") overviewMilitary();
else if (button === "overviewCellsButton") viewCellDetails();
// Click to Regenerate buttons
if (event.target.parentNode.id === "regenerateFeature") {
if (sessionStorage.getItem("regenerateFeatureDontAsk")) {processFeatureRegeneration(event, button); return;}
if (sessionStorage.getItem("regenerateFeatureDontAsk")) {
processFeatureRegeneration(event, button);
return;
}
alertMessage.innerHTML = `Regeneration will remove all the custom changes for the element.<br><br>Are you sure you want to proceed?`
$("#alert").dialog({resizable: false, title: "Regenerate element",
alertMessage.innerHTML = `Regeneration will remove all the custom changes for the element.<br><br>Are you sure you want to proceed?`;
$("#alert").dialog({
resizable: false,
title: "Regenerate element",
buttons: {
Proceed: function() {processFeatureRegeneration(event, button); $(this).dialog("close");},
Cancel: function() {$(this).dialog("close");}
Proceed: function () {
processFeatureRegeneration(event, button);
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
},
open: function() {
open: function () {
const pane = $(this).dialog("widget").find(".ui-dialog-buttonpane");
$('<span><input id="dontAsk" class="checkbox" type="checkbox"><label for="dontAsk" class="checkbox-label dontAsk"><i>do not ask again</i></label><span>').prependTo(pane);
},
close: function() {
close: function () {
const box = $(this).dialog("widget").find(".checkbox")[0];
if (!box) return;
if (box.checked) sessionStorage.setItem("regenerateFeatureDontAsk", true);
@ -48,29 +61,35 @@ toolsContent.addEventListener("click", function(event) {
}
// Click to Add buttons
if (button === "addLabel") toggleAddLabel(); else
if (button === "addBurgTool") toggleAddBurg(); else
if (button === "addRiver") toggleAddRiver(); else
if (button === "addRoute") toggleAddRoute(); else
if (button === "addMarker") toggleAddMarker();
if (button === "addLabel") toggleAddLabel();
else if (button === "addBurgTool") toggleAddBurg();
else if (button === "addRiver") toggleAddRiver();
else if (button === "addRoute") toggleAddRoute();
else if (button === "addMarker") toggleAddMarker();
});
function processFeatureRegeneration(event, button) {
if (button === "regenerateStateLabels") {BurgsAndStates.drawStateLabels(); if (!layerIsOn("toggleLabels")) toggleLabels();} else
if (button === "regenerateReliefIcons") {ReliefIcons(); if (!layerIsOn("toggleRelief")) toggleRelief();} else
if (button === "regenerateRoutes") {Routes.regenerate(); if (!layerIsOn("toggleRoutes")) toggleRoutes();} else
if (button === "regenerateRivers") regenerateRivers(); else
if (button === "regeneratePopulation") recalculatePopulation(); else
if (button === "regenerateStates") regenerateStates(); else
if (button === "regenerateProvinces") regenerateProvinces(); else
if (button === "regenerateBurgs") regenerateBurgs(); else
if (button === "regenerateEmblems") regenerateEmblems(); else
if (button === "regenerateReligions") regenerateReligions(); else
if (button === "regenerateCultures") regenerateCultures(); else
if (button === "regenerateMilitary") regenerateMilitary(); else
if (button === "regenerateIce") regenerateIce(); else
if (button === "regenerateMarkers") regenerateMarkers(event); else
if (button === "regenerateZones") regenerateZones(event);
if (button === "regenerateStateLabels") {
BurgsAndStates.drawStateLabels();
if (!layerIsOn("toggleLabels")) toggleLabels();
} else if (button === "regenerateReliefIcons") {
ReliefIcons();
if (!layerIsOn("toggleRelief")) toggleRelief();
} else if (button === "regenerateRoutes") {
Routes.regenerate();
if (!layerIsOn("toggleRoutes")) toggleRoutes();
} else if (button === "regenerateRivers") regenerateRivers();
else if (button === "regeneratePopulation") recalculatePopulation();
else if (button === "regenerateStates") regenerateStates();
else if (button === "regenerateProvinces") regenerateProvinces();
else if (button === "regenerateBurgs") regenerateBurgs();
else if (button === "regenerateEmblems") regenerateEmblems();
else if (button === "regenerateReligions") regenerateReligions();
else if (button === "regenerateCultures") regenerateCultures();
else if (button === "regenerateMilitary") regenerateMilitary();
else if (button === "regenerateIce") regenerateIce();
else if (button === "regenerateMarkers") regenerateMarkers(event);
else if (button === "regenerateZones") regenerateZones(event);
}
async function openEmblemEditor() {
@ -106,10 +125,10 @@ function recalculatePopulation() {
if (!b.i || b.removed || b.lock) return;
const i = b.cell;
b.population = rn(Math.max((pack.cells.s[i] + pack.cells.road[i] / 2) / 8 + b.i / 1000 + i % 100 / 1000, .1), 3);
b.population = rn(Math.max((pack.cells.s[i] + pack.cells.road[i] / 2) / 8 + b.i / 1000 + (i % 100) / 1000, 0.1), 3);
if (b.capital) b.population = b.population * 1.3; // increase capital population
if (b.port) b.population = b.population * 1.3; // increase port population
b.population = rn(b.population * gauss(2,3,.6,20,3), 3);
b.population = rn(b.population * gauss(2, 3, 0.6, 20, 3), 3);
});
}
@ -126,14 +145,19 @@ function regenerateStates() {
}
// burg local ids sorted by a bit randomized population:
const sorted = burgs.map((b, i) => [i, b.population * Math.random()]).sort((a, b) => b[1] - a[1]).map(b => b[0]);
const sorted = burgs
.map((b, i) => [i, b.population * Math.random()])
.sort((a, b) => b[1] - a[1])
.map(b => b[0]);
const capitalsTree = d3.quadtree();
// turn all old capitals into towns
burgs.filter(b => b.capital).forEach(b => {
moveBurgToGroup(b.i, "towns");
b.capital = 0;
});
burgs
.filter(b => b.capital)
.forEach(b => {
moveBurgToGroup(b.i, "towns");
b.capital = 0;
});
// remove emblems
document.querySelectorAll("[id^=stateCOA]").forEach(el => el.remove());
@ -145,7 +169,7 @@ function regenerateStates() {
// if desired states number is 0
if (regionsInput.value == 0) {
tip(`Cannot generate zero states. Please check the <i>States Number</i> option`, false, "warn");
pack.states = pack.states.slice(0,1); // remove all except of neutrals
pack.states = pack.states.slice(0, 1); // remove all except of neutrals
pack.states[0].diplomacy = []; // clear diplomacy
pack.provinces = [0]; // remove all provinces
pack.cells.state = new Uint16Array(pack.cells.i.length); // reset cells data
@ -165,10 +189,12 @@ function regenerateStates() {
pack.states = d3.range(count).map(i => {
if (!i) return {i, name: neutral};
let capital = null, x = 0, y = 0;
let capital = null,
x = 0,
y = 0;
for (const i of sorted) {
capital = burgs[i];
x = capital.x, y = capital.y;
(x = capital.x), (y = capital.y);
if (capitalsTree.find(x, y, spacing) === undefined) break;
spacing = Math.max(spacing - 1, 1);
}
@ -178,17 +204,17 @@ function regenerateStates() {
moveBurgToGroup(capital.i, "cities");
const culture = capital.culture;
const basename = capital.name.length < 9 && capital.cell%5 === 0 ? capital.name : Names.getCulture(culture, 3, 6, "", 0);
const basename = capital.name.length < 9 && capital.cell % 5 === 0 ? capital.name : Names.getCulture(culture, 3, 6, "", 0);
const name = Names.getState(basename, culture);
const nomadic = [1, 2, 3, 4].includes(pack.cells.biome[capital.cell]);
const type = nomadic ? "Nomadic" : pack.cultures[culture].type === "Nomadic" ? "Generic" : pack.cultures[culture].type;
const expansionism = rn(Math.random() * powerInput.value + 1, 1);
const cultureType = pack.cultures[culture].type;
const coa = COA.generate(capital.coa, .3, null, cultureType);
const coa = COA.generate(capital.coa, 0.3, null, cultureType);
coa.shield = capital.coa.shield;
return {i, name, type, capital:capital.i, center:capital.cell, culture, expansionism, coa};
return {i, name, type, capital: capital.i, center: capital.cell, culture, expansionism, coa};
});
BurgsAndStates.expandStates();
@ -199,8 +225,10 @@ function regenerateStates() {
BurgsAndStates.generateDiplomacy();
BurgsAndStates.defineStateForms();
BurgsAndStates.generateProvinces(true);
if (!layerIsOn("toggleStates")) toggleStates(); else drawStates();
if (!layerIsOn("toggleBorders")) toggleBorders(); else drawBorders();
if (!layerIsOn("toggleStates")) toggleStates();
else drawStates();
if (!layerIsOn("toggleBorders")) toggleBorders();
else drawBorders();
BurgsAndStates.drawStateLabels();
Military.generate();
if (layerIsOn("toggleEmblems")) drawEmblems(); // redrawEmblems
@ -224,43 +252,52 @@ function regenerateProvinces() {
}
function regenerateBurgs() {
const cells = pack.cells, states = pack.states, Lockedburgs = pack.burgs.filter(b =>b.lock);
const cells = pack.cells,
states = pack.states,
Lockedburgs = pack.burgs.filter(b => b.lock);
rankCells();
cells.burg = new Uint16Array(cells.i.length);
const burgs = pack.burgs = [0]; // clear burgs array
states.filter(s => s.i).forEach(s => s.capital = 0); // clear state capitals
pack.provinces.filter(p => p.i).forEach(p => p.burg = 0); // clear province capitals
const burgs = (pack.burgs = [0]); // clear burgs array
states.filter(s => s.i).forEach(s => (s.capital = 0)); // clear state capitals
pack.provinces.filter(p => p.i).forEach(p => (p.burg = 0)); // clear province capitals
const burgsTree = d3.quadtree();
const score = new Int16Array(cells.s.map(s => s * Math.random())); // cell score for capitals placement
const sorted = cells.i.filter(i => score[i] > 0 && cells.culture[i]).sort((a, b) => score[b] - score[a]); // filtered and sorted array of indexes
const burgsCount = manorsInput.value == 1000 ? rn(sorted.length / 5 / (grid.points.length / 10000) ** .8) + states.length : +manorsInput.value + states.length;
const spacing = (graphWidth + graphHeight) / 150 / (burgsCount ** .7 / 66); // base min distance between towns
const burgsCount = manorsInput.value == 1000 ? rn(sorted.length / 5 / (grid.points.length / 10000) ** 0.8) + states.length : +manorsInput.value + states.length;
const spacing = (graphWidth + graphHeight) / 150 / (burgsCount ** 0.7 / 66); // base min distance between towns
//clear locked list since ids will change
//burglock.selectAll("text").remove();
for (let j=0; j < Lockedburgs.length; j++) {
for (let j = 0; j < Lockedburgs.length; j++) {
const id = burgs.length;
const oldBurg = Lockedburgs[j];
oldBurg.i = id;
burgs.push(oldBurg);
burgsTree.add([oldBurg.x, oldBurg.y]);
cells.burg[oldBurg.cell] = id;
if (oldBurg.capital) {states[oldBurg.state].capital = id; states[oldBurg.state].center = oldBurg.cell;}
if (oldBurg.capital) {
states[oldBurg.state].capital = id;
states[oldBurg.state].center = oldBurg.cell;
}
//burglock.append("text").attr("data-id", id);
}
for (let i=0; i < sorted.length && burgs.length < burgsCount; i++) {
for (let i = 0; i < sorted.length && burgs.length < burgsCount; i++) {
const id = burgs.length;
const cell = sorted[i];
const x = cells.p[cell][0], y = cells.p[cell][1];
const x = cells.p[cell][0],
y = cells.p[cell][1];
const s = spacing * gauss(1, .3, .2, 2, 2); // randomize to make the placement not uniform
const s = spacing * gauss(1, 0.3, 0.2, 2, 2); // randomize to make the placement not uniform
if (burgsTree.find(x, y, s) !== undefined) continue; // to close to existing burg
const state = cells.state[cell];
const capital = state && !states[state].capital; // if state doesn't have capital, make this burg a capital, no capital for neutral lands
if (capital) {states[state].capital = id; states[state].center = cell;}
if (capital) {
states[state].capital = id;
states[state].center = cell;
}
const culture = cells.culture[cell];
const name = Names.getCulture(culture);
@ -270,16 +307,20 @@ function regenerateBurgs() {
}
// add a capital at former place for states without added capitals
states.filter(s => s.i && !s.removed && !s.capital).forEach(s => {
const burg = addBurg([cells.p[s.center][0], cells.p[s.center][1]]); // add new burg
s.capital = burg;
s.center = pack.burgs[burg].cell;
pack.burgs[burg].capital = 1;
pack.burgs[burg].state = s.i;
moveBurgToGroup(burg, "cities");
});
states
.filter(s => s.i && !s.removed && !s.capital)
.forEach(s => {
const burg = addBurg([cells.p[s.center][0], cells.p[s.center][1]]); // add new burg
s.capital = burg;
s.center = pack.burgs[burg].cell;
pack.burgs[burg].capital = 1;
pack.burgs[burg].state = s.i;
moveBurgToGroup(burg, "cities");
});
pack.features.forEach(f => {if (f.port) f.port = 0}); // reset features ports counter
pack.features.forEach(f => {
if (f.port) f.port = 0;
}); // reset features ports counter
BurgsAndStates.specifyBurgs();
BurgsAndStates.defineBurgFeatures();
BurgsAndStates.drawBurgs();
@ -313,10 +354,10 @@ function regenerateEmblems() {
if (!burg.i || burg.removed) return;
const state = pack.states[burg.state];
let kinship = state ? .25 : 0;
if (burg.capital) kinship += .1;
else if (burg.port) kinship -= .1;
if (state && burg.culture !== state.culture) kinship -= .25;
let kinship = state ? 0.25 : 0;
if (burg.capital) kinship += 0.1;
else if (burg.port) kinship -= 0.1;
if (state && burg.culture !== state.culture) kinship -= 0.25;
burg.coa = COA.generate(state ? state.coa : null, kinship, null, burg.type);
burg.coa.shield = COA.getShield(burg.culture, state ? burg.state : 0);
});
@ -327,16 +368,16 @@ function regenerateEmblems() {
let dominion = false;
if (!province.burg) {
dominion = P(.2);
if (province.formName === "Colony") dominion = P(.95); else
if (province.formName === "Island") dominion = P(.6); else
if (province.formName === "Islands") dominion = P(.5); else
if (province.formName === "Territory") dominion = P(.4); else
if (province.formName === "Land") dominion = P(.3);
dominion = P(0.2);
if (province.formName === "Colony") dominion = P(0.95);
else if (province.formName === "Island") dominion = P(0.6);
else if (province.formName === "Islands") dominion = P(0.5);
else if (province.formName === "Territory") dominion = P(0.4);
else if (province.formName === "Land") dominion = P(0.3);
}
const nameByBurg = province.burg && province.name.slice(0, 3) === parent.name.slice(0, 3);
const kinship = dominion ? 0 : nameByBurg ? .8 : .4;
const kinship = dominion ? 0 : nameByBurg ? 0.8 : 0.4;
const culture = pack.cells.culture[province.center];
const type = BurgsAndStates.getType(province.center, parent.port);
province.coa = COA.generate(parent.coa, kinship, dominion, type);
@ -348,7 +389,8 @@ function regenerateEmblems() {
function regenerateReligions() {
Religions.generate();
if (!layerIsOn("toggleReligions")) toggleReligions(); else drawReligions();
if (!layerIsOn("toggleReligions")) toggleReligions();
else drawReligions();
}
function regenerateCultures() {
@ -356,7 +398,8 @@ function regenerateCultures() {
Cultures.expand();
BurgsAndStates.updateCultures();
Religions.updateCultures();
if (!layerIsOn("toggleCultures")) toggleCultures(); else drawCultures();
if (!layerIsOn("toggleCultures")) toggleCultures();
else drawCultures();
refreshAllEditors();
}
@ -373,15 +416,18 @@ function regenerateIce() {
}
function regenerateMarkers(event) {
if (isCtrlClick(event)) prompt("Please provide markers number multiplier", {default:1, step:.01, min:0, max:100}, v => addNumberOfMarkers(v));
else addNumberOfMarkers(gauss(1, .5, .3, 5, 2));
if (isCtrlClick(event)) prompt("Please provide markers number multiplier", {default: 1, step: 0.01, min: 0, max: 100}, v => addNumberOfMarkers(v));
else addNumberOfMarkers(gauss(1, 0.5, 0.3, 5, 2));
function addNumberOfMarkers(number) {
// remove existing markers and assigned notes
markers.selectAll("use").each(function() {
const index = notes.findIndex(n => n.id === this.id);
if (index != -1) notes.splice(index, 1);
}).remove();
markers
.selectAll("use")
.each(function () {
const index = notes.findIndex(n => n.id === this.id);
if (index != -1) notes.splice(index, 1);
})
.remove();
addMarkers(number);
if (!layerIsOn("toggleMarkers")) toggleMarkers();
@ -389,8 +435,8 @@ function regenerateMarkers(event) {
}
function regenerateZones(event) {
if (isCtrlClick(event)) prompt("Please provide zones number multiplier", {default:1, step:.01, min:0, max:100}, v => addNumberOfZones(v));
else addNumberOfZones(gauss(1, .5, .6, 5, 2));
if (isCtrlClick(event)) prompt("Please provide zones number multiplier", {default: 1, step: 0.01, min: 0, max: 100}, v => addNumberOfZones(v));
else addNumberOfZones(gauss(1, 0.5, 0.6, 5, 2));
function addNumberOfZones(number) {
zones.selectAll("g").remove(); // remove existing zones
@ -408,10 +454,13 @@ function unpressClickToAddButton() {
function toggleAddLabel() {
const pressed = document.getElementById("addLabel").classList.contains("pressed");
if (pressed) {unpressClickToAddButton(); return;}
if (pressed) {
unpressClickToAddButton();
return;
}
addFeature.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed"));
addLabel.classList.add('pressed');
addLabel.classList.add("pressed");
closeDialogs(".stable");
viewbox.style("cursor", "crosshair").on("click", addLabelOnClick);
tip("Click on map to place label. Hold Shift to add multiple", true);
@ -428,10 +477,7 @@ function addLabelOnClick() {
const id = getNextId("label");
let group = labels.select("#addedLabels");
if (!group.size()) group = labels.append("g").attr("id", "addedLabels")
.attr("fill", "#3e3e4b").attr("opacity", 1).attr("stroke", "#3a3a3a")
.attr("stroke-width", 0).attr("font-family", "Almendra SC").attr("data-font", "Almendra+SC")
.attr("font-size", 18).attr("data-size", 18).attr("filter", null);
if (!group.size()) group = labels.append("g").attr("id", "addedLabels").attr("fill", "#3e3e4b").attr("opacity", 1).attr("stroke", "#3a3a3a").attr("stroke-width", 0).attr("font-family", "Almendra SC").attr("data-font", "Almendra+SC").attr("font-size", 18).attr("data-size", 18).attr("filter", null);
const example = group.append("text").attr("x", 0).attr("x", 0).text(name);
const width = example.node().getBBox().width;
@ -439,13 +485,22 @@ function addLabelOnClick() {
example.remove();
group.classed("hidden", false);
group.append("text").attr("id", id)
.append("textPath").attr("xlink:href", "#textPath_"+id).attr("startOffset", "50%").attr("font-size", "100%")
.append("tspan").attr("x", x).text(name);
group
.append("text")
.attr("id", id)
.append("textPath")
.attr("xlink:href", "#textPath_" + id)
.attr("startOffset", "50%")
.attr("font-size", "100%")
.append("tspan")
.attr("x", x)
.text(name);
defs.select("#textPaths")
.append("path").attr("id", "textPath_"+id)
.attr("d", `M${point[0]-width},${point[1]} h${width*2}`);
defs
.select("#textPaths")
.append("path")
.attr("id", "textPath_" + id)
.attr("d", `M${point[0] - width},${point[1]} h${width * 2}`);
if (d3.event.shiftKey === false) unpressClickToAddButton();
}
@ -466,7 +521,7 @@ function toggleAddRiver() {
}
addFeature.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed"));
addRiver.classList.add('pressed');
addRiver.classList.add("pressed");
document.getElementById("addNewRiver").classList.add("pressed");
closeDialogs(".stable");
viewbox.style("cursor", "crosshair").on("click", addRiverOnClick);
@ -486,22 +541,27 @@ function addRiverOnClick() {
// 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);
Rivers.resolveDepressions(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));
Rivers.resolveDepressions(h, 200);
while (i) {
cells.r[i] = river;
const x = cells.p[i][0], y = cells.p[i][1];
dataRiver.push({x, y, cell:i});
const x = cells.p[i][0],
y = cells.p[i][1];
dataRiver.push({x, y, cell: i});
const min = cells.c[i][d3.scan(cells.c[i], (a, b) => h[a] - h[b])]; // downhill cell
if (h[i] <= h[min]) {tip(`Cell ${i} is depressed, river cannot flow further`, false, "error"); return;}
const tx = cells.p[min][0], ty = cells.p[min][1];
if (h[i] <= h[min]) {
tip(`Cell ${i} is depressed, river cannot flow further`, false, "error");
return;
}
const tx = cells.p[min][0],
ty = cells.p[min][1];
if (h[min] < 20) {
// pour to water body
dataRiver.push({x: tx, y: ty, cell:i});
dataRiver.push({x: tx, y: ty, cell: i});
break;
}
@ -526,19 +586,22 @@ function addRiverOnClick() {
}
// extend old river
rivers.select("#river"+r).remove();
cells.i.filter(i => cells.r[i] === river).forEach(i => cells.r[i] = r);
riverCells.forEach(i => cells.r[i] = 0);
rivers.select("#river" + r).remove();
cells.i.filter(i => cells.r[i] === river).forEach(i => (cells.r[i] = r));
riverCells.forEach(i => (cells.r[i] = 0));
river = r;
cells.fl[min] = cells.fl[i] + grid.cells.prec[cells.g[min]];
i = min;
}
const points = Rivers.addMeandering(dataRiver, 1, .5);
const widthFactor = rn(.8 + Math.random() * .4, 1); // river width modifier [.8, 1.2]
const sourceWidth = .1;
const points = Rivers.addMeandering(dataRiver, 1, 0.5);
const widthFactor = rn(0.8 + Math.random() * 0.4, 1); // river width modifier [.8, 1.2]
const sourceWidth = 0.1;
const [path, length, offset] = Rivers.getPath(points, widthFactor, sourceWidth);
rivers.append("path").attr("d", path).attr("id", "river"+river);
rivers
.append("path")
.attr("d", path)
.attr("id", "river" + river);
// add new river to data or change extended river attributes
const r = pack.rivers.find(r => r.i === river);
@ -555,10 +618,10 @@ function addRiverOnClick() {
const source = dataRiver[0].cell;
const width = rn(offset ** 2, 2); // mounth width in km
const name = Rivers.getName(mouth);
const smallLength = pack.rivers.map(r => r.length||0).sort((a,b) => a-b)[Math.ceil(pack.rivers.length * .15)];
const type = length < smallLength ? rw({"Creek":9, "River":3, "Brook":3, "Stream":1}) : "River";
const smallLength = pack.rivers.map(r => r.length || 0).sort((a, b) => a - b)[Math.ceil(pack.rivers.length * 0.15)];
const type = length < smallLength ? rw({Creek: 9, River: 3, Brook: 3, Stream: 1}) : "River";
pack.rivers.push({i:river, source, mouth, discharge, length, width, widthFactor, sourceWidth, parent, basin, name, type});
pack.rivers.push({i: river, source, mouth, discharge, length, width, widthFactor, sourceWidth, parent, basin, name, type});
}
if (d3.event.shiftKey === false) {
@ -570,10 +633,13 @@ function addRiverOnClick() {
function toggleAddRoute() {
const pressed = document.getElementById("addRoute").classList.contains("pressed");
if (pressed) {unpressClickToAddButton(); return;}
if (pressed) {
unpressClickToAddButton();
return;
}
addFeature.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed"));
addRoute.classList.add('pressed');
addRoute.classList.add("pressed");
closeDialogs(".stable");
viewbox.style("cursor", "crosshair").on("click", addRouteOnClick);
tip("Click on map to add a first control point", true);
@ -590,10 +656,13 @@ function addRouteOnClick() {
function toggleAddMarker() {
const pressed = document.getElementById("addMarker").classList.contains("pressed");
if (pressed) {unpressClickToAddButton(); return;}
if (pressed) {
unpressClickToAddButton();
return;
}
addFeature.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed"));
addMarker.classList.add('pressed');
addMarker.classList.add("pressed");
closeDialogs(".stable");
viewbox.style("cursor", "crosshair").on("click", addMarkerOnClick);
tip("Click on map to add a marker. Hold Shift to add multiple", true);
@ -602,27 +671,44 @@ function toggleAddMarker() {
function addMarkerOnClick() {
const point = d3.mouse(this);
const x = rn(point[0], 2), y = rn(point[1], 2);
const x = rn(point[0], 2),
y = rn(point[1], 2);
const id = getNextId("markerElement");
const selected = markerSelectGroup.value;
const valid = selected && d3.select("#defs-markers").select("#"+selected).size();
const symbol = valid ? "#"+selected : "#marker0";
const valid =
selected &&
d3
.select("#defs-markers")
.select("#" + selected)
.size();
const symbol = valid ? "#" + selected : "#marker0";
const added = markers.select("[data-id='" + symbol + "']").size();
let desired = valid && added ? markers.select("[data-id='" + symbol + "']").attr("data-size") : 1;
if (isNaN(desired)) desired = 1;
const size = desired * 5 + 25 / scale;
markers.append("use").attr("id", id).attr("xlink:href", symbol).attr("data-id", symbol)
.attr("data-x", x).attr("data-y", y).attr("x", x - size / 2).attr("y", y - size)
.attr("data-size", desired).attr("width", size).attr("height", size);
markers
.append("use")
.attr("id", id)
.attr("xlink:href", symbol)
.attr("data-id", symbol)
.attr("data-x", x)
.attr("data-y", y)
.attr("x", x - size / 2)
.attr("y", y - size)
.attr("data-size", desired)
.attr("width", size)
.attr("height", size);
if (d3.event.shiftKey === false) unpressClickToAddButton();
}
function viewCellDetails() {
$("#cellInfo").dialog({
resizable: false, width: "22em", title: "Cell Details",
resizable: false,
width: "22em",
title: "Cell Details",
position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"}
});
}