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.
 
 
 

6538 lines
193 KiB

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