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

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