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

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