Compare commits

..

No commits in common. "a50c7c2a58859b746a84a1611b9dc1d58238b3ad" and "fe6a26316446a98077bc6985ab179908783d41ba" have entirely different histories.

15 changed files with 240 additions and 349 deletions

View File

@ -1,9 +1,11 @@
// VELOCITY // VELOCITY
export const VELOCITY_VECTOR_SCALE = 8E0;
export const VELOCITY_VECTOR_COLOR = 'rgba(150, 150, 150, 0.8)'; // optionally set to 'object color' export const VELOCITY_VECTOR_COLOR = 'rgba(150, 150, 150, 0.8)'; // optionally set to 'object color'
export const VELOCITY_VECTOR_WIDTH = 1.5; export const VELOCITY_VECTOR_WIDTH = 1.5;
export const VELOCITY_VECTOR_ARROWHEAD = true; export const VELOCITY_VECTOR_ARROWHEAD = true;
// ACCELERATION // ACCELERATION
export const ACCELERATION_VECTOR_SCALE = 8E0;
export const ACCELERATION_VECTOR_COLOR = 'rgba(0, 128, 0, 0.8)'; // optionally set to 'object color' export const ACCELERATION_VECTOR_COLOR = 'rgba(0, 128, 0, 0.8)'; // optionally set to 'object color'
export const ACCELERATION_VECTOR_WIDTH = 1.5; export const ACCELERATION_VECTOR_WIDTH = 1.5;
export const ACCELERATION_VECTOR_ARROWHEAD = true; export const ACCELERATION_VECTOR_ARROWHEAD = true;
@ -23,6 +25,7 @@ export const ARROWHEAD_WIDTH = 5;
export const OFFSCREEN_OBJECT_LINE_SCALE = 7; export const OFFSCREEN_OBJECT_LINE_SCALE = 7;
export const OFFSCREEN_OBJECT_LINE_WIDTH = 2; export const OFFSCREEN_OBJECT_LINE_WIDTH = 2;
export const OFFSCREEN_OBJECT_ARROWHEAD_LENGTH = 15; export const OFFSCREEN_OBJECT_ARROWHEAD_LENGTH = 15;
export const ZOOM_TO_FIT_PADDING = 50;
export const ZOOM_IN_FACTOR = 1; export const ZOOM_IN_FACTOR = 1;
export const ZOOM_OUT_FACTOR = -1; export const ZOOM_OUT_FACTOR = -1;
export const SCALE_POWER_MAX = 8; export const SCALE_POWER_MAX = 8;
@ -49,8 +52,5 @@ export const MODE_MASS_GENERATION = 'mass-gen';
export const MODE_PAN_VIEW = 'pan-view'; export const MODE_PAN_VIEW = 'pan-view';
export const MODE_OBJECT_SELECT = 'select'; export const MODE_OBJECT_SELECT = 'select';
// LOCAL STORAGE NAMESPACES // LOCAL STORAGE PREFIXES/SUFFIXES
export const TOOLBAR_EXPANDED_SUFFIX = 'lhg-toolbar-expanded'; export const TOOLBAR_EXPANDED_SUFFIX = 'lhg-toolbar-expanded';
export const OBJECT_MAGIC_PROP_PREFIX = '_lhg_';

View File

@ -67,6 +67,10 @@ export class Display {
ctx.fillRect(this.viewOrigin.x, this.viewOrigin.y, this.width, this.height); ctx.fillRect(this.viewOrigin.x, this.viewOrigin.y, this.width, this.height);
} }
drawObjects() {
this.sim.objects.forEachObject(obj => obj.drawObject(this.sim), {alive: null});
}
drawArrow(startX, startY, endX, endY, {style, width, arrowhead, arrowheadLength, fill, ifShort}) { drawArrow(startX, startY, endX, endY, {style, width, arrowhead, arrowheadLength, fill, ifShort}) {
const ctx = this.ctx; const ctx = this.ctx;
ctx.strokeStyle = style; ctx.strokeStyle = style;
@ -135,46 +139,28 @@ export class Display {
ctx.resetTransform(); ctx.resetTransform();
} }
frame(elapsedTime) { computePanning(elapsedTime) {
// Add another entry for the current pointer position
const { const {
touchStart: start, pointerHistory,
touchLatest: latest, panTouchStart: start,
panTouchLatest: latest,
} = this.sim.pointer ?? {}; } = this.sim.pointer ?? {};
if (pointerHistory?.length) {
const currentPointer = pointerHistory[pointerHistory.length - 1];
this.sim.pointer.updatePointer(currentPointer);
}
if (start && latest) { if (start && latest) {
// Direct translate // Direct translate
this.viewOrigin.x = start.viewOrigin.x - (latest.x - start.x) / this.scale; this.viewOrigin.x = start.viewOrigin.x - (latest.x - start.x) / this.scale;
this.viewOrigin.y = start.viewOrigin.y - (latest.y - start.y) / this.scale; this.viewOrigin.y = start.viewOrigin.y - (latest.y - start.y) / this.scale;
} } else if (this.sim.panning && !this.sim.panning.paused) {
let pdx = 0;
let pdy = 0;
if (this.sim.panning && !this.sim.panning.paused) {
// Apply update to viewOrigin based on panning // Apply update to viewOrigin based on panning
pdx = this.sim.panning.velocity.x * elapsedTime; const { velocity } = this.sim.panning;
pdy = this.sim.panning.velocity.y * elapsedTime; // TODO: something with time scale? Panning is too fast.
this.viewOrigin.x -= velocity.x * elapsedTime / 1000; // millisecond conversion?
this.viewOrigin.y -= velocity.y * elapsedTime / 1000;
} }
this.viewOrigin.x += pdx;
this.viewOrigin.y += pdy;
if (start && latest) {
// Update what's considered start
start.viewOrigin = {...this.viewOrigin};
start.x = latest.x;
start.y = latest.y;
}
if (this.sim.getOption('debug.panningInfo')) {
const {x, y} = this.sim.panning?.velocity ?? {};
this.sim.info['Panning Velocity'] = [`${x?.toPrecision(6)}, `, y?.toPrecision(6)];
const { centerOfMass } = this.sim.system.computeSystemCenter();
this.sim.info['Center of Mass'] = [`${centerOfMass.x.toPrecision(6)}, `, centerOfMass.y.toPrecision(6)];
this.sim.info['Net Angular Momentum'] = this.sim.system.computeSystemAngularMomentum().toPrecision(6);
}
// Clear canvas in preparation for other modules to render this frame
this.fillCanvas();
} }
} }

View File

@ -1,2 +0,0 @@
export function makeUtilityButton() {
}

View File

