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.
 
 
 

5188 wiersze
158 KiB

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