less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

4433 строки
135 KiB

  1. let selected = null;
  2. let prevSelected = null;
  3. let selectedEntity = null;
  4. let prevSelectedEntity = null;
  5. let entityIndex = 0;
  6. let clicked = null;
  7. let movingInBounds = false;
  8. let dragging = false;
  9. let clickTimeout = null;
  10. let dragOffsetX = null;
  11. let dragOffsetY = null;
  12. let preloaded = new Set();
  13. let panning = false;
  14. let panReady = true;
  15. let panOffsetX = null;
  16. let panOffsetY = null;
  17. let shiftHeld = false;
  18. let altHeld = false;
  19. let entityX;
  20. let canvasWidth;
  21. let canvasHeight;
  22. let dragScale = 1;
  23. let dragScaleHandle = null;
  24. let dragEntityScale = 1;
  25. let dragEntityScaleHandle = null;
  26. let scrollDirection = 0;
  27. let scrollHandle = null;
  28. let zoomDirection = 0;
  29. let zoomHandle = null;
  30. let sizeDirection = 0;
  31. let sizeHandle = null;
  32. let worldSizeDirty = false;
  33. let rulerMode = false;
  34. let rulers = [];
  35. let currentRuler = undefined;
  36. const tagDefs = {
  37. "anthro": "Anthro",
  38. "feral": "Feral",
  39. "taur": "Taur",
  40. "naga": "Naga",
  41. "goo": "Goo"
  42. }
  43. math.createUnit("humans", {
  44. definition: "5.75 feet"
  45. });
  46. math.createUnit("story", {
  47. definition: "12 feet",
  48. prefixes: "long"
  49. });
  50. math.createUnit("stories", {
  51. definition: "12 feet",
  52. prefixes: "long"
  53. });
  54. math.createUnit("buses", {
  55. definition: "11.95 meters",
  56. prefixes: "long"
  57. });
  58. math.createUnit("marathons", {
  59. definition: "26.2 miles",
  60. prefixes: "long"
  61. });
  62. math.createUnit("earths", {
  63. definition: "12756km",
  64. prefixes: "long"
  65. });
  66. math.createUnit("lightsecond", {
  67. definition: "299792458 meters",
  68. prefixes: "long"
  69. });
  70. math.createUnit("lightseconds", {
  71. definition: "299792458 meters",
  72. prefixes: "long"
  73. });
  74. math.createUnit("parsec", {
  75. definition: "3.086e16 meters",
  76. prefixes: "long"
  77. })
  78. math.createUnit("parsecs", {
  79. definition: "3.086e16 meters",
  80. prefixes: "long"
  81. })
  82. math.createUnit("lightyears", {
  83. definition: "9.461e15 meters",
  84. prefixes: "long"
  85. })
  86. math.createUnit("AU", {
  87. definition: "149597870700 meters"
  88. })
  89. math.createUnit("AUs", {
  90. definition: "149597870700 meters"
  91. })
  92. math.createUnit("dalton", {
  93. definition: "1.66e-27 kg",
  94. prefixes: "long"
  95. });
  96. math.createUnit("daltons", {
  97. definition: "1.66e-27 kg",
  98. prefixes: "long"
  99. });
  100. math.createUnit("solarradii", {
  101. definition: "695990 km",
  102. prefixes: "long"
  103. });
  104. math.createUnit("solarmasses", {
  105. definition: "2e30 kg",
  106. prefixes: "long"
  107. });
  108. math.createUnit("galaxy", {
  109. definition: "105700 lightyears",
  110. prefixes: "long"
  111. });
  112. math.createUnit("galaxies", {
  113. definition: "105700 lightyears",
  114. prefixes: "long"
  115. });
  116. math.createUnit("universe", {
  117. definition: "93.016e9 lightyears",
  118. prefixes: "long"
  119. });
  120. math.createUnit("universes", {
  121. definition: "93.016e9 lightyears",
  122. prefixes: "long"
  123. });
  124. math.createUnit("multiverse", {
  125. definition: "1e30 lightyears",
  126. prefixes: "long"
  127. });
  128. math.createUnit("multiverses", {
  129. definition: "1e30 lightyears",
  130. prefixes: "long"
  131. });
  132. math.createUnit("footballFields", {
  133. definition: "57600 feet^2",
  134. prefixes: "long"
  135. });
  136. math.createUnit("people", {
  137. definition: "75 liters",
  138. prefixes: "long"
  139. });
  140. math.createUnit("olympicPools", {
  141. definition: "2500 m^3",
  142. prefixes: "long"
  143. });
  144. math.createUnit("oceans", {
  145. definition: "700000000 km^3",
  146. prefixes: "long"
  147. });
  148. math.createUnit("earthVolumes", {
  149. definition: "1.0867813e12 km^3",
  150. prefixes: "long"
  151. });
  152. math.createUnit("universeVolumes", {
  153. definition: "4.2137775e+32 lightyears^3",
  154. prefixes: "long"
  155. });
  156. math.createUnit("multiverseVolumes", {
  157. definition: "5.2359878e+89 lightyears^3",
  158. prefixes: "long"
  159. });
  160. math.createUnit("peopleMass", {
  161. definition: "80 kg",
  162. prefixes: "long"
  163. });
  164. math.createUnit("cars", {
  165. definition: "1250kg",
  166. prefixes: "long"
  167. });
  168. math.createUnit("busMasses", {
  169. definition: "15000kg",
  170. prefixes: "long"
  171. });
  172. math.createUnit("earthMass", {
  173. definition: "5.97e24 kg",
  174. prefixes: "long"
  175. });
  176. math.createUnit("kcal", {
  177. definition: "4184 joules",
  178. prefixes: "long"
  179. })
  180. math.createUnit("foodPounds", {
  181. definition: "867 kcal",
  182. prefixes: "long"
  183. })
  184. math.createUnit("foodKilograms", {
  185. definition: "1909 kcal",
  186. prefixes: "long"
  187. })
  188. math.createUnit("peopleEaten", {
  189. definition: "125000 kcal",
  190. prefixes: "long"
  191. })
  192. math.createUnit("barn", {
  193. definition: "10e-28 m^2",
  194. prefixes: "long"
  195. })
  196. math.createUnit("barns", {
  197. definition: "10e-28 m^2",
  198. prefixes: "long"
  199. })
  200. math.createUnit("points", {
  201. definition: "0.013888888888888888888888888 inches",
  202. prefixes: "long"
  203. })
  204. math.createUnit("beardSeconds", {
  205. definition: "10 nanometers",
  206. prefixes: "long"
  207. })
  208. math.createUnit("smoots", {
  209. definition: "5.5833333 feet",
  210. prefixes: "long"
  211. })
  212. math.createUnit("furlongs", {
  213. definition: "660 feet",
  214. prefixes: "long"
  215. })
  216. math.createUnit("nanoacres", {
  217. definition: "1e-9 acres",
  218. prefixes: "long"
  219. })
  220. math.createUnit("barnMegaparsecs", {
  221. definition: "barn megaparsec",
  222. prefixes: "long"
  223. })
  224. math.createUnit("firkins", {
  225. definition: "90 lb",
  226. prefixes: "long"
  227. })
  228. math.createUnit("donkeySeconds", {
  229. definition: "250 joules",
  230. prefixes: "long"
  231. })
  232. const defaultUnits = {
  233. length: {
  234. metric: "meters",
  235. customary: "feet",
  236. relative: "stories",
  237. quirky: "smoots"
  238. },
  239. area: {
  240. metric: "meters^2",
  241. customary: "feet^2",
  242. relative: "footballFields",
  243. quirky: "nanoacres"
  244. },
  245. volume: {
  246. metric: "liters",
  247. customary: "gallons",
  248. relative: "olympicPools",
  249. volume: "barnmegaparsecs"
  250. },
  251. mass: {
  252. metric: "kilograms",
  253. customary: "lbs",
  254. relative: "peopleMass",
  255. quirky: "firkins"
  256. },
  257. energy: {
  258. metric: "kJ",
  259. customary: "kcal",
  260. relative: "peopleEaten",
  261. quirky: "donkeySeconds"
  262. }
  263. }
  264. const unitChoices = {
  265. length: {
  266. "metric": [
  267. "angstroms",
  268. "millimeters",
  269. "centimeters",
  270. "meters",
  271. "kilometers",
  272. ],
  273. "customary": [
  274. "inches",
  275. "feet",
  276. "miles",
  277. ],
  278. "relative": [
  279. "humans",
  280. "stories",
  281. "buses",
  282. "marathons",
  283. "earths",
  284. "lightseconds",
  285. "solarradii",
  286. "AUs",
  287. "lightyears",
  288. "parsecs",
  289. "galaxies",
  290. "universes",
  291. "multiverses"
  292. ],
  293. "quirky": [
  294. "beardSeconds",
  295. "points",
  296. "smoots",
  297. "furlongs"
  298. ]
  299. },
  300. area: {
  301. "metric": [
  302. "cm^2",
  303. "meters^2",
  304. "kilometers^2",
  305. ],
  306. "customary": [
  307. "feet^2",
  308. "acres",
  309. "miles^2"
  310. ],
  311. "relative": [
  312. "footballFields"
  313. ],
  314. "quirky": [
  315. "barns",
  316. "nanoacres"
  317. ]
  318. },
  319. volume: {
  320. "metric": [
  321. "milliliters",
  322. "liters",
  323. "m^3",
  324. ],
  325. "customary": [
  326. "floz",
  327. "cups",
  328. "pints",
  329. "quarts",
  330. "gallons",
  331. ],
  332. "relative": [
  333. "people",
  334. "olympicPools",
  335. "oceans",
  336. "earthVolumes",
  337. "universeVolumes",
  338. "multiverseVolumes",
  339. ],
  340. "quirky": [
  341. "barnMegaparsecs"
  342. ]
  343. },
  344. mass: {
  345. "metric": [
  346. "kilograms",
  347. "milligrams",
  348. "grams",
  349. "tonnes",
  350. ],
  351. "customary": [
  352. "lbs",
  353. "ounces",
  354. "tons"
  355. ],
  356. "relative": [
  357. "peopleMass",
  358. "cars",
  359. "busMasses",
  360. "earthMass",
  361. "solarmasses"
  362. ],
  363. "quirky": [
  364. "firkins"
  365. ]
  366. },
  367. energy: {
  368. "metric": [
  369. "kJ",
  370. "foodKilograms"
  371. ],
  372. "customary": [
  373. "kcal",
  374. "foodPounds"
  375. ],
  376. "relative": [
  377. "peopleEaten"
  378. ],
  379. "quirky": [
  380. "donkeySeconds"
  381. ]
  382. }
  383. }
  384. const config = {
  385. height: math.unit(1500, "meters"),
  386. x: 0,
  387. y: 0,
  388. minLineSize: 100,
  389. maxLineSize: 150,
  390. autoFit: false,
  391. drawYAxis: true,
  392. drawXAxis: false,
  393. autoFoodIntake: false,
  394. autoPreyCapacity: false
  395. }
  396. const availableEntities = {
  397. }
  398. const availableEntitiesByName = {
  399. }
  400. const entities = {
  401. }
  402. function constrainRel(coords) {
  403. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  404. const worldHeight = config.height.toNumber("meters");
  405. if (altHeld) {
  406. return coords;
  407. }
  408. return {
  409. x: Math.min(Math.max(coords.x, -worldWidth / 2 + config.x), worldWidth / 2 + config.x),
  410. y: Math.min(Math.max(coords.y, config.y), worldHeight + config.y)
  411. }
  412. }
  413. function snapPos(coords) {
  414. return constrainRel({
  415. x: coords.x,
  416. y: (!config.lockYAxis || altHeld) ? coords.y : (Math.abs(coords.y) < config.height.toNumber("meters")/20 ? 0 : coords.y)
  417. });
  418. }
  419. function adjustAbs(coords, oldHeight, newHeight) {
  420. const ratio = math.divide(newHeight, oldHeight);
  421. const x = (coords.x - config.x) * ratio + config.x;
  422. const y = (coords.y - config.y) * ratio + config.y;
  423. return { x: x, y: y};
  424. }
  425. function pos2pix(coords) {
  426. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  427. const worldHeight = config.height.toNumber("meters");
  428. const x = ((coords.x - config.x) / worldWidth + 0.5) * (canvasWidth - 50) + 50;
  429. const y = (1 - (coords.y - config.y) / worldHeight) * (canvasHeight - 50) + 50;
  430. return { x: x, y: y };
  431. }
  432. function pix2pos(coords) {
  433. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  434. const worldHeight = config.height.toNumber("meters");
  435. const x = (((coords.x - 50) / (canvasWidth - 50)) - 0.5) * worldWidth + config.x;
  436. const y = (1 - ((coords.y - 50) / (canvasHeight - 50))) * worldHeight + config.y;
  437. return { x: x, y: y };
  438. }
  439. function updateEntityElement(entity, element) {
  440. const position = pos2pix({ x: element.dataset.x, y: element.dataset.y });
  441. const view = entity.view;
  442. element.style.left = position.x + "px";
  443. element.style.top = position.y + "px";
  444. element.style.setProperty("--xpos", position.x + "px");
  445. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  446. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  447. const extra = entity.views[view].image.extra;
  448. const bottom = entity.views[view].image.bottom;
  449. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  450. let height = pixels * bonus;
  451. // working around a Firefox bug here
  452. if (height > 17895698) {
  453. height = 0;
  454. }
  455. element.style.setProperty("--height", height + "px");
  456. element.style.setProperty("--extra", height - pixels + "px");
  457. element.style.setProperty("--brightness", entity.brightness);
  458. if (entity.views[view].rename)
  459. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  460. else
  461. element.querySelector(".entity-name").innerText = entity.name;
  462. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  463. bottomName.style.left = position.x + entityX + "px";
  464. bottomName.style.bottom = "0vh";
  465. bottomName.innerText = entity.name;
  466. const topName = document.querySelector("#top-name-" + element.dataset.key);
  467. topName.style.left = position.x + entityX + "px";
  468. topName.style.top = "20vh";
  469. topName.innerText = entity.name;
  470. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  471. topName.classList.add("top-name-needed");
  472. } else {
  473. topName.classList.remove("top-name-needed");
  474. }
  475. }
  476. function updateRatios() {
  477. if (config.showRatios) {
  478. if (selectedEntity !== null && prevSelectedEntity !== null && selectedEntity !== prevSelectedEntity) {
  479. let first = selectedEntity.currentView.height;
  480. let second = prevSelectedEntity.currentView.height;
  481. let text = ""
  482. if (first.toNumber("meters") < second.toNumber("meters")) {
  483. text += selectedEntity.name + " is " + math.format(math.divide(second, first), { precision: 5 }) + " times smaller than " + prevSelectedEntity.name;
  484. } else {
  485. text += selectedEntity.name + " is " + math.format(math.divide(first, second), { precision: 5 })+ " times taller than " + prevSelectedEntity.name;
  486. }
  487. text += "\n";
  488. let apparentHeight = math.multiply(math.divide(second, first), math.unit(6, "feet"));
  489. if (config.units === "metric") {
  490. apparentHeight = apparentHeight.to("meters");
  491. }
  492. text += prevSelectedEntity.name + " looks " + math.format(apparentHeight, { precision: 3}) + " tall to " + selectedEntity.name;
  493. document.querySelector(".ratio-info").innerText = text;
  494. } else {
  495. document.querySelector(".ratio-info").innerText = "";
  496. }
  497. }
  498. }
  499. function updateSizes(dirtyOnly = false) {
  500. updateRatios();
  501. if (config.lockYAxis) {
  502. config.y = 0;
  503. }
  504. drawScales(dirtyOnly);
  505. let ordered = Object.entries(entities);
  506. ordered.sort((e1, e2) => {
  507. if (e1[1].priority != e2[1].priority) {
  508. return e2[1].priority - e1[1].priority;
  509. } else {
  510. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  511. }
  512. });
  513. let zIndex = ordered.length;
  514. ordered.forEach(entity => {
  515. const element = document.querySelector("#entity-" + entity[0]);
  516. element.style.zIndex = zIndex;
  517. if (!dirtyOnly || entity[1].dirty) {
  518. updateEntityElement(entity[1], element, zIndex);
  519. entity[1].dirty = false;
  520. }
  521. zIndex -= 1;
  522. });
  523. document.querySelector("#ground").style.top = pos2pix({x: 0, y: 0}).y + "px";
  524. drawRulers();
  525. }
  526. function drawRulers() {
  527. const canvas = document.querySelector("#rulers");
  528. /** @type {CanvasRenderingContext2D} */
  529. const ctx = canvas.getContext("2d");
  530. const deviceScale = window.devicePixelRatio;
  531. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  532. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  533. ctx.scale(deviceScale, deviceScale);
  534. rulers.concat(currentRuler ? [currentRuler] : []).forEach(rulerDef => {
  535. ctx.save();
  536. ctx.beginPath();
  537. const start = pos2pix({x: rulerDef.x0, y: rulerDef.y0});
  538. const end = pos2pix({x: rulerDef.x1, y: rulerDef.y1});
  539. ctx.moveTo(start.x, start.y);
  540. ctx.lineTo(end.x, end.y);
  541. ctx.lineWidth = 5;
  542. ctx.strokeStyle = "#f2f";
  543. ctx.stroke();
  544. const center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 };
  545. ctx.fillStyle = "#eeeeee";
  546. ctx.font = 'normal 24pt coda';
  547. ctx.translate(center.x, center.y);
  548. let angle = Math.atan2(end.y - start.y, end.x - start.x);
  549. if (angle < -Math.PI/2) {
  550. angle += Math.PI;
  551. }
  552. if (angle > Math.PI/2) {
  553. angle -= Math.PI;
  554. }
  555. ctx.rotate(angle);
  556. const offsetX = Math.cos(angle + Math.PI/2);
  557. const offsetY = Math.sin(angle + Math.PI/2);
  558. const distance = Math.sqrt(Math.pow(rulerDef.y1 - rulerDef.y0, 2) + Math.pow(rulerDef.x1 - rulerDef.x0, 2));
  559. const distanceInUnits = math.unit(distance, "meters").to(document.querySelector("#options-height-unit").value);
  560. const textSize = ctx.measureText(distanceInUnits.format({ precision: 3}));
  561. ctx.fillText(distanceInUnits.format({ precision: 3}), -offsetX * 10 - textSize.width / 2, -offsetY*10);
  562. ctx.restore();
  563. });
  564. }
  565. function drawScales(ifDirty = false) {
  566. const canvas = document.querySelector("#display");
  567. /** @type {CanvasRenderingContext2D} */
  568. const ctx = canvas.getContext("2d");
  569. const deviceScale = window.devicePixelRatio;
  570. ctx.canvas.width = Math.floor(canvas.clientWidth * deviceScale);
  571. ctx.canvas.height = Math.floor(canvas.clientHeight * deviceScale);
  572. ctx.scale(deviceScale, deviceScale);
  573. ctx.beginPath();
  574. ctx.rect(0, 0, canvas.width, canvas.height);
  575. ctx.fillStyle = "#333";
  576. ctx.fill();
  577. if (config.drawYAxis || config.drawAltitudes !== "none") {
  578. drawVerticalScale(ifDirty);
  579. }
  580. if (config.drawXAxis) {
  581. drawHorizontalScale(ifDirty);
  582. }
  583. }
  584. function drawVerticalScale(ifDirty = false) {
  585. if (ifDirty && !worldSizeDirty)
  586. return;
  587. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  588. let total = heightPer.clone();
  589. total.value = config.y;
  590. let y = ctx.canvas.clientHeight - 50;
  591. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  592. y += offset / heightPer.toNumber("meters") * pixelsPer;
  593. total = math.subtract(total, math.unit(offset, "meters"));
  594. for (; y >= 50; y -= pixelsPer) {
  595. drawTick(ctx, 50, y, total.format({ precision: 3 }));
  596. total = math.add(total, heightPer);
  597. }
  598. }
  599. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label, flipped=false) {
  600. const oldStroke = ctx.strokeStyle;
  601. const oldFill = ctx.fillStyle;
  602. ctx.beginPath();
  603. ctx.moveTo(x, y);
  604. ctx.lineTo(x + 20, y);
  605. ctx.strokeStyle = "#000000";
  606. ctx.stroke();
  607. ctx.beginPath();
  608. ctx.moveTo(x + 20, y);
  609. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  610. if (flipped) {
  611. ctx.strokeStyle = "#666666";
  612. } else {
  613. ctx.strokeStyle = "#aaaaaa";
  614. }
  615. ctx.stroke();
  616. ctx.beginPath();
  617. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  618. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  619. ctx.strokeStyle = "#000000";
  620. ctx.stroke();
  621. const oldFont = ctx.font;
  622. ctx.font = 'normal 24pt coda';
  623. ctx.fillStyle = "#dddddd";
  624. ctx.beginPath();
  625. if (flipped) {
  626. ctx.textAlign = "end";
  627. ctx.fillText(label, ctx.canvas.clientWidth - 70, y + 35)
  628. } else {
  629. ctx.fillText(label, x + 20, y + 35);
  630. }
  631. ctx.textAlign = "start";
  632. ctx.font = oldFont;
  633. ctx.strokeStyle = oldStroke;
  634. ctx.fillStyle = oldFill;
  635. }
  636. function drawAltitudeLine(ctx, height, label) {
  637. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber("meters");
  638. const y = ctx.canvas.clientHeight - 50 - (height.toNumber("meters") - config.y) * pixelScale;
  639. if (y < ctx.canvas.clientHeight - 100) {
  640. drawTick(ctx, 50, y, label, true);
  641. }
  642. }
  643. const canvas = document.querySelector("#display");
  644. /** @type {CanvasRenderingContext2D} */
  645. const ctx = canvas.getContext("2d");
  646. const pixelScale = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  647. let pixelsPer = pixelScale;
  648. heightPer = 1;
  649. if (pixelsPer < config.minLineSize) {
  650. const factor = math.ceil(config.minLineSize / pixelsPer);
  651. heightPer *= factor;
  652. pixelsPer *= factor;
  653. }
  654. if (pixelsPer > config.maxLineSize) {
  655. const factor = math.ceil(pixelsPer / config.maxLineSize);
  656. heightPer /= factor;
  657. pixelsPer /= factor;
  658. }
  659. if (heightPer == 0) {
  660. console.error("The world size is invalid! Refusing to draw the scale...");
  661. return;
  662. }
  663. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  664. ctx.beginPath();
  665. ctx.moveTo(50, 50);
  666. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  667. ctx.stroke();
  668. ctx.beginPath();
  669. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  670. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  671. ctx.stroke();
  672. if (config.drawYAxis) {
  673. drawTicks(ctx, pixelsPer, heightPer);
  674. }
  675. if (config.drawAltitudes == "atmosphere" || config.drawAltitudes == "all") {
  676. drawAltitudeLine(ctx, math.unit(8, "km"), "Troposphere");
  677. drawAltitudeLine(ctx, math.unit(17.5, "km"), "Ozone Layer");
  678. drawAltitudeLine(ctx, math.unit(50, "km"), "Stratosphere");
  679. drawAltitudeLine(ctx, math.unit(85, "km"), "Mesosphere");
  680. drawAltitudeLine(ctx, math.unit(675, "km"), "Thermosphere");
  681. drawAltitudeLine(ctx, math.unit(10000, "km"), "Exosphere");
  682. }
  683. if (config.drawAltitudes == "orbits" || config.drawAltitudes == "all") {
  684. drawAltitudeLine(ctx, math.unit(7, "miles"), "Cruising Altitude");
  685. drawAltitudeLine(ctx, math.unit(100, "km"), "Edge of Space (Kármán line)");
  686. drawAltitudeLine(ctx, math.unit(211.3, "miles"), "Space Station");
  687. drawAltitudeLine(ctx, math.unit(369.7, "miles"), "Hubble Telescope");
  688. drawAltitudeLine(ctx, math.unit(1500, "km"), "Low Earth Orbit");
  689. drawAltitudeLine(ctx, math.unit(20350, "km"), "GPS Satellites");
  690. drawAltitudeLine(ctx, math.unit(35786, "km"), "Geosynchronous Orbit");
  691. drawAltitudeLine(ctx, math.unit(238900, "miles"), "Lunar Orbit");
  692. drawAltitudeLine(ctx, math.unit(57.9e6, "km"), "Orbit of Mercury");
  693. drawAltitudeLine(ctx, math.unit(108.2e6, "km"), "Orbit of Venus");
  694. drawAltitudeLine(ctx, math.unit(1, "AU"), "Orbit of Earth");
  695. drawAltitudeLine(ctx, math.unit(227.9e6, "km"), "Orbit of Mars");
  696. drawAltitudeLine(ctx, math.unit(778.6e6, "km"), "Orbit of Jupiter");
  697. drawAltitudeLine(ctx, math.unit(1433.5e6, "km"), "Orbit of Saturn");
  698. drawAltitudeLine(ctx, math.unit(2872.5e6, "km"), "Orbit of Uranus");
  699. drawAltitudeLine(ctx, math.unit(4495.1e6, "km"), "Orbit of Neptune");
  700. drawAltitudeLine(ctx, math.unit(5906.4e6, "km"), "Orbit of Pluto");
  701. drawAltitudeLine(ctx, math.unit(2.7, "AU"), "Asteroid Belt");
  702. drawAltitudeLine(ctx, math.unit(123, "AU"), "Heliopause");
  703. drawAltitudeLine(ctx, math.unit(26e3, "lightyears"), "Orbit of Sol");
  704. }
  705. if (config.drawAltitudes == "weather" || config.drawAltitudes == "all") {
  706. drawAltitudeLine(ctx, math.unit(1000, "meters"), "Low-level Clouds");
  707. drawAltitudeLine(ctx, math.unit(3000, "meters"), "Mid-level Clouds");
  708. drawAltitudeLine(ctx, math.unit(10000, "meters"), "High-level Clouds");
  709. drawAltitudeLine(ctx, math.unit(20, "km"), "Polar Stratospheric Clouds");
  710. drawAltitudeLine(ctx, math.unit(80, "km"), "Noctilucent Clouds");
  711. drawAltitudeLine(ctx, math.unit(100, "km"), "Aurora");
  712. }
  713. if (config.drawAltitudes == "water" || config.drawAltitudes == "all") {
  714. drawAltitudeLine(ctx, math.unit(12100, "feet"), "Average Ocean Depth");
  715. drawAltitudeLine(ctx, math.unit(8376, "meters"), "Milkwaukee Deep");
  716. drawAltitudeLine(ctx, math.unit(10984, "meters"), "Challenger Deep");
  717. drawAltitudeLine(ctx, math.unit(5550, "meters"), "Molloy Deep");
  718. drawAltitudeLine(ctx, math.unit(7290, "meters"), "Sunda Deep");
  719. drawAltitudeLine(ctx, math.unit(592, "meters"), "Crater Lake");
  720. drawAltitudeLine(ctx, math.unit(7.5, "meters"), "Littoral Zone");
  721. drawAltitudeLine(ctx, math.unit(140, "meters"), "Continental Shelf");
  722. }
  723. if (config.drawAltitudes == "geology" || config.drawAltitudes == "all") {
  724. drawAltitudeLine(ctx, math.unit(35, "km"), "Crust");
  725. drawAltitudeLine(ctx, math.unit(670, "km"), "Upper Mantle");
  726. drawAltitudeLine(ctx, math.unit(2890, "km"), "Lower Mantle");
  727. drawAltitudeLine(ctx, math.unit(5150, "km"), "Outer Core");
  728. drawAltitudeLine(ctx, math.unit(6370, "km"), "Inner Core");
  729. }
  730. if (config.drawAltitudes == "thicknesses" || config.drawAltitudes == "all") {
  731. drawAltitudeLine(ctx, math.unit(0.335, "nm"), "Monolayer Graphene");
  732. drawAltitudeLine(ctx, math.unit(3, "um"), "Spider Silk");
  733. drawAltitudeLine(ctx, math.unit(0.07, "mm"), "Human Hair");
  734. drawAltitudeLine(ctx, math.unit(0.1, "mm"), "Sheet of Paper");
  735. drawAltitudeLine(ctx, math.unit(0.5, "mm"), "Yarn");
  736. drawAltitudeLine(ctx, math.unit(0.0155, "inches"), "Thread");
  737. drawAltitudeLine(ctx, math.unit(0.1, "um"), "Gold Leaf");
  738. drawAltitudeLine(ctx, math.unit(35, "um"), "PCB Trace");
  739. }
  740. }
  741. // this is a lot of copypizza...
  742. function drawHorizontalScale(ifDirty = false) {
  743. if (ifDirty && !worldSizeDirty)
  744. return;
  745. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  746. let total = heightPer.clone();
  747. total.value = math.unit(-config.x, "meters").toNumber(config.unit);
  748. // further adjust it to put the current position in the center
  749. total.value -= heightPer.toNumber("meters") / pixelsPer * (canvasWidth + 50) / 2;
  750. let x = ctx.canvas.clientWidth - 50;
  751. let offset = total.toNumber("meters") % heightPer.toNumber("meters");
  752. x += offset / heightPer.toNumber("meters") * pixelsPer;
  753. total = math.subtract(total, math.unit(offset, "meters"));
  754. for (; x >= 50 - pixelsPer; x -= pixelsPer) {
  755. // negate it so that the left side is negative
  756. drawTick(ctx, x, 50, math.multiply(-1, total).format({ precision: 3 }));
  757. total = math.add(total, heightPer);
  758. }
  759. }
  760. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, label) {
  761. const oldStroke = ctx.strokeStyle;
  762. const oldFill = ctx.fillStyle;
  763. ctx.beginPath();
  764. ctx.moveTo(x, y);
  765. ctx.lineTo(x, y + 20);
  766. ctx.strokeStyle = "#000000";
  767. ctx.stroke();
  768. ctx.beginPath();
  769. ctx.moveTo(x, y + 20);
  770. ctx.lineTo(x, ctx.canvas.clientHeight - 70);
  771. ctx.strokeStyle = "#aaaaaa";
  772. ctx.stroke();
  773. ctx.beginPath();
  774. ctx.moveTo(x, ctx.canvas.clientHeight - 70);
  775. ctx.lineTo(x, ctx.canvas.clientHeight - 50);
  776. ctx.strokeStyle = "#000000";
  777. ctx.stroke();
  778. const oldFont = ctx.font;
  779. ctx.font = 'normal 24pt coda';
  780. ctx.fillStyle = "#dddddd";
  781. ctx.beginPath();
  782. ctx.fillText(label, x + 35, y + 20);
  783. ctx.font = oldFont;
  784. ctx.strokeStyle = oldStroke;
  785. ctx.fillStyle = oldFill;
  786. }
  787. const canvas = document.querySelector("#display");
  788. /** @type {CanvasRenderingContext2D} */
  789. const ctx = canvas.getContext("2d");
  790. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  791. heightPer = 1;
  792. if (pixelsPer < config.minLineSize * 2) {
  793. const factor = math.ceil(config.minLineSize * 2/ pixelsPer);
  794. heightPer *= factor;
  795. pixelsPer *= factor;
  796. }
  797. if (pixelsPer > config.maxLineSize * 2) {
  798. const factor = math.ceil(pixelsPer / 2/ config.maxLineSize);
  799. heightPer /= factor;
  800. pixelsPer /= factor;
  801. }
  802. if (heightPer == 0) {
  803. console.error("The world size is invalid! Refusing to draw the scale...");
  804. return;
  805. }
  806. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  807. ctx.beginPath();
  808. ctx.moveTo(0, 50);
  809. ctx.lineTo(ctx.canvas.clientWidth, 50);
  810. ctx.stroke();
  811. ctx.beginPath();
  812. ctx.moveTo(0, ctx.canvas.clientHeight - 50);
  813. ctx.lineTo(ctx.canvas.clientWidth , ctx.canvas.clientHeight - 50);
  814. ctx.stroke();
  815. drawTicks(ctx, pixelsPer, heightPer);
  816. }
  817. // Entities are generated as needed, and we make a copy
  818. // every time - the resulting objects get mutated, after all.
  819. // But we also want to be able to read some information without
  820. // calling the constructor -- e.g. making a list of authors and
  821. // owners. So, this function is used to generate that information.
  822. // It is invoked like makeEntity so that it can be dropped in easily,
  823. // but returns an object that lets you construct many copies of an entity,
  824. // rather than creating a new entity.
  825. function createEntityMaker(info, views, sizes) {
  826. const maker = {};
  827. maker.name = info.name;
  828. maker.info = info;
  829. maker.sizes = sizes;
  830. maker.constructor = () => makeEntity(info, views, sizes);
  831. maker.authors = [];
  832. maker.owners = [];
  833. maker.nsfw = false;
  834. Object.values(views).forEach(view => {
  835. const authors = authorsOf(view.image.source);
  836. if (authors) {
  837. authors.forEach(author => {
  838. if (maker.authors.indexOf(author) == -1) {
  839. maker.authors.push(author);
  840. }
  841. });
  842. }
  843. const owners = ownersOf(view.image.source);
  844. if (owners) {
  845. owners.forEach(owner => {
  846. if (maker.owners.indexOf(owner) == -1) {
  847. maker.owners.push(owner);
  848. }
  849. });
  850. }
  851. if (isNsfw(view.image.source)) {
  852. maker.nsfw = true;
  853. }
  854. });
  855. return maker;
  856. }
  857. // This function serializes and parses its arguments to avoid sharing
  858. // references to a common object. This allows for the objects to be
  859. // safely mutated.
  860. function makeEntity(info, views, sizes) {
  861. const entityTemplate = {
  862. name: info.name,
  863. identifier: info.name,
  864. scale: 1,
  865. info: JSON.parse(JSON.stringify(info)),
  866. views: JSON.parse(JSON.stringify(views), math.reviver),
  867. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  868. init: function () {
  869. const entity = this;
  870. Object.entries(this.views).forEach(([viewKey, view]) => {
  871. view.parent = this;
  872. if (this.defaultView === undefined) {
  873. this.defaultView = viewKey;
  874. this.view = viewKey;
  875. }
  876. if (view.default) {
  877. this.defaultView = viewKey;
  878. this.view = viewKey;
  879. }
  880. // to remember the units the user last picked
  881. view.units = {};
  882. if (config.autoFoodIntake && view.attributes.weight !== undefined && view.attributes.energyNeed === undefined) {
  883. view.attributes.energyNeed = {
  884. name: "Food Intake",
  885. power: 3,
  886. type: "energy",
  887. base: math.unit(2000 * view.attributes.weight.base.toNumber("lbs") / 150, "kcal")
  888. }
  889. }
  890. if (config.autoPreyCapacity !== "none" && view.attributes.weight !== undefined && view.attributes.capacity === undefined) {
  891. view.attributes.capacity = {
  892. name: "Capacity",
  893. power: 3,
  894. type: "volume",
  895. base: math.unit((config.autoPreyCapacity == "same-size" ? 1 : 0.05) * view.attributes.weight.base.toNumber("lbs") / 150, "people")
  896. }
  897. }
  898. Object.entries(view.attributes).forEach(([key, val]) => {
  899. Object.defineProperty(
  900. view,
  901. key,
  902. {
  903. get: function () {
  904. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  905. },
  906. set: function (value) {
  907. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  908. this.parent.scale = newScale;
  909. }
  910. }
  911. );
  912. });
  913. });
  914. this.sizes.forEach(size => {
  915. if (size.default === true) {
  916. this.views[this.defaultView].height = size.height;
  917. this.size = size;
  918. }
  919. });
  920. if (this.size === undefined && this.sizes.length > 0) {
  921. this.views[this.defaultView].height = this.sizes[0].height;
  922. this.size = this.sizes[0];
  923. console.warn("No default size set for " + info.name);
  924. } else if (this.sizes.length == 0) {
  925. this.sizes = [
  926. {
  927. name: "Normal",
  928. height: this.views[this.defaultView].height
  929. }
  930. ];
  931. this.size = this.sizes[0];
  932. }
  933. this.desc = {};
  934. Object.entries(this.info).forEach(([key, value]) => {
  935. Object.defineProperty(
  936. this.desc,
  937. key,
  938. {
  939. get: function () {
  940. let text = value.text;
  941. if (entity.views[entity.view].info) {
  942. if (entity.views[entity.view].info[key]) {
  943. text = combineInfo(text, entity.views[entity.view].info[key]);
  944. }
  945. }
  946. if (entity.size.info) {
  947. if (entity.size.info[key]) {
  948. text = combineInfo(text, entity.size.info[key]);
  949. }
  950. }
  951. return { title: value.title, text: text };
  952. }
  953. }
  954. )
  955. });
  956. Object.defineProperty(
  957. this,
  958. "currentView",
  959. {
  960. get: function() {
  961. return entity.views[entity.view];
  962. }
  963. }
  964. )
  965. delete this.init;
  966. return this;
  967. }
  968. }.init();
  969. return entityTemplate;
  970. }
  971. function combineInfo(existing, next) {
  972. switch (next.mode) {
  973. case "replace":
  974. return next.text;
  975. case "prepend":
  976. return next.text + existing;
  977. case "append":
  978. return existing + next.text;
  979. }
  980. return existing;
  981. }
  982. function clickDown(target, x, y) {
  983. clicked = target;
  984. movingInBounds = false;
  985. const rect = target.getBoundingClientRect();
  986. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  987. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  988. dragOffsetX = x - rect.left + entX;
  989. dragOffsetY = y - rect.top + entY;
  990. x = x - dragOffsetX;
  991. y = y - dragOffsetY;
  992. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  993. movingInBounds = true;
  994. }
  995. clickTimeout = setTimeout(() => { dragging = true }, 200)
  996. target.classList.add("no-transition");
  997. }
  998. // could we make this actually detect the menu area?
  999. function hoveringInDeleteArea(e) {
  1000. return e.clientY < document.body.clientHeight / 10;
  1001. }
  1002. function clickUp(e) {
  1003. if (e.which != 1) {
  1004. return;
  1005. }
  1006. clearTimeout(clickTimeout);
  1007. if (clicked) {
  1008. clicked.classList.remove("no-transition");
  1009. if (dragging) {
  1010. dragging = false;
  1011. if (hoveringInDeleteArea(e)) {
  1012. removeEntity(clicked);
  1013. document.querySelector("#menubar").classList.remove("hover-delete");
  1014. }
  1015. } else {
  1016. select(clicked);
  1017. }
  1018. clicked = null;
  1019. }
  1020. }
  1021. function deselect(e) {
  1022. if (e !== undefined && e.which != 1) {
  1023. return;
  1024. }
  1025. if (selected) {
  1026. selected.classList.remove("selected");
  1027. }
  1028. if (prevSelected) {
  1029. prevSelected.classList.remove("prevSelected");
  1030. }
  1031. document.getElementById("options-selected-entity-none").selected = "selected";
  1032. clearAttribution();
  1033. selected = null;
  1034. clearViewList();
  1035. clearEntityOptions();
  1036. clearViewOptions();
  1037. document.querySelector("#delete-entity").disabled = true;
  1038. document.querySelector("#grow").disabled = true;
  1039. document.querySelector("#shrink").disabled = true;
  1040. document.querySelector("#fit").disabled = true;
  1041. }
  1042. function select(target) {
  1043. if (prevSelected !== null) {
  1044. prevSelected.classList.remove("prevSelected");
  1045. }
  1046. prevSelected = selected;
  1047. prevSelectedEntity = selectedEntity;
  1048. deselect();
  1049. selected = target;
  1050. selectedEntity = entities[target.dataset.key];
  1051. updateRatios();
  1052. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  1053. if (prevSelected !== null && config.showRatios && selected !== prevSelected) {
  1054. prevSelected.classList.add("prevSelected");
  1055. }
  1056. selected.classList.add("selected");
  1057. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  1058. configViewList(selectedEntity, selectedEntity.view);
  1059. configEntityOptions(selectedEntity, selectedEntity.view);
  1060. configViewOptions(selectedEntity, selectedEntity.view);
  1061. document.querySelector("#delete-entity").disabled = false;
  1062. document.querySelector("#grow").disabled = false;
  1063. document.querySelector("#shrink").disabled = false;
  1064. document.querySelector("#fit").disabled = false;
  1065. }
  1066. function configViewList(entity, selectedView) {
  1067. const list = document.querySelector("#entity-view");
  1068. list.innerHTML = "";
  1069. list.style.display = "block";
  1070. Object.keys(entity.views).forEach(view => {
  1071. const option = document.createElement("option");
  1072. option.innerText = entity.views[view].name;
  1073. option.value = view;
  1074. if (isNsfw(entity.views[view].image.source)) {
  1075. option.classList.add("nsfw")
  1076. }
  1077. if (view === selectedView) {
  1078. option.selected = true;
  1079. if (option.classList.contains("nsfw")) {
  1080. list.classList.add("nsfw");
  1081. } else {
  1082. list.classList.remove("nsfw");
  1083. }
  1084. }
  1085. list.appendChild(option);
  1086. });
  1087. }
  1088. function clearViewList() {
  1089. const list = document.querySelector("#entity-view");
  1090. list.innerHTML = "";
  1091. list.style.display = "none";
  1092. }
  1093. function updateWorldOptions(entity, view) {
  1094. const heightInput = document.querySelector("#options-height-value");
  1095. const heightSelect = document.querySelector("#options-height-unit");
  1096. const converted = config.height.toNumber(heightSelect.value);
  1097. setNumericInput(heightInput, converted);
  1098. }
  1099. function configEntityOptions(entity, view) {
  1100. const holder = document.querySelector("#options-entity");
  1101. document.querySelector("#entity-category-header").style.display = "block";
  1102. document.querySelector("#entity-category").style.display = "block";
  1103. holder.innerHTML = "";
  1104. const scaleLabel = document.createElement("div");
  1105. scaleLabel.classList.add("options-label");
  1106. scaleLabel.innerText = "Scale";
  1107. const scaleRow = document.createElement("div");
  1108. scaleRow.classList.add("options-row");
  1109. const scaleInput = document.createElement("input");
  1110. scaleInput.classList.add("options-field-numeric");
  1111. scaleInput.id = "options-entity-scale";
  1112. scaleInput.addEventListener("change", e => {
  1113. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  1114. entity.dirty = true;
  1115. if (config.autoFit) {
  1116. fitWorld();
  1117. } else {
  1118. updateSizes(true);
  1119. }
  1120. updateEntityOptions(entity, entity.view);
  1121. updateViewOptions(entity, entity.view);
  1122. });
  1123. scaleInput.addEventListener("keydown", e => {
  1124. e.stopPropagation();
  1125. })
  1126. scaleInput.setAttribute("min", 1);
  1127. scaleInput.setAttribute("type", "number");
  1128. setNumericInput(scaleInput, entity.scale);
  1129. scaleRow.appendChild(scaleInput);
  1130. holder.appendChild(scaleLabel);
  1131. holder.appendChild(scaleRow);
  1132. const nameLabel = document.createElement("div");
  1133. nameLabel.classList.add("options-label");
  1134. nameLabel.innerText = "Name";
  1135. const nameRow = document.createElement("div");
  1136. nameRow.classList.add("options-row");
  1137. const nameInput = document.createElement("input");
  1138. nameInput.classList.add("options-field-text");
  1139. nameInput.value = entity.name;
  1140. nameInput.addEventListener("input", e => {
  1141. entity.name = e.target.value;
  1142. entity.dirty = true;
  1143. updateSizes(true);
  1144. })
  1145. nameInput.addEventListener("keydown", e => {
  1146. e.stopPropagation();
  1147. })
  1148. nameRow.appendChild(nameInput);
  1149. holder.appendChild(nameLabel);
  1150. holder.appendChild(nameRow);
  1151. const defaultHolder = document.querySelector("#options-entity-defaults");
  1152. defaultHolder.innerHTML = "";
  1153. entity.sizes.forEach(defaultInfo => {
  1154. const button = document.createElement("button");
  1155. button.classList.add("options-button");
  1156. button.innerText = defaultInfo.name;
  1157. button.addEventListener("click", e => {
  1158. entity.views[entity.defaultView].height = defaultInfo.height;
  1159. entity.dirty = true;
  1160. updateEntityOptions(entity, entity.view);
  1161. updateViewOptions(entity, entity.view);
  1162. if (!checkFitWorld()) {
  1163. updateSizes(true);
  1164. }
  1165. if (config.autoFitSize) {
  1166. let targets = {};
  1167. targets[selected.dataset.key] = entities[selected.dataset.key];
  1168. fitEntities(targets);
  1169. }
  1170. });
  1171. defaultHolder.appendChild(button);
  1172. });
  1173. document.querySelector("#options-order-display").innerText = entity.priority;
  1174. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1175. document.querySelector("#options-ordering").style.display = "flex";
  1176. }
  1177. function updateEntityOptions(entity, view) {
  1178. const scaleInput = document.querySelector("#options-entity-scale");
  1179. setNumericInput(scaleInput, entity.scale);
  1180. document.querySelector("#options-order-display").innerText = entity.priority;
  1181. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1182. }
  1183. function clearEntityOptions() {
  1184. document.querySelector("#entity-category-header").style.display = "none";
  1185. document.querySelector("#entity-category").style.display = "none";
  1186. /*
  1187. const holder = document.querySelector("#options-entity");
  1188. holder.innerHTML = "";
  1189. document.querySelector("#options-entity-defaults").innerHTML = "";
  1190. document.querySelector("#options-ordering").style.display = "none";
  1191. document.querySelector("#options-ordering").style.display = "none";*/
  1192. }
  1193. function configViewOptions(entity, view) {
  1194. const holder = document.querySelector("#options-view");
  1195. document.querySelector("#view-category-header").style.display = "block";
  1196. document.querySelector("#view-category").style.display = "block";
  1197. holder.innerHTML = "";
  1198. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1199. const label = document.createElement("div");
  1200. label.classList.add("options-label");
  1201. label.innerText = val.name;
  1202. holder.appendChild(label);
  1203. const row = document.createElement("div");
  1204. row.classList.add("options-row");
  1205. holder.appendChild(row);
  1206. const input = document.createElement("input");
  1207. input.classList.add("options-field-numeric");
  1208. input.id = "options-view-" + key + "-input";
  1209. input.setAttribute("type", "number");
  1210. input.setAttribute("min", 1);
  1211. const select = document.createElement("select");
  1212. select.classList.add("options-field-unit");
  1213. select.id = "options-view-" + key + "-select"
  1214. Object.entries(unitChoices[val.type]).forEach(([group, entries]) => {
  1215. const optGroup = document.createElement("optgroup");
  1216. optGroup.label = group;
  1217. select.appendChild(optGroup);
  1218. entries.forEach(entry => {
  1219. const option = document.createElement("option");
  1220. option.innerText = entry;
  1221. if (entry == defaultUnits[val.type][config.units]) {
  1222. option.selected = true;
  1223. }
  1224. select.appendChild(option);
  1225. })
  1226. });
  1227. input.addEventListener("change", e => {
  1228. const value = input.value == 0 ? 1 : input.value;
  1229. entity.views[view][key] = math.unit(value, select.value);
  1230. entity.dirty = true;
  1231. if (config.autoFit) {
  1232. fitWorld();
  1233. } else {
  1234. updateSizes(true);
  1235. }
  1236. updateEntityOptions(entity, view);
  1237. updateViewOptions(entity, view, key);
  1238. });
  1239. input.addEventListener("keydown", e => {
  1240. e.stopPropagation();
  1241. })
  1242. if (entity.currentView.units[key]) {
  1243. select.value = entity.currentView.units[key];
  1244. } else {
  1245. entity.currentView.units[key] = select.value;
  1246. }
  1247. select.dataset.oldUnit = select.value;
  1248. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  1249. // TODO does this ever cause a change in the world?
  1250. select.addEventListener("input", e => {
  1251. const value = input.value == 0 ? 1 : input.value;
  1252. const oldUnit = select.dataset.oldUnit;
  1253. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  1254. entity.dirty = true;
  1255. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  1256. select.dataset.oldUnit = select.value;
  1257. entity.views[view].units[key] = select.value;
  1258. if (config.autoFit) {
  1259. fitWorld();
  1260. } else {
  1261. updateSizes(true);
  1262. }
  1263. updateEntityOptions(entity, view);
  1264. updateViewOptions(entity, view, key);
  1265. });
  1266. row.appendChild(input);
  1267. row.appendChild(select);
  1268. });
  1269. }
  1270. function updateViewOptions(entity, view, changed) {
  1271. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1272. if (key != changed) {
  1273. const input = document.querySelector("#options-view-" + key + "-input");
  1274. const select = document.querySelector("#options-view-" + key + "-select");
  1275. const currentUnit = select.value;
  1276. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  1277. setNumericInput(input, convertedAmount);
  1278. }
  1279. });
  1280. }
  1281. function setNumericInput(input, value, round = 6) {
  1282. if (typeof value == "string") {
  1283. value = parseFloat(value)
  1284. }
  1285. input.value = value.toPrecision(round);
  1286. }
  1287. function getSortedEntities() {
  1288. return Object.keys(entities).sort((a, b) => {
  1289. const entA = entities[a];
  1290. const entB = entities[b];
  1291. const viewA = entA.view;
  1292. const viewB = entB.view;
  1293. const heightA = entA.views[viewA].height.to("meter").value;
  1294. const heightB = entB.views[viewB].height.to("meter").value;
  1295. return heightA - heightB;
  1296. });
  1297. }
  1298. function clearViewOptions() {
  1299. document.querySelector("#view-category-header").style.display = "none";
  1300. document.querySelector("#view-category").style.display = "none";
  1301. }
  1302. // this is a crime against humanity, and also stolen from
  1303. // stack overflow
  1304. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  1305. const testCanvas = document.createElement("canvas");
  1306. testCanvas.id = "test-canvas";
  1307. const testCtx = testCanvas.getContext("2d");
  1308. function testClick(event) {
  1309. // oh my god I can't believe I'm doing this
  1310. const target = event.target;
  1311. if (rulerMode) {
  1312. return;
  1313. }
  1314. // Get click coordinates
  1315. let w = target.width;
  1316. let h = target.height;
  1317. let ratioW = 1, ratioH = 1;
  1318. // Limit the size of the canvas so that very large images don't cause problems)
  1319. if (w > 1000) {
  1320. ratioW = w / 1000;
  1321. w /= ratioW;
  1322. h /= ratioW;
  1323. }
  1324. if (h > 1000) {
  1325. ratioH = h / 1000;
  1326. w /= ratioH;
  1327. h /= ratioH;
  1328. }
  1329. const ratio = ratioW * ratioH;
  1330. var x = event.clientX - target.getBoundingClientRect().x,
  1331. y = event.clientY - target.getBoundingClientRect().y,
  1332. alpha;
  1333. testCtx.canvas.width = w;
  1334. testCtx.canvas.height = h;
  1335. // Draw image to canvas
  1336. // and read Alpha channel value
  1337. testCtx.drawImage(target, 0, 0, w, h);
  1338. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  1339. // If pixel is transparent,
  1340. // retrieve the element underneath and trigger its click event
  1341. if (alpha === 0) {
  1342. const oldDisplay = target.style.display;
  1343. target.style.display = "none";
  1344. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  1345. newTarget.dispatchEvent(new MouseEvent(event.type, {
  1346. "clientX": event.clientX,
  1347. "clientY": event.clientY
  1348. }));
  1349. target.style.display = oldDisplay;
  1350. } else {
  1351. clickDown(target.parentElement, event.clientX, event.clientY);
  1352. }
  1353. }
  1354. function arrangeEntities(order) {
  1355. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1356. let sum = 0;
  1357. order.forEach(key => {
  1358. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1359. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1360. let height = image.height;
  1361. let width = image.width;
  1362. if (height == 0) {
  1363. height = 100;
  1364. }
  1365. if (width == 0) {
  1366. width = height;
  1367. }
  1368. sum += meters * width / height;
  1369. });
  1370. let x = config.x - sum / 2;
  1371. order.forEach(key => {
  1372. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1373. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1374. let height = image.height;
  1375. let width = image.width;
  1376. if (height == 0) {
  1377. height = 100;
  1378. }
  1379. if (width == 0) {
  1380. width = height;
  1381. }
  1382. x += meters * width / height / 2;
  1383. document.querySelector("#entity-" + key).dataset.x = x;
  1384. document.querySelector("#entity-" + key).dataset.y = config.y;
  1385. x += meters * width / height / 2;
  1386. })
  1387. fitWorld();
  1388. updateSizes();
  1389. }
  1390. function removeAllEntities() {
  1391. Object.keys(entities).forEach(key => {
  1392. removeEntity(document.querySelector("#entity-" + key));
  1393. });
  1394. }
  1395. function clearAttribution() {
  1396. document.querySelector("#attribution-category-header").style.display = "none";
  1397. document.querySelector("#options-attribution").style.display = "none";
  1398. }
  1399. function displayAttribution(file) {
  1400. document.querySelector("#attribution-category-header").style.display = "block";
  1401. document.querySelector("#options-attribution").style.display = "inline";
  1402. const authors = authorsOfFull(file);
  1403. const owners = ownersOfFull(file);
  1404. const citations = citationsOf(file);
  1405. const source = sourceOf(file);
  1406. const authorHolder = document.querySelector("#options-attribution-authors");
  1407. const ownerHolder = document.querySelector("#options-attribution-owners");
  1408. const citationHolder = document.querySelector("#options-attribution-citations");
  1409. const sourceHolder = document.querySelector("#options-attribution-source");
  1410. if (authors === []) {
  1411. const div = document.createElement("div");
  1412. div.innerText = "Unknown";
  1413. authorHolder.innerHTML = "";
  1414. authorHolder.appendChild(div);
  1415. } else if (authors === undefined) {
  1416. const div = document.createElement("div");
  1417. div.innerText = "Not yet entered";
  1418. authorHolder.innerHTML = "";
  1419. authorHolder.appendChild(div);
  1420. } else {
  1421. authorHolder.innerHTML = "";
  1422. const list = document.createElement("ul");
  1423. authorHolder.appendChild(list);
  1424. authors.forEach(author => {
  1425. const authorEntry = document.createElement("li");
  1426. if (author.url) {
  1427. const link = document.createElement("a");
  1428. link.href = author.url;
  1429. link.innerText = author.name;
  1430. authorEntry.appendChild(link);
  1431. } else {
  1432. const div = document.createElement("div");
  1433. div.innerText = author.name;
  1434. authorEntry.appendChild(div);
  1435. }
  1436. list.appendChild(authorEntry);
  1437. });
  1438. }
  1439. if (owners === []) {
  1440. const div = document.createElement("div");
  1441. div.innerText = "Unknown";
  1442. ownerHolder.innerHTML = "";
  1443. ownerHolder.appendChild(div);
  1444. } else if (owners === undefined) {
  1445. const div = document.createElement("div");
  1446. div.innerText = "Not yet entered";
  1447. ownerHolder.innerHTML = "";
  1448. ownerHolder.appendChild(div);
  1449. } else {
  1450. ownerHolder.innerHTML = "";
  1451. const list = document.createElement("ul");
  1452. ownerHolder.appendChild(list);
  1453. owners.forEach(owner => {
  1454. const ownerEntry = document.createElement("li");
  1455. if (owner.url) {
  1456. const link = document.createElement("a");
  1457. link.href = owner.url;
  1458. link.innerText = owner.name;
  1459. ownerEntry.appendChild(link);
  1460. } else {
  1461. const div = document.createElement("div");
  1462. div.innerText = owner.name;
  1463. ownerEntry.appendChild(div);
  1464. }
  1465. list.appendChild(ownerEntry);
  1466. });
  1467. }
  1468. if (citations === [] || citations === undefined) {
  1469. } else {
  1470. citationHolder.innerHTML = "";
  1471. const list = document.createElement("ul");
  1472. citationHolder.appendChild(list);
  1473. citations.forEach(citation => {
  1474. const citationEntry = document.createElement("li");
  1475. const link = document.createElement("a");
  1476. link.style.display = "block";
  1477. link.href = citation;
  1478. link.innerText = new URL(citation).host;
  1479. citationEntry.appendChild(link);
  1480. list.appendChild(citationEntry);
  1481. })
  1482. }
  1483. if (source === null) {
  1484. const div = document.createElement("div");
  1485. div.innerText = "No link";
  1486. sourceHolder.innerHTML = "";
  1487. sourceHolder.appendChild(div);
  1488. } else if (source === undefined) {
  1489. const div = document.createElement("div");
  1490. div.innerText = "Not yet entered";
  1491. sourceHolder.innerHTML = "";
  1492. sourceHolder.appendChild(div);
  1493. } else {
  1494. sourceHolder.innerHTML = "";
  1495. const link = document.createElement("a");
  1496. link.style.display = "block";
  1497. link.href = source;
  1498. link.innerText = new URL(source).host;
  1499. sourceHolder.appendChild(link);
  1500. }
  1501. }
  1502. function removeEntity(element) {
  1503. if (selected == element) {
  1504. deselect();
  1505. }
  1506. if (clicked == element) {
  1507. clicked = null;
  1508. }
  1509. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  1510. option.parentElement.removeChild(option);
  1511. delete entities[element.dataset.key];
  1512. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  1513. const topName = document.querySelector("#top-name-" + element.dataset.key);
  1514. bottomName.parentElement.removeChild(bottomName);
  1515. topName.parentElement.removeChild(topName);
  1516. element.parentElement.removeChild(element);
  1517. }
  1518. function checkEntity(entity) {
  1519. Object.values(entity.views).forEach(view => {
  1520. if (authorsOf(view.image.source) === undefined) {
  1521. console.warn("No authors: " + view.image.source);
  1522. }
  1523. });
  1524. }
  1525. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  1526. checkEntity(entity);
  1527. // preload all of the entity's views
  1528. Object.values(entity.views).forEach(view => {
  1529. if (!preloaded.has(view.image.source)) {
  1530. let img = new Image();
  1531. img.src = view.image.source;
  1532. preloaded.add(view.image.source);
  1533. }
  1534. });
  1535. const box = document.createElement("div");
  1536. box.classList.add("entity-box");
  1537. const img = document.createElement("img");
  1538. img.classList.add("entity-image");
  1539. img.addEventListener("dragstart", e => {
  1540. e.preventDefault();
  1541. });
  1542. const nameTag = document.createElement("div");
  1543. nameTag.classList.add("entity-name");
  1544. nameTag.innerText = entity.name;
  1545. box.appendChild(img);
  1546. box.appendChild(nameTag);
  1547. const image = entity.views[view].image;
  1548. img.src = image.source;
  1549. if (image.bottom !== undefined) {
  1550. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1551. } else {
  1552. img.style.setProperty("--offset", ((-1) * 100) + "%")
  1553. }
  1554. box.dataset.x = x;
  1555. box.dataset.y = y;
  1556. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  1557. img.addEventListener("touchstart", e => {
  1558. const fakeEvent = {
  1559. target: e.target,
  1560. clientX: e.touches[0].clientX,
  1561. clientY: e.touches[0].clientY,
  1562. which: 1
  1563. };
  1564. testClick(fakeEvent);
  1565. if (clicked) { e.stopPropagation() }
  1566. });
  1567. const heightBar = document.createElement("div");
  1568. heightBar.classList.add("height-bar");
  1569. box.appendChild(heightBar);
  1570. box.id = "entity-" + entityIndex;
  1571. box.dataset.key = entityIndex;
  1572. entity.view = view;
  1573. if (entity.priority === undefined)
  1574. entity.priority = 0;
  1575. if (entity.brightness === undefined)
  1576. entity.brightness = 1;
  1577. entities[entityIndex] = entity;
  1578. entity.index = entityIndex;
  1579. const world = document.querySelector("#entities");
  1580. world.appendChild(box);
  1581. const bottomName = document.createElement("div");
  1582. bottomName.classList.add("bottom-name");
  1583. bottomName.id = "bottom-name-" + entityIndex;
  1584. bottomName.innerText = entity.name;
  1585. bottomName.addEventListener("click", () => select(box));
  1586. world.appendChild(bottomName);
  1587. const topName = document.createElement("div");
  1588. topName.classList.add("top-name");
  1589. topName.id = "top-name-" + entityIndex;
  1590. topName.innerText = entity.name;
  1591. topName.addEventListener("click", () => select(box));
  1592. world.appendChild(topName);
  1593. const entityOption = document.createElement("option");
  1594. entityOption.id = "options-selected-entity-" + entityIndex;
  1595. entityOption.value = entityIndex;
  1596. entityOption.innerText = entity.name;
  1597. document.getElementById("options-selected-entity").appendChild(entityOption);
  1598. entityIndex += 1;
  1599. if (config.autoFit) {
  1600. fitWorld();
  1601. }
  1602. if (selectEntity)
  1603. select(box);
  1604. entity.dirty = true;
  1605. if (refresh && config.autoFitAdd) {
  1606. let targets = {};
  1607. targets[entityIndex - 1] = entity;
  1608. fitEntities(targets);
  1609. }
  1610. if (refresh)
  1611. updateSizes(true);
  1612. }
  1613. window.onblur = function () {
  1614. altHeld = false;
  1615. shiftHeld = false;
  1616. }
  1617. window.onfocus = function () {
  1618. window.dispatchEvent(new Event("keydown"));
  1619. }
  1620. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1621. function toggleFullScreen() {
  1622. var doc = window.document;
  1623. var docEl = doc.documentElement;
  1624. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1625. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1626. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1627. requestFullScreen.call(docEl);
  1628. }
  1629. else {
  1630. cancelFullScreen.call(doc);
  1631. }
  1632. }
  1633. function handleResize() {
  1634. const oldCanvasWidth = canvasWidth;
  1635. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1636. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1637. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1638. const change = oldCanvasWidth / canvasWidth;
  1639. updateSizes();
  1640. }
  1641. function prepareSidebar() {
  1642. const menubar = document.querySelector("#sidebar-menu");
  1643. [
  1644. {
  1645. name: "Show/hide sidebar",
  1646. id: "menu-toggle-sidebar",
  1647. icon: "fas fa-chevron-circle-down",
  1648. rotates: true
  1649. },
  1650. {
  1651. name: "Fullscreen",
  1652. id: "menu-fullscreen",
  1653. icon: "fas fa-compress"
  1654. },
  1655. {
  1656. name: "Clear",
  1657. id: "menu-clear",
  1658. icon: "fas fa-file"
  1659. },
  1660. {
  1661. name: "Sort by height",
  1662. id: "menu-order-height",
  1663. icon: "fas fa-sort-numeric-up"
  1664. },
  1665. {
  1666. name: "Permalink",
  1667. id: "menu-permalink",
  1668. icon: "fas fa-link"
  1669. },
  1670. {
  1671. name: "Export to clipboard",
  1672. id: "menu-export",
  1673. icon: "fas fa-share"
  1674. },
  1675. {
  1676. name: "Import from clipboard",
  1677. id: "menu-import",
  1678. icon: "fas fa-share",
  1679. classes: ["flipped"]
  1680. },
  1681. {
  1682. name: "Save Scene",
  1683. id: "menu-save",
  1684. icon: "fas fa-download",
  1685. input: true
  1686. },
  1687. {
  1688. name: "Load Scene",
  1689. id: "menu-load",
  1690. icon: "fas fa-upload",
  1691. select: true
  1692. },
  1693. {
  1694. name: "Delete Scene",
  1695. id: "menu-delete",
  1696. icon: "fas fa-trash",
  1697. select: true
  1698. },
  1699. {
  1700. name: "Load Autosave",
  1701. id: "menu-load-autosave",
  1702. icon: "fas fa-redo"
  1703. },
  1704. {
  1705. name: "Add Image",
  1706. id: "menu-add-image",
  1707. icon: "fas fa-camera"
  1708. },
  1709. {
  1710. name: "Clear Rulers",
  1711. id: "menu-clear-rulers",
  1712. icon: "fas fa-ruler"
  1713. }
  1714. ].forEach(entry => {
  1715. const buttonHolder = document.createElement("div");
  1716. buttonHolder.classList.add("menu-button-holder");
  1717. const button = document.createElement("button");
  1718. button.id = entry.id;
  1719. button.classList.add("menu-button");
  1720. const icon = document.createElement("i");
  1721. icon.classList.add(...entry.icon.split(" "));
  1722. if (entry.rotates) {
  1723. icon.classList.add("rotate-backward", "transitions");
  1724. }
  1725. if (entry.classes) {
  1726. entry.classes.forEach(cls => icon.classList.add(cls));
  1727. }
  1728. const actionText = document.createElement("span");
  1729. actionText.innerText = entry.name;
  1730. actionText.classList.add("menu-text");
  1731. const srText = document.createElement("span");
  1732. srText.classList.add("sr-only");
  1733. srText.innerText = entry.name;
  1734. button.appendChild(icon);
  1735. button.appendChild(srText);
  1736. buttonHolder.appendChild(button);
  1737. buttonHolder.appendChild(actionText);
  1738. if (entry.input) {
  1739. const input = document.createElement("input");
  1740. buttonHolder.appendChild(input);
  1741. input.placeholder = "default";
  1742. input.addEventListener("keyup", e => {
  1743. if (e.key === "Enter") {
  1744. const name = document.querySelector("#menu-save ~ input").value;
  1745. if (/\S/.test(name)) {
  1746. saveScene(name);
  1747. }
  1748. updateSaveInfo();
  1749. e.preventDefault();
  1750. }
  1751. })
  1752. }
  1753. if (entry.select) {
  1754. const select = document.createElement("select");
  1755. buttonHolder.appendChild(select);
  1756. }
  1757. menubar.appendChild(buttonHolder);
  1758. });
  1759. }
  1760. function checkBodyClass(cls) {
  1761. return document.body.classList.contains(cls);
  1762. }
  1763. function toggleBodyClass(cls, setting) {
  1764. if (setting) {
  1765. document.body.classList.add(cls);
  1766. } else {
  1767. document.body.classList.remove(cls);
  1768. }
  1769. }
  1770. const settingsData = {
  1771. "lock-y-axis": {
  1772. name: "Lock Y-Axis",
  1773. desc: "Keep the camera at ground-level",
  1774. type: "toggle",
  1775. default: true,
  1776. get value() {
  1777. return config.lockYAxis;
  1778. },
  1779. set value(param) {
  1780. config.lockYAxis = param;
  1781. if (param) {
  1782. config.y = 0;
  1783. updateSizes();
  1784. document.querySelector("#scroll-up").disabled = true;
  1785. document.querySelector("#scroll-down").disabled = true;
  1786. } else {
  1787. document.querySelector("#scroll-up").disabled = false;
  1788. document.querySelector("#scroll-down").disabled = false;
  1789. }
  1790. }
  1791. },
  1792. "auto-scale": {
  1793. name: "Auto-Size World",
  1794. desc: "Constantly zoom to fit the largest entity",
  1795. type: "toggle",
  1796. default: false,
  1797. get value() {
  1798. return config.autoFit;
  1799. },
  1800. set value(param) {
  1801. config.autoFit = param;
  1802. checkFitWorld();
  1803. }
  1804. },
  1805. "show-vertical-scale": {
  1806. name: "Show Vertical Scale",
  1807. desc: "Draw vertical scale marks",
  1808. type: "toggle",
  1809. default: true,
  1810. get value() {
  1811. return config.drawYAxis;
  1812. },
  1813. set value(param) {
  1814. config.drawYAxis = param;
  1815. drawScales(false);
  1816. }
  1817. },
  1818. "show-altitudes": {
  1819. name: "Show Altitudes",
  1820. desc: "Draw interesting altitudes",
  1821. type: "select",
  1822. default: "none",
  1823. options: [
  1824. "none",
  1825. "all",
  1826. "atmosphere",
  1827. "orbits",
  1828. "weather",
  1829. "water",
  1830. "geology",
  1831. "thicknesses"
  1832. ],
  1833. get value() {
  1834. return config.drawAltitudes;
  1835. },
  1836. set value(param) {
  1837. config.drawAltitudes = param;
  1838. drawScales(false);
  1839. }
  1840. },
  1841. "show-horizontal-scale": {
  1842. name: "Show Horiziontal Scale",
  1843. desc: "Draw horizontal scale marks",
  1844. type: "toggle",
  1845. default: false,
  1846. get value() {
  1847. return config.drawXAxis;
  1848. },
  1849. set value(param) {
  1850. config.drawXAxis = param;
  1851. drawScales(false);
  1852. }
  1853. },
  1854. "zoom-when-adding": {
  1855. name: "Zoom When Adding",
  1856. desc: "Zoom to fit when you add a new entity",
  1857. type: "toggle",
  1858. default: true,
  1859. get value() {
  1860. return config.autoFitAdd;
  1861. },
  1862. set value(param) {
  1863. config.autoFitAdd = param;
  1864. }
  1865. },
  1866. "zoom-when-sizing": {
  1867. name: "Zoom When Sizing",
  1868. desc: "Zoom to fit when you select an entity's size",
  1869. type: "toggle",
  1870. default: true,
  1871. get value() {
  1872. return config.autoFitSize;
  1873. },
  1874. set value(param) {
  1875. config.autoFitSize = param;
  1876. }
  1877. },
  1878. "show-ratios": {
  1879. name: "Show Ratios",
  1880. desc: "Show the proportions between the current selection and the most recent selection.",
  1881. type: "toggle",
  1882. default: true,
  1883. get value() {
  1884. return config.showRatios;
  1885. },
  1886. set value(param) {
  1887. config.showRatios = param;
  1888. if (param) {
  1889. document.body.querySelector(".ratio-info").style.display = "block";
  1890. } else {
  1891. document.body.querySelector(".ratio-info").style.display = "none";
  1892. }
  1893. }
  1894. },
  1895. "units": {
  1896. name: "Default Units",
  1897. desc: "Which kind of unit to use by default",
  1898. type: "select",
  1899. default: "metric",
  1900. options: [
  1901. "metric",
  1902. "customary",
  1903. "relative",
  1904. "quirky"
  1905. ],
  1906. get value() {
  1907. return config.units;
  1908. },
  1909. set value(param) {
  1910. config.units = param;
  1911. updateSizes();
  1912. }
  1913. },
  1914. "names": {
  1915. name: "Show Names",
  1916. desc: "Display names over entities",
  1917. type: "toggle",
  1918. default: true,
  1919. get value() {
  1920. return checkBodyClass("toggle-entity-name");
  1921. },
  1922. set value(param) {
  1923. toggleBodyClass("toggle-entity-name", param);
  1924. }
  1925. },
  1926. "bottom-names": {
  1927. name: "Bottom Names",
  1928. desc: "Display names at the bottom",
  1929. type: "toggle",
  1930. default: false,
  1931. get value() {
  1932. return checkBodyClass("toggle-bottom-name");
  1933. },
  1934. set value(param) {
  1935. toggleBodyClass("toggle-bottom-name", param);
  1936. }
  1937. },
  1938. "top-names": {
  1939. name: "Show Arrows",
  1940. desc: "Point to entities that are much larger than the current view",
  1941. type: "toggle",
  1942. default: false,
  1943. get value() {
  1944. return checkBodyClass("toggle-top-name");
  1945. },
  1946. set value(param) {
  1947. toggleBodyClass("toggle-top-name", param);
  1948. }
  1949. },
  1950. "height-bars": {
  1951. name: "Height Bars",
  1952. desc: "Draw dashed lines to the top of each entity",
  1953. type: "toggle",
  1954. default: false,
  1955. get value() {
  1956. return checkBodyClass("toggle-height-bars");
  1957. },
  1958. set value(param) {
  1959. toggleBodyClass("toggle-height-bars", param);
  1960. }
  1961. },
  1962. "glowing-entities": {
  1963. name: "Glowing Edges",
  1964. desc: "Makes all entities glow",
  1965. type: "toggle",
  1966. default: false,
  1967. get value() {
  1968. return checkBodyClass("toggle-entity-glow");
  1969. },
  1970. set value(param) {
  1971. toggleBodyClass("toggle-entity-glow", param);
  1972. }
  1973. },
  1974. "solid-ground": {
  1975. name: "Solid Ground",
  1976. desc: "Draw solid ground at the y=0 line",
  1977. type: "toggle",
  1978. default: true,
  1979. get value() {
  1980. return checkBodyClass("toggle-bottom-cover");
  1981. },
  1982. set value(param) {
  1983. toggleBodyClass("toggle-bottom-cover", param);
  1984. }
  1985. },
  1986. "auto-food-intake": {
  1987. name: "Estimate Food Intake",
  1988. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  1989. type: "toggle",
  1990. default: false,
  1991. get value() {
  1992. return config.autoFoodIntake
  1993. },
  1994. set value(param) {
  1995. config.autoFoodIntake = param
  1996. }
  1997. },
  1998. "auto-prey-capacity": {
  1999. name: "Estimate Prey Capacity",
  2000. desc: "Guess how much prey creatures can hold, based on their mass",
  2001. type: "select",
  2002. default: "none",
  2003. options: [
  2004. "none",
  2005. "realistic",
  2006. "same-size"
  2007. ],
  2008. get value() {
  2009. return config.autoPreyCapacity;
  2010. },
  2011. set value(param) {
  2012. config.autoPreyCapacity = param;
  2013. }
  2014. },
  2015. }
  2016. function getBoundingBox(entities, margin = 0.05) {
  2017. }
  2018. function prepareSettings(userSettings) {
  2019. const menubar = document.querySelector("#settings-menu");
  2020. Object.entries(settingsData).forEach(([id, entry]) => {
  2021. const holder = document.createElement("label");
  2022. holder.classList.add("settings-holder");
  2023. const input = document.createElement("input");
  2024. input.id = "setting-" + id;
  2025. const name = document.createElement("label");
  2026. name.innerText = entry.name;
  2027. name.classList.add("settings-name");
  2028. name.setAttribute("for", input.id);
  2029. const desc = document.createElement("label");
  2030. desc.innerText = entry.desc;
  2031. desc.classList.add("settings-desc");
  2032. desc.setAttribute("for", input.id);
  2033. if (entry.type == "toggle") {
  2034. input.type = "checkbox";
  2035. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  2036. holder.setAttribute("for", input.id);
  2037. holder.appendChild(name);
  2038. holder.appendChild(input);
  2039. holder.appendChild(desc);
  2040. menubar.appendChild(holder);
  2041. const update = () => {
  2042. if (input.checked) {
  2043. holder.classList.add("enabled");
  2044. holder.classList.remove("disabled");
  2045. } else {
  2046. holder.classList.remove("enabled");
  2047. holder.classList.add("disabled");
  2048. }
  2049. entry.value = input.checked;
  2050. }
  2051. update();
  2052. input.addEventListener("change", update);
  2053. } else if (entry.type == "select") {
  2054. // we don't use the input element we made!
  2055. const select = document.createElement("select");
  2056. select.id = "setting-" + id;
  2057. entry.options.forEach(choice => {
  2058. const option = document.createElement("option");
  2059. option.innerText = choice;
  2060. select.appendChild(option);
  2061. })
  2062. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  2063. holder.appendChild(name);
  2064. holder.appendChild(select);
  2065. holder.appendChild(desc);
  2066. menubar.appendChild(holder);
  2067. holder.classList.add("enabled");
  2068. const update = () => {
  2069. entry.value = select.value;
  2070. }
  2071. update();
  2072. select.addEventListener("change", update);
  2073. }
  2074. })
  2075. }
  2076. function prepareMenu() {
  2077. prepareSidebar();
  2078. updateSaveInfo();
  2079. if (checkHelpDate()) {
  2080. document.querySelector("#open-help").classList.add("highlighted");
  2081. }
  2082. }
  2083. function updateSaveInfo() {
  2084. const saves = getSaves();
  2085. const load = document.querySelector("#menu-load ~ select");
  2086. load.innerHTML = "";
  2087. saves.forEach(save => {
  2088. const option = document.createElement("option");
  2089. option.innerText = save;
  2090. option.value = save;
  2091. load.appendChild(option);
  2092. });
  2093. const del = document.querySelector("#menu-delete ~ select");
  2094. del.innerHTML = "";
  2095. saves.forEach(save => {
  2096. const option = document.createElement("option");
  2097. option.innerText = save;
  2098. option.value = save;
  2099. del.appendChild(option);
  2100. });
  2101. }
  2102. function getSaves() {
  2103. try {
  2104. const results = [];
  2105. Object.keys(localStorage).forEach(key => {
  2106. if (key.startsWith("macrovision-save-")) {
  2107. results.push(key.replace("macrovision-save-", ""));
  2108. }
  2109. })
  2110. return results;
  2111. } catch (err) {
  2112. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2113. console.error(err);
  2114. return false;
  2115. }
  2116. }
  2117. function getUserSettings() {
  2118. try {
  2119. const settings = JSON.parse(localStorage.getItem("settings"));
  2120. return settings === null ? {} : settings;
  2121. } catch {
  2122. return {};
  2123. }
  2124. }
  2125. function exportUserSettings() {
  2126. const settings = {};
  2127. Object.entries(settingsData).forEach(([id, entry]) => {
  2128. settings[id] = entry.value;
  2129. });
  2130. return settings;
  2131. }
  2132. function setUserSettings(settings) {
  2133. try {
  2134. localStorage.setItem("settings", JSON.stringify(settings));
  2135. } catch {
  2136. // :(
  2137. }
  2138. }
  2139. const lastHelpChange = 1601955834693;
  2140. function checkHelpDate() {
  2141. try {
  2142. const old = localStorage.getItem("help-viewed");
  2143. if (old === null || old < lastHelpChange) {
  2144. return true;
  2145. }
  2146. return false;
  2147. } catch {
  2148. console.warn("Could not set the help-viewed date");
  2149. return false;
  2150. }
  2151. }
  2152. function setHelpDate() {
  2153. try {
  2154. localStorage.setItem("help-viewed", Date.now());
  2155. } catch {
  2156. console.warn("Could not set the help-viewed date");
  2157. }
  2158. }
  2159. function doYScroll() {
  2160. const worldHeight = config.height.toNumber("meters");
  2161. config.y += scrollDirection * worldHeight / 180;
  2162. updateSizes();
  2163. scrollDirection *= 1.05;
  2164. }
  2165. function doXScroll() {
  2166. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2167. config.x += scrollDirection * worldWidth / 180 ;
  2168. updateSizes();
  2169. scrollDirection *= 1.05;
  2170. }
  2171. function doZoom() {
  2172. const oldHeight = config.height;
  2173. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  2174. zoomDirection *= 1.05;
  2175. }
  2176. function doSize() {
  2177. if (selected) {
  2178. const entity = entities[selected.dataset.key];
  2179. const oldHeight = entity.views[entity.view].height;
  2180. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  2181. entity.dirty = true;
  2182. updateEntityOptions(entity, entity.view);
  2183. updateViewOptions(entity, entity.view);
  2184. updateSizes(true);
  2185. sizeDirection *= 1.01;
  2186. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  2187. const worldHeight = config.height.toNumber("meters");
  2188. if (ownHeight > worldHeight) {
  2189. setWorldHeight(config.height, entity.views[entity.view].height)
  2190. } else if (ownHeight * 10 < worldHeight) {
  2191. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  2192. }
  2193. }
  2194. }
  2195. document.addEventListener("DOMContentLoaded", () => {
  2196. prepareMenu();
  2197. prepareEntities();
  2198. document.querySelector("#open-help").addEventListener("click", e => {
  2199. setHelpDate();
  2200. document.querySelector("#open-help").classList.remove("highlighted");
  2201. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  2202. });
  2203. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  2204. copyScreenshot();
  2205. toast("Copied to clipboard!");
  2206. });
  2207. document.querySelector("#save-screenshot").addEventListener("click", e => {
  2208. saveScreenshot();
  2209. });
  2210. document.querySelector("#open-screenshot").addEventListener("click", e => {
  2211. openScreenshot();
  2212. });
  2213. document.querySelector("#toggle-menu").addEventListener("click", e => {
  2214. const popoutMenu = document.querySelector("#sidebar-menu");
  2215. if (popoutMenu.classList.contains("visible")) {
  2216. popoutMenu.classList.remove("visible");
  2217. } else {
  2218. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2219. const rect = e.target.getBoundingClientRect();
  2220. popoutMenu.classList.add("visible");
  2221. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2222. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2223. }
  2224. e.stopPropagation();
  2225. });
  2226. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  2227. e.stopPropagation();
  2228. });
  2229. document.addEventListener("click", e => {
  2230. document.querySelector("#sidebar-menu").classList.remove("visible");
  2231. });
  2232. document.querySelector("#toggle-settings").addEventListener("click", e => {
  2233. const popoutMenu = document.querySelector("#settings-menu");
  2234. if (popoutMenu.classList.contains("visible")) {
  2235. popoutMenu.classList.remove("visible");
  2236. } else {
  2237. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2238. const rect = e.target.getBoundingClientRect();
  2239. popoutMenu.classList.add("visible");
  2240. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2241. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2242. }
  2243. e.stopPropagation();
  2244. });
  2245. document.querySelector("#settings-menu").addEventListener("click", e => {
  2246. e.stopPropagation();
  2247. });
  2248. document.addEventListener("click", e => {
  2249. document.querySelector("#settings-menu").classList.remove("visible");
  2250. });
  2251. window.addEventListener("unload", () => {
  2252. saveScene("autosave");
  2253. setUserSettings(exportUserSettings());
  2254. });
  2255. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  2256. if (e.target.value == "None") {
  2257. deselect()
  2258. } else {
  2259. select(document.querySelector("#entity-" + e.target.value));
  2260. }
  2261. });
  2262. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  2263. const sidebar = document.querySelector("#options");
  2264. if (sidebar.classList.contains("hidden")) {
  2265. sidebar.classList.remove("hidden");
  2266. e.target.classList.remove("rotate-forward");
  2267. e.target.classList.add("rotate-backward");
  2268. } else {
  2269. sidebar.classList.add("hidden");
  2270. e.target.classList.add("rotate-forward");
  2271. e.target.classList.remove("rotate-backward");
  2272. }
  2273. handleResize();
  2274. });
  2275. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2276. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2277. if (selected) {
  2278. entities[selected.dataset.key].priority += 1;
  2279. }
  2280. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2281. updateSizes();
  2282. });
  2283. document.querySelector("#options-order-back").addEventListener("click", e => {
  2284. if (selected) {
  2285. entities[selected.dataset.key].priority -= 1;
  2286. }
  2287. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2288. updateSizes();
  2289. });
  2290. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  2291. if (selected) {
  2292. entities[selected.dataset.key].brightness += 1;
  2293. }
  2294. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2295. updateSizes();
  2296. });
  2297. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  2298. if (selected) {
  2299. entities[selected.dataset.key].brightness = Math.max(entities[selected.dataset.key].brightness -1, 0);
  2300. }
  2301. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2302. updateSizes();
  2303. });
  2304. document.querySelector("#options-flip").addEventListener("click", e => {
  2305. if (selected) {
  2306. selected.querySelector(".entity-image").classList.toggle("flipped");
  2307. }
  2308. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2309. updateSizes();
  2310. });
  2311. const sceneChoices = document.querySelector("#scene-choices");
  2312. Object.entries(scenes).forEach(([id, scene]) => {
  2313. const option = document.createElement("option");
  2314. option.innerText = id;
  2315. option.value = id;
  2316. sceneChoices.appendChild(option);
  2317. });
  2318. document.querySelector("#load-scene").addEventListener("click", e => {
  2319. const chosen = sceneChoices.value;
  2320. removeAllEntities();
  2321. scenes[chosen]();
  2322. });
  2323. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2324. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2325. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2326. document.querySelector("#options-height-value").addEventListener("change", e => {
  2327. updateWorldHeight();
  2328. })
  2329. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  2330. e.stopPropagation();
  2331. })
  2332. const unitSelector = document.querySelector("#options-height-unit");
  2333. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  2334. const optGroup = document.createElement("optgroup");
  2335. optGroup.label = group;
  2336. unitSelector.appendChild(optGroup);
  2337. entries.forEach(entry => {
  2338. const option = document.createElement("option");
  2339. option.innerText = entry;
  2340. // we haven't loaded user settings yet, so we can't choose the unit just yet
  2341. unitSelector.appendChild(option);
  2342. })
  2343. });
  2344. unitSelector.addEventListener("input", e => {
  2345. checkFitWorld();
  2346. const scaleInput = document.querySelector("#options-height-value");
  2347. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(e.target.value);
  2348. setNumericInput(scaleInput, newVal);
  2349. updateWorldHeight();
  2350. unitSelector.dataset.oldUnit = unitSelector.value;
  2351. });
  2352. param = new URL(window.location.href).searchParams.get("scene");
  2353. document.querySelector("#world").addEventListener("mousedown", e => {
  2354. // only middle mouse clicks
  2355. if (e.which == 2) {
  2356. panning = true;
  2357. panOffsetX = e.clientX;
  2358. panOffsetY = e.clientY;
  2359. Object.keys(entities).forEach(key => {
  2360. document.querySelector("#entity-" + key).classList.add("no-transition");
  2361. });
  2362. }
  2363. });
  2364. document.addEventListener("mouseup", e => {
  2365. if (e.which == 2) {
  2366. panning = false;
  2367. Object.keys(entities).forEach(key => {
  2368. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2369. });
  2370. }
  2371. });
  2372. document.querySelector("#world").addEventListener("touchstart", e => {
  2373. if (!rulerMode) {
  2374. panning = true;
  2375. panOffsetX = e.touches[0].clientX;
  2376. panOffsetY = e.touches[0].clientY;
  2377. e.preventDefault();
  2378. Object.keys(entities).forEach(key => {
  2379. document.querySelector("#entity-" + key).classList.add("no-transition");
  2380. });
  2381. }
  2382. });
  2383. document.querySelector("#world").addEventListener("touchend", e => {
  2384. panning = false;
  2385. Object.keys(entities).forEach(key => {
  2386. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2387. });
  2388. });
  2389. document.querySelector("#world").addEventListener("mousedown", e => {
  2390. // only left mouse clicks
  2391. if (e.which == 1 && rulerMode) {
  2392. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2393. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2394. const pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  2395. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y };
  2396. }
  2397. });
  2398. document.querySelector("#world").addEventListener("mouseup", e => {
  2399. // only left mouse clicks
  2400. if (e.which == 1 && currentRuler) {
  2401. rulers.push(currentRuler);
  2402. currentRuler = null;
  2403. rulerMode = false;
  2404. }
  2405. });
  2406. document.querySelector("#world").addEventListener("touchstart", e => {
  2407. if (rulerMode) {
  2408. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2409. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2410. const pos = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  2411. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y };
  2412. }
  2413. });
  2414. document.querySelector("#world").addEventListener("touchend", e => {
  2415. if (currentRuler) {
  2416. rulers.push(currentRuler);
  2417. currentRuler = null;
  2418. rulerMode = false;
  2419. }
  2420. });
  2421. document.querySelector("body").appendChild(testCtx.canvas);
  2422. world.addEventListener("mousedown", e => deselect(e));
  2423. world.addEventListener("touchstart", e => deselect({
  2424. which: 1,
  2425. }));
  2426. document.querySelector("#entities").addEventListener("mousedown", deselect);
  2427. document.querySelector("#display").addEventListener("mousedown", deselect);
  2428. document.addEventListener("mouseup", e => clickUp(e));
  2429. document.addEventListener("touchend", e => {
  2430. const fakeEvent = {
  2431. target: e.target,
  2432. clientX: e.changedTouches[0].clientX,
  2433. clientY: e.changedTouches[0].clientY,
  2434. which: 1
  2435. };
  2436. clickUp(fakeEvent);
  2437. });
  2438. const viewList = document.querySelector("#entity-view");
  2439. document.querySelector("#entity-view").addEventListener("input", e => {
  2440. const entity = entities[selected.dataset.key];
  2441. entity.view = e.target.value;
  2442. const image = entities[selected.dataset.key].views[e.target.value].image;
  2443. selected.querySelector(".entity-image").src = image.source;
  2444. configViewOptions(entity, entity.view);
  2445. displayAttribution(image.source);
  2446. if (image.bottom !== undefined) {
  2447. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  2448. } else {
  2449. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  2450. }
  2451. updateSizes();
  2452. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  2453. updateViewOptions(entities[selected.dataset.key], e.target.value);
  2454. });
  2455. document.querySelector("#entity-view").addEventListener("input", e => {
  2456. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  2457. viewList.classList.add("nsfw");
  2458. } else {
  2459. viewList.classList.remove("nsfw");
  2460. }
  2461. })
  2462. clearViewList();
  2463. document.querySelector("#menu-clear").addEventListener("click", e => {
  2464. removeAllEntities();
  2465. });
  2466. document.querySelector("#delete-entity").disabled = true;
  2467. document.querySelector("#delete-entity").addEventListener("click", e => {
  2468. if (selected) {
  2469. removeEntity(selected);
  2470. selected = null;
  2471. }
  2472. });
  2473. document.querySelector("#menu-order-height").addEventListener("click", e => {
  2474. const order = Object.keys(entities).sort((a, b) => {
  2475. const entA = entities[a];
  2476. const entB = entities[b];
  2477. const viewA = entA.view;
  2478. const viewB = entB.view;
  2479. const heightA = entA.views[viewA].height.to("meter").value;
  2480. const heightB = entB.views[viewB].height.to("meter").value;
  2481. return heightA - heightB;
  2482. });
  2483. arrangeEntities(order);
  2484. });
  2485. // TODO: write some generic logic for this lol
  2486. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  2487. scrollDirection = -1;
  2488. clearInterval(scrollHandle);
  2489. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2490. e.stopPropagation();
  2491. });
  2492. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  2493. scrollDirection = 1;
  2494. clearInterval(scrollHandle);
  2495. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2496. e.stopPropagation();
  2497. });
  2498. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  2499. scrollDirection = -1;
  2500. clearInterval(scrollHandle);
  2501. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2502. e.stopPropagation();
  2503. });
  2504. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  2505. scrollDirection = 1;
  2506. clearInterval(scrollHandle);
  2507. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2508. e.stopPropagation();
  2509. });
  2510. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  2511. scrollDirection = 1;
  2512. clearInterval(scrollHandle);
  2513. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2514. e.stopPropagation();
  2515. });
  2516. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  2517. scrollDirection = -1;
  2518. clearInterval(scrollHandle);
  2519. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2520. e.stopPropagation();
  2521. });
  2522. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  2523. scrollDirection = 1;
  2524. clearInterval(scrollHandle);
  2525. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2526. e.stopPropagation();
  2527. });
  2528. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  2529. scrollDirection = -1;
  2530. clearInterval(scrollHandle);
  2531. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2532. e.stopPropagation();
  2533. });
  2534. document.addEventListener("mouseup", e => {
  2535. clearInterval(scrollHandle);
  2536. scrollHandle = null;
  2537. });
  2538. document.addEventListener("touchend", e => {
  2539. clearInterval(scrollHandle);
  2540. scrollHandle = null;
  2541. });
  2542. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  2543. zoomDirection = -1;
  2544. clearInterval(zoomHandle);
  2545. zoomHandle = setInterval(doZoom, 1000 / 20);
  2546. e.stopPropagation();
  2547. });
  2548. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  2549. zoomDirection = 1;
  2550. clearInterval(zoomHandle);
  2551. zoomHandle = setInterval(doZoom, 1000 / 20);
  2552. e.stopPropagation();
  2553. });
  2554. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  2555. zoomDirection = -1;
  2556. clearInterval(zoomHandle);
  2557. zoomHandle = setInterval(doZoom, 1000 / 20);
  2558. e.stopPropagation();
  2559. });
  2560. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  2561. zoomDirection = 1;
  2562. clearInterval(zoomHandle);
  2563. zoomHandle = setInterval(doZoom, 1000 / 20);
  2564. e.stopPropagation();
  2565. });
  2566. document.addEventListener("mouseup", e => {
  2567. clearInterval(zoomHandle);
  2568. zoomHandle = null;
  2569. });
  2570. document.addEventListener("touchend", e => {
  2571. clearInterval(zoomHandle);
  2572. zoomHandle = null;
  2573. });
  2574. document.querySelector("#shrink").addEventListener("mousedown", e => {
  2575. sizeDirection = -1;
  2576. clearInterval(sizeHandle);
  2577. sizeHandle = setInterval(doSize, 1000 / 20);
  2578. e.stopPropagation();
  2579. });
  2580. document.querySelector("#grow").addEventListener("mousedown", e => {
  2581. sizeDirection = 1;
  2582. clearInterval(sizeHandle);
  2583. sizeHandle = setInterval(doSize, 1000 / 20);
  2584. e.stopPropagation();
  2585. });
  2586. document.querySelector("#shrink").addEventListener("touchstart", e => {
  2587. sizeDirection = -1;
  2588. clearInterval(sizeHandle);
  2589. sizeHandle = setInterval(doSize, 1000 / 20);
  2590. e.stopPropagation();
  2591. });
  2592. document.querySelector("#grow").addEventListener("touchstart", e => {
  2593. sizeDirection = 1;
  2594. clearInterval(sizeHandle);
  2595. sizeHandle = setInterval(doSize, 1000 / 20);
  2596. e.stopPropagation();
  2597. });
  2598. document.addEventListener("mouseup", e => {
  2599. clearInterval(sizeHandle);
  2600. sizeHandle = null;
  2601. });
  2602. document.addEventListener("touchend", e => {
  2603. clearInterval(sizeHandle);
  2604. sizeHandle = null;
  2605. });
  2606. document.querySelector("#ruler").addEventListener("click", e => {
  2607. rulerMode = !rulerMode;
  2608. if (rulerMode) {
  2609. toast("Ready to draw a ruler mark");
  2610. } else {
  2611. toast("Cancelled ruler mode");
  2612. }
  2613. });
  2614. document.querySelector("#ruler").addEventListener("mousedown", e => {
  2615. e.stopPropagation();
  2616. });
  2617. document.querySelector("#ruler").addEventListener("touchstart", e => {
  2618. e.stopPropagation();
  2619. });
  2620. document.querySelector("#fit").addEventListener("click", e => {
  2621. if (selected) {
  2622. let targets = {};
  2623. targets[selected.dataset.key] = entities[selected.dataset.key];
  2624. fitEntities(targets);
  2625. }
  2626. });
  2627. document.querySelector("#fit").addEventListener("mousedown", e => {
  2628. e.stopPropagation();
  2629. });
  2630. document.querySelector("#fit").addEventListener("touchstart", e => {
  2631. e.stopPropagation();
  2632. });
  2633. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  2634. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  2635. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  2636. document.addEventListener("keydown", e => {
  2637. if (e.key == "Delete") {
  2638. if (selected) {
  2639. removeEntity(selected);
  2640. selected = null;
  2641. }
  2642. }
  2643. })
  2644. document.addEventListener("keydown", e => {
  2645. if (e.key == "Shift") {
  2646. shiftHeld = true;
  2647. e.preventDefault();
  2648. } else if (e.key == "Alt") {
  2649. altHeld = true;
  2650. movingInBounds = false; // don't snap the object back in bounds when we let go
  2651. e.preventDefault();
  2652. }
  2653. });
  2654. document.addEventListener("keyup", e => {
  2655. if (e.key == "Shift") {
  2656. shiftHeld = false;
  2657. e.preventDefault();
  2658. } else if (e.key == "Alt") {
  2659. altHeld = false;
  2660. e.preventDefault();
  2661. }
  2662. });
  2663. window.addEventListener("resize", handleResize);
  2664. // TODO: further investigate why the tool initially starts out with wrong
  2665. // values under certain circumstances (seems to be narrow aspect ratios -
  2666. // maybe the menu bar is animating when it shouldn't)
  2667. setTimeout(handleResize, 250);
  2668. setTimeout(handleResize, 500);
  2669. setTimeout(handleResize, 750);
  2670. setTimeout(handleResize, 1000);
  2671. document.querySelector("#menu-permalink").addEventListener("click", e => {
  2672. linkScene();
  2673. });
  2674. document.querySelector("#menu-export").addEventListener("click", e => {
  2675. copyScene();
  2676. });
  2677. document.querySelector("#menu-import").addEventListener("click", e => {
  2678. pasteScene();
  2679. });
  2680. document.querySelector("#menu-save").addEventListener("click", e => {
  2681. const name = document.querySelector("#menu-save ~ input").value;
  2682. if (/\S/.test(name)) {
  2683. saveScene(name);
  2684. }
  2685. updateSaveInfo();
  2686. });
  2687. document.querySelector("#menu-load").addEventListener("click", e => {
  2688. const name = document.querySelector("#menu-load ~ select").value;
  2689. if (/\S/.test(name)) {
  2690. loadScene(name);
  2691. }
  2692. });
  2693. document.querySelector("#menu-delete").addEventListener("click", e => {
  2694. const name = document.querySelector("#menu-delete ~ select").value;
  2695. if (/\S/.test(name)) {
  2696. deleteScene(name);
  2697. }
  2698. });
  2699. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  2700. loadScene("autosave");
  2701. });
  2702. document.querySelector("#menu-add-image").addEventListener("click", e => {
  2703. document.querySelector("#file-upload-picker").click();
  2704. });
  2705. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  2706. if (e.target.files.length > 0) {
  2707. for (let i=0; i<e.target.files.length; i++) {
  2708. customEntityFromFile(e.target.files[i]);
  2709. }
  2710. }
  2711. })
  2712. document.querySelector("#menu-clear-rulers").addEventListener("click", e => {
  2713. rulers = [];
  2714. drawRulers();
  2715. });
  2716. document.addEventListener("paste", e => {
  2717. let index = 0;
  2718. let item = null;
  2719. let found = false;
  2720. for (; index < e.clipboardData.items.length; index++) {
  2721. item = e.clipboardData.items[index];
  2722. if (item.type == "image/png") {
  2723. found = true;
  2724. break;
  2725. }
  2726. }
  2727. if (!found) {
  2728. return;
  2729. }
  2730. let url = null;
  2731. const file = item.getAsFile();
  2732. customEntityFromFile(file);
  2733. });
  2734. document.querySelector("#world").addEventListener("dragover", e => {
  2735. e.preventDefault();
  2736. })
  2737. document.querySelector("#world").addEventListener("drop", e => {
  2738. e.preventDefault();
  2739. if (e.dataTransfer.files.length > 0) {
  2740. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2741. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2742. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  2743. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  2744. }
  2745. })
  2746. clearEntityOptions();
  2747. clearViewOptions();
  2748. clearAttribution();
  2749. // we do this last because configuring settings can cause things
  2750. // to happen (e.g. auto-fit)
  2751. prepareSettings(getUserSettings());
  2752. // now that we have this loaded, we can set it
  2753. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  2754. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  2755. // ...and then update the world height by setting off an input event
  2756. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  2757. }));
  2758. if (param === null) {
  2759. scenes["Empty"]();
  2760. }
  2761. else {
  2762. try {
  2763. const data = JSON.parse(b64DecodeUnicode(param));
  2764. if (data.entities === undefined) {
  2765. return;
  2766. }
  2767. if (data.world === undefined) {
  2768. return;
  2769. }
  2770. importScene(data);
  2771. } catch (err) {
  2772. console.error(err);
  2773. scenes["Empty"]();
  2774. // probably wasn't valid data
  2775. }
  2776. }
  2777. document.querySelector("#world").addEventListener("wheel", e => {
  2778. if (shiftHeld) {
  2779. if (selected) {
  2780. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  2781. const entity = entities[selected.dataset.key];
  2782. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  2783. entity.dirty = true;
  2784. updateEntityOptions(entity, entity.view);
  2785. updateViewOptions(entity, entity.view);
  2786. updateSizes(true);
  2787. } else {
  2788. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2789. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  2790. updateSizes();
  2791. updateSizes();
  2792. }
  2793. } else {
  2794. if (config.autoFit) {
  2795. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  2796. } else {
  2797. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  2798. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  2799. if (!config.lockYAxis) {
  2800. config.y += change / 2;
  2801. }
  2802. setWorldHeight(config.height, math.multiply(config.height, dir));
  2803. updateWorldOptions();
  2804. }
  2805. }
  2806. checkFitWorld();
  2807. })
  2808. updateWorldHeight();
  2809. });
  2810. function customEntityFromFile(file, x=0.5, y=0.5) {
  2811. file.arrayBuffer().then(buf => {
  2812. arr = new Uint8Array(buf);
  2813. blob = new Blob([arr], {type: file.type });
  2814. url = window.URL.createObjectURL(blob)
  2815. makeCustomEntity(url, x, y);
  2816. });
  2817. }
  2818. function makeCustomEntity(url, x=0.5, y=0.5) {
  2819. const maker = createEntityMaker(
  2820. {
  2821. name: "Custom Entity"
  2822. },
  2823. {
  2824. custom: {
  2825. attributes: {
  2826. height: {
  2827. name: "Height",
  2828. power: 1,
  2829. type: "length",
  2830. base: math.unit(6, "feet")
  2831. }
  2832. },
  2833. image: {
  2834. source: url
  2835. },
  2836. name: "Image",
  2837. info: {},
  2838. rename: false
  2839. }
  2840. },
  2841. []
  2842. );
  2843. const entity = maker.constructor();
  2844. entity.scale = config.height.toNumber("feet") / 20;
  2845. entity.ephemeral = true;
  2846. displayEntity(entity, "custom", x, y, true, true);
  2847. }
  2848. const filterDefs = {
  2849. none: {
  2850. id: "none",
  2851. name: "No Filter",
  2852. extract: maker => [],
  2853. render: name => name,
  2854. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2855. },
  2856. author: {
  2857. id: "author",
  2858. name: "Authors",
  2859. extract: maker => maker.authors ? maker.authors : [],
  2860. render: author => attributionData.people[author].name,
  2861. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2862. },
  2863. owner: {
  2864. id: "owner",
  2865. name: "Owners",
  2866. extract: maker => maker.owners ? maker.owners : [],
  2867. render: owner => attributionData.people[owner].name,
  2868. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2869. },
  2870. species: {
  2871. id: "species",
  2872. name: "Species",
  2873. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  2874. render: species => speciesData[species].name,
  2875. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2876. },
  2877. tags: {
  2878. id: "tags",
  2879. name: "Tags",
  2880. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  2881. render: tag => tagDefs[tag],
  2882. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2883. },
  2884. size: {
  2885. id: "size",
  2886. name: "Normal Size",
  2887. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  2888. if (result && !size.default) {
  2889. return result;
  2890. }
  2891. let meters = size.height.toNumber("meters");
  2892. if (meters < 1e-1) {
  2893. return ["micro"];
  2894. } else if (meters < 1e1) {
  2895. return ["moderate"];
  2896. } else {
  2897. return ["macro"];
  2898. }
  2899. }, null)) : [],
  2900. render: tag => { return {
  2901. "micro": "Micro",
  2902. "moderate": "Moderate",
  2903. "macro": "Macro"
  2904. }[tag]},
  2905. sort: (tag1, tag2) => {
  2906. const order = {
  2907. "micro": 0,
  2908. "moderate": 1,
  2909. "macro": 2
  2910. };
  2911. return order[tag1[0]] - order[tag2[0]];
  2912. }
  2913. },
  2914. allSizes: {
  2915. id: "allSizes",
  2916. name: "Possible Size",
  2917. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  2918. const height = size.height;
  2919. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  2920. if (result) {
  2921. return result;
  2922. } else {
  2923. if (math.compare(height, value) <= 0) {
  2924. return name;
  2925. }
  2926. }
  2927. }, null);
  2928. set.add(result ? result : "infinite");
  2929. return set;
  2930. }, new Set())) : [],
  2931. render: tag => tag[0].toUpperCase() + tag.slice(1),
  2932. sort: (tag1, tag2) => {
  2933. const order = [
  2934. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  2935. "galactic", "universal", "omniversal", "infinite"
  2936. ]
  2937. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  2938. }
  2939. }
  2940. }
  2941. const sizeCategories = {
  2942. "atomic": math.unit(100, "angstroms"),
  2943. "microscopic": math.unit(100, "micrometers"),
  2944. "tiny": math.unit(100, "millimeters"),
  2945. "small": math.unit(1, "meter"),
  2946. "moderate": math.unit(3, "meters"),
  2947. "large": math.unit(10, "meters"),
  2948. "macro": math.unit(300, "meters"),
  2949. "megamacro": math.unit(1000, "kilometers"),
  2950. "planetary": math.unit(10, "earths"),
  2951. "stellar": math.unit(10, "solarradii"),
  2952. "galactic": math.unit(10, "galaxies"),
  2953. "universal": math.unit(10, "universes"),
  2954. "omniversal": math.unit(10, "multiverses")
  2955. };
  2956. function prepareEntities() {
  2957. availableEntities["buildings"] = makeBuildings();
  2958. availableEntities["characters"] = makeCharacters();
  2959. availableEntities["creatures"] = makeCreatures();
  2960. availableEntities["dildos"] = makeDildos();
  2961. availableEntities["fiction"] = makeFiction();
  2962. availableEntities["food"] = makeFood();
  2963. availableEntities["furniture"] = makeFurniture();
  2964. availableEntities["landmarks"] = makeLandmarks();
  2965. availableEntities["naturals"] = makeNaturals();
  2966. availableEntities["objects"] = makeObjects();
  2967. availableEntities["pokemon"] = makePokemon();
  2968. availableEntities["real-buildings"] = makeRealBuildings();
  2969. availableEntities["real-terrain"] = makeRealTerrains();
  2970. availableEntities["species"] = makeSpecies();
  2971. availableEntities["vehicles"] = makeVehicles();
  2972. availableEntities["species"].forEach(x => {
  2973. if (x.name == "Human") {
  2974. availableEntities["food"].push(x);
  2975. }
  2976. })
  2977. availableEntities["characters"].sort((x, y) => {
  2978. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  2979. });
  2980. availableEntities["species"].sort((x, y) => {
  2981. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  2982. });
  2983. const holder = document.querySelector("#spawners");
  2984. const filterHolder = document.querySelector("#filters");
  2985. const categorySelect = document.createElement("select");
  2986. categorySelect.id = "category-picker";
  2987. const filterSelect = document.createElement("select");
  2988. filterSelect.id = "filter-picker";
  2989. holder.appendChild(categorySelect);
  2990. filterHolder.appendChild(filterSelect);
  2991. const filterSets = {};
  2992. Object.values(filterDefs).forEach(filter => {
  2993. filterSets[filter.id] = new Set();
  2994. })
  2995. Object.entries(availableEntities).forEach(([category, entityList]) => {
  2996. const select = document.createElement("select");
  2997. select.id = "create-entity-" + category;
  2998. select.classList.add("entity-select");
  2999. for (let i = 0; i < entityList.length; i++) {
  3000. const entity = entityList[i];
  3001. const option = document.createElement("option");
  3002. option.value = i;
  3003. option.innerText = entity.name;
  3004. select.appendChild(option);
  3005. if (entity.nsfw) {
  3006. option.classList.add("nsfw");
  3007. }
  3008. Object.values(filterDefs).forEach(filter => {
  3009. filter.extract(entity).forEach(result => {
  3010. filterSets[filter.id].add(result);
  3011. });
  3012. });
  3013. availableEntitiesByName[entity.name] = entity;
  3014. };
  3015. select.addEventListener("change", e => {
  3016. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  3017. select.classList.add("nsfw");
  3018. } else {
  3019. select.classList.remove("nsfw");
  3020. }
  3021. // preload the entity's first image
  3022. const entity = entityList[select.selectedIndex].constructor();
  3023. let img = new Image();
  3024. img.src = entity.currentView.image.source;
  3025. })
  3026. const button = document.createElement("button");
  3027. button.id = "create-entity-" + category + "-button";
  3028. button.classList.add("entity-button");
  3029. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  3030. button.addEventListener("click", e => {
  3031. const newEntity = entityList[select.value].constructor()
  3032. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + (config.lockYAxis ? 0 : config.height.toNumber("meters")/2), true, true);
  3033. });
  3034. const categoryOption = document.createElement("option");
  3035. categoryOption.value = category
  3036. categoryOption.innerText = category;
  3037. if (category == "characters") {
  3038. categoryOption.selected = true;
  3039. select.classList.add("category-visible");
  3040. button.classList.add("category-visible");
  3041. }
  3042. categorySelect.appendChild(categoryOption);
  3043. holder.appendChild(select);
  3044. holder.appendChild(button);
  3045. });
  3046. Object.values(filterDefs).forEach(filter => {
  3047. const option = document.createElement("option");
  3048. option.innerText = filter.name;
  3049. option.value = filter.id;
  3050. filterSelect.appendChild(option);
  3051. const filterNameSelect = document.createElement("select");
  3052. filterNameSelect.classList.add("filter-select");
  3053. filterNameSelect.id = "filter-" + filter.id;
  3054. filterHolder.appendChild(filterNameSelect);
  3055. const button = document.createElement("button");
  3056. button.classList.add("filter-button");
  3057. button.id = "create-filtered-" + filter.id + "-button";
  3058. filterHolder.appendChild(button);
  3059. const counter = document.createElement("div");
  3060. counter.classList.add("button-counter");
  3061. counter.innerText = "10";
  3062. button.appendChild(counter);
  3063. const i = document.createElement("i");
  3064. i.classList.add("fas");
  3065. i.classList.add("fa-plus");
  3066. button.appendChild(i);
  3067. button.addEventListener("click", e => {
  3068. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  3069. const count = makers.length + 2;
  3070. let index = 1;
  3071. if (makers.length > 50) {
  3072. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  3073. return;
  3074. }
  3075. }
  3076. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3077. const spawned = makers.map(element => {
  3078. const category = document.querySelector("#category-picker").value;
  3079. const maker = availableEntities[category][element.value];
  3080. const entity = maker.constructor()
  3081. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  3082. index += 1;
  3083. return entityIndex - 1;
  3084. });
  3085. updateSizes(true);
  3086. if (config.autoFitAdd) {
  3087. let targets = {};
  3088. spawned.forEach(key => {
  3089. targets[key] = entities[key];
  3090. })
  3091. fitEntities(targets);
  3092. }
  3093. });
  3094. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  3095. const option = document.createElement("option");
  3096. option.innerText = name[1];
  3097. option.value = name[0];
  3098. filterNameSelect.appendChild(option);
  3099. });
  3100. filterNameSelect.addEventListener("change", e => {
  3101. updateFilter();
  3102. });
  3103. });
  3104. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  3105. categorySelect.addEventListener("input", e => {
  3106. const oldSelect = document.querySelector(".entity-select.category-visible");
  3107. oldSelect.classList.remove("category-visible");
  3108. const oldButton = document.querySelector(".entity-button.category-visible");
  3109. oldButton.classList.remove("category-visible");
  3110. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  3111. newSelect.classList.add("category-visible");
  3112. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  3113. newButton.classList.add("category-visible");
  3114. recomputeFilters();
  3115. updateFilter();
  3116. });
  3117. recomputeFilters();
  3118. filterSelect.addEventListener("input", e => {
  3119. const oldSelect = document.querySelector(".filter-select.category-visible");
  3120. if (oldSelect)
  3121. oldSelect.classList.remove("category-visible");
  3122. const newSelect = document.querySelector("#filter-" + e.target.value);
  3123. if (newSelect && e.target.value != "none")
  3124. newSelect.classList.add("category-visible");
  3125. updateFilter();
  3126. });
  3127. }
  3128. // Only display authors and owners if they appear
  3129. // somewhere in the current entity list
  3130. function recomputeFilters() {
  3131. const category = document.querySelector("#category-picker").value;
  3132. const filterSets = {};
  3133. Object.values(filterDefs).forEach(filter => {
  3134. filterSets[filter.id] = new Set();
  3135. });
  3136. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3137. const entity = availableEntities[category][element.value];
  3138. Object.values(filterDefs).forEach(filter => {
  3139. filter.extract(entity).forEach(result => {
  3140. filterSets[filter.id].add(result);
  3141. });
  3142. });
  3143. });
  3144. Object.values(filterDefs).forEach(filter => {
  3145. // always show the "none" option
  3146. let found = filter.id == "none";
  3147. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  3148. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  3149. element.classList.remove("filtered");
  3150. element.disabled = false;
  3151. found = true;
  3152. } else {
  3153. element.classList.add("filtered");
  3154. element.disabled = true;
  3155. }
  3156. });
  3157. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  3158. if (found) {
  3159. filterOption.classList.remove("filtered");
  3160. filterOption.disabled = false;
  3161. } else {
  3162. filterOption.classList.add("filtered");
  3163. filterOption.disabled = true;
  3164. }
  3165. });
  3166. document.querySelector("#filter-picker").value = "none";
  3167. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  3168. }
  3169. function updateFilter() {
  3170. const category = document.querySelector("#category-picker").value;
  3171. const type = document.querySelector("#filter-picker").value;
  3172. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  3173. clearFilter();
  3174. if (!filterKeySelect) {
  3175. return;
  3176. }
  3177. const key = filterKeySelect.value;
  3178. let current = document.querySelector(".entity-select.category-visible").value;
  3179. let replace = false;
  3180. let first = null;
  3181. let count = 0;
  3182. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3183. let keep = type == "none";
  3184. if (filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  3185. keep = true;
  3186. }
  3187. if (!keep) {
  3188. element.classList.add("filtered");
  3189. element.disabled = true;
  3190. if (current == element.value) {
  3191. replace = true;
  3192. }
  3193. } else {
  3194. count += 1;
  3195. if (!first) {
  3196. first = element.value;
  3197. }
  3198. }
  3199. });
  3200. const button = document.querySelector(".filter-select.category-visible + button");
  3201. if (button) {
  3202. button.querySelector(".button-counter").innerText = count;
  3203. }
  3204. if (replace) {
  3205. document.querySelector(".entity-select.category-visible").value = first;
  3206. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  3207. }
  3208. }
  3209. function clearFilter() {
  3210. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3211. element.classList.remove("filtered");
  3212. element.disabled = false;
  3213. });
  3214. }
  3215. document.addEventListener("mousemove", (e) => {
  3216. if (currentRuler) {
  3217. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3218. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3219. let position = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3220. currentRuler.x1 = position.x;
  3221. currentRuler.y1 = position.y;
  3222. }
  3223. drawRulers();
  3224. });
  3225. document.addEventListener("touchmove", (e) => {
  3226. if (currentRuler) {
  3227. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3228. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3229. let position = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3230. currentRuler.x1 = position.x;
  3231. currentRuler.y1 = position.y;
  3232. }
  3233. drawRulers();
  3234. });
  3235. document.addEventListener("mousemove", (e) => {
  3236. if (clicked) {
  3237. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  3238. if (movingInBounds) {
  3239. position = snapPos(position);
  3240. } else {
  3241. let x = e.clientX - dragOffsetX;
  3242. let y = e.clientY - dragOffsetY;
  3243. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  3244. movingInBounds = true;
  3245. }
  3246. }
  3247. clicked.dataset.x = position.x;
  3248. clicked.dataset.y = position.y;
  3249. updateEntityElement(entities[clicked.dataset.key], clicked);
  3250. if (hoveringInDeleteArea(e)) {
  3251. document.querySelector("#menubar").classList.add("hover-delete");
  3252. } else {
  3253. document.querySelector("#menubar").classList.remove("hover-delete");
  3254. }
  3255. }
  3256. if (panning && panReady) {
  3257. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3258. const worldHeight = config.height.toNumber("meters");
  3259. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  3260. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  3261. panOffsetX = e.clientX;
  3262. panOffsetY = e.clientY;
  3263. updateSizes();
  3264. panReady = false;
  3265. setTimeout(() => panReady=true, 1000/120);
  3266. }
  3267. });
  3268. document.addEventListener("touchmove", (e) => {
  3269. if (clicked) {
  3270. e.preventDefault();
  3271. let x = e.touches[0].clientX;
  3272. let y = e.touches[0].clientY;
  3273. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  3274. clicked.dataset.x = position.x;
  3275. clicked.dataset.y = position.y;
  3276. updateEntityElement(entities[clicked.dataset.key], clicked);
  3277. // what a hack
  3278. // I should centralize this 'fake event' creation...
  3279. if (hoveringInDeleteArea({ clientY: y })) {
  3280. document.querySelector("#menubar").classList.add("hover-delete");
  3281. } else {
  3282. document.querySelector("#menubar").classList.remove("hover-delete");
  3283. }
  3284. }
  3285. if (panning && panReady) {
  3286. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3287. const worldHeight = config.height.toNumber("meters");
  3288. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  3289. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  3290. panOffsetX = e.touches[0].clientX;
  3291. panOffsetY = e.touches[0].clientY;
  3292. updateSizes();
  3293. panReady = false;
  3294. setTimeout(() => panReady=true, 1000/60);
  3295. }
  3296. }, { passive: false });
  3297. function checkFitWorld() {
  3298. if (config.autoFit) {
  3299. fitWorld();
  3300. return true;
  3301. }
  3302. return false;
  3303. }
  3304. function fitWorld(manual = false, factor = 1.1) {
  3305. if (Object.keys(entities).length > 0) {
  3306. fitEntities(entities, factor);
  3307. }
  3308. }
  3309. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  3310. let minX = Infinity;
  3311. let maxX = -Infinity;
  3312. let minY = Infinity;
  3313. let maxY = -Infinity;
  3314. let count = 0;
  3315. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3316. const worldHeight = config.height.toNumber("meters");
  3317. Object.entries(targetEntities).forEach(([key, entity]) => {
  3318. const view = entity.view;
  3319. let extra = entity.views[view].image.extra;
  3320. extra = extra === undefined ? 1 : extra;
  3321. const image = document.querySelector("#entity-" + key + " > .entity-image");
  3322. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  3323. let width = image.width;
  3324. let height = image.height;
  3325. // only really relevant if the images haven't loaded in yet
  3326. if (height == 0) {
  3327. height = 100;
  3328. }
  3329. if (width == 0) {
  3330. width = height;
  3331. }
  3332. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  3333. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  3334. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  3335. const yBottom = y;
  3336. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  3337. minX = Math.min(minX, xBottom);
  3338. maxX = Math.max(maxX, xTop);
  3339. minY = Math.min(minY, yBottom);
  3340. maxY = Math.max(maxY, yTop);
  3341. count += 1;
  3342. });
  3343. if (config.lockYAxis) {
  3344. minY = 0;
  3345. }
  3346. let ySize = (maxY - minY) * factor;
  3347. let xSize = (maxX - minX) * factor;
  3348. if (xSize / ySize > worldWidth / worldHeight) {
  3349. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  3350. }
  3351. config.x = (maxX + minX) / 2;
  3352. config.y = minY;
  3353. height = math.unit(ySize, "meter")
  3354. setWorldHeight(config.height, math.multiply(height, factor));
  3355. }
  3356. // TODO why am I doing this
  3357. function updateWorldHeight() {
  3358. const unit = document.querySelector("#options-height-unit").value;
  3359. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  3360. const oldHeight = config.height;
  3361. setWorldHeight(oldHeight, math.unit(value, unit));
  3362. }
  3363. function setWorldHeight(oldHeight, newHeight) {
  3364. worldSizeDirty = true;
  3365. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  3366. const unit = document.querySelector("#options-height-unit").value;
  3367. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  3368. Object.entries(entities).forEach(([key, entity]) => {
  3369. const element = document.querySelector("#entity-" + key);
  3370. let newPosition;
  3371. if (altHeld) {
  3372. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  3373. } else {
  3374. newPosition = { x: element.dataset.x, y: element.dataset.y };
  3375. }
  3376. element.dataset.x = newPosition.x;
  3377. element.dataset.y = newPosition.y;
  3378. });
  3379. updateSizes();
  3380. }
  3381. function loadScene(name = "default") {
  3382. if (name === "") {
  3383. name = "default"
  3384. }
  3385. try {
  3386. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  3387. if (data === null) {
  3388. console.error("Couldn't load " + name)
  3389. return false;
  3390. }
  3391. importScene(data);
  3392. toast("Loaded " + name);
  3393. return true;
  3394. } catch (err) {
  3395. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  3396. console.error(err);
  3397. return false;
  3398. }
  3399. }
  3400. function saveScene(name = "default") {
  3401. try {
  3402. const string = JSON.stringify(exportScene());
  3403. localStorage.setItem("macrovision-save-" + name, string);
  3404. toast("Saved as " + name);
  3405. } catch (err) {
  3406. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  3407. console.error(err);
  3408. }
  3409. }
  3410. function deleteScene(name = "default") {
  3411. if (confirm("Really delete the " + name + " scene?")) {
  3412. try {
  3413. localStorage.removeItem("macrovision-save-" + name)
  3414. toast("Deleted " + name);
  3415. } catch (err) {
  3416. console.error(err);
  3417. }
  3418. }
  3419. updateSaveInfo();
  3420. }
  3421. function exportScene() {
  3422. const results = {};
  3423. results.entities = [];
  3424. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  3425. const element = document.querySelector("#entity-" + key);
  3426. results.entities.push({
  3427. name: entity.identifier,
  3428. customName: entity.name,
  3429. scale: entity.scale,
  3430. view: entity.view,
  3431. x: element.dataset.x,
  3432. y: element.dataset.y,
  3433. priority: entity.priority,
  3434. brightness: entity.brightness
  3435. });
  3436. });
  3437. const unit = document.querySelector("#options-height-unit").value;
  3438. results.world = {
  3439. height: config.height.toNumber(unit),
  3440. unit: unit,
  3441. x: config.x,
  3442. y: config.y
  3443. }
  3444. results.version = migrationDefs.length;
  3445. return results;
  3446. }
  3447. // btoa doesn't like anything that isn't ASCII
  3448. // great
  3449. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  3450. // for providing an alternative
  3451. function b64EncodeUnicode(str) {
  3452. // first we use encodeURIComponent to get percent-encoded UTF-8,
  3453. // then we convert the percent encodings into raw bytes which
  3454. // can be fed into btoa.
  3455. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  3456. function toSolidBytes(match, p1) {
  3457. return String.fromCharCode('0x' + p1);
  3458. }));
  3459. }
  3460. function b64DecodeUnicode(str) {
  3461. // Going backwards: from bytestream, to percent-encoding, to original string.
  3462. return decodeURIComponent(atob(str).split('').map(function (c) {
  3463. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  3464. }).join(''));
  3465. }
  3466. function linkScene() {
  3467. loc = new URL(window.location);
  3468. const link = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  3469. window.history.replaceState(null, "Macrovision", link);
  3470. try {
  3471. navigator.clipboard.writeText(link);
  3472. toast("Copied permalink to clipboard");
  3473. } catch {
  3474. toast("Couldn't copy permalink");
  3475. }
  3476. }
  3477. function copyScene() {
  3478. const results = exportScene();
  3479. navigator.clipboard.writeText(JSON.stringify(results));
  3480. }
  3481. function pasteScene() {
  3482. try {
  3483. navigator.clipboard.readText().then(text => {
  3484. const data = JSON.parse(text);
  3485. if (data.entities === undefined) {
  3486. return;
  3487. }
  3488. if (data.world === undefined) {
  3489. return;
  3490. }
  3491. importScene(data);
  3492. }).catch(err => alert(err));
  3493. } catch (err) {
  3494. console.error(err);
  3495. // probably wasn't valid data
  3496. }
  3497. }
  3498. // TODO - don't just search through every single entity
  3499. // probably just have a way to do lookups directly
  3500. function findEntity(name) {
  3501. return availableEntitiesByName[name];
  3502. }
  3503. const migrationDefs = [
  3504. /*
  3505. Migration: 0 -> 1
  3506. Adds x and y coordinates for the camera
  3507. */
  3508. data => {
  3509. data.world.x = 0;
  3510. data.world.y = 0;
  3511. },
  3512. /*
  3513. Migration: 1 -> 2
  3514. Adds priority and brightness to each entity
  3515. */
  3516. data => {
  3517. data.entities.forEach(entity => {
  3518. entity.priority = 0;
  3519. entity.brightness = 1;
  3520. });
  3521. },
  3522. /*
  3523. Migration: 2 -> 3
  3524. Custom names are exported
  3525. */
  3526. data => {
  3527. data.entities.forEach(entity => {
  3528. entity.customName = entity.name
  3529. });
  3530. }
  3531. ]
  3532. function migrateScene(data) {
  3533. if (data.version === undefined) {
  3534. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  3535. console.trace()
  3536. data.version = 0;
  3537. } else if (data.version < migrationDefs.length) {
  3538. migrationDefs[data.version](data);
  3539. data.version += 1;
  3540. migrateScene(data);
  3541. }
  3542. }
  3543. function importScene(data) {
  3544. removeAllEntities();
  3545. migrateScene(data);
  3546. data.entities.forEach(entityInfo => {
  3547. const entity = findEntity(entityInfo.name).constructor();
  3548. entity.name = entityInfo.customName;
  3549. entity.scale = entityInfo.scale;
  3550. entity.priority = entityInfo.priority;
  3551. entity.brightness = entityInfo.brightness;
  3552. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  3553. });
  3554. config.height = math.unit(data.world.height, data.world.unit);
  3555. config.x = data.world.x;
  3556. config.y = data.world.y;
  3557. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  3558. document.querySelector("#options-height-value").value = height;
  3559. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  3560. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3561. if (data.canvasWidth) {
  3562. doHorizReposition(data.canvasWidth / canvasWidth);
  3563. }
  3564. updateSizes();
  3565. }
  3566. function renderToCanvas() {
  3567. const ctx = document.querySelector("#display").getContext("2d");
  3568. Object.entries(entities).sort((ent1, ent2) => {
  3569. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  3570. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  3571. return z1 - z2;
  3572. }).forEach(([id, entity]) => {
  3573. element = document.querySelector("#entity-" + id);
  3574. img = element.querySelector("img");
  3575. let x = parseFloat(element.dataset.x);
  3576. let y = parseFloat(element.dataset.y);
  3577. let coords = pos2pix({x: x, y: y});
  3578. let offset = img.style.getPropertyValue("--offset");
  3579. offset = parseFloat(offset.substring(0, offset.length-1))
  3580. x = coords.x - img.getBoundingClientRect().width/2;
  3581. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  3582. let xSize = img.getBoundingClientRect().width;
  3583. let ySize = img.getBoundingClientRect().height;
  3584. const oldFilter = ctx.filter
  3585. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  3586. ctx.filter = `brightness(${brightness})`;
  3587. ctx.drawImage(img, x, y, xSize, ySize);
  3588. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  3589. ctx.filter = oldFilter
  3590. });
  3591. }
  3592. function exportCanvas(callback) {
  3593. /** @type {CanvasRenderingContext2D} */
  3594. const ctx = document.querySelector("#display").getContext("2d");
  3595. const blob = ctx.canvas.toBlob(callback);
  3596. }
  3597. function generateScreenshot(callback) {
  3598. /** @type {CanvasRenderingContext2D} */
  3599. const ctx = document.querySelector("#display").getContext("2d");
  3600. if (checkBodyClass("toggle-bottom-cover")) {
  3601. ctx.fillStyle = "#000";
  3602. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  3603. }
  3604. renderToCanvas();
  3605. ctx.fillStyle = "#777";
  3606. ctx.font = "normal normal lighter 16pt coda";
  3607. ctx.fillText("macrovision.crux.sexy", 10, 25);
  3608. exportCanvas(blob => {
  3609. callback(blob);
  3610. });
  3611. }
  3612. function copyScreenshot() {
  3613. if (window.ClipboardItem === undefined) {
  3614. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  3615. return;
  3616. }
  3617. generateScreenshot(blob => {
  3618. navigator.clipboard.write([
  3619. new ClipboardItem({
  3620. "image/png": blob
  3621. })
  3622. ]);
  3623. });
  3624. drawScales(false);
  3625. }
  3626. function saveScreenshot() {
  3627. generateScreenshot(blob => {
  3628. const a = document.createElement("a");
  3629. a.href = URL.createObjectURL(blob);
  3630. a.setAttribute("download", "macrovision.png");
  3631. a.click();
  3632. });
  3633. drawScales(false);
  3634. }
  3635. function openScreenshot() {
  3636. generateScreenshot(blob => {
  3637. const a = document.createElement("a");
  3638. a.href = URL.createObjectURL(blob);
  3639. a.setAttribute("target", "_blank");
  3640. a.click();
  3641. });
  3642. drawScales(false);
  3643. }
  3644. const rateLimits = {};
  3645. function toast(msg) {
  3646. let div = document.createElement("div");
  3647. div.innerHTML = msg;
  3648. div.classList.add("toast");
  3649. document.body.appendChild(div);
  3650. setTimeout(() => {
  3651. document.body.removeChild(div);
  3652. }, 5000)
  3653. }
  3654. function toastRateLimit(msg, key, delay) {
  3655. if (!rateLimits[key]) {
  3656. toast(msg);
  3657. rateLimits[key] = setTimeout(() => {
  3658. delete rateLimits[key]
  3659. }, delay);
  3660. }
  3661. }
  3662. let lastTime = undefined;
  3663. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  3664. Object.keys(entities).forEach(key => {
  3665. document.querySelector("#entity-" + key).classList.add("no-transition");
  3666. });
  3667. config.x = fromX;
  3668. config.y = fromY;
  3669. config.height = math.unit(fromHeight, "meters")
  3670. updateSizes();
  3671. lastTime = undefined;
  3672. requestAnimationFrame((timestamp) => panTo(toX, toY, toHeight, (toX - fromX) / duration, (toY - fromY) / duration, (toHeight - fromHeight) / duration, timestamp, duration));
  3673. }
  3674. function panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining) {
  3675. if (lastTime === undefined) {
  3676. lastTime = timestamp;
  3677. }
  3678. dt = timestamp - lastTime;
  3679. remaining -= dt;
  3680. console.log(lastTime, remaining, dt)
  3681. if (remaining < 0) {
  3682. dt += remaining
  3683. }
  3684. let newX = config.x + xSpeed * dt;
  3685. let newY = config.y + ySpeed * dt;
  3686. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  3687. console.log(newX);
  3688. if (remaining > 0) {
  3689. requestAnimationFrame((timestamp) => panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining))
  3690. } else {
  3691. Object.keys(entities).forEach(key => {
  3692. document.querySelector("#entity-" + key).classList.remove("no-transition");
  3693. });
  3694. }
  3695. config.x = newX;
  3696. config.y = newY;
  3697. config.height = math.unit(newHeight, "meters");
  3698. updateSizes();
  3699. }