less copy protection, more size visualization
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

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