less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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