This commit is contained in:
Azgaar 2022-04-15 14:47:56 +05:00
parent 5703e62177
commit ae0979fc68
3 changed files with 6211 additions and 4539 deletions

3222
index.html

File diff suppressed because one or more lines are too long

View file

@ -5,10 +5,11 @@ main function: resample(options);
*/ */
window.Submap = (function () { window.Submap = (function () {
const isWater = (map, id) => map.grid.cells.h[map.pack.cells.g[id]] < 20? true: false; const isWater = (map, id) => (map.grid.cells.h[map.pack.cells.g[id]] < 20 ? true : false);
const inMap = (x, y) => x > 0 && x < graphWidth && y > 0 && y < graphHeight; const inMap = (x, y) => x > 0 && x < graphWidth && y > 0 && y < graphHeight;
function resample(parentMap, options) { /* function resample(parentMap, options) {
/*
generate new map based on an existing one (resampling parentMap) generate new map based on an existing one (resampling parentMap)
parentMap: {seed, grid, pack} from original map parentMap: {seed, grid, pack} from original map
options = { options = {
@ -27,9 +28,9 @@ window.Submap = (function () {
const projection = options.projection; const projection = options.projection;
const inverse = options.inverse; const inverse = options.inverse;
const stage = s => INFO && console.log('SUBMAP:', s); const stage = s => INFO && console.log("SUBMAP:", s);
const timeStart = performance.now(); const timeStart = performance.now();
const childMap = { grid, pack } const childMap = {grid, pack};
invokeActiveZooming(); invokeActiveZooming();
// copy seed // copy seed
@ -50,9 +51,9 @@ window.Submap = (function () {
const oldid = qtree.find(tx, ty, Infinity)[2]; const oldid = qtree.find(tx, ty, Infinity)[2];
f(i, oldid); f(i, oldid);
} }
} };
stage("Resampling heightmap, temperature and precipitation.") stage("Resampling heightmap, temperature and precipitation.");
// resample heightmap from old WorldState // resample heightmap from old WorldState
const n = grid.points.length; const n = grid.points.length;
grid.cells.h = new Uint8Array(n); // heightmap grid.cells.h = new Uint8Array(n); // heightmap
@ -70,7 +71,7 @@ window.Submap = (function () {
grid.cells.prec[id] = oldGrid.cells.prec[cid]; grid.cells.prec[id] = oldGrid.cells.prec[cid];
if (options.depressRivers) forwardGridMap[cid].push(id); if (options.depressRivers) forwardGridMap[cid].push(id);
reverseGridMap[id] = cid; reverseGridMap[id] = cid;
}) });
// TODO: add smooth/noise function for h, temp, prec n times // TODO: add smooth/noise function for h, temp, prec n times
// smooth heightmap // smooth heightmap
@ -79,16 +80,14 @@ window.Submap = (function () {
if (options.smoothHeightMap) { if (options.smoothHeightMap) {
const gcells = grid.cells; const gcells = grid.cells;
gcells.h.forEach((h, i) => { gcells.h.forEach((h, i) => {
const hs = gcells.c[i].map(c=>gcells.h[c]) const hs = gcells.c[i].map(c => gcells.h[c]);
hs.push(h) hs.push(h);
gcells.h[i] = h>=20 gcells.h[i] = h >= 20 ? Math.max(d3.mean(hs), 20) : Math.min(d3.mean(hs), 19);
? Math.max(d3.mean(hs),20)
: Math.min(d3.mean(hs),19);
}); });
} }
if (options.depressRivers) { if (options.depressRivers) {
stage("Generating riverbeds.") stage("Generating riverbeds.");
const rbeds = new Uint16Array(grid.cells.i.length); const rbeds = new Uint16Array(grid.cells.i.length);
// and erode riverbeds // and erode riverbeds
@ -97,8 +96,7 @@ window.Submap = (function () {
if (oldpc < 0) return; // ignore out-of-map marker (-1) if (oldpc < 0) return; // ignore out-of-map marker (-1)
const oldc = parentMap.pack.cells.g[oldpc]; const oldc = parentMap.pack.cells.g[oldpc];
const targetCells = forwardGridMap[oldc]; const targetCells = forwardGridMap[oldc];
if (!targetCells) if (!targetCells) throw "TargetCell shouldn't be empty.";
throw "TargetCell shouldn't be empty.";
targetCells.forEach(c => { targetCells.forEach(c => {
if (grid.cells.h[c] < 20) return; if (grid.cells.h[c] < 20) return;
rbeds[c] = 1; rbeds[c] = 1;
@ -112,7 +110,7 @@ window.Submap = (function () {
}); });
} }
stage("Detect features, ocean and generating lakes.") stage("Detect features, ocean and generating lakes.");
markFeatures(); markFeatures();
markupGridOcean(); markupGridOcean();
@ -127,11 +125,11 @@ window.Submap = (function () {
calculateMapCoordinates(); calculateMapCoordinates();
// calculateTemperatures(); // calculateTemperatures();
// generatePrecipitation(); // generatePrecipitation();
stage("Cell cleanup.") stage("Cell cleanup.");
reGraph(); reGraph();
// remove misclassified cells // remove misclassified cells
stage("Define coastline.") stage("Define coastline.");
drawCoastline(); drawCoastline();
/****************************************************/ /****************************************************/
@ -151,11 +149,11 @@ window.Submap = (function () {
cells.crossroad = new Uint16Array(pn); cells.crossroad = new Uint16Array(pn);
cells.province = new Uint16Array(pn); cells.province = new Uint16Array(pn);
stage("Resampling culture, state and religion map.") stage("Resampling culture, state and religion map.");
for (const [id, gridCellId] of cells.g.entries()) { for (const [id, gridCellId] of cells.g.entries()) {
const oldGridId = reverseGridMap[gridCellId]; const oldGridId = reverseGridMap[gridCellId];
if (oldGridId === undefined) { if (oldGridId === undefined) {
console.error('Can not find old cell id', reverseGridMap, 'in', gridCellId); console.error("Can not find old cell id", reverseGridMap, "in", gridCellId);
continue; continue;
} }
// find old parent's children // find old parent's children
@ -192,7 +190,7 @@ window.Submap = (function () {
console.error("Distance is not a number!", "Old point:", oldpx, oldpy); console.error("Distance is not a number!", "Old point:", oldpx, oldpy);
} }
if (nd < d) [d, oldid] = [nd, oid]; if (nd < d) [d, oldid] = [nd, oid];
}) });
if (oldid === undefined) { if (oldid === undefined) {
console.warn("Warning, no match for", id, "(parent:", gridCellId, ")"); console.warn("Warning, no match for", id, "(parent:", gridCellId, ")");
continue; continue;
@ -200,7 +198,7 @@ window.Submap = (function () {
} }
if (isWater(childMap, id) !== isWater(parentMap, oldid)) { if (isWater(childMap, id) !== isWater(parentMap, oldid)) {
WARN && console.warn('Type discrepancy detected:', id, oldid, `${pack.cells.t[id]} != ${oldCells.t[oldid]}`); WARN && console.warn("Type discrepancy detected:", id, oldid, `${pack.cells.t[id]} != ${oldCells.t[oldid]}`);
} }
cells.culture[id] = oldCells.culture[oldid]; cells.culture[id] = oldCells.culture[oldid];
@ -208,10 +206,10 @@ window.Submap = (function () {
cells.religion[id] = oldCells.religion[oldid]; cells.religion[id] = oldCells.religion[oldid];
cells.province[id] = oldCells.province[oldid]; cells.province[id] = oldCells.province[oldid];
// reverseMap.set(id, oldid) // reverseMap.set(id, oldid)
forwardMap[oldid].push(id) forwardMap[oldid].push(id);
} }
stage("Regenerating river network.") stage("Regenerating river network.");
Rivers.generate(); Rivers.generate();
drawRivers(); drawRivers();
Lakes.defineGroup(); Lakes.defineGroup();
@ -229,16 +227,14 @@ window.Submap = (function () {
// fix culture centers // fix culture centers
const validCultures = new Set(pack.cells.culture); const validCultures = new Set(pack.cells.culture);
pack.cultures.forEach((c, i) => { pack.cultures.forEach((c, i) => {
if (!i) return // ignore wildlands if (!i) return; // ignore wildlands
if (!validCultures.has(i)) { if (!validCultures.has(i)) {
c.removed = true; c.removed = true;
c.center = null; c.center = null;
return return;
} }
const newCenters = forwardMap[c.center] const newCenters = forwardMap[c.center];
c.center = newCenters.length c.center = newCenters.length ? newCenters[0] : pack.cells.culture.findIndex(x => x === i);
? newCenters[0]
: pack.cells.culture.findIndex(x => x===i);
}); });
stage("Porting and locking burgs."); stage("Porting and locking burgs.");
@ -269,12 +265,10 @@ window.Submap = (function () {
if (!p || p.removed) return; if (!p || p.removed) return;
if (!validProvinces.has(i)) { if (!validProvinces.has(i)) {
p.removed = true; p.removed = true;
return return;
} }
const newCenters = forwardMap[p.center] const newCenters = forwardMap[p.center];
p.center = newCenters.length p.center = newCenters.length ? newCenters[0] : pack.cells.province.findIndex(x => x === i);
? newCenters[0]
: pack.cells.province.findIndex(x => x===i);
}); });
BurgsAndStates.drawBurgs(); BurgsAndStates.drawBurgs();
@ -296,7 +290,7 @@ window.Submap = (function () {
[m.x, m.y] = projection(m.x, m.y); [m.x, m.y] = projection(m.x, m.y);
[m.bx, m.by] = projection(m.bx, m.by); [m.bx, m.by] = projection(m.bx, m.by);
const cc = forwardMap[m.cell]; const cc = forwardMap[m.cell];
m.cell = (cc && cc.length)? cc[0]: null; m.cell = cc && cc.length ? cc[0] : null;
} }
s.military = s.military.filter(m => m.cell).map((m, i) => ({...m, i})); s.military = s.military.filter(m => m.cell).map((m, i) => ({...m, i}));
} }
@ -331,34 +325,38 @@ window.Submap = (function () {
* returns [cellid, neighbor] tuple or undefined if no such cell. * returns [cellid, neighbor] tuple or undefined if no such cell.
* accepts coordinates (x, y) * accepts coordinates (x, y)
*/ */
const findNearest = (f, g, max=3) => (px,py) => { const findNearest =
const d2 = c => (px-pack.cells.p[c][0])**2 + (py-pack.cells.p[c][0])**2 (f, g, max = 3) =>
(px, py) => {
const d2 = c => (px - pack.cells.p[c][0]) ** 2 + (py - pack.cells.p[c][0]) ** 2;
const startCell = findCell(px, py); const startCell = findCell(px, py);
const tested = new Set([startCell]); // ignore analyzed cells const tested = new Set([startCell]); // ignore analyzed cells
const kernel = (cs, level) => { const kernel = (cs, level) => {
const [bestf, bestg] = cs.filter(f).reduce(([cf, cg], c) => { const [bestf, bestg] = cs.filter(f).reduce(
([cf, cg], c) => {
const neighbors = pack.cells.c[c]; const neighbors = pack.cells.c[c];
const betterg = neighbors.filter(g).reduce((u, x) => d2(x)<d2(u)? x:u); const betterg = neighbors.filter(g).reduce((u, x) => (d2(x) < d2(u) ? x : u));
if (cf === undefined) return [c, betterg]; if (cf === undefined) return [c, betterg];
return (betterg && d2(cf) < d2(c))? [c, betterg]: [cf, cg]; return betterg && d2(cf) < d2(c) ? [c, betterg] : [cf, cg];
}, [undefined, undefined]); },
[undefined, undefined]
);
if (bestf && bestg) return [bestf, bestg]; if (bestf && bestg) return [bestf, bestg];
// no suitable pair found, retry with next ring // no suitable pair found, retry with next ring
const targets = new Set(cs.map(c => pack.cells.c[c]).flat()) const targets = new Set(cs.map(c => pack.cells.c[c]).flat());
const ring = Array.from(targets).filter(nc => !tested.has(nc)); const ring = Array.from(targets).filter(nc => !tested.has(nc));
if (level >= max || !ring.length) if (level >= max || !ring.length) return [undefined, undefined];
return [undefined, undefined];
ring.forEach(c => tested.add(c)); ring.forEach(c => tested.add(c));
return kernel(ring, level + 1); return kernel(ring, level + 1);
} };
const pair = kernel([startCell], 1); const pair = kernel([startCell], 1);
return pair; return pair;
} };
function copyBurgs(parentMap, projection, options) { function copyBurgs(parentMap, projection, options) {
const cells = pack.cells; const cells = pack.cells;
const childMap = { grid, pack } const childMap = {grid, pack};
pack.burgs = parentMap.pack.burgs; pack.burgs = parentMap.pack.burgs;
// remap burgs to the best new cell // remap burgs to the best new cell
@ -379,10 +377,12 @@ window.Submap = (function () {
const nearCoast = c => cells.t[c] === -1; const nearCoast = c => cells.t[c] === -1;
// check if we need to relocate the burg // check if we need to relocate the burg
if (cells.burg[cityCell]) // already occupied if (cells.burg[cityCell])
// already occupied
searchFunc = findNearest(isFreeLand, _ => true, 3); searchFunc = findNearest(isFreeLand, _ => true, 3);
if (isWater(childMap, cityCell) || b.port) // burg is in water or port if (isWater(childMap, cityCell) || b.port)
// burg is in water or port
searchFunc = findNearest(isFreeLand, nearCoast, 6); searchFunc = findNearest(isFreeLand, nearCoast, 6);
if (searchFunc) { if (searchFunc) {
@ -397,7 +397,7 @@ window.Submap = (function () {
[b.x, b.y] = b.port ? getMiddlePoint(newCell, neighbor) : cells.p[newCell]; [b.x, b.y] = b.port ? getMiddlePoint(newCell, neighbor) : cells.p[newCell];
if (b.port) b.port = cells.f[neighbor]; // copy feature number if (b.port) b.port = cells.f[neighbor]; // copy feature number
b.cell = newCell; b.cell = newCell;
if (b.port && !isWater(childMap, neighbor)) console.error('betrayal! negihbor must be water!', b); if (b.port && !isWater(childMap, neighbor)) console.error("betrayal! negihbor must be water!", b);
} else { } else {
b.cell = cityCell; b.cell = cityCell;
} }
@ -407,5 +407,5 @@ window.Submap = (function () {
} }
// export // export
return { resample, findNearest } return {resample, findNearest};
})(); })();

View file

@ -15,7 +15,9 @@ function openSubmapOptions() {
$(this).dialog("close"); $(this).dialog("close");
generateSubmap(); generateSubmap();
}, },
Cancel: function () { $(this).dialog("close"); }, Cancel: function () {
$(this).dialog("close");
}
} }
}); });
} }
@ -29,18 +31,20 @@ function openRemapOptions() {
position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"}, position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"},
buttons: { buttons: {
Resample: function () { Resample: function () {
const cellNumId = Number(document.getElementById('submapPointsInput').value); const cellNumId = Number(document.getElementById("submapPointsInput").value);
const cells = cellsDensityConstants[cellNumId]; const cells = cellsDensityConstants[cellNumId];
$(this).dialog("close"); $(this).dialog("close");
if (!cells) { if (!cells) {
console.error('Unknown cell number!'); console.error("Unknown cell number!");
return; return;
} }
changeCellsDensity(cellNumId); changeCellsDensity(cellNumId);
resampleCurrentMap(); resampleCurrentMap();
}, },
Cancel: function () { $(this).dialog("close"); }, Cancel: function () {
}, $(this).dialog("close");
}
}
}); });
} }
@ -57,20 +61,19 @@ const resampleCurrentMap = debounce(function () {
promoteTowns: false, promoteTowns: false,
smoothHeightMap: false, smoothHeightMap: false,
projection: (x, y) => [x, y], projection: (x, y) => [x, y],
inverse: (x,y) => [x, y], inverse: (x, y) => [x, y]
} };
startResample(options); startResample(options);
}, 1000); }, 1000);
const generateSubmap = debounce(function () { const generateSubmap = debounce(function () {
// Create submap from the current map // Create submap from the current map
// submap limits defined by the current window size (canvas viewport) // submap limits defined by the current window size (canvas viewport)
WARN && console.warn("Resampling current map"); WARN && console.warn("Resampling current map");
closeDialogs("#worldConfigurator, #options3d"); closeDialogs("#worldConfigurator, #options3d");
const checked = id => Boolean(document.getElementById(id).checked) const checked = id => Boolean(document.getElementById(id).checked);
// Create projection func from current zoom extents // Create projection func from current zoom extents
const [[x0, y0], [x1, y1]] = getViewBoxExtent(); const [[x0, y0], [x1, y1]] = getViewBoxExtent();
@ -82,28 +85,27 @@ const generateSubmap = debounce(function () {
addLakesInDepressions: checked("submapAddLakeInDepression"), addLakesInDepressions: checked("submapAddLakeInDepression"),
promoteTowns: checked("submapPromoteTowns"), promoteTowns: checked("submapPromoteTowns"),
smoothHeightMap: scale > 2, smoothHeightMap: scale > 2,
inverse: (x,y) => [x * (x1-x0) / graphWidth + x0, y * (y1-y0) / graphHeight + y0], inverse: (x, y) => [(x * (x1 - x0)) / graphWidth + x0, (y * (y1 - y0)) / graphHeight + y0],
projection: (x, y) => [(x-x0) * graphWidth / (x1-x0), (y-y0) * graphHeight / (y1-y0)], projection: (x, y) => [((x - x0) * graphWidth) / (x1 - x0), ((y - y0) * graphHeight) / (y1 - y0)]
} };
// converting map position on the planet // converting map position on the planet
const mapSizeOutput = document.getElementById("mapSizeOutput"); const mapSizeOutput = document.getElementById("mapSizeOutput");
const latitudeOutput = document.getElementById("latitudeOutput"); const latitudeOutput = document.getElementById("latitudeOutput");
const latN = 90 - (180 - mapSizeInput.value / 100 * 180) * latitudeOutput.value / 100; const latN = 90 - ((180 - (mapSizeInput.value / 100) * 180) * latitudeOutput.value) / 100;
const newLatN = latN - y0 / graphHeight * mapSizeOutput.value * 180 / 100; const newLatN = latN - ((y0 / graphHeight) * mapSizeOutput.value * 180) / 100;
mapSizeOutput.value /= scale; mapSizeOutput.value /= scale;
latitudeOutput.value = (90 - newLatN) / (180 - mapSizeOutput.value / 100 * 180) * 100; latitudeOutput.value = ((90 - newLatN) / (180 - (mapSizeOutput.value / 100) * 180)) * 100;
document.getElementById("mapSizeInput").value = mapSizeOutput.value; document.getElementById("mapSizeInput").value = mapSizeOutput.value;
document.getElementById("latitudeInput").value = latitudeOutput.value; document.getElementById("latitudeInput").value = latitudeOutput.value;
// fix scale // fix scale
distanceScaleInput.value = distanceScaleOutput.value = rn(distanceScale = distanceScaleOutput.value / scale, 2); distanceScaleInput.value = distanceScaleOutput.value = rn((distanceScale = distanceScaleOutput.value / scale), 2);
populationRateInput.value = populationRateOutput.value = rn(populationRate = populationRateOutput.value / scale, 2); populationRateInput.value = populationRateOutput.value = rn((populationRate = populationRateOutput.value / scale), 2);
customization = 0; customization = 0;
startResample(options); startResample(options);
}, 1000); }, 1000);
async function startResample(options) { async function startResample(options) {
undraw(); undraw();
resetZoom(0); resetZoom(0);
@ -112,15 +114,15 @@ async function startResample(options) {
pack: deepCopy(pack), pack: deepCopy(pack),
seed, seed,
graphWidth, graphWidth,
graphHeight, graphHeight
}; };
try { try {
const oldScale = scale; const oldScale = scale;
await Submap.resample(oldstate, options); await Submap.resample(oldstate, options);
if (options.promoteTowns) { if (options.promoteTowns) {
const groupName = 'largetowns'; const groupName = "largetowns";
moveAllBurgsToGroup('towns', groupName); moveAllBurgsToGroup("towns", groupName);
changeRadius(rn(oldScale * 0.8, 2), groupName); changeRadius(rn(oldScale * 0.8, 2), groupName);
changeFontSize(svg.select(`#labels #${groupName}`), rn(oldScale * 2, 2)); changeFontSize(svg.select(`#labels #${groupName}`), rn(oldScale * 2, 2));
invokeActiveZooming(); invokeActiveZooming();
@ -132,7 +134,7 @@ async function startResample(options) {
oldstate = null; // destroy old state to free memory oldstate = null; // destroy old state to free memory
restoreLayers(); restoreLayers();
turnButtonOn('toggleMarkers'); turnButtonOn("toggleMarkers");
if (ThreeD.options.isOn) ThreeD.redraw(); if (ThreeD.options.isOn) ThreeD.redraw();
if ($("#worldConfigurator").is(":visible")) editWorld(); if ($("#worldConfigurator").is(":visible")) editWorld();
} }
@ -149,7 +151,9 @@ function showSubmapErrorHandler(error) {
title: "Generation error", title: "Generation error",
width: "32em", width: "32em",
buttons: { buttons: {
Ok: function () { $(this).dialog("close"); } Ok: function () {
$(this).dialog("close");
}
}, },
position: {my: "center", at: "center", of: "svg"} position: {my: "center", at: "center", of: "svg"}
}); });