aframe-babia-components 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/common/city-history.js +53 -0
  2. package/components/visualizers/babia-boats.js +229 -2060
  3. package/components/visualizers/babia-city-evocells.js +189 -0
  4. package/components/visualizers/babia-city-evostreets.js +163 -0
  5. package/components/visualizers/babia-city-gospermap.js +190 -0
  6. package/components/visualizers/babia-city-hexgrid.js +6 -0
  7. package/components/visualizers/babia-city-hilbert.js +5 -0
  8. package/components/visualizers/babia-city-history-resistant.js +5 -0
  9. package/components/visualizers/babia-city-morton.js +5 -0
  10. package/components/visualizers/babia-city-voronoi.js +3 -211
  11. package/components/visualizers/boats/interactions.js +194 -0
  12. package/components/visualizers/boats/layout.js +148 -0
  13. package/components/visualizers/boats/legend.js +135 -0
  14. package/components/visualizers/evocells/history.js +69 -0
  15. package/components/visualizers/evocells/layout.js +170 -0
  16. package/components/visualizers/evocells/rectangles.js +183 -0
  17. package/components/visualizers/evostreets/layout.js +171 -0
  18. package/components/visualizers/gospermap/curve.js +91 -0
  19. package/components/visualizers/gospermap/layout.js +221 -0
  20. package/components/visualizers/gospermap/prisms.js +152 -0
  21. package/components/visualizers/gospermap/regions.js +99 -0
  22. package/components/visualizers/gospermap/selection.js +65 -0
  23. package/components/visualizers/hexgrid/grid.js +70 -0
  24. package/components/visualizers/hexgrid/layout.js +90 -0
  25. package/components/visualizers/hexgrid/prisms.js +71 -0
  26. package/components/visualizers/hilbert/layout.js +131 -0
  27. package/components/visualizers/history-resistant/layout.js +128 -0
  28. package/components/visualizers/morton/layout.js +79 -0
  29. package/components/visualizers/peak-lot-plan.js +72 -0
  30. package/components/visualizers/prism-city.js +226 -0
  31. package/components/visualizers/voronoi/history.js +35 -0
  32. package/components/visualizers/voronoi/hover-legend.js +6 -1
  33. package/components/visualizers/voronoi/layout.js +58 -23
  34. package/dist/aframe-babia-components.js +5872 -3118
  35. package/dist/aframe-babia-components.min.js +1 -1
  36. package/dist/aframe-babia-components.min.js.map +1 -1
  37. package/index.js +7 -0
  38. package/package.json +1 -1