@ -1,6 +1,7 @@
import { import {
ACCELERATION_VECTOR_ARROWHEAD, ACCELERATION_VECTOR_ARROWHEAD,
ACCELERATION_VECTOR_COLOR, ACCELERATION_VECTOR_COLOR,
ACCELERATION_VECTOR_SCALE,
ACCELERATION_VECTOR_WIDTH, ACCELERATION_VECTOR_WIDTH,
OFFSCREEN_OBJECT_ARROWHEAD_LENGTH, OFFSCREEN_OBJECT_ARROWHEAD_LENGTH,
OFFSCREEN_OBJECT_LINE_SCALE, OFFSCREEN_OBJECT_LINE_SCALE,
@ -11,12 +12,11 @@ import {
PATH_TRACES_WIDTH, PATH_TRACES_WIDTH,
VELOCITY_VECTOR_ARROWHEAD, VELOCITY_VECTOR_ARROWHEAD,
VELOCITY_VECTOR_COLOR, VELOCITY_VECTOR_COLOR,
VELOCITY_VECTOR_SCALE,
VELOCITY_VECTOR_WIDTH, VELOCITY_VECTOR_WIDTH,
} from './config.js'; } from './config.js';
export class MassObject { export class MassObject {
sim = undefined;
id = undefined;
mass = 0; mass = 0;
density = 1; density = 1;
position = {x: undefined, y: undefined}; position = {x: undefined, y: undefined};
@ -28,9 +28,7 @@ export class MassObject {
history = []; history = [];
alive = true; alive = true;
constructor(sim, x, y) { constructor(x, y) {
this.sim = sim;
this.id = crypto.randomUUID();
this.position.x = x; this.position.x = x;
this.position.y = y; this.position.y = y;
this.color.r = Math.random() * 256; this.color.r = Math.random() * 256;
@ -88,7 +86,7 @@ export class MassObject {
const opacity = dashedTraces ? PATH_TRACES_DASHED_OPACITY : PATH_TRACES_OPACITY; const opacity = dashedTraces ? PATH_TRACES_DASHED_OPACITY : PATH_TRACES_OPACITY;
ctx.strokeStyle = PATH_TRACES_COLOR === 'object color' ? ctx.strokeStyle = PATH_TRACES_COLOR === 'object color' ?
`rgba(${r}, ${g}, ${b}, ${opacity})` : PATH_TRACES_COLOR; `rgba(${r}, ${g}, ${b}, ${opacity})` : PATH_TRACES_COLOR;
ctx.lineWidth = PATH_TRACES_WIDTH / this.sim.display.scale; ctx.lineWidth = PATH_TRACES_WIDTH / this.scale;
ctx.beginPath(); ctx.beginPath();
let dash = false; let dash = false;
for (let i = 0; i < this.history.length; i++) { for (let i = 0; i < this.history.length; i++) {
@ -144,8 +142,8 @@ export class MassObject {
const arrowDirection = Math.atan2(py - cy, px - cx); const arrowDirection = Math.atan2(py - cy, px - cx);
// Length of arrow based on distance (logarithmic scale) // Length of arrow based on distance (logarithmic scale)
const distance = Math.sqrt((x - px) ** 2, (y - py) ** 2); const distance = Math.sqrt((x - px) ** 2, (y - py) ** 2) * this.scale;
const arrowLength = Math.log(distance + 1) * OFFSCREEN_OBJECT_LINE_SCALE / this.sim.display.scale; const arrowLength = Math.log(distance) * OFFSCREEN_OBJECT_LINE_SCALE / this.scale;
const startAx = px - arrowLength * Math.cos(arrowDirection); const startAx = px - arrowLength * Math.cos(arrowDirection);
const startAy = py - arrowLength * Math.sin(arrowDirection); const startAy = py - arrowLength * Math.sin(arrowDirection);
sim.display.drawArrow(startAx, startAy, px, py, { sim.display.drawArrow(startAx, startAy, px, py, {
@ -167,19 +165,9 @@ export class MassObject {
// Draw arrow for the velocity // Draw arrow for the velocity
if (sim.getOption('display.velocity')) { if (sim.getOption('display.velocity')) {
// If this object is being dragged by the user, const speed = Math.sqrt(vx ** 2 + vy ** 2);
// show the pointer velocity instead of object velocity const endVx = x + VELOCITY_VECTOR_SCALE * vx / speed * Math.log(speed);
const vecScale = this.sim.getOption('param.velocityScale'); const endVy = y + VELOCITY_VECTOR_SCALE * vy / speed * Math.log(speed);
const selected = this.sim.system.getSelectedOrCreating();
const velocity = selected?.id === this.id ?
this.sim.pointer.latestVelocity ?? {x: 0, y: 0} :
{x: vx, y: vy};
const speed = Math.sqrt(velocity.x ** 2, velocity.y ** 2);
const arrowDirection = Math.atan2(velocity.y, velocity.x);
// Prevent negative numbers by adding 1
const arrowLength = Math.log(speed + 1) * vecScale / this.sim.display.scale;
const endVx = x + arrowLength * Math.cos(arrowDirection);
const endVy = y + arrowLength * Math.sin(arrowDirection);
const style = VELOCITY_VECTOR_COLOR === 'object color' ? const style = VELOCITY_VECTOR_COLOR === 'object color' ?
`rgb(${r}, ${g}, ${b})` : VELOCITY_VECTOR_COLOR; `rgb(${r}, ${g}, ${b})` : VELOCITY_VECTOR_COLOR;
sim.display.drawArrow(x, y, endVx, endVy, { sim.display.drawArrow(x, y, endVx, endVy, {
@ -193,13 +181,11 @@ export class MassObject {
// Draw arrow for acceleration // Draw arrow for acceleration
if (sim.getOption('display.acceleration')) { if (sim.getOption('display.acceleration')) {
const vecScale = this.sim.getOption('param.accelerationScale');
const accelerationMagnitude = Math.sqrt(acceleration.x ** 2 + acceleration.y ** 2); const accelerationMagnitude = Math.sqrt(acceleration.x ** 2 + acceleration.y ** 2);
const arrowDirection = Math.atan2(acceleration.y, acceleration.x); const endAx = x + ACCELERATION_VECTOR_SCALE * acceleration.x /
// Prevent negative numbers by adding e accelerationMagnitude * Math.log(accelerationMagnitude);
const arrowLength = Math.log(accelerationMagnitude + 1) * vecScale / this.sim.display.scale; const endAy = y + ACCELERATION_VECTOR_SCALE * acceleration.y /
const endAx = x + arrowLength * Math.cos(arrowDirection); accelerationMagnitude * Math.log(accelerationMagnitude);
const endAy = y + arrowLength * Math.sin(arrowDirection);
const style = ACCELERATION_VECTOR_COLOR === 'object color' ? const style = ACCELERATION_VECTOR_COLOR === 'object color' ?
`rgb(${r}, ${g}, ${b})` : ACCELERATION_VECTOR_COLOR; `rgb(${r}, ${g}, ${b})` : ACCELERATION_VECTOR_COLOR;
sim.display.drawArrow(x, y, endAx, endAy, { sim.display.drawArrow(x, y, endAx, endAy, {

View File

@ -1,10 +1,10 @@
import { MassObject } from './object.js'; import { MassObject } from './object.js';
import { ZOOM_TO_FIT_PADDING } from './config.js';
export class System { export class Objects {
objects = []; objects = [];
creatingObject = undefined; creatingObject = undefined;
selectedObject = undefined; selectedObject = undefined;
selectObjectStart = undefined;
paused = false; paused = false;
panVelocityPaused = undefined; panVelocityPaused = undefined;
@ -35,9 +35,8 @@ export class System {
// Create an object with mass that grows as pointer is held down // Create an object with mass that grows as pointer is held down
createObject(x, y) { createObject(x, y) {
const idx = this.objects.length; const idx = this.objects.length;
const obj = new MassObject(this.sim, x, y); const obj = new MassObject(x, y, idx);
this.creatingObject = idx; this.creatingObject = idx;
this.selectedObjectStart = {x, y, pointer: {x, y}};
this.objects.push(obj); this.objects.push(obj);
// Pause the simulation during mass creation; this avoids some complex local dynamics // Pause the simulation during mass creation; this avoids some complex local dynamics
if (this.sim.getOption('pauseDuring.creation')) { if (this.sim.getOption('pauseDuring.creation')) {
@ -60,10 +59,8 @@ export class System {
return this.objects[i]; return this.objects[i];
} }
selectObject(i, pointer) { selectObject(i) {
this.selectedObject = i; this.selectedObject = i;
const {x, y} = this.object(i).position;
this.selectedObjectStart = {x, y, pointer};
if (this.sim.getOption('pauseDuring.selection')) { if (this.sim.getOption('pauseDuring.selection')) {
this.pause(); this.pause();
} }
@ -71,7 +68,6 @@ export class System {
deselect() { deselect() {
this.selectedObject = undefined; this.selectedObject = undefined;
this.selectedObjectStart = undefined;
this.resume(); this.resume();
} }
@ -87,45 +83,30 @@ export class System {
} }
get boundingBox() { get boundingBox() {
const box = this.reduce(({start, end}, obj) => { const box = this.reduce((acc, obj) => {
const lx = obj.position.x - obj.radius; if (acc.start.x === undefined) {
const gx = obj.position.x + obj.radius; acc.start = {...obj.position};
const ly = obj.position.y - obj.radius; acc.end = {...obj.position};
const gy = obj.position.y + obj.radius; } else {
let ret; if (obj.position.x < acc.start.x) acc.start.x = obj.position.x;
if (start.x === undefined) { if (obj.position.x > acc.end.x) acc.end.x = obj.position.x;
ret = { if (obj.position.y < acc.start.y) acc.start.y = obj.position.y;
start: {x: lx, y: ly}, if (obj.position.y > acc.end.y) acc.end.y = obj.position.y;
end: {x: gx, y: gy},
};
return ret;
} }
ret = {
start: {
x: Math.min(start.x, lx),
y: Math.min(start.y, ly),
},
end: {
x: Math.max(end.x, gx),
y: Math.max(end.y, gy),
}
};
return ret;
}, { }, {
start: {x: undefined, y: undefined}, start: {x: undefined, y: undefined},
end: {x: undefined, y: undefined}, end: {x: undefined, y: undefined},
}); });
box.start.x = (box.start.x ?? 0); box.start.x = (box.start.x ?? 0) - ZOOM_TO_FIT_PADDING;
box.start.y = (box.start.y ?? 0); box.start.y = (box.start.y ?? 0) - ZOOM_TO_FIT_PADDING;
box.end.x = (box.end.x ?? 0); box.end.x = (box.end.x ?? 0) + ZOOM_TO_FIT_PADDING;
box.end.y = (box.end.y ?? 0); box.end.y = (box.end.y ?? 0) + ZOOM_TO_FIT_PADDING;
return box; return box;
} }
objectAtLocation(x, y) { objectAtLocation(x, y) {
let idx = undefined; let idx = undefined;
this.selectedObjectStart = undefined;
this.forEachObject((obj, i) => { this.forEachObject((obj, i) => {
// If distance to object is less than object's radius, we are touching the object // If distance to object is less than object's radius, we are touching the object
const dist = Math.pow((obj.position.x - x)**2 + (obj.position.y - y)**2, 1/2); const dist = Math.pow((obj.position.x - x)**2 + (obj.position.y - y)**2, 1/2);
@ -142,7 +123,7 @@ export class System {
const touchingObject = this.objectAtLocation(x, y); const touchingObject = this.objectAtLocation(x, y);
if (touchingObject !== undefined) { if (touchingObject !== undefined) {
this.selectObject(touchingObject, {x, y}); this.selectObject(touchingObject);
} else { } else {
// Otherwise, create a new object // Otherwise, create a new object
this.createObject(x, y); this.createObject(x, y);
@ -150,31 +131,24 @@ export class System {
} }
handlePointerUp() { handlePointerUp() {
const obj = this.getSelectedOrCreating();
if (obj === undefined) return;
this.doneCreatingObject(); this.doneCreatingObject();
this.deselect(); this.deselect();
// Convert pointer velocity to simulation scale
// Including time scale - if time is slow, our motion is relatively faster
const pointer = {...this.sim.pointer.latestVelocity};
obj.velocity.x = pointer.x / this.sim.display.scale * this.sim.timeScale;
obj.velocity.y = pointer.y / this.sim.display.scale * this.sim.timeScale;
if (this.sim.panning?.velocity) {
obj.velocity.x += this.sim.panning.velocity.x;
obj.velocity.y += this.sim.panning.velocity.y;
}
} }
handlePointerMove({x, y}) { handlePointerMove({x, y, vx, vy}) {
// If the cursor moves while creating an object, or while an object is selected, // If the cursor moves while creating an object, or while an object is selected,
// update the position and velocity of the object
// update the position using the pointer motion but the velocity using the pointer velocity // update the position using the pointer motion but the velocity using the pointer velocity
const obj = this.getSelectedOrCreating(); const obj = this.getSelectedOrCreating();
if (obj === undefined) return; if (obj === undefined) return;
const start = this.selectedObjectStart; if (this.sim.panning?.velocity) {
obj.position.x = start.x + (x - start.pointer.x); vx += this.sim.panning.velocity.x;
obj.position.y = start.y + (y - start.pointer.y); vy += this.sim.panning.velocity.y;
obj.velocity.x = 0; }
obj.velocity.y = 0; obj.position.x = x;
obj.position.y = y;
obj.velocity.x = vx;
obj.velocity.y = vy;
} }
// cb: (obj, idx) => {} // cb: (obj, idx) => {}
@ -189,10 +163,6 @@ export class System {
} }
} }
drawObjects() {
this.forEachObject(obj => obj.drawObject(this.sim), {alive: null});
}
// cb: (acc, obj, idx) => {} // cb: (acc, obj, idx) => {}
reduce(cb, initial, opts) { reduce(cb, initial, opts) {
let acc = initial; let acc = initial;
@ -231,7 +201,9 @@ export class System {
} }
// elapsedTime is given in milliseconds // elapsedTime is given in milliseconds
frame(elapsedTime) { computeFrame(elapsedTime) {
// convert elapsed time to seconds
elapsedTime /= 1000;
// If we're creating an object, increment its mass // If we're creating an object, increment its mass
// with the mass creation rate accelerating over time // with the mass creation rate accelerating over time
@ -239,7 +211,8 @@ export class System {
if (this.creatingObject !== undefined) { if (this.creatingObject !== undefined) {
const obj = this.objects[this.creatingObject]; const obj = this.objects[this.creatingObject];
let massCreationRate = this.sim.getOption('param.massCreationRate'); // Putting in a somewhat arbitrary scaling factor here
let massCreationRate = this.sim.getOption('param.massCreationRate') / 1000;
// Mass creation rate acceleration // Mass creation rate acceleration
if (this.sim.getOption('param.massAcceleration')) { if (this.sim.getOption('param.massAcceleration')) {
massCreationRate *= obj.age; massCreationRate *= obj.age;
@ -251,6 +224,8 @@ export class System {
this.computeForces(); this.computeForces();
if (this.sim.playing) { if (this.sim.playing) {
// TODO: If creating/selected object, clamp its position to the cursor
// Predict positions (Velocity verlet method) // Predict positions (Velocity verlet method)
this.forEachObject(obj => { this.forEachObject(obj => {
obj.currentAcceleration = {...obj.acceleration}; obj.currentAcceleration = {...obj.acceleration};
@ -332,39 +307,26 @@ export class System {
} }
// Display objects info // Display objects info
// First clear info from previous frame
this.forEachObject((_obj, i) => {
delete this.sim.info[`Object ${i}`];
}, { alive: null });
if (this.sim.getOption('debug.objectsInfo')) { if (this.sim.getOption('debug.objectsInfo')) {
const aliveOnly = this.sim.getOption('debug.aliveObjects');
this.forEachObject((obj, i) => { this.forEachObject((obj, i) => {
const speed = Math.pow(obj.velocity.x ** 2 + obj.velocity.y ** 2, 1/2); const speed = Math.pow(obj.velocity.x ** 2 + obj.velocity.y ** 2, 1/2);
const accel = Math.pow(obj.acceleration.x ** 2 + obj.acceleration.y ** 2, 1/2);
// Invert y so that the angle is counterclockwise from x-axis // Invert y so that the angle is counterclockwise from x-axis
const direction = Math.atan2(-obj.velocity.y, obj.velocity.x) * 180 / Math.PI; const direction = Math.atan2(-obj.velocity.y, obj.velocity.x) * 180 / Math.PI;
const accelDir = Math.atan2(-obj.acceleration.y, obj.acceleration.x) * 180 / Math.PI;
const {r, g, b} = obj.color;
this.sim.info[`Object ${i}`] = [ this.sim.info[`Object ${i}`] = [
`<span style="background-color: rgb(${r},${g},${b});">&nbsp;&nbsp;</span>`, `${obj.position.x.toPrecision(6)}, `,
`${obj.position.x.toPrecision(4)}, `, `${obj.position.y.toPrecision(6)}, `,
`${obj.position.y.toPrecision(4)}, `, `${obj.mass.toPrecision(6)} kg, `,
`${obj.mass.toPrecision(4)} kg, `,
`${speed.toPrecision(2)} m/s, ${direction.toPrecision(2)}°`, `${speed.toPrecision(2)} m/s, ${direction.toPrecision(2)}°`,
`${accel.toPrecision(2)} m/s<sup>2</sup>, ${accelDir.toPrecision(2)}°`,
`Alive: ${obj.alive}`, `Alive: ${obj.alive}`,
]; ];
}, { alive: aliveOnly || null }); }, { alive: null });
} }
// Render the objects
this.drawObjects();
} }
computeSystemCenter() { computeSystemCenter() {
// Determine center of mass // Determine center of mass
const { totalMass, count, totalMassLocation } = const { totalMass, count, totalMassLocation } =
this.reduce((acc, obj) => ({ this.sim.objects.reduce((acc, obj) => ({
count: acc.count + 1, count: acc.count + 1,
totalMass: acc.totalMass + obj.mass, totalMass: acc.totalMass + obj.mass,
totalMassLocation: { totalMassLocation: {
@ -383,7 +345,7 @@ export class System {
} : {x: 0, y: 0}; } : {x: 0, y: 0};
// Determine average momentum // Determine average momentum
const netMomentum = this.reduce((acc, obj) => ({ const netMomentum = this.sim.objects.reduce((acc, obj) => ({
x: acc.x + obj.mass * obj.velocity.x, x: acc.x + obj.mass * obj.velocity.x,
y: acc.y + obj.mass * obj.velocity.y, y: acc.y + obj.mass * obj.velocity.y,
}), { x: 0, y: 0 }); }), { x: 0, y: 0 });

View File

@ -1,14 +1,11 @@
import { import {
EVENT_OPTION_SET, EVENT_OPTION_SET,
OBJECT_MAGIC_PROP_PREFIX,
} from './config.js'; } from './config.js';
export class Options { export class Options {
sim = undefined; sim = undefined;
options = undefined; options = undefined;
values = {}; values = {};
undefinedObj = { [OBJECT_MAGIC_PROP_PREFIX + 'undefined']: true};
nullObj = { [OBJECT_MAGIC_PROP_PREFIX + 'null']: true};
getStorageKey(path) { getStorageKey(path) {
return `${path}:options`; return `${path}:options`;
@ -37,27 +34,10 @@ export class Options {
} }
toStored(value) { toStored(value) {
if (value === undefined) {
// TODO: Do we want to interpret this as removing from storage?
// Let's just treat it as a value for now;
// Semantically it works because when retrieved, it will return undefined,
// which is the same result you get if the key is not set
return JSON.stringify(this.undefinedObj);
} else if (value === null) {
return JSON.stringify(this.nullObj);
}
return JSON.stringify(value); return JSON.stringify(value);
} }
// value: string
fromStored(value) { fromStored(value) {
if (value === null) {
return undefined;
} else if (value === JSON.stringify(this.undefinedObj)) {
return undefined;
} else if (value === JSON.stringify(this.nullObj)) {
return null;
}
return JSON.parse(value); return JSON.parse(value);
} }

View File

@ -12,7 +12,7 @@ export class Overlay {
infoBox.classList.add(OVERLAY_INFO_BOX_CLASSNAME); infoBox.classList.add(OVERLAY_INFO_BOX_CLASSNAME);
} }
frame() { renderInfo() {
this.infoBox.innerHTML = ''; this.infoBox.innerHTML = '';
const table = document.createElement('table'); const table = document.createElement('table');
for (let [k, v] of Object.entries(this.sim.info)) { for (let [k, v] of Object.entries(this.sim.info)) {

View File

@ -13,8 +13,8 @@ export class Pointer {
sim = undefined; sim = undefined;
pointerHistory = []; pointerHistory = [];
touchStart = undefined; // {x: undefined, y: undefined, t: undefined}; panTouchStart = undefined; // {x: undefined, y: undefined, t: undefined};
touchLatest = undefined; // {x: undefined, y: undefined, t: undefined}; panTouchLatest = undefined; // {x: undefined, y: undefined, t: undefined};
suppressClick = false; suppressClick = false;
constructor(sim) { constructor(sim) {
@ -61,7 +61,7 @@ export class Pointer {
getPointerVelocity(points = POINTER_HISTORY_SIZE) { getPointerVelocity(points = POINTER_HISTORY_SIZE) {
// Average over pointer history // Average over pointer history
if (this.pointerHistory.length < 2) { if (this.pointerHistory.length < 2) {
return this.latestVelocity ?? {x: 0, y: 0, dt: 1}; return this.latestPointerVelocity ?? {x: 0, y: 0, dt: 1};
} }
points = Math.min(points, POINTER_HISTORY_SIZE, this.pointerHistory.length); points = Math.min(points, POINTER_HISTORY_SIZE, this.pointerHistory.length);
const start = this.pointerHistory[this.pointerHistory.length - points]; const start = this.pointerHistory[this.pointerHistory.length - points];
@ -79,7 +79,7 @@ export class Pointer {
} }
updatePointer({x, y}) { updatePointer({x, y}) {
const t = this.sim.rawTime; const t = document.timeline.currentTime;
while (this.pointerHistory.length >= POINTER_HISTORY_SIZE) { while (this.pointerHistory.length >= POINTER_HISTORY_SIZE) {
this.pointerHistory.shift(); this.pointerHistory.shift();
} }
@ -87,7 +87,7 @@ export class Pointer {
this.pointerHistory.push({t, x, y, v}); this.pointerHistory.push({t, x, y, v});
} }
get latestVelocity() { get latestPointerVelocity() {
const latestPointer = this.pointerHistory[this.pointerHistory.length - 1]; const latestPointer = this.pointerHistory[this.pointerHistory.length - 1];
return latestPointer?.v; return latestPointer?.v;
} }
@ -98,21 +98,16 @@ export class Pointer {
if (this.sim.isCurrentMode(MODE_MASS_GENERATION)) { if (this.sim.isCurrentMode(MODE_MASS_GENERATION)) {
const {x, y} = this.sim.screenToSim(clientX, clientY) const {x, y} = this.sim.screenToSim(clientX, clientY)
this.sim.system.handlePointerDown({x, y}); this.sim.objects.handlePointerDown({x, y});
} else if (this.sim.isCurrentMode(MODE_PAN_VIEW)) { } else if (this.sim.isCurrentMode(MODE_PAN_VIEW)) {
this.touchStart = { this.panTouchStart = {
x: clientX, x: clientX,
y: clientY, y: clientY,
t: this.sim.rawTime, t: document.timeline.currentTime,
viewOrigin: {...this.sim.display.viewOrigin}, viewOrigin: {...this.sim.display.viewOrigin},
}; };
this.touchLatest = { this.panTouchLatest = {...this.panTouchStart};
...this.touchStart,
dx: 0,
dy: 0,
dt: 0,
};
} else if (this.sim.isCurrentMode(MODE_OBJECT_SELECT)) { } else if (this.sim.isCurrentMode(MODE_OBJECT_SELECT)) {
// TODO: Start a selection box // TODO: Start a selection box
@ -122,27 +117,26 @@ export class Pointer {
handlePointerUp({x: clientX, y: clientY}) { handlePointerUp({x: clientX, y: clientY}) {
if (this.sim.isCurrentMode(MODE_MASS_GENERATION)) { if (this.sim.isCurrentMode(MODE_MASS_GENERATION)) {
const {x, y} = this.sim.screenToSim(clientX, clientY); const {x, y} = this.sim.screenToSim(clientX, clientY);
this.sim.system.handlePointerUp({x, y}); this.sim.objects.handlePointerUp({x, y});
} else if (this.sim.isCurrentMode(MODE_PAN_VIEW)) { } else if (this.sim.isCurrentMode(MODE_PAN_VIEW)) {
// Set panning velocity // Set panning velocity
if (this.touchStart && this.touchLatest) { if (this.panTouchStart && this.panTouchLatest) {
if (!this.touchLatest.dt) { const dt = (this.panTouchLatest.t - this.panTouchStart.t) / 1000;
if (!dt) {
this.sim.panning = undefined; this.sim.panning = undefined;
} else { } else {
const v = {...this.latestVelocity}; const v = {...this.latestPointerVelocity};
// Convert pointer velocity to simulation scale // Convert pointer velocity to simulation scale
// Also multiply by -1 because the camera is panning opposite to v.x /= this.sim.display.scale;
// the pointer velocity v.y /= this.sim.display.scale;
v.x /= -this.sim.display.scale;
v.y /= -this.sim.display.scale;
this.sim.panning = { this.sim.panning = {
velocity: v velocity: v
}; };
} }
this.touchStart = undefined; this.panTouchStart = undefined;
} }
} }
} }
@ -153,30 +147,23 @@ export class Pointer {
this.updatePointer({x: clientX, y: clientY}); this.updatePointer({x: clientX, y: clientY});
if (this.sim.isCurrentMode(MODE_MASS_GENERATION)) { if (this.sim.isCurrentMode(MODE_MASS_GENERATION)) {
// Convert pointer velocity to simulation scale
const vx = this.latestPointerVelocity.x / this.sim.display.scale;
const vy = this.latestPointerVelocity.y / this.sim.display.scale;
const {x, y} = this.sim.screenToSim(clientX, clientY); const {x, y} = this.sim.screenToSim(clientX, clientY);
this.sim.system.handlePointerMove({x, y}); this.sim.objects.handlePointerMove({x, y, vx, vy});
} else if (this.sim.isCurrentMode(MODE_PAN_VIEW)) { } else if (this.sim.isCurrentMode(MODE_PAN_VIEW)) {
if (this.touchStart) { if (this.panTouchStart) {
// Event loop should be able to read // Event loop should be able to read
this.touchLatest = { this.panTouchLatest = {
x: clientX, x: clientX,
y: clientY, y: clientY,
t: this.sim.rawTime, t: this.sim.rawTime,
dx: clientX - this.touchStart.x,
dy: clientY - this.touchStart.y,
dt: this.sim.rawTime - this.touchStart.t,
}; };
} }
} }
} }
frame() {
// Add another entry for the current pointer position
const { pointerHistory } = this.sim.pointer ?? {};
if (pointerHistory?.length) {
const currentPointer = pointerHistory[pointerHistory.length - 1];
this.sim.pointer.updatePointer(currentPointer);
}
}
} }

View File

@ -4,12 +4,10 @@ export const simOptions = {
selection: ['Pause While Selecting', 'boolean', true], selection: ['Pause While Selecting', 'boolean', true],
}, },
display: { display: {
traces: ['Path Trace', 'boolean', true],
dashedTraces: ['Dashed', 'boolean', false, {tall: true}],
velocity: ['Velocity Vector', 'boolean', true], velocity: ['Velocity Vector', 'boolean', true],
acceleration: ['Accel Vector', 'boolean', true], acceleration: ['Accel Vector', 'boolean', true],
velocityScale: ['Velocity<br>Vec Scale', 'number', 20], traces: ['Path Trace', 'boolean', true],
accelerationScale: ['Accel<br>Vec Scale', 'number', 20], dashedTraces: ['Dashed', 'boolean', false, {tall: true}],
}, },
collision: { collision: {
merge: ['Merge Masses<br>on Collision', 'boolean', true, {wide: true}], merge: ['Merge Masses<br>on Collision', 'boolean', true, {wide: true}],
@ -22,9 +20,8 @@ export const simOptions = {
}, },
debug: { debug: {
objectsInfo: ['Objects Info', 'boolean', false], objectsInfo: ['Objects Info', 'boolean', false],
aliveObjects: ['Alive Only', 'boolean', false],
cursorInfo: ['Cursor Info', 'boolean', false], cursorInfo: ['Cursor Info', 'boolean', false],
frameRate: ['Frame Rate', 'boolean', false], frameRate: ['Frame Rate', 'boolean', false, {wide: true}],
currentMode: ['Current Mode', 'boolean', false], currentMode: ['Current Mode', 'boolean', false],
panningInfo: ['Panning Info', 'boolean', false], panningInfo: ['Panning Info', 'boolean', false],
}, },

View File

@ -12,9 +12,9 @@ export function initializeTools(sim) {
sim.toolbars = { sim.toolbars = {
tools: new Toolbar(sim, 'Tools'), tools: new Toolbar(sim, 'Tools'),
modes: new Toolbar(sim, 'Modes'), modes: new Toolbar(sim, 'Modes'),
utils: new Toolbar(sim, 'Utils', { expanded: false }), utils: new Toolbar(sim, 'Utility', { expanded: false }),
options: new Toolbar(sim, 'Options'), options: new Toolbar(sim, 'Options'),
params: new Toolbar(sim, 'Params'), params: new Toolbar(sim, 'Parameters'),
debug: new Toolbar(sim, 'Debug', { expanded: false }), debug: new Toolbar(sim, 'Debug', { expanded: false }),
}; };
const { tools, modes, options, params, debug, utils } = sim.toolbars; const { tools, modes, options, params, debug, utils } = sim.toolbars;

View File

@ -1,11 +1,12 @@
import { import {
EVENT_ZOOM, EVENT_ZOOM,
FRAMERATE_SAMPLE_DURATION, FRAMERATE_SAMPLE_DURATION,
SCALE_POWER_MAX,
SCALE_POWER_MIN,
} from './config.js'; } from './config.js';
import { Display } from './display.js'; import { Display } from './display.js';
import { System } from './system.js'; import { Objects } from './objects.js';
import { Options } from './options.js'; import { Options } from './options.js';
import { Zoom } from './zoom.js';
import { simOptions } from './sim-options.js'; import { simOptions } from './sim-options.js';
import { initializeTools } from './sim-tools.js'; import { initializeTools } from './sim-tools.js';
@ -13,19 +14,16 @@ export class Sim {
info = {}; info = {};
rawTime = undefined; rawTime = undefined;
time = undefined; time = undefined;
timeScale = undefined;
nextZoom = undefined; nextZoom = undefined;
playing = true; playing = true;
recentFrames = []; recentFrames = [];
frameRate = 0; frameRate = 0;
panning = undefined;
system = undefined; objects = undefined;
display = undefined; display = undefined;
overlay = undefined; overlay = undefined;
pointer = undefined; pointer = undefined;
zoom = undefined; panning = undefined;
toolbarGroups = {}; toolbarGroups = {};
toolbars = {}; toolbars = {};
@ -33,10 +31,23 @@ export class Sim {
getCurrentMode = () => undefined; getCurrentMode = () => undefined;
setCurrentMode = () => undefined; setCurrentMode = () => undefined;
getOption = () => undefined; getOption = () => undefined;
setOption = () => undefined;
onModeEnter = () => undefined; onModeEnter = () => undefined;
onModeLeave = () => undefined; onModeLeave = () => undefined;
markFrame(t) {
const { recentFrames: rfs } = this;
rfs.push(t);
if (rfs.length < 2) return;
const oldest = rfs[0];
const newest = rfs[rfs.length - 1];
const count = rfs.length;
const duration = (newest - oldest) / 1000; // ms to s
this.frameRate = count / duration;
if (duration >= FRAMERATE_SAMPLE_DURATION) {
rfs.shift();
}
}
constructor(divId) { constructor(divId) {
this.divId = divId; this.divId = divId;
const div = document.getElementById(this.divId); const div = document.getElementById(this.divId);
@ -44,8 +55,7 @@ export class Sim {
this.options = new Options(this, simOptions); this.options = new Options(this, simOptions);
this.display = new Display(this); this.display = new Display(this);
this.system = new System(this); this.objects = new Objects(this);
this.zoom = new Zoom(this);
initializeTools(this); initializeTools(this);
@ -55,23 +65,40 @@ export class Sim {
requestAnimationFrame(t => this.loop(t)); requestAnimationFrame(t => this.loop(t));
} }
markFrame(t) { // It's better not to change the scale in the middle of possible frame calculations,
const { recentFrames: rfs } = this; // so use this to schedule it and let the event loop pick it up.
rfs.push(t);
if (rfs.length < 2) return;
const oldest = rfs[0];
const newest = rfs[rfs.length - 1];
const count = rfs.length;
const duration = (newest - oldest);
this.frameRate = 1000 * count / duration; // Converting from ms to s
if (duration >= FRAMERATE_SAMPLE_DURATION) {
rfs.shift();
}
}
// velocity should be in Sim coordinate scale // velocity should be in Sim coordinate scale
scheduleZoom({x, y}, factor, velocity) { scheduleZoom({x, y}, factor, velocity) {
this.zoom.scheduleZoom({x, y}, factor, velocity); this.nextZoom = {x, y, factor, velocity};
}
// x, y should be in Sim coordinates
// velocity should be in Sim coordinate scale
zoom({x, y, factor, velocity}) {
// x, y are the mouse coordinates, which should be the center of the new view frame
// the new view origin should be x, y minus half the new view width and height
// compute new scale
this.display.scalePower += factor;
// TODO: Lossy rescaling to expand zoom range
if (this.display.scalePower > SCALE_POWER_MAX) this.display.scalePower = SCALE_POWER_MAX;
if (this.display.scalePower < SCALE_POWER_MIN) this.display.scalePower = SCALE_POWER_MIN;
// compute coordinates of new view frame
this.display.viewOrigin.x = x - this.display.width / 2;
this.display.viewOrigin.y = y - this.display.height / 2;
this.pointer.clearPointerHistory();
if (this.playing && velocity) {
this.panning = {
velocity: {
x: -velocity.x,
y: -velocity.y,
}
};
}
const e = new CustomEvent(EVENT_ZOOM);
this.div.dispatchEvent(e);
} }
// Transform display coordinates to simulator coordinates using scale and viewOrigin // Transform display coordinates to simulator coordinates using scale and viewOrigin
@ -89,8 +116,7 @@ export class Sim {
getScaleDisplay() { getScaleDisplay() {
const scale = 2 ** Math.abs(this.display.scalePower); const scale = 2 ** Math.abs(this.display.scalePower);
const scaleText = this.display.scalePower >= 0 ? `${scale}` : `1/${scale}`; return this.display.scalePower >= 0 ? `${scale}` : `1/${scale}`;
return `${scaleText} (${this.display.scalePower})`;
} }
// cb: () => undefined // cb: () => undefined
@ -103,9 +129,11 @@ export class Sim {
// Main loop // Main loop
loop(currentTime) { loop(currentTime) {
this.markFrame(currentTime); this.markFrame(currentTime);
this.timeScale = this.getOption('param.timeScale'); const timeScale = this.getOption('param.timeScale');
const elapsedTime = (currentTime - this.rawTime) * this.timeScale; // elapsedTime in milliseconds
// rawTime in milliseconds
const elapsedTime = (currentTime - this.rawTime) / timeScale;
this.rawTime = currentTime; this.rawTime = currentTime;
if (this.playing) { if (this.playing) {
@ -120,14 +148,27 @@ export class Sim {
this.info['Frame Rate'] = this.frameRate?.toPrecision(3); this.info['Frame Rate'] = this.frameRate?.toPrecision(3);
} }
this.zoom.frame(); if (this.nextZoom) {
this.display.frame(elapsedTime); this.zoom(this.nextZoom);
this.system.frame(elapsedTime); this.nextZoom = undefined;
this.overlay.frame(); }
if (this.getOption('debug.panningInfo')) {
const {x, y} = this.panning?.velocity ?? {};
this.info['Panning Velocity'] = [`${x?.toPrecision(6)}, `, y?.toPrecision(6)];
const { centerOfMass } = this.objects.computeSystemCenter();
this.info['Center of Mass'] = [`${centerOfMass.x.toPrecision(6)}, `, centerOfMass.y.toPrecision(6)];
this.info['Net Angular Momentum'] = this.objects.computeSystemAngularMomentum().toPrecision(6);
}
this.objects.computeFrame(elapsedTime);
this.overlay.renderInfo();
// this.display.computePanning(elapsedTime);
this.display.fillCanvas();
this.display.drawObjects();
for (const group in this.toolbarGroups) { for (const group in this.toolbarGroups) {
this.toolbarGroups[group].frame(); this.toolbarGroups[group].frame();
} }
requestAnimationFrame(t => this.loop(t)); requestAnimationFrame(t => this.loop(t));
} }
} }

View File

@ -43,11 +43,18 @@ export class OptionsTool extends Tool {
const value = this.sim.getOption(path); const value = this.sim.getOption(path);
button.style.opacity = value ? '100%' : '50%'; button.style.opacity = value ? '100%' : '50%';
this.sim.onOptionSet(path, value => { this.sim.onOptionSet(path, value => {
console.log('option set cb', path, value);
button.style.opacity = value ? '100%' : '50%'; button.style.opacity = value ? '100%' : '50%';
console.log('button opacity', button.style.opacity);
});
button.addEventListener('click', () => {
const value = this.sim.options.getOption(path, true);
console.log('click, option value', value);
this.sim.setOption(path, !value);
}); });
button.addEventListener('click', () => { button.addEventListener('click', () => {
const value = this.sim.getOption(path); const value = this.sim.getOption(path);
this.sim.setOption(path, !value); this.setOption(path, !value);
}); });
return button; return button;
} }

View File

@ -7,6 +7,10 @@ import {
export class UtilityTool extends Tool { export class UtilityTool extends Tool {
currentTimeEl = undefined; currentTimeEl = undefined;
get displayScaleText() {
return `Scale: ${this.sim.getScaleDisplay()}`;
}
get timeText() { get timeText() {
let time = this.sim.time; let time = this.sim.time;
// Time in milliseconds // Time in milliseconds
@ -41,37 +45,50 @@ export class UtilityTool extends Tool {
const zeroVelocity = document.createElement('button'); const zeroVelocity = document.createElement('button');
const clearTraces = document.createElement('button'); const clearTraces = document.createElement('button');
const zoomAll = document.createElement('button');
const currentScale = document.createElement('button')
const currentTime = document.createElement('button'); const currentTime = document.createElement('button');
const clearDebug = document.createElement('button'); const clearDebug = document.createElement('button');
this.currentTimeEl = currentTime; this.currentTimeEl = currentTime;
this.div.appendChild(currentTime); this.div.appendChild(currentTime);
this.div.appendChild(currentScale);
this.div.appendChild(zoomAll);
this.div.appendChild(zeroVelocity); this.div.appendChild(zeroVelocity);
this.div.appendChild(clearTraces); this.div.appendChild(clearTraces);
this.div.appendChild(clearDebug); this.div.appendChild(clearDebug);
zeroVelocity.classList.add(WIDE_CLASSNAME); zeroVelocity.classList.add(WIDE_CLASSNAME);
clearTraces.classList.add(WIDE_CLASSNAME); clearTraces.classList.add(WIDE_CLASSNAME);
zoomAll.classList.add(WIDE_CLASSNAME);
currentScale.classList.add(WIDE_CLASSNAME);
currentScale.classList.add(TOOL_INFO_CLASSNAME);
currentTime.classList.add(TOOL_INFO_CLASSNAME); currentTime.classList.add(TOOL_INFO_CLASSNAME);
currentTime.classList.add(WIDE_CLASSNAME); currentTime.classList.add(WIDE_CLASSNAME);
clearDebug.classList.add(WIDE_CLASSNAME); clearDebug.classList.add(WIDE_CLASSNAME);
zeroVelocity.innerHTML = 'Zero Momentum'; zeroVelocity.innerHTML = 'Zero Momentum';
clearTraces.innerHTML = 'Clear Traces'; clearTraces.innerHTML = 'Clear Traces';
zoomAll.innerHTML = 'Zoom to Fit';
currentScale.innerHTML = this.displayScaleText;
currentTime.innerHTML = this.timeText; currentTime.innerHTML = this.timeText;
clearDebug.innerHTML = 'Clear Debug'; clearDebug.innerHTML = 'Clear Debug';
this.sim.onZoom(() => {
currentScale.innerHTML = this.displayScaleText;
});
zeroVelocity.addEventListener('click', () => { zeroVelocity.addEventListener('click', () => {
// Determine center of mass and average momentum // Determine center of mass and average momentum
const { totalMass, netMomentum } = this.sim.system.computeSystemCenter(); const { totalMass, netMomentum } = this.sim.objects.computeSystemCenter();
const netVelocity = { const netVelocity = {
x: netMomentum.x / totalMass, x: netMomentum.x / totalMass,
y: netMomentum.y / totalMass, y: netMomentum.y / totalMass,
}; };
// Apply offset to all object velocities // Apply offset to all object velocities
this.sim.system.forEachObject(obj => { this.sim.objects.forEachObject(obj => {
obj.velocity.x -= netVelocity.x; obj.velocity.x -= netVelocity.x;
obj.velocity.y -= netVelocity.y; obj.velocity.y -= netVelocity.y;
}); });
@ -82,11 +99,41 @@ export class UtilityTool extends Tool {
clearTraces.addEventListener('click', () => { clearTraces.addEventListener('click', () => {
// Obliterate object histories // Obliterate object histories
this.sim.system.forEachObject(obj => { this.sim.objects.forEachObject(obj => {
obj.history = []; obj.history = [];
}, {alive: null}); }, {alive: null});
}); });
zoomAll.addEventListener('click', () => {
// Determine bounding box
const box = this.sim.objects.boundingBox;
const x = (box.start.x + box.end.x) / 2;
const y = (box.start.y + box.end.y) / 2;
const widthRatio = Math.abs(box.start.x - box.end.x) / this.sim.display.width;
const heightRatio = Math.abs(box.start.y - box.end.y) / this.sim.display.height;
const biggerRatio = Math.max(widthRatio, heightRatio);
const base2factor = Math.log(1/biggerRatio) / Math.log(2) - 0.5;
const factor = Math.floor(base2factor);
// Determine average momentum and set panning velocity to match
const netMomentum = {x: 0, y: 0};
let totalMass = 0;
let count = 0;
this.sim.objects.forEachObject(obj => {
count++;
netMomentum.x += obj.mass * obj.velocity.x;
netMomentum.y += obj.mass * obj.velocity.y;
totalMass += obj.mass;
});
if (!count) {
return;
}
const netVelocity = {
x: netMomentum.x / totalMass,
y: netMomentum.y / totalMass,
};
this.sim.scheduleZoom({x, y}, factor, netVelocity)
});
clearDebug.addEventListener('click', () => { clearDebug.addEventListener('click', () => {
this.sim.info = {}; this.sim.info = {};
}); });

View File

@ -2,42 +2,20 @@ import { Tool } from '../tool.js';
import { import {
ZOOM_IN_FACTOR, ZOOM_IN_FACTOR,
ZOOM_OUT_FACTOR, ZOOM_OUT_FACTOR,
WIDE_CLASSNAME,
TALL_CLASSNAME,
TOOL_INFO_CLASSNAME,
} from '../config.js'; } from '../config.js';
export class Zoom extends Tool { export class Zoom extends Tool {
get displayScaleText() {
return `Scale: ${this.sim.getScaleDisplay()}`;
}
constructor(container) { constructor(container) {
super(container); super(container);
const currentScale = document.createElement('button')
const zoomOut = document.createElement('button'); const zoomOut = document.createElement('button');
const zoomIn = document.createElement('button'); const zoomIn = document.createElement('button');
const zoomAll = document.createElement('button');
this.div.appendChild(currentScale);
this.div.appendChild(zoomOut); this.div.appendChild(zoomOut);
this.div.appendChild(zoomIn); this.div.appendChild(zoomIn);
this.div.appendChild(zoomAll);
currentScale.classList.add(WIDE_CLASSNAME);
currentScale.classList.add(TOOL_INFO_CLASSNAME);
zoomAll.classList.add(WIDE_CLASSNAME);
zoomAll.classList.add(TALL_CLASSNAME);
currentScale.innerHTML = this.displayScaleText;
zoomOut.innerHTML = 'Zoom<br>Out'; zoomOut.innerHTML = 'Zoom<br>Out';
zoomIn.innerHTML = 'Zoom<br>In'; zoomIn.innerHTML = 'Zoom<br>In';
zoomAll.innerHTML = 'Zoom to Fit';
this.sim.onZoom(() => {
currentScale.innerHTML = this.displayScaleText;
});
zoomOut.addEventListener('click', () => { zoomOut.addEventListener('click', () => {
// Aim at center of view // Aim at center of view
@ -52,25 +30,5 @@ export class Zoom extends Tool {
const y = this.sim.display.height * this.sim.display.scale / 2; const y = this.sim.display.height * this.sim.display.scale / 2;
this.sim.scheduleZoom(this.sim.screenToSim(x, y), ZOOM_IN_FACTOR); this.sim.scheduleZoom(this.sim.screenToSim(x, y), ZOOM_IN_FACTOR);
}); });
zoomAll.addEventListener('click', () => {
// Determine bounding box
const box = this.sim.system.boundingBox;
const x = (box.start.x + box.end.x) / 2;
const y = (box.start.y + box.end.y) / 2;
const widthRatio = Math.abs(box.start.x - box.end.x) / this.sim.display.width;
const heightRatio = Math.abs(box.start.y - box.end.y) / this.sim.display.height;
const biggerRatio = Math.max(widthRatio, heightRatio);
const base2factor = Math.log2(1 / biggerRatio) - 1;
const factor = Math.ceil(base2factor);
// Determine average momentum and set panning velocity to match
const { netMomentum, totalMass } = this.sim.system.computeSystemCenter();
const netVelocity = {
x: netMomentum.x / totalMass,
y: netMomentum.y / totalMass,
};
this.sim.scheduleZoom({x, y}, factor, netVelocity)
});
} }
} }

58
zoom.js
View File

@ -1,58 +0,0 @@
import {
EVENT_ZOOM,
SCALE_POWER_MAX,
SCALE_POWER_MIN,
} from './config.js';
export class Zoom {
sim = undefined;
nextZoom = undefined;
constructor(sim) {
this.sim = sim;
}
// velocity should be in Sim coordinate scale
scheduleZoom({x, y}, factor, velocity) {
this.nextZoom = {x, y, factor, velocity};
}
frame() {
if (this.nextZoom) {
this.zoom(this.nextZoom);
this.nextZoom = undefined;
}
}
// x, y should be in Sim coordinates
// velocity should be in Sim coordinate scale
zoom({x, y, factor, velocity}) {
const { display } = this.sim;
// x, y are the mouse coordinates, which should be the center of the new view frame
// the new view origin should be x, y minus half the new view width and height
// compute new scale
// TODO: Lossy rescaling to expand zoom range
let scalePower = display.scalePower + factor;
scalePower = Math.max(scalePower, SCALE_POWER_MIN);
scalePower = Math.min(scalePower, SCALE_POWER_MAX);
this.sim.display.scalePower = scalePower;
// compute coordinates of new view frame
display.viewOrigin.x = x - display.width / 2;
display.viewOrigin.y = y - display.height / 2;
// Pointer history is stored in client coordinates, so we shouldn't need to clear it?
// this.pointer.clearPointerHistory();
// TODO: If paused, set panning velocity on resume
if (this.sim.playing && velocity) {
this.sim.panning = {
velocity: { ...velocity }
};
}
const e = new CustomEvent(EVENT_ZOOM);
this.sim.div.dispatchEvent(e);
}
}