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

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