@@ -0,0 +1,79 @@
1
+ const {PeakLotPlan} = require('../peak-lot-plan');
2
+
3
+ // Local Morton codes interleave the X and Z coordinate bits:
4
+ // code = ... z1 x1 z0 x0. Reading a prefix fixes a region of the map.
5
+ // Fold codes from the least significant bit up: first join X neighbours,
6
+ // then Z neighbours, then X again. Unlike Hilbert, no quadrant rotates.
7
+ function prefixTree(nodes, codeOf) {
8
+ let level = new Map(nodes.map(node => [codeOf(node), node]));
9
+ for (let alongX = true; level.size > 1; alongX = !alongX) {
10
+ const parents = new Map();
11
+ for (const code of level.keys()) {
12
+ const prefix = Math.floor(code / 2);
13
+ if (parents.has(prefix)) continue;
14
+ const low = level.get(2 * prefix), high = level.get(2 * prefix + 1);
15
+ // In reflow a whole prefix may be vacant. Give its space to the
16
+ // occupied half without renumbering that half's surviving codes.
17
+ parents.set(prefix, low && high ? {low, high, alongX, mass: low.mass + high.mass} : low || high);
18
+ }
19
+ level = parents;
20
+ }
21
+ return level.values().next().value;
22
+ }
23
+
24
+ function cappedInset(x0, z0, x1, z1, distance) {
25
+ return Math.min(Math.max(0, distance), (x1 - x0) / 6, (z1 - z0) / 6);
26
+ }
27
+
28
+ // A regular 4^k group of equal weights produces the literal 2^k × 2^k
29
+ // Morton grid. For other weights keep the same prefix cuts, but move each
30
+ // cut in proportion to mass so that areas still encode the mapped metric.
31
+ function partitionLots(roots, options, codeOf) {
32
+ const lots = new Map(), anchors = new Map();
33
+ function placeGroup(nodes, x0, z0, x1, z1) {
34
+ const tree = prefixTree(nodes, codeOf), w = x1 - x0, h = z1 - z0;
35
+ // A directory is a new local grid. If its first cut would subdivide
36
+ // an already narrow side, transpose that whole grid once. This keeps
37
+ // nested two-child packages from degenerating into parallel slivers.
38
+ const transpose = tree.alongX ? h > 2 * w : w > 2 * h;
39
+ place(tree, x0, z0, x1, z1, transpose);
40
+ }
41
+ function place(node, x0, z0, x1, z1, transpose) {
42
+ if (node.low) {
43
+ const share = node.low.mass / node.mass;
44
+ if (node.alongX !== transpose) {
45
+ const x = x0 + (x1 - x0) * share;
46
+ place(node.low, x0, z0, x, z1, transpose);
47
+ place(node.high, x, z0, x1, z1, transpose);
48
+ } else {
49
+ const z = z0 + (z1 - z0) * share;
50
+ place(node.low, x0, z0, x1, z, transpose);
51
+ place(node.high, x0, z, x1, z1, transpose);
52
+ }
53
+ return;
54
+ }
55
+ const gap = cappedInset(x0, z0, x1, z1, options.separation / 2);
56
+ x0 += gap; z0 += gap; x1 -= gap; z1 -= gap;
57
+ // CityPrisms uses {x,y} for vertices in the X/Z ground plane.
58
+ const polygon = [{x: x0, y: z0}, {x: x1, y: z0}, {x: x1, y: z1}, {x: x0, y: z1}];
59
+ lots.set(node.key, {polygon, mass: node.mass});
60
+ anchors.set(node.key, codeOf(node));
61
+ if (node.children?.length) {
62
+ const pad = cappedInset(x0, z0, x1, z1, options.border);
63
+ placeGroup(node.children, x0 + pad, z0 + pad, x1 - pad, z1 - pad);
64
+ }
65
+ }
66
+ const r = (options.size > 0 ? options.size : 8) / 2;
67
+ if (roots.length) placeGroup(roots, -r, -r, r, r);
68
+ return {lots, anchors};
69
+ }
70
+
71
+ class MortonPlan extends PeakLotPlan {
72
+ constructor(options) {
73
+ // Use the first-seen sibling ordinal in BOTH modes. A reflow changes
74
+ // the cut widths, not the surviving buildings' logical coordinates.
75
+ super(options, (roots, d) => partitionLots(roots, d, node => this.slots.get(node.key).order));
76
+ }
77
+ }
78
+
79
+ module.exports = {MortonPlan};
@@ -0,0 +1,72 @@
1
+ const {snapshot, occupy} = require('./voronoi/layout');
2
+
3
+ // Reserve a partition of peak leaf masses, not a mesh or a copy of the data
4
+ // for each date. Only arrivals and new peaks invalidate this partition.
5
+ class PeakLotPlan {
6
+ constructor(options, partition, compare) {
7
+ this.options = {time_evolution_reserve_space: true, ...options};
8
+ this.partition = partition;
9
+ this.roots = [];
10
+ this.slots = new Map();
11
+ // Ordered treemaps start in input order. Surviving/returning siblings
12
+ // keep their rank; newly seen siblings append in their input order.
13
+ const rank = node => this.slots.get(node.key)?.order ?? Number.MAX_SAFE_INTEGER;
14
+ this.compare = compare || ((a, b) => rank(a) - rank(b));
15
+ }
16
+
17
+ observe(records) {
18
+ const live = snapshot(records, this.options, this.compare);
19
+ const merge = (nodes, siblings) => {
20
+ for (const {key, children, mass} of nodes) {
21
+ let slot = this.slots.get(key);
22
+ if (!slot) {
23
+ slot = {key, children: children ? [] : null, mass: 0, order: siblings.length};
24
+ this.slots.set(key, slot);
25
+ siblings.push(slot);
26
+ this.dirty = true;
27
+ }
28
+ if (children) merge(children, slot.children);
29
+ else if (mass > slot.mass) {
30
+ slot.mass = mass;
31
+ this.dirty = true;
32
+ }
33
+ }
34
+ };
35
+ merge(live.roots, this.roots);
36
+ return live;
37
+ }
38
+
39
+ invalidateGeometry() {
40
+ this.dirty = true;
41
+ }
42
+
43
+ reservedLots() {
44
+ if (!this.atlas || this.dirty) {
45
+ const weigh = siblings => {
46
+ siblings.sort(this.compare);
47
+ let total = 0;
48
+ for (const slot of siblings) {
49
+ if (slot.children) slot.mass = weigh(slot.children) || 0.5;
50
+ total += slot.mass;
51
+ }
52
+ return total;
53
+ };
54
+ weigh(this.roots);
55
+ this.atlas = this.partition(this.roots, this.options, this.atlas?.anchors);
56
+ this.dirty = false;
57
+ }
58
+ return this.atlas;
59
+ }
60
+
61
+ reflow(roots) {
62
+ return this.partition(roots, this.options);
63
+ }
64
+
65
+ frame(records, revision = this.clock?.selectedIndex) {
66
+ const live = this.observe(records);
67
+ const plan = this.options.time_evolution_reserve_space ? this.reservedLots() : this.reflow(live.roots, revision);
68
+ return occupy(live, plan, this.options);
69
+ }
70
+ }
71
+
72
+ module.exports = {PeakLotPlan};
@@ -0,0 +1,226 @@
1
+ /* global AFRAME */
2
+ const {colors, findProdComponent, parseJson} = require('../others/common');
3
+ const {NotiBuffer} = require('../../common/noti-buffer');
4
+ const {number} = require('./voronoi/layout');
5
+ const {planFor} = require('../../common/city-history');
6
+ const {CityPrisms} = require('./voronoi/prisms');
7
+ const {CellLabel} = require('./voronoi/hover-legend');
8
+ const {QuarterSelection} = require('./voronoi/quarter-selection');
9
+ const THREE = AFRAME.THREE;
10
+ const controls = new Set(['legend', 'animation', 'animationDuration', 'from', 'data']);
11
+
12
+ function setColor(color, cell, range, options) {
13
+ const value = cell.data[options.color];
14
+ if (cell.quarter) return color.set(options.base_color);
15
+ if (!options.color || value == null || value === '') return color.set(options.building_color);
16
+ const n = number(value);
17
+ if (Number.isFinite(n)) {
18
+ const t = range.colorMax > range.colorMin ? (n - range.colorMin) / (range.colorMax - range.colorMin) : 0.5;
19
+ return color.setHSL((1 - t) * 0.62, 0.72, 0.48);
20
+ }
21
+ // Category colours must not depend on the order or presence of other keys.
22
+ let hash = 0;
23
+ for (const c of String(value)) hash = (31 * hash + c.charCodeAt(0)) >>> 0;
24
+ return color.set(colors.get(hash, 'categoric'));
25
+ }
26
+
27
+ // Each registration gets its own schema and ground plan; selection, clocks
28
+ // and subscriptions are shared even for districts made of multiple tiles.
29
+ module.exports = (Plan, selectEvent, Prisms = CityPrisms) => ({
30
+ schema: {
31
+ data: {type: 'asset'},
32
+ from: {type: 'string'},
33
+ field: {type: 'string', default: 'uid'},
34
+ width: {type: 'string', default: 'width'},
35
+ depth: {type: 'string', default: 'depth'},
36
+ area: {type: 'string'},
37
+ height: {type: 'string', default: 'height'},
38
+ color: {type: 'string'},
39
+ minBuildingHeight: {type: 'number', default: 0.03},
40
+ maxBuildingHeight: {type: 'number', default: 2},
41
+ diffBuildingHeight: {type: 'boolean', default: false},
42
+ size: {type: 'number', default: 8},
43
+ separation: {type: 'number', default: 0.08},
44
+ border: {type: 'number', default: 0.12},
45
+ zone_elevation: {type: 'number', default: 0.08},
46
+ base_color: {type: 'color', default: '#98e690'},
47
+ quarterHighlightColor: {type: 'color', default: '#2867CC'},
48
+ building_color: {type: 'color', default: '#E6B9A1'},
49
+ legend: {type: 'boolean', default: true},
50
+ time_evolution_reserve_space: {type: 'boolean', default: true},
51
+ animation: {type: 'boolean', default: true},
52
+ animationDuration: {type: 'number', default: 500}
53
+ },
54
+
55
+ init: function () {
56
+ this.notiBuffer = new NotiBuffer();
57
+ this.anchors = new Map();
58
+ this.prisms = new Prisms(THREE, this.el);
59
+ this.group = this.prisms.group;
60
+ this.meshes = this.prisms.meshes;
61
+ this.el.setObject3D(this.attrName, this.group);
62
+ this.selection = new QuarterSelection(THREE, this.el.sceneEl.object3D);
63
+ this.cursors = new Set();
64
+ this.onDisconnect = event => this.forgetCursor(event.currentTarget);
65
+ this.onCanvasMove = () => { this.mouseOverCanvas = true; };
66
+ this.onCanvasLeave = () => {
67
+ this.mouseOverCanvas = false;
68
+ this.updateHover();
69
+ };
70
+ },
71
+
72
+ update: function (oldData) {
73
+ const {data, from} = this.data;
74
+ if (['field', 'area', 'width', 'depth'].some(k => this.data[k] !== oldData[k])) this.plan = null;
75
+ else if (this.plan && ['size', 'border', 'separation'].some(k => this.data[k] !== oldData[k])) {
76
+ this.plan.invalidateGeometry?.();
77
+ }
78
+ if (data !== oldData.data || (!data && from !== oldData.from)) {
79
+ this.unsubscribe();
80
+ // Successive inline snapshots are one stream, but a new source must
81
+ // never inherit another project's lots, anchors or selection.
82
+ if (!data || !oldData.data) {
83
+ this.plan = null;
84
+ this.selection.set(null, this.prisms, this.data);
85
+ }
86
+ if (data) return this.processData(parseJson(data));
87
+ // Same producers and ID convention as boats; a file URL belongs on queryjson.
88
+ const prod = (!from || document.getElementById(from)) && findProdComponent(this.data, this.el);
89
+ if (prod && prod.notiBuffer) {
90
+ this.prodComponent = prod;
91
+ if (prod.notiBuffer.data === undefined) this.processData([]);
92
+ this.subscription = prod.notiBuffer.register(snapshot => this.processData(snapshot));
93
+ } else {
94
+ console.warn(this.attrName + ': no producer found', from || this.el);
95
+ this.processData([]);
96
+ }
97
+ return;
98
+ }
99
+ if (!this.data.animation || !(this.data.animationDuration > 0)) this.prisms.finish();
100
+ if (!this.data.legend) this.hideLegend();
101
+ // A tooltip or playback toggle should not solve hundreds of cells again.
102
+ const redraw = Object.keys(this.data).some(k => !controls.has(k) && this.data[k] !== oldData[k]);
103
+ if (this.newData && redraw) this.draw(false);
104
+ },
105
+
106
+ processData: function (snapshot) {
107
+ this.newData = snapshot;
108
+ this.draw(this.data.animation && this.meshes.size > 0);
109
+ this.notiBuffer.set(snapshot);
110
+ },
111
+
112
+ draw: function (animate) {
113
+ this.plan = planFor(Plan, this.plan, this.data, this.prodComponent);
114
+ const {cells, range, anchors} = this.plan.frame(this.newData);
115
+ this.hideLegend();
116
+ const ms = animate && cells.length ? this.data.animationDuration : 0;
117
+ this.prisms.set(cells, anchors, Number.isFinite(ms) ? Math.max(0, ms) : 0,
118
+ (color, cell) => setColor(color, cell, range, this.data));
119
+ this.anchors = anchors;
120
+ // Surviving keys reuse their meshes. Clear the tint immediately if the
121
+ // quarter is leaving (or became a leaf), not after its departure tween.
122
+ const mesh = this.selection.mesh;
123
+ if (mesh) {
124
+ const cell = mesh.userData.cell;
125
+ this.selection.set(cell.quarter && anchors.has(cell.key) ? mesh : null, this.prisms, this.data);
126
+ }
127
+ },
128
+
129
+ play: function () {
130
+ const canvas = this.el.sceneEl.canvas;
131
+ if (canvas) {
132
+ canvas.addEventListener('mousemove', this.onCanvasMove);
133
+ canvas.addEventListener('mouseleave', this.onCanvasLeave);
134
+ }
135
+ },
136
+
137
+ pause: function () {
138
+ const canvas = this.el.sceneEl.canvas;
139
+ if (canvas) {
140
+ canvas.removeEventListener('mousemove', this.onCanvasMove);
141
+ canvas.removeEventListener('mouseleave', this.onCanvasLeave);
142
+ }
143
+ for (const cursor of this.cursors) cursor.removeEventListener('controllerdisconnected', this.onDisconnect);
144
+ this.cursors.clear();
145
+ this.mouseOverCanvas = false;
146
+ this.hideLegend();
147
+ },
148
+
149
+ tick: function (time, delta) {
150
+ this.prisms.step(delta);
151
+ this.selection.update(this.prisms);
152
+ if (this.cursors.size && this.data.legend) this.updateHover();
153
+ },
154
+
155
+ pickedCell: function (hit) {
156
+ const mesh = hit?.object;
157
+ const cell = mesh?.parent === this.group && mesh.visible && mesh.userData.cell;
158
+ return cell && this.anchors.has(cell.key) ? cell : null;
159
+ },
160
+
161
+ updateHover: function () {
162
+ // All lots share an entity. Reuse the cursors' current intersections
163
+ // (no extra raycasts), with the last entering hand taking precedence.
164
+ let best;
165
+ for (const cursor of this.cursors) {
166
+ const mouse = cursor.components.cursor?.data.rayOrigin === 'mouse';
167
+ if (mouse && (best || !this.mouseOverCanvas || this.el.sceneEl.is('vr-mode'))) continue;
168
+ const ray = cursor.components.raycaster;
169
+ const hit = ray?.data.enabled && ray.getIntersection(this.el);
170
+ const cell = this.pickedCell(hit);
171
+ if (cell && !cell.quarter && hit.point) best = hit;
172
+ }
173
+ if (!best || !this.data.legend) return this.hideLegend();
174
+ if (!this.tooltip) this.tooltip = new CellLabel(THREE, this.el.sceneEl.object3D);
175
+ this.tooltip.show(best.object.userData.cell, best.point, this.data);
176
+ },
177
+
178
+ forgetCursor: function (cursor) {
179
+ if (!this.cursors.delete(cursor)) return;
180
+ cursor.removeEventListener('controllerdisconnected', this.onDisconnect);
181
+ this.updateHover();
182
+ },
183
+
184
+ hideLegend: function () {
185
+ if (this.tooltip) this.tooltip.hide();
186
+ },
187
+
188
+ events: {
189
+ mouseenter: function (event) {
190
+ const cursor = event.detail?.cursorEl;
191
+ if (!cursor?.components.raycaster) return;
192
+ this.cursors.add(cursor);
193
+ cursor.addEventListener('controllerdisconnected', this.onDisconnect);
194
+ this.updateHover();
195
+ },
196
+ mouseleave: function (event) {
197
+ this.forgetCursor(event.detail?.cursorEl);
198
+ },
199
+ click: function (event) {
200
+ const hit = event.detail?.intersection;
201
+ const cell = this.pickedCell(hit);
202
+ if (!cell) return;
203
+ const {id, data, quarter} = cell, detail = {id, data, quarter};
204
+ if (quarter) {
205
+ detail.selected = this.selection.mesh !== hit.object;
206
+ this.selection.set(detail.selected ? hit.object : null, this.prisms, this.data);
207
+ }
208
+ this.el.emit(selectEvent, detail);
209
+ }
210
+ },
211
+
212
+ unsubscribe: function () {
213
+ if (this.prodComponent) this.prodComponent.notiBuffer.unregister(this.subscription);
214
+ this.prodComponent = null;
215
+ },
216
+
217
+ remove: function () {
218
+ this.unsubscribe();
219
+ this.plan = null;
220
+ this.selection.dispose();
221
+ this.prisms.clear();
222
+ if (this.tooltip) this.tooltip.dispose();
223
+ this.anchors.clear();
224
+ this.el.removeObject3D(this.attrName);
225
+ }
226
+ });
@@ -0,0 +1,35 @@
1
+ const {byKey, snapshot, partitionLots} = require('./layout');
2
+ const {PeakLotPlan} = require('../peak-lot-plan');
3
+
4
+ class VoronoiPlan extends PeakLotPlan {
5
+ constructor(options) {
6
+ super(options, partitionLots, byKey);
7
+ this.reflowSites = [];
8
+ }
9
+
10
+ invalidateGeometry() {
11
+ super.invalidateGeometry();
12
+ this.reflowSites.length = 0;
13
+ }
14
+
15
+ reflow(roots, revision) {
16
+ if (!this.treeAt || !Number.isInteger(revision)) {
17
+ const plan = partitionLots(roots, this.options, this.previous);
18
+ this.previous = plan.anchors;
19
+ return plan;
20
+ }
21
+ // Reproduce the original online layout even on a direct seek: seed from
22
+ // survivors of the preceding *date*, never from a future or reserved lot.
23
+ // Fill skipped dates on demand. Cache only site directions, not polygons.
24
+ const sites = this.reflowSites;
25
+ for (let i = sites.length; i < revision; i++) {
26
+ const past = snapshot(this.treeAt(i), this.options);
27
+ sites.push(partitionLots(past.roots, this.options, sites[i-1]).anchors);
28
+ }
29
+ const plan = partitionLots(roots, this.options, sites[revision] || sites[revision-1]);
30
+ if (revision === sites.length) sites.push(plan.anchors);
31
+ return plan;
32
+ }
33
+ }
34
+
35
+ module.exports = {VoronoiPlan};
@@ -37,9 +37,14 @@ class CellLabel {
37
37
 
38
38
  paint(lines) {
39
39
  const ctx = this.ctx, canvas = ctx.canvas, line = 36, pad = 14;
40
+ const height = lines.length * line + 2 * pad;
41
+ if (height > canvas.height) {
42
+ // Custom boats templates can be longer than a cell's standard metrics.
43
+ this.texture.dispose();
44
+ canvas.height = height;
45
+ }
40
46
  ctx.font = 'bold 26px sans-serif';
41
47
  const width = Math.min(canvas.width, Math.max(180, ...lines.map(s => Math.ceil(ctx.measureText(s).width) + 2 * pad)));
42
- const height = lines.length * line + 2 * pad;
43
48
  ctx.fillStyle = '#132733';
44
49
  ctx.fillRect(0, 0, width, height);
45
50
  ctx.fillStyle = '#ffffff';
@@ -1,4 +1,4 @@
1
- const {partition, inset} = require('./power-diagram');
1
+ const {partition, inset, centroid} = require('./power-diagram');
2
2
 
3
3
  function number(value) {
4
4
  if (typeof value !== 'number' && !(typeof value === 'string' && value.trim())) return NaN;
@@ -12,7 +12,13 @@ function positive(value) {
12
12
  return n > 0 ? n : 0.5;
13
13
  }
14
14
 
15
- function hierarchy(records, path, options, range) {
15
+ function footprint(row, options) {
16
+ return options.area ? positive(row[options.area]) : positive(row[options.width]) * positive(row[options.depth]);
17
+ }
18
+
19
+ const byKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
20
+
21
+ function hierarchy(records, path, options, range, compare) {
16
22
  const occurrences = new Map();
17
23
  const nodes = records.map((data, index) => {
18
24
  const id = String(data[options.field] ?? data.uid ?? data.id ?? data.name ?? index);
@@ -20,13 +26,15 @@ function hierarchy(records, path, options, range) {
20
26
  occurrences.set(id, count + 1);
21
27
  // Keep paths containing slashes, duplicate names in different quarters,
22
28
  // and even duplicate sibling IDs distinct without assigning DOM IDs.
23
- const key = path + '/' + JSON.stringify([id, count]);
29
+ const quarter = Array.isArray(data.children);
30
+ // A path can be a file in one revision and a directory in another.
31
+ const key = path + '/' + JSON.stringify([id, count, quarter]);
24
32
  const node = {id, key, data};
25
- if (Array.isArray(data.children)) {
26
- node.children = hierarchy(data.children, key, options, range);
33
+ if (quarter) {
34
+ node.children = hierarchy(data.children, key, options, range, compare);
27
35
  node.mass = node.children.reduce((sum, n) => sum + n.mass, 0) || 0.5;
28
36
  } else {
29
- node.mass = options.area ? positive(data[options.area]) : positive(data[options.width]) * positive(data[options.depth]);
37
+ node.mass = footprint(data, options);
30
38
  node.metric = number(data[options.height]);
31
39
  if (node.metric >= 0) {
32
40
  range.min = Math.min(range.min, node.metric);
@@ -40,34 +48,61 @@ function hierarchy(records, path, options, range) {
40
48
  }
41
49
  return node;
42
50
  });
43
- // No dependency on the arrival order of uniquely identified siblings.
44
- return nodes.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
51
+ return nodes.sort(compare);
45
52
  }
46
53
 
47
- function layout(records, options, previous = new Map()) {
48
- const anchors = new Map(), cells = [];
54
+ function snapshot(records, options, compare = byKey) {
49
55
  const range = {min: Infinity, max: 0, colorMin: Infinity, colorMax: -Infinity};
50
- const roots = hierarchy(records, '', options, range);
51
- const low = options.diffBuildingHeight ? range.min : 0;
52
- const minHeight = Math.max(0, options.minBuildingHeight);
53
- const span = Math.max(0, options.maxBuildingHeight - minHeight);
54
- const elevation = Math.max(0, options.zone_elevation);
56
+ const rows = Array.isArray(records) ? records : records ? [records] : [];
57
+ return {roots: hierarchy(rows, '', options, range, compare), range};
58
+ }
55
59
 
56
- function visit(nodes, boundary, base) {
60
+ function partitionLots(roots, options, previous = new Map()) {
61
+ const lots = new Map(), anchors = new Map();
62
+ function visit(nodes, boundary) {
57
63
  if (!nodes.length) return;
58
64
  const polygons = partition(boundary, nodes, previous, anchors);
59
65
  nodes.forEach((node, i) => {
60
66
  const polygon = inset(polygons[i], options.separation / 2);
61
- const quarter = !!node.children;
62
- const fraction = node.metric >= low && range.max > low ? (node.metric - low) / (range.max - low) : 0;
63
- const height = quarter ? elevation : minHeight + span * fraction;
64
- cells.push({key: node.key, id: node.id, data: node.data, quarter, polygon, base, height});
65
- if (quarter) visit(node.children, inset(polygon, options.border), base + elevation);
67
+ lots.set(node.key, {polygon, mass: node.mass});
68
+ if (node.children) visit(node.children, inset(polygon, options.border));
66
69
  });
67
70
  }
68
71
  const r = positive(options.size) / 2;
69
- visit(roots, [{x: -r, y: -r}, {x: r, y: -r}, {x: r, y: r}, {x: -r, y: r}], 0);
72
+ visit(roots, [{x: -r, y: -r}, {x: r, y: -r}, {x: r, y: r}, {x: -r, y: r}]);
73
+ return {lots, anchors};
74
+ }
75
+
76
+ // Project only the live rows onto the plan. Heights, colours and event data
77
+ // belong to this date; a vacant lot has no mesh, anchor for picking, or label.
78
+ function occupy({roots, range}, plan, options) {
79
+ const cells = [], anchors = new Map();
80
+ const low = options.diffBuildingHeight ? range.min : 0;
81
+ const minHeight = Math.max(0, options.minBuildingHeight);
82
+ const span = Math.max(0, options.maxBuildingHeight - minHeight);
83
+ const elevation = Math.max(0, options.zone_elevation);
84
+ function visit(nodes, base) {
85
+ for (const {key, id, data, children, mass, metric} of nodes) {
86
+ const lot = plan.lots.get(key), quarter = !!children;
87
+ let polygon = lot.polygon;
88
+ if (!quarter && mass < lot.mass) {
89
+ const c = centroid(polygon), side = Math.sqrt(mass / lot.mass);
90
+ polygon = polygon.map(p => ({x: c.x + side * (p.x - c.x), y: c.y + side * (p.y - c.y)}));
91
+ }
92
+ const fraction = metric >= low && range.max > low ? (metric - low) / (range.max - low) : 0;
93
+ const height = quarter ? elevation : minHeight + span * fraction;
94
+ cells.push({key, id, data, quarter, polygon, base, height});
95
+ anchors.set(key, plan.anchors.get(key));
96
+ if (quarter) visit(children, base + elevation);
97
+ }
98
+ }
99
+ visit(roots, 0);
70
100
  return {cells, anchors, range};
71
101
  }
72
102
 
73
- module.exports = {layout, number};
103
+ function layout(records, options, previous) {
104
+ const live = snapshot(records, options);
105
+ return occupy(live, partitionLots(live.roots, options, previous), options);
106
+ }
107
+
108
+ module.exports = {layout, number, positive, footprint, byKey, snapshot, partitionLots, occupy};