less copy protection, more size visualization
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

6356 satır
188 KiB

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