less copy protection, more size visualization
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

6359 líneas
188 KiB

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