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

6593 строки
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. testCtx.translate(-actualW / 2, -actualH / 2);
  2308. testCtx.drawImage(target, actualW / 2 - w / 2, actualH / 2 - h / 2, w, h);
  2309. testCtx.fillStyle = "red";
  2310. testCtx.fillRect(actualW / 2, actualH / 2, 10, 10);
  2311. testCtx.restore();
  2312. testCtx.fillStyle = "red";
  2313. alpha = testCtx.getImageData(xTarget, yTarget, 1, 1).data[3];
  2314. testCtx.fillRect(xTarget, yTarget, 3, 3);
  2315. // If the pixel is transparent,
  2316. // retrieve the element underneath and trigger its click event
  2317. if (alpha === 0) {
  2318. const oldDisplay = target.style.display;
  2319. target.style.display = "none";
  2320. const newTarget = document.elementFromPoint(
  2321. event.clientX,
  2322. event.clientY
  2323. );
  2324. newTarget.dispatchEvent(
  2325. new MouseEvent(event.type, {
  2326. clientX: event.clientX,
  2327. clientY: event.clientY,
  2328. })
  2329. );
  2330. target.style.display = oldDisplay;
  2331. } else {
  2332. clickDown(target.parentElement, event.clientX, event.clientY);
  2333. }
  2334. testCtx.restore();
  2335. }
  2336. function arrangeEntities(order) {
  2337. const worldWidth =
  2338. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  2339. let sum = 0;
  2340. order.forEach((key) => {
  2341. const image = document.querySelector(
  2342. "#entity-" + key + " > .entity-image"
  2343. );
  2344. const meters =
  2345. entities[key].views[entities[key].view].height.toNumber("meters");
  2346. let height = image.height;
  2347. let width = image.width;
  2348. if (height == 0) {
  2349. height = 100;
  2350. }
  2351. if (width == 0) {
  2352. width = height;
  2353. }
  2354. sum += (meters * width) / height;
  2355. });
  2356. let x = config.x - sum / 2;
  2357. order.forEach((key) => {
  2358. const image = document.querySelector(
  2359. "#entity-" + key + " > .entity-image"
  2360. );
  2361. const meters =
  2362. entities[key].views[entities[key].view].height.toNumber("meters");
  2363. let height = image.height;
  2364. let width = image.width;
  2365. if (height == 0) {
  2366. height = 100;
  2367. }
  2368. if (width == 0) {
  2369. width = height;
  2370. }
  2371. x += (meters * width) / height / 2;
  2372. document.querySelector("#entity-" + key).dataset.x = x;
  2373. document.querySelector("#entity-" + key).dataset.y = config.y;
  2374. x += (meters * width) / height / 2;
  2375. });
  2376. fitWorld();
  2377. updateSizes();
  2378. }
  2379. function removeAllEntities() {
  2380. Object.keys(entities).forEach((key) => {
  2381. removeEntity(document.querySelector("#entity-" + key));
  2382. });
  2383. }
  2384. function clearAttribution() {
  2385. document.querySelector("#attribution-category-header").style.display =
  2386. "none";
  2387. document.querySelector("#options-attribution").style.display = "none";
  2388. }
  2389. function displayAttribution(file) {
  2390. document.querySelector("#attribution-category-header").style.display =
  2391. "block";
  2392. document.querySelector("#options-attribution").style.display = "inline";
  2393. const authors = authorsOfFull(file);
  2394. const owners = ownersOfFull(file);
  2395. const citations = citationsOf(file);
  2396. const source = sourceOf(file);
  2397. const authorHolder = document.querySelector("#options-attribution-authors");
  2398. const ownerHolder = document.querySelector("#options-attribution-owners");
  2399. const citationHolder = document.querySelector(
  2400. "#options-attribution-citations"
  2401. );
  2402. const sourceHolder = document.querySelector("#options-attribution-source");
  2403. if (authors === []) {
  2404. const div = document.createElement("div");
  2405. div.innerText = "Unknown";
  2406. authorHolder.innerHTML = "";
  2407. authorHolder.appendChild(div);
  2408. } else if (authors === undefined) {
  2409. const div = document.createElement("div");
  2410. div.innerText = "Not yet entered";
  2411. authorHolder.innerHTML = "";
  2412. authorHolder.appendChild(div);
  2413. } else {
  2414. authorHolder.innerHTML = "";
  2415. const list = document.createElement("ul");
  2416. authorHolder.appendChild(list);
  2417. authors.forEach((author) => {
  2418. const authorEntry = document.createElement("li");
  2419. if (author.url) {
  2420. const link = document.createElement("a");
  2421. link.href = author.url;
  2422. link.innerText = author.name;
  2423. link.rel = "noreferrer no opener";
  2424. link.target = "_blank";
  2425. authorEntry.appendChild(link);
  2426. } else {
  2427. const div = document.createElement("div");
  2428. div.innerText = author.name;
  2429. authorEntry.appendChild(div);
  2430. }
  2431. list.appendChild(authorEntry);
  2432. });
  2433. }
  2434. if (owners === []) {
  2435. const div = document.createElement("div");
  2436. div.innerText = "Unknown";
  2437. ownerHolder.innerHTML = "";
  2438. ownerHolder.appendChild(div);
  2439. } else if (owners === undefined) {
  2440. const div = document.createElement("div");
  2441. div.innerText = "Not yet entered";
  2442. ownerHolder.innerHTML = "";
  2443. ownerHolder.appendChild(div);
  2444. } else {
  2445. ownerHolder.innerHTML = "";
  2446. const list = document.createElement("ul");
  2447. ownerHolder.appendChild(list);
  2448. owners.forEach((owner) => {
  2449. const ownerEntry = document.createElement("li");
  2450. if (owner.url) {
  2451. const link = document.createElement("a");
  2452. link.href = owner.url;
  2453. link.innerText = owner.name;
  2454. link.rel = "noreferrer no opener";
  2455. link.target = "_blank";
  2456. ownerEntry.appendChild(link);
  2457. } else {
  2458. const div = document.createElement("div");
  2459. div.innerText = owner.name;
  2460. ownerEntry.appendChild(div);
  2461. }
  2462. list.appendChild(ownerEntry);
  2463. });
  2464. }
  2465. citationHolder.innerHTML = "";
  2466. if (citations === [] || citations === undefined) {
  2467. } else {
  2468. citationHolder.innerHTML = "";
  2469. const list = document.createElement("ul");
  2470. citationHolder.appendChild(list);
  2471. citations.forEach((citation) => {
  2472. const citationEntry = document.createElement("li");
  2473. const link = document.createElement("a");
  2474. link.style.display = "block";
  2475. link.href = citation;
  2476. link.innerText = new URL(citation).host;
  2477. link.rel = "noreferrer no opener";
  2478. link.target = "_blank";
  2479. citationEntry.appendChild(link);
  2480. list.appendChild(citationEntry);
  2481. });
  2482. }
  2483. if (source === null) {
  2484. const div = document.createElement("div");
  2485. div.innerText = "No link";
  2486. sourceHolder.innerHTML = "";
  2487. sourceHolder.appendChild(div);
  2488. } else if (source === undefined) {
  2489. const div = document.createElement("div");
  2490. div.innerText = "Not yet entered";
  2491. sourceHolder.innerHTML = "";
  2492. sourceHolder.appendChild(div);
  2493. } else {
  2494. sourceHolder.innerHTML = "";
  2495. const link = document.createElement("a");
  2496. link.style.display = "block";
  2497. link.href = source;
  2498. link.innerText = new URL(source).host;
  2499. link.rel = "noreferrer no opener";
  2500. link.target = "_blank";
  2501. sourceHolder.appendChild(link);
  2502. }
  2503. }
  2504. function removeEntity(element) {
  2505. if (selected == element) {
  2506. deselect();
  2507. }
  2508. if (clicked == element) {
  2509. clicked = null;
  2510. }
  2511. const option = document.querySelector(
  2512. "#options-selected-entity-" + element.dataset.key
  2513. );
  2514. option.parentElement.removeChild(option);
  2515. delete entities[element.dataset.key];
  2516. const bottomName = document.querySelector(
  2517. "#bottom-name-" + element.dataset.key
  2518. );
  2519. const topName = document.querySelector("#top-name-" + element.dataset.key);
  2520. bottomName.parentElement.removeChild(bottomName);
  2521. topName.parentElement.removeChild(topName);
  2522. element.parentElement.removeChild(element);
  2523. selectedEntity = null;
  2524. prevSelectedEntity = null;
  2525. updateInfo();
  2526. }
  2527. function checkEntity(entity) {
  2528. Object.values(entity.views).forEach((view) => {
  2529. if (authorsOf(view.image.source) === undefined) {
  2530. console.warn("No authors: " + view.image.source);
  2531. }
  2532. });
  2533. }
  2534. function preloadViews(entity) {
  2535. Object.values(entity.views).forEach((view) => {
  2536. if (Object.keys(entity.forms).length > 0) {
  2537. if (entity.form !== view.form) {
  2538. return;
  2539. }
  2540. }
  2541. if (!preloaded.has(view.image.source)) {
  2542. let img = new Image();
  2543. img.src = view.image.source;
  2544. preloaded.add(view.image.source);
  2545. }
  2546. });
  2547. }
  2548. function displayEntity(
  2549. entity,
  2550. view,
  2551. x,
  2552. y,
  2553. selectEntity = false,
  2554. refresh = false
  2555. ) {
  2556. checkEntity(entity);
  2557. // preload all of the entity's views
  2558. preloadViews(entity);
  2559. const box = document.createElement("div");
  2560. box.classList.add("entity-box");
  2561. const img = document.createElement("img");
  2562. img.classList.add("entity-image");
  2563. img.addEventListener("dragstart", (e) => {
  2564. e.preventDefault();
  2565. });
  2566. const nameTag = document.createElement("div");
  2567. nameTag.classList.add("entity-name");
  2568. nameTag.innerText = entity.name;
  2569. box.appendChild(img);
  2570. box.appendChild(nameTag);
  2571. const image = entity.views[view].image;
  2572. img.src = image.source;
  2573. if (image.bottom !== undefined) {
  2574. img.style.setProperty("--offset", (-1 + image.bottom) * 100 + "%");
  2575. } else {
  2576. img.style.setProperty("--offset", -1 * 100 + "%");
  2577. }
  2578. box.dataset.x = x;
  2579. box.dataset.y = y;
  2580. img.addEventListener("mousedown", (e) => {
  2581. if (e.which == 1) {
  2582. testClick(e);
  2583. if (clicked) {
  2584. e.stopPropagation();
  2585. }
  2586. }
  2587. });
  2588. img.addEventListener("touchstart", (e) => {
  2589. const fakeEvent = {
  2590. target: e.target,
  2591. clientX: e.touches[0].clientX,
  2592. clientY: e.touches[0].clientY,
  2593. which: 1,
  2594. };
  2595. testClick(fakeEvent);
  2596. if (clicked) {
  2597. e.stopPropagation();
  2598. }
  2599. });
  2600. const heightBar = document.createElement("div");
  2601. heightBar.classList.add("height-bar");
  2602. box.appendChild(heightBar);
  2603. box.id = "entity-" + entityIndex;
  2604. box.dataset.key = entityIndex;
  2605. entity.view = view;
  2606. if (entity.priority === undefined) entity.priority = 0;
  2607. if (entity.brightness === undefined) entity.brightness = 1;
  2608. entities[entityIndex] = entity;
  2609. entity.index = entityIndex;
  2610. const world = document.querySelector("#entities");
  2611. world.appendChild(box);
  2612. const bottomName = document.createElement("div");
  2613. bottomName.classList.add("bottom-name");
  2614. bottomName.id = "bottom-name-" + entityIndex;
  2615. bottomName.innerText = entity.name;
  2616. bottomName.addEventListener("click", () => select(box));
  2617. world.appendChild(bottomName);
  2618. const topName = document.createElement("div");
  2619. topName.classList.add("top-name");
  2620. topName.id = "top-name-" + entityIndex;
  2621. topName.innerText = entity.name;
  2622. topName.addEventListener("click", () => select(box));
  2623. world.appendChild(topName);
  2624. const entityOption = document.createElement("option");
  2625. entityOption.id = "options-selected-entity-" + entityIndex;
  2626. entityOption.value = entityIndex;
  2627. entityOption.innerText = entity.name;
  2628. document
  2629. .getElementById("options-selected-entity")
  2630. .appendChild(entityOption);
  2631. entityIndex += 1;
  2632. if (config.autoFit) {
  2633. fitWorld();
  2634. }
  2635. updateEntityProperties(box);
  2636. if (selectEntity) select(box);
  2637. entity.dirty = true;
  2638. if (refresh && config.autoFitAdd) {
  2639. let targets = {};
  2640. targets[entityIndex - 1] = entity;
  2641. fitEntities(targets);
  2642. }
  2643. if (refresh) updateSizes(true);
  2644. }
  2645. window.onblur = function () {
  2646. altHeld = false;
  2647. shiftHeld = false;
  2648. };
  2649. window.onfocus = function () {
  2650. window.dispatchEvent(new Event("keydown"));
  2651. };
  2652. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  2653. function toggleFullScreen() {
  2654. var doc = window.document;
  2655. var docEl = doc.documentElement;
  2656. var requestFullScreen =
  2657. docEl.requestFullscreen ||
  2658. docEl.mozRequestFullScreen ||
  2659. docEl.webkitRequestFullScreen ||
  2660. docEl.msRequestFullscreen;
  2661. var cancelFullScreen =
  2662. doc.exitFullscreen ||
  2663. doc.mozCancelFullScreen ||
  2664. doc.webkitExitFullscreen ||
  2665. doc.msExitFullscreen;
  2666. if (
  2667. !doc.fullscreenElement &&
  2668. !doc.mozFullScreenElement &&
  2669. !doc.webkitFullscreenElement &&
  2670. !doc.msFullscreenElement
  2671. ) {
  2672. requestFullScreen.call(docEl);
  2673. } else {
  2674. cancelFullScreen.call(doc);
  2675. }
  2676. }
  2677. function handleResize(update = true) {
  2678. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2679. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2680. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2681. if (update)
  2682. updateSizes();
  2683. }
  2684. function preparePopoutMenu() {
  2685. const menubar = document.querySelector("#sidebar-menu");
  2686. [
  2687. {
  2688. name: "Show/hide sidebar",
  2689. id: "menu-toggle-sidebar",
  2690. icon: "fas fa-chevron-circle-down",
  2691. rotates: true,
  2692. },
  2693. {
  2694. name: "Fullscreen",
  2695. id: "menu-fullscreen",
  2696. icon: "fas fa-compress",
  2697. },
  2698. {
  2699. name: "Clear",
  2700. id: "menu-clear",
  2701. icon: "fas fa-file",
  2702. },
  2703. {
  2704. name: "Sort by height",
  2705. id: "menu-order-height",
  2706. icon: "fas fa-sort-numeric-up",
  2707. },
  2708. {
  2709. name: "Permalink",
  2710. id: "menu-permalink",
  2711. icon: "fas fa-link",
  2712. },
  2713. {
  2714. name: "Export to clipboard",
  2715. id: "menu-export",
  2716. icon: "fas fa-share",
  2717. },
  2718. {
  2719. name: "Import from clipboard",
  2720. id: "menu-import",
  2721. icon: "fas fa-share",
  2722. classes: ["flipped"],
  2723. },
  2724. {
  2725. name: "Save Scene",
  2726. id: "menu-save",
  2727. icon: "fas fa-download",
  2728. input: true,
  2729. },
  2730. {
  2731. name: "Load Scene",
  2732. id: "menu-load",
  2733. icon: "fas fa-upload",
  2734. select: true,
  2735. },
  2736. {
  2737. name: "Delete Scene",
  2738. id: "menu-delete",
  2739. icon: "fas fa-trash",
  2740. select: true,
  2741. },
  2742. {
  2743. name: "Load Autosave",
  2744. id: "menu-load-autosave",
  2745. icon: "fas fa-redo",
  2746. },
  2747. {
  2748. name: "Load Preset",
  2749. id: "menu-preset",
  2750. icon: "fas fa-play",
  2751. select: true,
  2752. },
  2753. {
  2754. name: "Add Image",
  2755. id: "menu-add-image",
  2756. icon: "fas fa-camera",
  2757. },
  2758. {
  2759. name: "Clear Rulers",
  2760. id: "menu-clear-rulers",
  2761. icon: "fas fa-ruler",
  2762. },
  2763. ].forEach((entry) => {
  2764. const buttonHolder = document.createElement("div");
  2765. buttonHolder.classList.add("menu-button-holder");
  2766. const button = document.createElement("button");
  2767. button.id = entry.id;
  2768. button.classList.add("menu-button");
  2769. const icon = document.createElement("i");
  2770. icon.classList.add(...entry.icon.split(" "));
  2771. if (entry.rotates) {
  2772. icon.classList.add("rotate-backward", "transitions");
  2773. }
  2774. if (entry.classes) {
  2775. entry.classes.forEach((cls) => icon.classList.add(cls));
  2776. }
  2777. const actionText = document.createElement("span");
  2778. actionText.innerText = entry.name;
  2779. actionText.classList.add("menu-text");
  2780. const srText = document.createElement("span");
  2781. srText.classList.add("sr-only");
  2782. srText.innerText = entry.name;
  2783. button.appendChild(icon);
  2784. button.appendChild(srText);
  2785. buttonHolder.appendChild(button);
  2786. buttonHolder.appendChild(actionText);
  2787. if (entry.input) {
  2788. const input = document.createElement("input");
  2789. buttonHolder.appendChild(input);
  2790. input.placeholder = "default";
  2791. input.addEventListener("keyup", (e) => {
  2792. if (e.key === "Enter") {
  2793. const name =
  2794. document.querySelector("#menu-save ~ input").value;
  2795. if (/\S/.test(name)) {
  2796. saveScene(name);
  2797. }
  2798. updateSaveInfo();
  2799. e.preventDefault();
  2800. }
  2801. });
  2802. }
  2803. if (entry.select) {
  2804. const select = document.createElement("select");
  2805. buttonHolder.appendChild(select);
  2806. }
  2807. menubar.appendChild(buttonHolder);
  2808. });
  2809. document
  2810. .querySelector("#menu-toggle-sidebar")
  2811. .addEventListener("click", (e) => {
  2812. const sidebar = document.querySelector("#options");
  2813. if (sidebar.classList.contains("hidden")) {
  2814. sidebar.classList.remove("hidden");
  2815. e.target.classList.remove("rotate-forward");
  2816. e.target.classList.add("rotate-backward");
  2817. } else {
  2818. sidebar.classList.add("hidden");
  2819. e.target.classList.add("rotate-forward");
  2820. e.target.classList.remove("rotate-backward");
  2821. }
  2822. handleResize();
  2823. });
  2824. document
  2825. .querySelector("#menu-fullscreen")
  2826. .addEventListener("click", toggleFullScreen);
  2827. const sceneChoices = document.querySelector("#menu-preset ~ select");
  2828. Object.entries(scenes).forEach(([id, scene]) => {
  2829. const option = document.createElement("option");
  2830. option.innerText = id;
  2831. option.value = id;
  2832. sceneChoices.appendChild(option);
  2833. });
  2834. document.querySelector("#menu-preset").addEventListener("click", (e) => {
  2835. const chosen = sceneChoices.value;
  2836. removeAllEntities();
  2837. scenes[chosen]();
  2838. });
  2839. document.querySelector("#menu-clear").addEventListener("click", (e) => {
  2840. removeAllEntities();
  2841. });
  2842. document.querySelector("#delete-entity").disabled = true;
  2843. document.querySelector("#delete-entity").addEventListener("click", (e) => {
  2844. if (selected) {
  2845. removeEntity(selected);
  2846. selected = null;
  2847. }
  2848. });
  2849. document
  2850. .querySelector("#menu-order-height")
  2851. .addEventListener("click", (e) => {
  2852. const order = Object.keys(entities).sort((a, b) => {
  2853. const entA = entities[a];
  2854. const entB = entities[b];
  2855. const viewA = entA.view;
  2856. const viewB = entB.view;
  2857. const heightA = entA.views[viewA].height.to("meter").value;
  2858. const heightB = entB.views[viewB].height.to("meter").value;
  2859. return heightA - heightB;
  2860. });
  2861. arrangeEntities(order);
  2862. });
  2863. document
  2864. .querySelector("#options-world-fit")
  2865. .addEventListener("click", () => fitWorld(true));
  2866. document
  2867. .querySelector("#options-reset-pos-x")
  2868. .addEventListener("click", () => {
  2869. config.x = 0;
  2870. updateSizes();
  2871. });
  2872. document
  2873. .querySelector("#options-reset-pos-y")
  2874. .addEventListener("click", () => {
  2875. config.y = 0;
  2876. updateSizes();
  2877. });
  2878. document.querySelector("#menu-permalink").addEventListener("click", (e) => {
  2879. linkScene();
  2880. });
  2881. document.querySelector("#menu-export").addEventListener("click", (e) => {
  2882. copyScene();
  2883. });
  2884. document.querySelector("#menu-import").addEventListener("click", (e) => {
  2885. pasteScene();
  2886. });
  2887. document.querySelector("#menu-save").addEventListener("click", (e) => {
  2888. const name = document.querySelector("#menu-save ~ input").value;
  2889. if (/\S/.test(name)) {
  2890. saveScene(name);
  2891. }
  2892. updateSaveInfo();
  2893. });
  2894. document.querySelector("#menu-load").addEventListener("click", (e) => {
  2895. const name = document.querySelector("#menu-load ~ select").value;
  2896. if (/\S/.test(name)) {
  2897. loadScene(name);
  2898. }
  2899. });
  2900. document.querySelector("#menu-delete").addEventListener("click", (e) => {
  2901. const name = document.querySelector("#menu-delete ~ select").value;
  2902. if (/\S/.test(name)) {
  2903. deleteScene(name);
  2904. }
  2905. });
  2906. }
  2907. function checkBodyClass(cls) {
  2908. return document.body.classList.contains(cls);
  2909. }
  2910. function toggleBodyClass(cls, setting) {
  2911. if (setting) {
  2912. document.body.classList.add(cls);
  2913. } else {
  2914. document.body.classList.remove(cls);
  2915. }
  2916. }
  2917. const backgroundColors = {
  2918. none: "#00000000",
  2919. black: "#000",
  2920. dark: "#111",
  2921. medium: "#333",
  2922. light: "#555",
  2923. };
  2924. const settingsCategories = {
  2925. background: "Background",
  2926. controls: "Controls",
  2927. info: "Info",
  2928. visuals: "Visuals",
  2929. };
  2930. const groundPosChoices = [
  2931. "very-high",
  2932. "high",
  2933. "medium",
  2934. "low",
  2935. "very-low",
  2936. "bottom",
  2937. ];
  2938. const settingsData = {
  2939. "show-vertical-scale": {
  2940. name: "Vertical Scale",
  2941. desc: "Draw vertical scale marks",
  2942. type: "toggle",
  2943. default: true,
  2944. get value() {
  2945. return config.drawYAxis;
  2946. },
  2947. set value(param) {
  2948. config.drawYAxis = param;
  2949. drawScales(false);
  2950. },
  2951. },
  2952. "show-horizontal-scale": {
  2953. name: "Horiziontal Scale",
  2954. desc: "Draw horizontal scale marks",
  2955. type: "toggle",
  2956. default: false,
  2957. get value() {
  2958. return config.drawXAxis;
  2959. },
  2960. set value(param) {
  2961. config.drawXAxis = param;
  2962. drawScales(false);
  2963. },
  2964. },
  2965. "show-altitudes": {
  2966. name: "Altitudes",
  2967. desc: "Draw interesting altitudes",
  2968. type: "select",
  2969. default: "none",
  2970. disabled: "none",
  2971. options: [
  2972. "none",
  2973. "all",
  2974. "atmosphere",
  2975. "orbits",
  2976. "weather",
  2977. "water",
  2978. "geology",
  2979. "thicknesses",
  2980. "airspaces",
  2981. "races",
  2982. "olympic-records",
  2983. "d&d-sizes",
  2984. ],
  2985. get value() {
  2986. return config.drawAltitudes;
  2987. },
  2988. set value(param) {
  2989. config.drawAltitudes = param;
  2990. drawScales(false);
  2991. },
  2992. },
  2993. "lock-y-axis": {
  2994. name: "Lock Y-Axis",
  2995. desc: "Keep the camera at ground-level",
  2996. type: "toggle",
  2997. default: true,
  2998. get value() {
  2999. return config.lockYAxis;
  3000. },
  3001. set value(param) {
  3002. config.lockYAxis = param;
  3003. updateScrollButtons();
  3004. if (param) {
  3005. updateSizes();
  3006. }
  3007. },
  3008. },
  3009. "ground-snap": {
  3010. name: "Snap to Ground",
  3011. desc: "Snap things to the ground",
  3012. type: "toggle",
  3013. default: true,
  3014. get value() {
  3015. return config.groundSnap;
  3016. },
  3017. set value(param) {
  3018. config.groundSnap = param;
  3019. },
  3020. },
  3021. "axis-spacing": {
  3022. name: "Axis Spacing",
  3023. desc: "How frequent the axis lines are",
  3024. type: "select",
  3025. default: "standard",
  3026. options: ["dense", "standard", "sparse"],
  3027. get value() {
  3028. return config.axisSpacing;
  3029. },
  3030. set value(param) {
  3031. config.axisSpacing = param;
  3032. const factor = {
  3033. dense: 0.5,
  3034. standard: 1,
  3035. sparse: 2,
  3036. }[param];
  3037. config.minLineSize = factor * 100;
  3038. config.maxLineSize = factor * 150;
  3039. updateSizes();
  3040. },
  3041. },
  3042. "ground-type": {
  3043. name: "Ground",
  3044. desc: "What kind of ground to show, if any",
  3045. type: "select",
  3046. default: "black",
  3047. disabled: "none",
  3048. options: ["none", "black", "dark", "medium", "light"],
  3049. get value() {
  3050. return config.groundKind;
  3051. },
  3052. set value(param) {
  3053. config.groundKind = param;
  3054. document
  3055. .querySelector("#ground")
  3056. .style.setProperty("--ground-color", backgroundColors[param]);
  3057. },
  3058. },
  3059. "ground-pos": {
  3060. name: "Ground Position",
  3061. desc: "How high the ground is if the y-axis is locked",
  3062. type: "select",
  3063. default: "very-low",
  3064. options: groundPosChoices,
  3065. get value() {
  3066. return config.groundPos;
  3067. },
  3068. set value(param) {
  3069. config.groundPos = param;
  3070. updateScrollButtons();
  3071. updateSizes();
  3072. },
  3073. },
  3074. "background-brightness": {
  3075. name: "Background Color",
  3076. desc: "How bright the background is",
  3077. type: "select",
  3078. default: "medium",
  3079. options: ["black", "dark", "medium", "light"],
  3080. get value() {
  3081. return config.background;
  3082. },
  3083. set value(param) {
  3084. config.background = param;
  3085. drawScales();
  3086. },
  3087. },
  3088. "auto-scale": {
  3089. name: "Auto-Size World",
  3090. desc: "Constantly zoom to fit the largest entity",
  3091. type: "toggle",
  3092. default: false,
  3093. get value() {
  3094. return config.autoFit;
  3095. },
  3096. set value(param) {
  3097. config.autoFit = param;
  3098. checkFitWorld();
  3099. },
  3100. },
  3101. "auto-units": {
  3102. name: "Auto-Select Units",
  3103. desc: "Automatically switch units when zooming in and out",
  3104. type: "toggle",
  3105. default: false,
  3106. get value() {
  3107. return config.autoUnits;
  3108. },
  3109. set value(param) {
  3110. config.autoUnits = param;
  3111. },
  3112. },
  3113. "zoom-when-adding": {
  3114. name: "Zoom On Add",
  3115. desc: "Zoom to fit when you add a new entity",
  3116. type: "toggle",
  3117. default: false,
  3118. get value() {
  3119. return config.autoFitAdd;
  3120. },
  3121. set value(param) {
  3122. config.autoFitAdd = param;
  3123. },
  3124. },
  3125. "zoom-when-sizing": {
  3126. name: "Zoom On Size",
  3127. desc: "Zoom to fit when you select an entity's size",
  3128. type: "toggle",
  3129. default: false,
  3130. get value() {
  3131. return config.autoFitSize;
  3132. },
  3133. set value(param) {
  3134. config.autoFitSize = param;
  3135. },
  3136. },
  3137. "show-ratios": {
  3138. name: "Show Ratios",
  3139. desc: "Show the proportions between the current selection and the most recent selection.",
  3140. type: "toggle",
  3141. default: false,
  3142. get value() {
  3143. return config.showRatios;
  3144. },
  3145. set value(param) {
  3146. config.showRatios = param;
  3147. updateInfo();
  3148. },
  3149. },
  3150. "show-horizon": {
  3151. name: "Show Horizon",
  3152. desc: "Show how far the horizon would be for the selected character",
  3153. type: "toggle",
  3154. default: false,
  3155. get value() {
  3156. return config.showHorizon;
  3157. },
  3158. set value(param) {
  3159. config.showHorizon = param;
  3160. updateInfo();
  3161. },
  3162. },
  3163. "attach-rulers": {
  3164. name: "Attach Rulers",
  3165. desc: "Rulers will attach to the currently-selected entity, moving around with it.",
  3166. type: "toggle",
  3167. default: true,
  3168. get value() {
  3169. return config.rulersStick;
  3170. },
  3171. set value(param) {
  3172. config.rulersStick = param;
  3173. },
  3174. },
  3175. units: {
  3176. name: "Default Units",
  3177. desc: "Which kind of unit to use by default",
  3178. type: "select",
  3179. default: "metric",
  3180. options: ["metric", "customary", "relative", "quirky", "human"],
  3181. get value() {
  3182. return config.units;
  3183. },
  3184. set value(param) {
  3185. config.units = param;
  3186. updateSizes();
  3187. },
  3188. },
  3189. names: {
  3190. name: "Show Names",
  3191. desc: "Display names over entities",
  3192. type: "toggle",
  3193. default: true,
  3194. get value() {
  3195. return checkBodyClass("toggle-entity-name");
  3196. },
  3197. set value(param) {
  3198. toggleBodyClass("toggle-entity-name", param);
  3199. },
  3200. },
  3201. "bottom-names": {
  3202. name: "Bottom Names",
  3203. desc: "Display names at the bottom",
  3204. type: "toggle",
  3205. default: false,
  3206. get value() {
  3207. return checkBodyClass("toggle-bottom-name");
  3208. },
  3209. set value(param) {
  3210. toggleBodyClass("toggle-bottom-name", param);
  3211. },
  3212. },
  3213. "top-names": {
  3214. name: "Show Arrows",
  3215. desc: "Point to entities that are much larger than the current view",
  3216. type: "toggle",
  3217. default: false,
  3218. get value() {
  3219. return checkBodyClass("toggle-top-name");
  3220. },
  3221. set value(param) {
  3222. toggleBodyClass("toggle-top-name", param);
  3223. },
  3224. },
  3225. "height-bars": {
  3226. name: "Height Bars",
  3227. desc: "Draw dashed lines to the top of each entity",
  3228. type: "toggle",
  3229. default: false,
  3230. get value() {
  3231. return checkBodyClass("toggle-height-bars");
  3232. },
  3233. set value(param) {
  3234. toggleBodyClass("toggle-height-bars", param);
  3235. },
  3236. },
  3237. "flag-nsfw": {
  3238. name: "Flag NSFW",
  3239. desc: "Highlight NSFW things in red",
  3240. type: "toggle",
  3241. default: false,
  3242. get value() {
  3243. return checkBodyClass("flag-nsfw");
  3244. },
  3245. set value(param) {
  3246. toggleBodyClass("flag-nsfw", param);
  3247. },
  3248. },
  3249. "glowing-entities": {
  3250. name: "Glowing Edges",
  3251. desc: "Makes all entities glow",
  3252. type: "toggle",
  3253. default: false,
  3254. get value() {
  3255. return checkBodyClass("toggle-entity-glow");
  3256. },
  3257. set value(param) {
  3258. toggleBodyClass("toggle-entity-glow", param);
  3259. },
  3260. },
  3261. "select-style": {
  3262. name: "Selection Style",
  3263. desc: "How to highlight selected entities (outlines are laggier",
  3264. type: "select",
  3265. default: "color",
  3266. options: ["color", "outline"],
  3267. get value() {
  3268. if (checkBodyClass("highlight-color")) {
  3269. return "color";
  3270. } else {
  3271. return "outline";
  3272. }
  3273. },
  3274. set value(param) {
  3275. toggleBodyClass("highlight-color", param === "color");
  3276. toggleBodyClass("highlight-outline", param === "outline");
  3277. },
  3278. },
  3279. smoothing: {
  3280. name: "Smoothing",
  3281. desc: "Smooth out movements and size changes. Disable for better performance.",
  3282. type: "toggle",
  3283. default: true,
  3284. get value() {
  3285. return checkBodyClass("smoothing");
  3286. },
  3287. set value(param) {
  3288. toggleBodyClass("smoothing", param);
  3289. },
  3290. },
  3291. "auto-mass": {
  3292. name: "Estimate Mass",
  3293. desc: "Guess the mass of things that don't have one specified using the selected body type",
  3294. type: "select",
  3295. default: "off",
  3296. disabled: "off",
  3297. options: ["off", "human", "quadruped at shoulder"],
  3298. get value() {
  3299. return config.autoMass;
  3300. },
  3301. set value(param) {
  3302. config.autoMass = param;
  3303. },
  3304. },
  3305. "auto-food-intake": {
  3306. name: "Estimate Food Intake",
  3307. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  3308. type: "toggle",
  3309. default: false,
  3310. get value() {
  3311. return config.autoFoodIntake;
  3312. },
  3313. set value(param) {
  3314. config.autoFoodIntake = param;
  3315. },
  3316. },
  3317. "auto-caloric-value": {
  3318. name: "Estimate Caloric Value",
  3319. desc: "Guess how much food a creature is worth -- 860kcal per pound",
  3320. type: "toggle",
  3321. default: false,
  3322. get value() {
  3323. return config.autoCaloricValue;
  3324. },
  3325. set value(param) {
  3326. config.autoCaloricValue = param;
  3327. },
  3328. },
  3329. "auto-prey-capacity": {
  3330. name: "Estimate Prey Capacity",
  3331. desc: "Guess how much prey creatures can hold, based on their mass",
  3332. type: "select",
  3333. default: "off",
  3334. disabled: "off",
  3335. options: ["off", "realistic", "same-size"],
  3336. get value() {
  3337. return config.autoPreyCapacity;
  3338. },
  3339. set value(param) {
  3340. config.autoPreyCapacity = param;
  3341. },
  3342. },
  3343. "auto-swallow-size": {
  3344. name: "Estimate Swallow Size",
  3345. desc: "Guess how much creatures can swallow at once, based on their height",
  3346. type: "select",
  3347. default: "off",
  3348. disabled: "off",
  3349. options: ["off", "casual", "big-swallow", "same-size-predator"],
  3350. get value() {
  3351. return config.autoSwallowSize;
  3352. },
  3353. set value(param) {
  3354. config.autoSwallowSize = param;
  3355. },
  3356. },
  3357. "edit-default-attributes": {
  3358. name: "Edit Default Attributes",
  3359. desc: "Lets you edit non-custom attributes",
  3360. type: "toggle",
  3361. default: false,
  3362. get value() {
  3363. return config.editDefaultAttributes
  3364. },
  3365. set value(param) {
  3366. config.editDefaultAttributes = param;
  3367. if (selected) {
  3368. const entity = entities[selected.dataset.key]
  3369. configViewOptions(entity, entity.view);
  3370. }
  3371. }
  3372. }
  3373. };
  3374. function prepareSettings(userSettings) {
  3375. const menubar = document.querySelector("#settings-menu");
  3376. Object.entries(settingsData).forEach(([id, entry]) => {
  3377. const holder = document.createElement("label");
  3378. holder.classList.add("settings-holder");
  3379. const input = document.createElement("input");
  3380. input.id = "setting-" + id;
  3381. const vertical = document.createElement("div");
  3382. vertical.classList.add("settings-vertical");
  3383. const name = document.createElement("label");
  3384. name.innerText = entry.name;
  3385. name.classList.add("settings-name");
  3386. name.setAttribute("for", input.id);
  3387. const desc = document.createElement("label");
  3388. desc.innerText = entry.desc;
  3389. desc.classList.add("settings-desc");
  3390. desc.setAttribute("for", input.id);
  3391. if (entry.type == "toggle") {
  3392. input.type = "checkbox";
  3393. input.checked =
  3394. userSettings[id] === undefined
  3395. ? entry.default
  3396. : userSettings[id];
  3397. holder.setAttribute("for", input.id);
  3398. vertical.appendChild(name);
  3399. vertical.appendChild(desc);
  3400. holder.appendChild(vertical);
  3401. holder.appendChild(input);
  3402. menubar.appendChild(holder);
  3403. const update = () => {
  3404. if (input.checked) {
  3405. holder.classList.add("enabled");
  3406. holder.classList.remove("disabled");
  3407. } else {
  3408. holder.classList.remove("enabled");
  3409. holder.classList.add("disabled");
  3410. }
  3411. entry.value = input.checked;
  3412. };
  3413. setTimeout(update);
  3414. input.addEventListener("change", update);
  3415. } else if (entry.type == "select") {
  3416. // we don't use the input element we made!
  3417. const select = document.createElement("select");
  3418. select.id = "setting-" + id;
  3419. entry.options.forEach((choice) => {
  3420. const option = document.createElement("option");
  3421. option.innerText = choice;
  3422. select.appendChild(option);
  3423. });
  3424. select.value =
  3425. userSettings[id] === undefined
  3426. ? entry.default
  3427. : userSettings[id];
  3428. vertical.appendChild(name);
  3429. vertical.appendChild(desc);
  3430. holder.appendChild(vertical);
  3431. holder.appendChild(select);
  3432. menubar.appendChild(holder);
  3433. const update = () => {
  3434. entry.value = select.value;
  3435. if (
  3436. entry.disabled !== undefined &&
  3437. entry.value !== entry.disabled
  3438. ) {
  3439. holder.classList.add("enabled");
  3440. holder.classList.remove("disabled");
  3441. } else {
  3442. holder.classList.remove("enabled");
  3443. holder.classList.add("disabled");
  3444. }
  3445. };
  3446. update();
  3447. select.addEventListener("change", update);
  3448. }
  3449. });
  3450. }
  3451. function updateSaveInfo() {
  3452. const saves = getSaves();
  3453. const load = document.querySelector("#menu-load ~ select");
  3454. load.innerHTML = "";
  3455. saves.forEach((save) => {
  3456. const option = document.createElement("option");
  3457. option.innerText = save;
  3458. option.value = save;
  3459. load.appendChild(option);
  3460. });
  3461. const del = document.querySelector("#menu-delete ~ select");
  3462. del.innerHTML = "";
  3463. saves.forEach((save) => {
  3464. const option = document.createElement("option");
  3465. option.innerText = save;
  3466. option.value = save;
  3467. del.appendChild(option);
  3468. });
  3469. }
  3470. function getSaves() {
  3471. try {
  3472. const results = [];
  3473. Object.keys(localStorage).forEach((key) => {
  3474. if (key.startsWith("macrovision-save-")) {
  3475. results.push(key.replace("macrovision-save-", ""));
  3476. }
  3477. });
  3478. return results;
  3479. } catch (err) {
  3480. alert(
  3481. "Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error."
  3482. );
  3483. console.error(err);
  3484. return false;
  3485. }
  3486. }
  3487. function getUserSettings() {
  3488. try {
  3489. const settings = JSON.parse(localStorage.getItem("settings"));
  3490. return settings === null ? {} : settings;
  3491. } catch {
  3492. return {};
  3493. }
  3494. }
  3495. function exportUserSettings() {
  3496. const settings = {};
  3497. Object.entries(settingsData).forEach(([id, entry]) => {
  3498. settings[id] = entry.value;
  3499. });
  3500. return settings;
  3501. }
  3502. function setUserSettings(settings) {
  3503. try {
  3504. localStorage.setItem("settings", JSON.stringify(settings));
  3505. } catch {
  3506. // :(
  3507. }
  3508. }
  3509. function doYScroll() {
  3510. const worldHeight = config.height.toNumber("meters");
  3511. config.y += (scrollDirection * worldHeight) / 180;
  3512. updateSizes();
  3513. scrollDirection *= 1.05;
  3514. }
  3515. function doXScroll() {
  3516. const worldWidth =
  3517. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  3518. config.x += (scrollDirection * worldWidth) / 180;
  3519. updateSizes();
  3520. scrollDirection *= 1.05;
  3521. }
  3522. function doZoom() {
  3523. const oldHeight = config.height;
  3524. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  3525. zoomDirection *= 1.05;
  3526. }
  3527. function doSize() {
  3528. if (selected) {
  3529. const entity = entities[selected.dataset.key];
  3530. const oldHeight = entity.views[entity.view].height;
  3531. entity.views[entity.view].height = math.multiply(
  3532. oldHeight,
  3533. sizeDirection < 0 ? -1 / sizeDirection : sizeDirection
  3534. );
  3535. entity.dirty = true;
  3536. updateEntityOptions(entity, entity.view);
  3537. updateViewOptions(entity, entity.view);
  3538. updateSizes(true);
  3539. sizeDirection *= 1.01;
  3540. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  3541. let extra = entity.views[entity.view].image.extra;
  3542. extra = extra === undefined ? 1 : extra;
  3543. const worldHeight = config.height.toNumber("meters");
  3544. if (ownHeight * extra > worldHeight) {
  3545. setWorldHeight(
  3546. config.height,
  3547. math.multiply(entity.views[entity.view].height, extra)
  3548. );
  3549. } else if (ownHeight * extra * 10 < worldHeight) {
  3550. setWorldHeight(
  3551. config.height,
  3552. math.multiply(entity.views[entity.view].height, extra * 10)
  3553. );
  3554. }
  3555. }
  3556. }
  3557. function selectNewUnit() {
  3558. const unitSelector = document.querySelector("#options-height-unit");
  3559. checkFitWorld();
  3560. const scaleInput = document.querySelector("#options-height-value");
  3561. const newVal = math
  3562. .unit(scaleInput.value, unitSelector.dataset.oldUnit)
  3563. .toNumber(unitSelector.value);
  3564. setNumericInput(scaleInput, newVal);
  3565. updateWorldHeight();
  3566. unitSelector.dataset.oldUnit = unitSelector.value;
  3567. }
  3568. // given a world position, return the position relative to the entity at normal scale
  3569. function entityRelativePosition(pos, entityElement) {
  3570. const entity = entities[entityElement.dataset.key];
  3571. const x = parseFloat(entityElement.dataset.x);
  3572. const y = parseFloat(entityElement.dataset.y);
  3573. pos.x -= x;
  3574. pos.y -= y;
  3575. pos.x /= entity.scale;
  3576. pos.y /= entity.scale;
  3577. return pos;
  3578. }
  3579. function setupMenuButtons() {
  3580. document
  3581. .querySelector("#copy-screenshot")
  3582. .addEventListener("click", (e) => {
  3583. copyScreenshot();
  3584. });
  3585. document
  3586. .querySelector("#save-screenshot")
  3587. .addEventListener("click", (e) => {
  3588. saveScreenshot();
  3589. });
  3590. document
  3591. .querySelector("#open-screenshot")
  3592. .addEventListener("click", (e) => {
  3593. openScreenshot();
  3594. });
  3595. document.querySelector("#toggle-menu").addEventListener("click", (e) => {
  3596. const popoutMenu = document.querySelector("#sidebar-menu");
  3597. if (popoutMenu.classList.contains("visible")) {
  3598. popoutMenu.classList.remove("visible");
  3599. } else {
  3600. document
  3601. .querySelectorAll(".popout-menu")
  3602. .forEach((menu) => menu.classList.remove("visible"));
  3603. const rect = e.target.getBoundingClientRect();
  3604. popoutMenu.classList.add("visible");
  3605. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  3606. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  3607. let menuWidth = popoutMenu.getBoundingClientRect().width;
  3608. let screenWidth = window.innerWidth;
  3609. if (menuWidth * 1.5 > screenWidth) {
  3610. popoutMenu.style.left = 25 + "px";
  3611. }
  3612. }
  3613. e.stopPropagation();
  3614. });
  3615. document.querySelector("#sidebar-menu").addEventListener("click", (e) => {
  3616. e.stopPropagation();
  3617. });
  3618. document.querySelector("#sidebar-menu").addEventListener("touchstart", (e) => {
  3619. e.stopPropagation();
  3620. });
  3621. document.addEventListener("click", (e) => {
  3622. document.querySelector("#sidebar-menu").classList.remove("visible");
  3623. });
  3624. document.addEventListener("touchstart", (e) => {
  3625. document.querySelector("#sidebar-menu").classList.remove("visible");
  3626. });
  3627. document
  3628. .querySelector("#toggle-settings")
  3629. .addEventListener("click", (e) => {
  3630. const popoutMenu = document.querySelector("#settings-menu");
  3631. if (popoutMenu.classList.contains("visible")) {
  3632. popoutMenu.classList.remove("visible");
  3633. } else {
  3634. document
  3635. .querySelectorAll(".popout-menu")
  3636. .forEach((menu) => menu.classList.remove("visible"));
  3637. const rect = e.target.getBoundingClientRect();
  3638. popoutMenu.classList.add("visible");
  3639. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  3640. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  3641. let menuWidth = popoutMenu.getBoundingClientRect().width;
  3642. let screenWidth = window.innerWidth;
  3643. if (menuWidth * 1.5 > screenWidth) {
  3644. popoutMenu.style.left = 25 + "px";
  3645. }
  3646. }
  3647. e.stopPropagation();
  3648. });
  3649. document.querySelector("#settings-menu").addEventListener("click", (e) => {
  3650. e.stopPropagation();
  3651. });
  3652. document.querySelector("#settings-menu").addEventListener("touchstart", (e) => {
  3653. e.stopPropagation();
  3654. });
  3655. document.addEventListener("click", (e) => {
  3656. document.querySelector("#settings-menu").classList.remove("visible");
  3657. });
  3658. document.addEventListener("touchstart", (e) => {
  3659. document.querySelector("#settings-menu").classList.remove("visible");
  3660. });
  3661. document.querySelector("#toggle-filters").addEventListener("click", (e) => {
  3662. const popoutMenu = document.querySelector("#filters-menu");
  3663. if (popoutMenu.classList.contains("visible")) {
  3664. popoutMenu.classList.remove("visible");
  3665. } else {
  3666. document
  3667. .querySelectorAll(".popout-menu")
  3668. .forEach((menu) => menu.classList.remove("visible"));
  3669. const rect = e.target.getBoundingClientRect();
  3670. popoutMenu.classList.add("visible");
  3671. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  3672. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  3673. let menuWidth = popoutMenu.getBoundingClientRect().width;
  3674. let screenWidth = window.innerWidth;
  3675. if (menuWidth * 1.5 > screenWidth) {
  3676. popoutMenu.style.left = 25 + "px";
  3677. }
  3678. }
  3679. e.stopPropagation();
  3680. });
  3681. document.querySelector("#filters-menu").addEventListener("click", (e) => {
  3682. e.stopPropagation();
  3683. });
  3684. document.querySelector("#filters-menu").addEventListener("touchstart", (e) => {
  3685. e.stopPropagation();
  3686. });
  3687. document.addEventListener("click", (e) => {
  3688. document.querySelector("#filters-menu").classList.remove("visible");
  3689. });
  3690. document.addEventListener("touchstart", (e) => {
  3691. document.querySelector("#filters-menu").classList.remove("visible");
  3692. });
  3693. document.querySelector("#toggle-info").addEventListener("click", (e) => {
  3694. const popoutMenu = document.querySelector("#info-menu");
  3695. if (popoutMenu.classList.contains("visible")) {
  3696. popoutMenu.classList.remove("visible");
  3697. } else {
  3698. document
  3699. .querySelectorAll(".popout-menu")
  3700. .forEach((menu) => menu.classList.remove("visible"));
  3701. const rect = e.target.getBoundingClientRect();
  3702. popoutMenu.classList.add("visible");
  3703. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  3704. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  3705. let menuWidth = popoutMenu.getBoundingClientRect().width;
  3706. let screenWidth = window.innerWidth;
  3707. if (menuWidth * 1.5 > screenWidth) {
  3708. popoutMenu.style.left = 25 + "px";
  3709. }
  3710. }
  3711. e.stopPropagation();
  3712. });
  3713. document.querySelector("#info-menu").addEventListener("click", (e) => {
  3714. e.stopPropagation();
  3715. });
  3716. document.querySelector("#info-menu").addEventListener("touchstart", (e) => {
  3717. e.stopPropagation();
  3718. });
  3719. document.addEventListener("click", (e) => {
  3720. document.querySelector("#info-menu").classList.remove("visible");
  3721. });
  3722. document.addEventListener("touchstart", (e) => {
  3723. document.querySelector("#info-menu").classList.remove("visible");
  3724. });
  3725. }
  3726. function setupSidebar() {
  3727. document
  3728. .querySelector("#options-selected-entity")
  3729. .addEventListener("input", (e) => {
  3730. if (e.target.value == "None") {
  3731. deselect();
  3732. } else {
  3733. select(document.querySelector("#entity-" + e.target.value));
  3734. }
  3735. });
  3736. document
  3737. .querySelector("#options-order-forward")
  3738. .addEventListener("click", (e) => {
  3739. if (selected) {
  3740. entities[selected.dataset.key].priority += 1;
  3741. }
  3742. document.querySelector("#options-order-display").innerText =
  3743. entities[selected.dataset.key].priority;
  3744. updateSizes();
  3745. });
  3746. document
  3747. .querySelector("#options-order-back")
  3748. .addEventListener("click", (e) => {
  3749. if (selected) {
  3750. entities[selected.dataset.key].priority -= 1;
  3751. }
  3752. document.querySelector("#options-order-display").innerText =
  3753. entities[selected.dataset.key].priority;
  3754. updateSizes();
  3755. });
  3756. document
  3757. .querySelector("#options-brightness-up")
  3758. .addEventListener("click", (e) => {
  3759. if (selected) {
  3760. entities[selected.dataset.key].brightness += 0.5;
  3761. updateEntityProperties(selected);
  3762. }
  3763. document.querySelector("#options-brightness-display").innerText =
  3764. entities[selected.dataset.key].brightness;
  3765. updateSizes();
  3766. });
  3767. document
  3768. .querySelector("#options-brightness-down")
  3769. .addEventListener("click", (e) => {
  3770. if (selected) {
  3771. entities[selected.dataset.key].brightness -= 0.5;
  3772. updateEntityProperties(selected);
  3773. }
  3774. document.querySelector("#options-brightness-display").innerText =
  3775. entities[selected.dataset.key].brightness;
  3776. updateSizes();
  3777. });
  3778. document
  3779. .querySelector("#options-rotate-left")
  3780. .addEventListener("click", (e) => {
  3781. if (selected) {
  3782. entities[selected.dataset.key].rotation -= Math.PI / 4;
  3783. updateEntityProperties(selected);
  3784. }
  3785. updateSizes();
  3786. });
  3787. document
  3788. .querySelector("#options-rotate-right")
  3789. .addEventListener("click", (e) => {
  3790. if (selected) {
  3791. entities[selected.dataset.key].rotation += Math.PI / 4;
  3792. updateEntityProperties(selected);
  3793. }
  3794. updateSizes();
  3795. });
  3796. document.querySelector("#options-flip").addEventListener("click", (e) => {
  3797. if (selected) {
  3798. entities[selected.dataset.key].flipped = !entities[selected.dataset.key].flipped
  3799. updateEntityProperties(selected);
  3800. }
  3801. updateSizes();
  3802. });
  3803. const formList = document.querySelector("#entity-form");
  3804. formList.addEventListener("input", (e) => {
  3805. const entity = entities[selected.dataset.key];
  3806. entity.form = e.target.value;
  3807. const oldView = entity.currentView;
  3808. entity.view = entity.formViews[entity.form];
  3809. // to set the size properly, even if we use a non-default view
  3810. if (Object.keys(entity.forms).length > 0)
  3811. entity.views[entity.view].height =
  3812. entity.formSizes[entity.form].height;
  3813. let found = Object.entries(entity.views).find(([key, view]) => {
  3814. return view.form === entity.form && view.name === oldView.name;
  3815. });
  3816. const newView = found ? found[0] : entity.formViews[entity.form];
  3817. entity.view = newView;
  3818. preloadViews(entity);
  3819. configViewList(entity, entity.view);
  3820. const image = entity.views[entity.view].image;
  3821. selected.querySelector(".entity-image").src = image.source;
  3822. configViewOptions(entity, entity.view);
  3823. displayAttribution(image.source);
  3824. if (image.bottom !== undefined) {
  3825. selected
  3826. .querySelector(".entity-image")
  3827. .style.setProperty("--offset", (-1 + image.bottom) * 100 + "%");
  3828. } else {
  3829. selected
  3830. .querySelector(".entity-image")
  3831. .style.setProperty("--offset", -1 * 100 + "%");
  3832. }
  3833. if (config.autoFitSize) {
  3834. let targets = {};
  3835. targets[selected.dataset.key] = entities[selected.dataset.key];
  3836. fitEntities(targets);
  3837. }
  3838. configSizeList(entity);
  3839. updateSizes();
  3840. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3841. updateViewOptions(entities[selected.dataset.key], entity.view);
  3842. });
  3843. const viewList = document.querySelector("#entity-view");
  3844. document.querySelector("#entity-view").addEventListener("input", (e) => {
  3845. const entity = entities[selected.dataset.key];
  3846. entity.view = e.target.value;
  3847. preloadViews(entity);
  3848. const image =
  3849. entities[selected.dataset.key].views[e.target.value].image;
  3850. selected.querySelector(".entity-image").src = image.source;
  3851. configViewOptions(entity, entity.view);
  3852. displayAttribution(image.source);
  3853. if (image.bottom !== undefined) {
  3854. selected
  3855. .querySelector(".entity-image")
  3856. .style.setProperty("--offset", (-1 + image.bottom) * 100 + "%");
  3857. } else {
  3858. selected
  3859. .querySelector(".entity-image")
  3860. .style.setProperty("--offset", -1 * 100 + "%");
  3861. }
  3862. updateSizes();
  3863. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3864. updateViewOptions(entities[selected.dataset.key], e.target.value);
  3865. });
  3866. document.querySelector("#entity-view").addEventListener("input", (e) => {
  3867. if (
  3868. viewList.options[viewList.selectedIndex].classList.contains("nsfw")
  3869. ) {
  3870. viewList.classList.add("nsfw");
  3871. } else {
  3872. viewList.classList.remove("nsfw");
  3873. }
  3874. });
  3875. }
  3876. function setupScrollButtons() {
  3877. // TODO: write some generic logic for this lol
  3878. document
  3879. .querySelector("#scroll-left")
  3880. .addEventListener("mousedown", (e) => {
  3881. scrollDirection = -1;
  3882. clearInterval(scrollHandle);
  3883. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3884. e.stopPropagation();
  3885. });
  3886. document
  3887. .querySelector("#scroll-right")
  3888. .addEventListener("mousedown", (e) => {
  3889. scrollDirection = 1;
  3890. clearInterval(scrollHandle);
  3891. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3892. e.stopPropagation();
  3893. });
  3894. document
  3895. .querySelector("#scroll-left")
  3896. .addEventListener("touchstart", (e) => {
  3897. scrollDirection = -1;
  3898. clearInterval(scrollHandle);
  3899. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3900. e.stopPropagation();
  3901. });
  3902. document
  3903. .querySelector("#scroll-right")
  3904. .addEventListener("touchstart", (e) => {
  3905. scrollDirection = 1;
  3906. clearInterval(scrollHandle);
  3907. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3908. e.stopPropagation();
  3909. });
  3910. document.querySelector("#scroll-up").addEventListener("mousedown", (e) => {
  3911. if (config.lockYAxis) {
  3912. moveGround(true);
  3913. } else {
  3914. scrollDirection = 1;
  3915. clearInterval(scrollHandle);
  3916. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3917. e.stopPropagation();
  3918. }
  3919. });
  3920. document
  3921. .querySelector("#scroll-down")
  3922. .addEventListener("mousedown", (e) => {
  3923. if (config.lockYAxis) {
  3924. moveGround(false);
  3925. } else {
  3926. scrollDirection = -1;
  3927. clearInterval(scrollHandle);
  3928. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3929. e.stopPropagation();
  3930. }
  3931. });
  3932. document.querySelector("#scroll-up").addEventListener("touchstart", (e) => {
  3933. if (config.lockYAxis) {
  3934. moveGround(true);
  3935. } else {
  3936. scrollDirection = 1;
  3937. clearInterval(scrollHandle);
  3938. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3939. e.stopPropagation();
  3940. }
  3941. });
  3942. document
  3943. .querySelector("#scroll-down")
  3944. .addEventListener("touchstart", (e) => {
  3945. if (config.lockYAxis) {
  3946. moveGround(false);
  3947. } else {
  3948. scrollDirection = -1;
  3949. clearInterval(scrollHandle);
  3950. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3951. e.stopPropagation();
  3952. }
  3953. });
  3954. document.addEventListener("mouseup", (e) => {
  3955. clearInterval(scrollHandle);
  3956. scrollHandle = null;
  3957. });
  3958. document.addEventListener("touchend", (e) => {
  3959. clearInterval(scrollHandle);
  3960. scrollHandle = null;
  3961. });
  3962. document.querySelector("#zoom-in").addEventListener("mousedown", (e) => {
  3963. zoomDirection = -1;
  3964. clearInterval(zoomHandle);
  3965. zoomHandle = setInterval(doZoom, 1000 / 20);
  3966. e.stopPropagation();
  3967. });
  3968. document.querySelector("#zoom-out").addEventListener("mousedown", (e) => {
  3969. zoomDirection = 1;
  3970. clearInterval(zoomHandle);
  3971. zoomHandle = setInterval(doZoom, 1000 / 20);
  3972. e.stopPropagation();
  3973. });
  3974. document.querySelector("#zoom-in").addEventListener("touchstart", (e) => {
  3975. zoomDirection = -1;
  3976. clearInterval(zoomHandle);
  3977. zoomHandle = setInterval(doZoom, 1000 / 20);
  3978. e.stopPropagation();
  3979. });
  3980. document.querySelector("#zoom-out").addEventListener("touchstart", (e) => {
  3981. zoomDirection = 1;
  3982. clearInterval(zoomHandle);
  3983. zoomHandle = setInterval(doZoom, 1000 / 20);
  3984. e.stopPropagation();
  3985. });
  3986. document.addEventListener("mouseup", (e) => {
  3987. clearInterval(zoomHandle);
  3988. zoomHandle = null;
  3989. });
  3990. document.addEventListener("touchend", (e) => {
  3991. clearInterval(zoomHandle);
  3992. zoomHandle = null;
  3993. });
  3994. document.querySelector("#shrink").addEventListener("mousedown", (e) => {
  3995. sizeDirection = -1;
  3996. clearInterval(sizeHandle);
  3997. sizeHandle = setInterval(doSize, 1000 / 20);
  3998. e.stopPropagation();
  3999. });
  4000. document.querySelector("#grow").addEventListener("mousedown", (e) => {
  4001. sizeDirection = 1;
  4002. clearInterval(sizeHandle);
  4003. sizeHandle = setInterval(doSize, 1000 / 20);
  4004. e.stopPropagation();
  4005. });
  4006. document.querySelector("#shrink").addEventListener("touchstart", (e) => {
  4007. sizeDirection = -1;
  4008. clearInterval(sizeHandle);
  4009. sizeHandle = setInterval(doSize, 1000 / 20);
  4010. e.stopPropagation();
  4011. });
  4012. document.querySelector("#grow").addEventListener("touchstart", (e) => {
  4013. sizeDirection = 1;
  4014. clearInterval(sizeHandle);
  4015. sizeHandle = setInterval(doSize, 1000 / 20);
  4016. e.stopPropagation();
  4017. });
  4018. document.addEventListener("mouseup", (e) => {
  4019. clearInterval(sizeHandle);
  4020. sizeHandle = null;
  4021. });
  4022. document.addEventListener("touchend", (e) => {
  4023. clearInterval(sizeHandle);
  4024. sizeHandle = null;
  4025. });
  4026. document.querySelector("#ruler").addEventListener("click", (e) => {
  4027. rulerMode = !rulerMode;
  4028. if (rulerMode) {
  4029. toast("Ready to draw a ruler mark");
  4030. } else {
  4031. toast("Cancelled ruler mode");
  4032. }
  4033. });
  4034. document.querySelector("#ruler").addEventListener("mousedown", (e) => {
  4035. e.stopPropagation();
  4036. });
  4037. document.querySelector("#ruler").addEventListener("touchstart", (e) => {
  4038. e.stopPropagation();
  4039. });
  4040. document.querySelector("#fit").addEventListener("click", (e) => {
  4041. if (selected) {
  4042. let targets = {};
  4043. targets[selected.dataset.key] = entities[selected.dataset.key];
  4044. fitEntities(targets);
  4045. }
  4046. });
  4047. document.querySelector("#fit").addEventListener("mousedown", (e) => {
  4048. e.stopPropagation();
  4049. });
  4050. document.querySelector("#fit").addEventListener("touchstart", (e) => {
  4051. e.stopPropagation();
  4052. });
  4053. }
  4054. function prepareMenu() {
  4055. preparePopoutMenu();
  4056. updateSaveInfo();
  4057. setupMenuButtons();
  4058. setupSidebar();
  4059. setupScrollButtons();
  4060. }
  4061. function prepareEvents() {
  4062. window.addEventListener("unload", () => {
  4063. saveScene("autosave");
  4064. setUserSettings(exportUserSettings());
  4065. });
  4066. document.querySelector("#world").addEventListener("mousedown", (e) => {
  4067. // only middle mouse clicks
  4068. if (e.which == 2) {
  4069. panning = true;
  4070. panOffsetX = e.clientX;
  4071. panOffsetY = e.clientY;
  4072. Object.keys(entities).forEach((key) => {
  4073. document
  4074. .querySelector("#entity-" + key)
  4075. .classList.add("no-transition");
  4076. });
  4077. }
  4078. });
  4079. document.addEventListener("mouseup", (e) => {
  4080. if (e.which == 2) {
  4081. panning = false;
  4082. Object.keys(entities).forEach((key) => {
  4083. document
  4084. .querySelector("#entity-" + key)
  4085. .classList.remove("no-transition");
  4086. });
  4087. }
  4088. });
  4089. document.querySelector("#world").addEventListener("touchstart", (e) => {
  4090. if (!rulerMode) {
  4091. panning = true;
  4092. panOffsetX = e.touches[0].clientX;
  4093. panOffsetY = e.touches[0].clientY;
  4094. e.preventDefault();
  4095. Object.keys(entities).forEach((key) => {
  4096. document
  4097. .querySelector("#entity-" + key)
  4098. .classList.add("no-transition");
  4099. });
  4100. }
  4101. });
  4102. document.querySelector("#world").addEventListener("touchend", (e) => {
  4103. panning = false;
  4104. Object.keys(entities).forEach((key) => {
  4105. document
  4106. .querySelector("#entity-" + key)
  4107. .classList.remove("no-transition");
  4108. });
  4109. });
  4110. document.querySelector("#world").addEventListener("mousedown", (e) => {
  4111. // only left mouse clicks
  4112. if (e.which == 1 && rulerMode) {
  4113. let entX = document
  4114. .querySelector("#entities")
  4115. .getBoundingClientRect().x;
  4116. let entY = document
  4117. .querySelector("#entities")
  4118. .getBoundingClientRect().y;
  4119. let pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  4120. if (config.rulersStick && selected) {
  4121. pos = entityRelativePosition(pos, selected);
  4122. }
  4123. currentRuler = {
  4124. x0: pos.x,
  4125. y0: pos.y,
  4126. x1: pos.y,
  4127. y1: pos.y,
  4128. entityKey: null,
  4129. };
  4130. if (config.rulersStick && selected) {
  4131. currentRuler.entityKey = selected.dataset.key;
  4132. }
  4133. }
  4134. });
  4135. document.querySelector("#world").addEventListener("mouseup", (e) => {
  4136. // only left mouse clicks
  4137. if (e.which == 1 && currentRuler) {
  4138. rulers.push(currentRuler);
  4139. currentRuler = null;
  4140. rulerMode = false;
  4141. }
  4142. });
  4143. document.querySelector("#world").addEventListener("touchstart", (e) => {
  4144. if (rulerMode) {
  4145. let entX = document
  4146. .querySelector("#entities")
  4147. .getBoundingClientRect().x;
  4148. let entY = document
  4149. .querySelector("#entities")
  4150. .getBoundingClientRect().y;
  4151. let pos = pix2pos({
  4152. x: e.touches[0].clientX - entX,
  4153. y: e.touches[0].clientY - entY,
  4154. });
  4155. if (config.rulersStick && selected) {
  4156. pos = entityRelativePosition(pos, selected);
  4157. }
  4158. currentRuler = {
  4159. x0: pos.x,
  4160. y0: pos.y,
  4161. x1: pos.y,
  4162. y1: pos.y,
  4163. entityKey: null,
  4164. };
  4165. if (config.rulersStick && selected) {
  4166. currentRuler.entityKey = selected.dataset.key;
  4167. }
  4168. }
  4169. });
  4170. document.querySelector("#world").addEventListener("touchend", (e) => {
  4171. if (currentRuler) {
  4172. rulers.push(currentRuler);
  4173. currentRuler = null;
  4174. rulerMode = false;
  4175. }
  4176. });
  4177. document.querySelector("body").appendChild(testCtx.canvas);
  4178. world.addEventListener("mousedown", (e) => deselect(e));
  4179. world.addEventListener("touchstart", (e) =>
  4180. deselect({
  4181. which: 1,
  4182. })
  4183. );
  4184. document.querySelector("#entities").addEventListener("mousedown", deselect);
  4185. document.querySelector("#display").addEventListener("mousedown", deselect);
  4186. document.addEventListener("mouseup", (e) => clickUp(e));
  4187. document.addEventListener("touchend", (e) => {
  4188. const fakeEvent = {
  4189. target: e.target,
  4190. clientX: e.changedTouches[0].clientX,
  4191. clientY: e.changedTouches[0].clientY,
  4192. which: 1,
  4193. };
  4194. clickUp(fakeEvent);
  4195. });
  4196. document.addEventListener("keydown", (e) => {
  4197. if (e.key == "Delete" || e.key == "Backspace") {
  4198. if (selected) {
  4199. removeEntity(selected);
  4200. selected = null;
  4201. }
  4202. }
  4203. });
  4204. document.addEventListener("keydown", (e) => {
  4205. if (e.key == "Shift") {
  4206. shiftHeld = true;
  4207. e.preventDefault();
  4208. } else if (e.key == "Alt") {
  4209. altHeld = true;
  4210. movingInBounds = false; // don't snap the object back in bounds when we let go
  4211. e.preventDefault();
  4212. }
  4213. });
  4214. document.addEventListener("keyup", (e) => {
  4215. if (e.key == "Shift") {
  4216. shiftHeld = false;
  4217. e.preventDefault();
  4218. } else if (e.key == "Alt") {
  4219. altHeld = false;
  4220. e.preventDefault();
  4221. }
  4222. });
  4223. document.addEventListener("paste", (e) => {
  4224. let index = 0;
  4225. let item = null;
  4226. let found = false;
  4227. for (; index < e.clipboardData.items.length; index++) {
  4228. item = e.clipboardData.items[index];
  4229. if (item.type == "image/png") {
  4230. found = true;
  4231. break;
  4232. }
  4233. }
  4234. if (!found) {
  4235. return;
  4236. }
  4237. let url = null;
  4238. const file = item.getAsFile();
  4239. customEntityFromFile(file);
  4240. });
  4241. document.querySelector("#world").addEventListener("dragover", (e) => {
  4242. e.preventDefault();
  4243. });
  4244. document.querySelector("#world").addEventListener("drop", (e) => {
  4245. e.preventDefault();
  4246. if (e.dataTransfer.files.length > 0) {
  4247. let entX = document
  4248. .querySelector("#entities")
  4249. .getBoundingClientRect().x;
  4250. let entY = document
  4251. .querySelector("#entities")
  4252. .getBoundingClientRect().y;
  4253. let coords = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  4254. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  4255. }
  4256. });
  4257. document.querySelector("#world").addEventListener("wheel", (e) => {
  4258. let magnitude = Math.abs(e.deltaY / 100);
  4259. if (shiftHeld) {
  4260. // macs do horizontal scrolling with shift held
  4261. let delta = e.deltaY;
  4262. if (e.deltaY == 0) {
  4263. magnitude = Math.abs(e.deltaX / 100);
  4264. delta = e.deltaX;
  4265. }
  4266. if (selected) {
  4267. let dir = delta > 0 ? 10 / 11 : 11 / 10;
  4268. dir -= 1;
  4269. dir *= magnitude;
  4270. dir += 1;
  4271. const entity = entities[selected.dataset.key];
  4272. entity.views[entity.view].height = math.multiply(
  4273. entity.views[entity.view].height,
  4274. dir
  4275. );
  4276. entity.dirty = true;
  4277. updateEntityOptions(entity, entity.view);
  4278. updateViewOptions(entity, entity.view);
  4279. updateSizes(true);
  4280. } else {
  4281. const worldWidth =
  4282. (config.height.toNumber("meters") / canvasHeight) *
  4283. canvasWidth;
  4284. config.x += ((e.deltaY > 0 ? 1 : -1) * worldWidth) / 20;
  4285. updateSizes();
  4286. updateSizes();
  4287. }
  4288. } else {
  4289. if (config.autoFit) {
  4290. toastRateLimit(
  4291. "Zoom is locked! Check Settings to disable.",
  4292. "zoom-lock",
  4293. 1000
  4294. );
  4295. } else {
  4296. let dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  4297. dir -= 1;
  4298. dir *= magnitude;
  4299. dir += 1;
  4300. const change =
  4301. config.height.toNumber("meters") -
  4302. math.multiply(config.height, dir).toNumber("meters");
  4303. if (!config.lockYAxis) {
  4304. config.y += change / 2;
  4305. }
  4306. setWorldHeight(
  4307. config.height,
  4308. math.multiply(config.height, dir)
  4309. );
  4310. updateWorldOptions();
  4311. }
  4312. }
  4313. checkFitWorld();
  4314. });
  4315. document.addEventListener("mousemove", (e) => {
  4316. if (currentRuler) {
  4317. let entX = document
  4318. .querySelector("#entities")
  4319. .getBoundingClientRect().x;
  4320. let entY = document
  4321. .querySelector("#entities")
  4322. .getBoundingClientRect().y;
  4323. let position = pix2pos({
  4324. x: e.clientX - entX,
  4325. y: e.clientY - entY,
  4326. });
  4327. if (config.rulersStick && selected) {
  4328. position = entityRelativePosition(position, selected);
  4329. }
  4330. currentRuler.x1 = position.x;
  4331. currentRuler.y1 = position.y;
  4332. }
  4333. drawRulers();
  4334. });
  4335. document.addEventListener("touchmove", (e) => {
  4336. if (currentRuler) {
  4337. let entX = document
  4338. .querySelector("#entities")
  4339. .getBoundingClientRect().x;
  4340. let entY = document
  4341. .querySelector("#entities")
  4342. .getBoundingClientRect().y;
  4343. let position = pix2pos({
  4344. x: e.touches[0].clientX - entX,
  4345. y: e.touches[0].clientY - entY,
  4346. });
  4347. if (config.rulersStick && selected) {
  4348. position = entityRelativePosition(position, selected);
  4349. }
  4350. currentRuler.x1 = position.x;
  4351. currentRuler.y1 = position.y;
  4352. }
  4353. drawRulers();
  4354. });
  4355. document.addEventListener("mousemove", (e) => {
  4356. if (clicked) {
  4357. let position = pix2pos({
  4358. x: e.clientX - dragOffsetX,
  4359. y: e.clientY - dragOffsetY,
  4360. });
  4361. if (movingInBounds) {
  4362. position = snapPos(position);
  4363. } else {
  4364. let x = e.clientX - dragOffsetX;
  4365. let y = e.clientY - dragOffsetY;
  4366. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  4367. movingInBounds = true;
  4368. }
  4369. }
  4370. clicked.dataset.x = position.x;
  4371. clicked.dataset.y = position.y;
  4372. updateEntityElement(entities[clicked.dataset.key], clicked);
  4373. if (hoveringInDeleteArea(e)) {
  4374. document
  4375. .querySelector("#menubar")
  4376. .classList.add("hover-delete");
  4377. } else {
  4378. document
  4379. .querySelector("#menubar")
  4380. .classList.remove("hover-delete");
  4381. }
  4382. }
  4383. if (panning && panReady) {
  4384. const worldWidth =
  4385. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  4386. const worldHeight = config.height.toNumber("meters");
  4387. config.x -= ((e.clientX - panOffsetX) / canvasWidth) * worldWidth;
  4388. config.y += ((e.clientY - panOffsetY) / canvasHeight) * worldHeight;
  4389. panOffsetX = e.clientX;
  4390. panOffsetY = e.clientY;
  4391. updateSizes();
  4392. panReady = false;
  4393. setTimeout(() => (panReady = true), 1000 / 120);
  4394. }
  4395. });
  4396. document.addEventListener(
  4397. "touchmove",
  4398. (e) => {
  4399. if (clicked) {
  4400. e.preventDefault();
  4401. let x = e.touches[0].clientX;
  4402. let y = e.touches[0].clientY;
  4403. const position = snapPos(
  4404. pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY })
  4405. );
  4406. clicked.dataset.x = position.x;
  4407. clicked.dataset.y = position.y;
  4408. updateEntityElement(entities[clicked.dataset.key], clicked);
  4409. // what a hack
  4410. // I should centralize this 'fake event' creation...
  4411. if (hoveringInDeleteArea({ clientY: y })) {
  4412. document
  4413. .querySelector("#menubar")
  4414. .classList.add("hover-delete");
  4415. } else {
  4416. document
  4417. .querySelector("#menubar")
  4418. .classList.remove("hover-delete");
  4419. }
  4420. }
  4421. if (panning && panReady) {
  4422. const worldWidth =
  4423. (config.height.toNumber("meters") / canvasHeight) *
  4424. canvasWidth;
  4425. const worldHeight = config.height.toNumber("meters");
  4426. config.x -=
  4427. ((e.touches[0].clientX - panOffsetX) / canvasWidth) *
  4428. worldWidth;
  4429. config.y +=
  4430. ((e.touches[0].clientY - panOffsetY) / canvasHeight) *
  4431. worldHeight;
  4432. panOffsetX = e.touches[0].clientX;
  4433. panOffsetY = e.touches[0].clientY;
  4434. updateSizes();
  4435. panReady = false;
  4436. setTimeout(() => (panReady = true), 1000 / 60);
  4437. }
  4438. },
  4439. { passive: false }
  4440. );
  4441. document
  4442. .querySelector("#search-box")
  4443. .addEventListener("change", (e) => doSearch(e.target.value));
  4444. document
  4445. .querySelector("#search-box")
  4446. .addEventListener("keydown", e => e.stopPropagation());
  4447. }
  4448. document.addEventListener("DOMContentLoaded", () => {
  4449. prepareMenu();
  4450. prepareEntities();
  4451. prepareEvents();
  4452. handleResize(false);
  4453. document
  4454. .querySelector("#options-height-value")
  4455. .addEventListener("change", (e) => {
  4456. updateWorldHeight();
  4457. });
  4458. document
  4459. .querySelector("#options-height-value")
  4460. .addEventListener("keydown", (e) => {
  4461. e.stopPropagation();
  4462. });
  4463. const unitSelector = document.querySelector("#options-height-unit");
  4464. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  4465. const optGroup = document.createElement("optgroup");
  4466. optGroup.label = group;
  4467. unitSelector.appendChild(optGroup);
  4468. entries.forEach((entry) => {
  4469. const option = document.createElement("option");
  4470. option.innerText = entry;
  4471. // we haven't loaded user settings yet, so we can't choose the unit just yet
  4472. unitSelector.appendChild(option);
  4473. });
  4474. });
  4475. unitSelector.addEventListener("input", selectNewUnit);
  4476. param = window.location.hash;
  4477. // we now use the fragment for links, but we should still support old stuff:
  4478. if (param.length > 0) {
  4479. param = param.substring(1);
  4480. } else {
  4481. param = new URL(window.location.href).searchParams.get("scene");
  4482. }
  4483. clearViewList();
  4484. window.addEventListener("resize", handleResize);
  4485. // TODO: further investigate why the tool initially starts out with wrong
  4486. // values under certain circumstances (seems to be narrow aspect ratios -
  4487. // maybe the menu bar is animating when it shouldn't)
  4488. setTimeout(handleResize, 250);
  4489. setTimeout(handleResize, 500);
  4490. setTimeout(handleResize, 750);
  4491. setTimeout(handleResize, 1000);
  4492. document
  4493. .querySelector("#menu-load-autosave")
  4494. .addEventListener("click", (e) => {
  4495. loadScene("autosave");
  4496. });
  4497. document.querySelector("#menu-add-image").addEventListener("click", (e) => {
  4498. document.querySelector("#file-upload-picker").click();
  4499. });
  4500. document
  4501. .querySelector("#file-upload-picker")
  4502. .addEventListener("change", (e) => {
  4503. if (e.target.files.length > 0) {
  4504. for (let i = 0; i < e.target.files.length; i++) {
  4505. customEntityFromFile(e.target.files[i]);
  4506. }
  4507. }
  4508. });
  4509. document
  4510. .querySelector("#menu-clear-rulers")
  4511. .addEventListener("click", (e) => {
  4512. rulers = [];
  4513. drawRulers();
  4514. });
  4515. clearEntityOptions();
  4516. clearViewOptions();
  4517. clearAttribution();
  4518. // we do this last because configuring settings can cause things
  4519. // to happen (e.g. auto-fit)
  4520. prepareSettings(getUserSettings());
  4521. // now that we have this loaded, we can set it
  4522. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  4523. document.querySelector("#options-height-unit").value =
  4524. defaultUnits.length[config.units];
  4525. // ...and then update the world height by setting off an input event
  4526. document
  4527. .querySelector("#options-height-unit")
  4528. .dispatchEvent(new Event("input", {}));
  4529. if (param === null) {
  4530. scenes["Empty"]();
  4531. } else {
  4532. try {
  4533. const data = JSON.parse(b64DecodeUnicode(param), math.reviver);
  4534. if (data.entities === undefined) {
  4535. return;
  4536. }
  4537. if (data.world === undefined) {
  4538. return;
  4539. }
  4540. importScene(data);
  4541. } catch (err) {
  4542. console.error(err);
  4543. scenes["Empty"]();
  4544. // probably wasn't valid data
  4545. }
  4546. }
  4547. updateWorldHeight();
  4548. // Webkit doesn't draw resized SVGs correctly. It will always draw them at their intrinsic size, I think
  4549. // This checks for that.
  4550. webkitBugTest.onload = () => {
  4551. testCtx.canvas.width = 500;
  4552. testCtx.canvas.height = 500;
  4553. testCtx.clearRect(0, 0, 500, 500);
  4554. testCtx.drawImage(webkitBugTest, 0, 0, 500, 500);
  4555. webkitCanvasBug = testCtx.getImageData(250, 250, 1, 1).data[3] == 0;
  4556. if (webkitCanvasBug) {
  4557. toast(
  4558. "Heads up: Safari can't select through gaps or take screenshots (check the console for info!)"
  4559. );
  4560. console.log(
  4561. "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 :("
  4562. );
  4563. }
  4564. };
  4565. updateFilter();
  4566. });
  4567. let searchText = "";
  4568. function doSearch(value) {
  4569. searchText = value;
  4570. updateFilter();
  4571. }
  4572. function customEntityFromFile(file, x = 0.5, y = 0.5) {
  4573. file.arrayBuffer().then((buf) => {
  4574. arr = new Uint8Array(buf);
  4575. blob = new Blob([arr], { type: file.type });
  4576. url = window.URL.createObjectURL(blob);
  4577. makeCustomEntity(url, x, y);
  4578. });
  4579. }
  4580. function makeCustomEntity(url, x = 0.5, y = 0.5) {
  4581. const maker = createEntityMaker(
  4582. {
  4583. name: "Custom Entity",
  4584. },
  4585. {
  4586. custom: {
  4587. attributes: {
  4588. height: {
  4589. name: "Height",
  4590. power: 1,
  4591. type: "length",
  4592. base: math.unit(6, "feet"),
  4593. },
  4594. },
  4595. image: {
  4596. source: url,
  4597. },
  4598. name: "Image",
  4599. info: {},
  4600. rename: false,
  4601. },
  4602. },
  4603. []
  4604. );
  4605. const entity = maker.constructor();
  4606. entity.scale = config.height.toNumber("feet") / 20;
  4607. entity.ephemeral = true;
  4608. displayEntity(entity, "custom", x, y, true, true);
  4609. }
  4610. const filterDefs = {
  4611. author: {
  4612. id: "author",
  4613. name: "Authors",
  4614. extract: (maker) => (maker.authors ? maker.authors : []),
  4615. render: (author) => attributionData.people[author].name,
  4616. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1]),
  4617. },
  4618. owner: {
  4619. id: "owner",
  4620. name: "Owners",
  4621. extract: (maker) => (maker.owners ? maker.owners : []),
  4622. render: (owner) => attributionData.people[owner].name,
  4623. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1]),
  4624. },
  4625. species: {
  4626. id: "species",
  4627. name: "Species",
  4628. extract: (maker) =>
  4629. maker.info && maker.info.species
  4630. ? getSpeciesInfo(maker.info.species)
  4631. : [],
  4632. render: (species) => speciesData[species].name,
  4633. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1]),
  4634. },
  4635. tags: {
  4636. id: "tags",
  4637. name: "Tags",
  4638. extract: (maker) =>
  4639. maker.info && maker.info.tags ? maker.info.tags : [],
  4640. render: (tag) => tagDefs[tag],
  4641. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1]),
  4642. },
  4643. size: {
  4644. id: "size",
  4645. name: "Normal Size",
  4646. extract: (maker) =>
  4647. maker.sizes && maker.sizes.length > 0
  4648. ? Array.from(
  4649. maker.sizes.reduce((result, size) => {
  4650. if (result && !size.default) {
  4651. return result;
  4652. }
  4653. let meters = size.height.toNumber("meters");
  4654. if (meters < 1e-1) {
  4655. return ["micro"];
  4656. } else if (meters < 1e1) {
  4657. return ["moderate"];
  4658. } else {
  4659. return ["macro"];
  4660. }
  4661. }, null)
  4662. )
  4663. : [],
  4664. render: (tag) => {
  4665. return {
  4666. micro: "Micro",
  4667. moderate: "Moderate",
  4668. macro: "Macro",
  4669. }[tag];
  4670. },
  4671. sort: (tag1, tag2) => {
  4672. const order = {
  4673. micro: 0,
  4674. moderate: 1,
  4675. macro: 2,
  4676. };
  4677. return order[tag1[0]] - order[tag2[0]];
  4678. },
  4679. },
  4680. allSizes: {
  4681. id: "allSizes",
  4682. name: "Possible Size",
  4683. extract: (maker) =>
  4684. maker.sizes
  4685. ? Array.from(
  4686. maker.sizes.reduce((set, size) => {
  4687. const height = size.height;
  4688. let result = Object.entries(sizeCategories).reduce(
  4689. (result, [name, value]) => {
  4690. if (result) {
  4691. return result;
  4692. } else {
  4693. if (math.compare(height, value) <= 0) {
  4694. return name;
  4695. }
  4696. }
  4697. },
  4698. null
  4699. );
  4700. set.add(result ? result : "infinite");
  4701. return set;
  4702. }, new Set())
  4703. )
  4704. : [],
  4705. render: (tag) => tag[0].toUpperCase() + tag.slice(1),
  4706. sort: (tag1, tag2) => {
  4707. const order = [
  4708. "atomic",
  4709. "microscopic",
  4710. "tiny",
  4711. "small",
  4712. "moderate",
  4713. "large",
  4714. "macro",
  4715. "megamacro",
  4716. "planetary",
  4717. "stellar",
  4718. "galactic",
  4719. "universal",
  4720. "omniversal",
  4721. "infinite",
  4722. ];
  4723. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  4724. },
  4725. },
  4726. };
  4727. const filterStates = {};
  4728. const sizeCategories = {
  4729. atomic: math.unit(100, "angstroms"),
  4730. microscopic: math.unit(100, "micrometers"),
  4731. tiny: math.unit(100, "millimeters"),
  4732. small: math.unit(1, "meter"),
  4733. moderate: math.unit(3, "meters"),
  4734. large: math.unit(10, "meters"),
  4735. macro: math.unit(300, "meters"),
  4736. megamacro: math.unit(1000, "kilometers"),
  4737. planetary: math.unit(10, "earths"),
  4738. stellar: math.unit(10, "solarradii"),
  4739. galactic: math.unit(10, "galaxies"),
  4740. universal: math.unit(10, "universes"),
  4741. omniversal: math.unit(10, "multiverses"),
  4742. };
  4743. function prepareEntities() {
  4744. availableEntities["buildings"] = makeBuildings();
  4745. availableEntities["characters"] = makeCharacters();
  4746. availableEntities["clothing"] = makeClothing();
  4747. availableEntities["creatures"] = makeCreatures();
  4748. availableEntities["fiction"] = makeFiction();
  4749. availableEntities["food"] = makeFood();
  4750. availableEntities["furniture"] = makeFurniture();
  4751. availableEntities["landmarks"] = makeLandmarks();
  4752. availableEntities["naturals"] = makeNaturals();
  4753. availableEntities["objects"] = makeObjects();
  4754. availableEntities["pokemon"] = makePokemon();
  4755. availableEntities["real-buildings"] = makeRealBuildings();
  4756. availableEntities["real-terrain"] = makeRealTerrains();
  4757. availableEntities["species"] = makeSpecies();
  4758. availableEntities["vehicles"] = makeVehicles();
  4759. availableEntities["species"].forEach((x) => {
  4760. if (x.name == "Human") {
  4761. availableEntities["food"].push(x);
  4762. }
  4763. });
  4764. availableEntities["characters"].sort((x, y) => {
  4765. return x.name.localeCompare(y.name);
  4766. });
  4767. availableEntities["species"].sort((x, y) => {
  4768. return x.name.localeCompare(y.name);
  4769. });
  4770. availableEntities["objects"].sort((x, y) => {
  4771. return x.name.localeCompare(y.name);
  4772. });
  4773. availableEntities["furniture"].sort((x, y) => {
  4774. return x.name.localeCompare(y.name);
  4775. });
  4776. const holder = document.querySelector("#spawners");
  4777. const filterMenu = document.querySelector("#filters-menu");
  4778. const categorySelect = document.createElement("select");
  4779. categorySelect.id = "category-picker";
  4780. holder.appendChild(categorySelect);
  4781. const filterSets = {};
  4782. Object.values(filterDefs).forEach((filter) => {
  4783. filterSets[filter.id] = new Set();
  4784. filterStates[filter.id] = false;
  4785. });
  4786. Object.entries(availableEntities).forEach(([category, entityList]) => {
  4787. const select = document.createElement("select");
  4788. select.id = "create-entity-" + category;
  4789. select.classList.add("entity-select");
  4790. for (let i = 0; i < entityList.length; i++) {
  4791. const entity = entityList[i];
  4792. const option = document.createElement("option");
  4793. option.value = i;
  4794. option.innerText = entity.name;
  4795. select.appendChild(option);
  4796. if (entity.nsfw) {
  4797. option.classList.add("nsfw");
  4798. }
  4799. Object.values(filterDefs).forEach((filter) => {
  4800. filter.extract(entity).forEach((result) => {
  4801. filterSets[filter.id].add(result);
  4802. });
  4803. });
  4804. availableEntitiesByName[entity.name] = entity;
  4805. }
  4806. select.addEventListener("change", (e) => {
  4807. if (
  4808. select.options[select.selectedIndex]?.classList.contains("nsfw")
  4809. ) {
  4810. select.classList.add("nsfw");
  4811. } else {
  4812. select.classList.remove("nsfw");
  4813. }
  4814. // preload the entity's first image
  4815. const entity = entityList[select.selectedIndex]?.constructor();
  4816. if (entity) {
  4817. let img = new Image();
  4818. img.src = entity.currentView.image.source;
  4819. }
  4820. });
  4821. const button = document.createElement("button");
  4822. button.id = "create-entity-" + category + "-button";
  4823. button.classList.add("entity-button");
  4824. button.innerHTML = '<i class="far fa-plus-square"></i>';
  4825. button.addEventListener("click", (e) => {
  4826. if (entityList[select.value] == null) return;
  4827. const newEntity = entityList[select.value].constructor();
  4828. let yOffset = 0;
  4829. if (config.lockYAxis) {
  4830. yOffset = getVerticalOffset();
  4831. } else {
  4832. yOffset = config.lockYAxis
  4833. ? 0
  4834. : config.height.toNumber("meters") / 2;
  4835. }
  4836. displayEntity(
  4837. newEntity,
  4838. newEntity.defaultView,
  4839. config.x,
  4840. config.y + yOffset,
  4841. true,
  4842. true
  4843. );
  4844. });
  4845. const categoryOption = document.createElement("option");
  4846. categoryOption.value = category;
  4847. categoryOption.innerText = category;
  4848. if (category == "characters") {
  4849. categoryOption.selected = true;
  4850. select.classList.add("category-visible");
  4851. button.classList.add("category-visible");
  4852. }
  4853. categorySelect.appendChild(categoryOption);
  4854. holder.appendChild(select);
  4855. holder.appendChild(button);
  4856. });
  4857. Object.values(filterDefs).forEach((filter) => {
  4858. const filterHolder = document.createElement("label");
  4859. filterHolder.setAttribute("for", "filter-toggle-" + filter.id);
  4860. filterHolder.classList.add("filter-holder");
  4861. const filterToggle = document.createElement("input");
  4862. filterToggle.type = "checkbox";
  4863. filterToggle.id = "filter-toggle-" + filter.id;
  4864. filterHolder.appendChild(filterToggle);
  4865. filterToggle.addEventListener("input", e => {
  4866. filterStates[filter.id] = filterToggle.checked
  4867. if (filterToggle.checked) {
  4868. filterHolder.classList.add("enabled");
  4869. } else {
  4870. filterHolder.classList.remove("enabled");
  4871. }
  4872. clearFilter();
  4873. updateFilter();
  4874. });
  4875. const filterLabel = document.createElement("div");
  4876. filterLabel.innerText = filter.name;
  4877. filterHolder.appendChild(filterLabel);
  4878. const filterNameSelect = document.createElement("select");
  4879. filterNameSelect.classList.add("filter-select");
  4880. filterNameSelect.id = "filter-" + filter.id;
  4881. filterHolder.appendChild(filterNameSelect);
  4882. filterMenu.appendChild(filterHolder);
  4883. Array.from(filterSets[filter.id])
  4884. .map((name) => [name, filter.render(name)])
  4885. .sort(filterDefs[filter.id].sort)
  4886. .forEach((name) => {
  4887. const option = document.createElement("option");
  4888. option.innerText = name[1];
  4889. option.value = name[0];
  4890. filterNameSelect.appendChild(option);
  4891. });
  4892. filterNameSelect.addEventListener("change", (e) => {
  4893. updateFilter();
  4894. });
  4895. });
  4896. const spawnButton = document.createElement("button");
  4897. spawnButton.id = "spawn-all"
  4898. spawnButton.addEventListener("click", e => {
  4899. spawnAll();
  4900. });
  4901. filterMenu.appendChild(spawnButton);
  4902. console.log(
  4903. "Loaded " + Object.keys(availableEntitiesByName).length + " entities"
  4904. );
  4905. categorySelect.addEventListener("input", (e) => {
  4906. const oldSelect = document.querySelector(
  4907. ".entity-select.category-visible"
  4908. );
  4909. oldSelect.classList.remove("category-visible");
  4910. const oldButton = document.querySelector(
  4911. ".entity-button.category-visible"
  4912. );
  4913. oldButton.classList.remove("category-visible");
  4914. const newSelect = document.querySelector(
  4915. "#create-entity-" + e.target.value
  4916. );
  4917. newSelect.classList.add("category-visible");
  4918. const newButton = document.querySelector(
  4919. "#create-entity-" + e.target.value + "-button"
  4920. );
  4921. newButton.classList.add("category-visible");
  4922. recomputeFilters();
  4923. updateFilter();
  4924. });
  4925. recomputeFilters();
  4926. ratioInfo = document.body.querySelector(".extra-info");
  4927. }
  4928. function spawnAll() {
  4929. const makers = Array.from(
  4930. document.querySelector(".entity-select.category-visible")
  4931. ).filter((element) => !element.classList.contains("filtered"));
  4932. const count = makers.length + 2;
  4933. let index = 1;
  4934. if (makers.length > 50) {
  4935. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  4936. return;
  4937. }
  4938. }
  4939. const worldWidth =
  4940. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  4941. const spawned = makers.map((element) => {
  4942. const category = document.querySelector("#category-picker").value;
  4943. const maker = availableEntities[category][element.value];
  4944. const entity = maker.constructor();
  4945. displayEntity(
  4946. entity,
  4947. entity.view,
  4948. -worldWidth * 0.45 +
  4949. config.x +
  4950. (worldWidth * 0.9 * index) / (count - 1),
  4951. config.y
  4952. );
  4953. index += 1;
  4954. return entityIndex - 1;
  4955. });
  4956. updateSizes(true);
  4957. if (config.autoFitAdd) {
  4958. let targets = {};
  4959. spawned.forEach((key) => {
  4960. targets[key] = entities[key];
  4961. });
  4962. fitEntities(targets);
  4963. }
  4964. }
  4965. // Only display authors and owners if they appear
  4966. // somewhere in the current entity list
  4967. function recomputeFilters() {
  4968. const category = document.querySelector("#category-picker").value;
  4969. const filterSets = {};
  4970. Object.values(filterDefs).forEach((filter) => {
  4971. filterSets[filter.id] = new Set();
  4972. });
  4973. availableEntities[category].forEach((entity) => {
  4974. Object.values(filterDefs).forEach((filter) => {
  4975. filter.extract(entity).forEach((result) => {
  4976. filterSets[filter.id].add(result);
  4977. });
  4978. });
  4979. });
  4980. Object.values(filterDefs).forEach((filter) => {
  4981. filterStates[filter.id] = false;
  4982. document.querySelector("#filter-toggle-" + filter.id).checked = false
  4983. document.querySelector("#filter-toggle-" + filter.id).dispatchEvent(new Event("click"))
  4984. // always show the "none" option
  4985. let found = filter.id == "none";
  4986. const filterSelect = document.querySelector("#filter-" + filter.id);
  4987. const filterSelectHolder = filterSelect.parentElement;
  4988. filterSelect.querySelectorAll("option").forEach((element) => {
  4989. if (
  4990. filterSets[filter.id].has(element.value) ||
  4991. filter.id == "none"
  4992. ) {
  4993. element.classList.remove("filtered");
  4994. element.disabled = false;
  4995. found = true;
  4996. } else {
  4997. element.classList.add("filtered");
  4998. element.disabled = true;
  4999. }
  5000. });
  5001. if (found) {
  5002. filterSelectHolder.style.display = "";
  5003. } else {
  5004. filterSelectHolder.style.display = "none";
  5005. }
  5006. });
  5007. }
  5008. function updateFilter() {
  5009. const category = document.querySelector("#category-picker").value;
  5010. const types = Object.values(filterDefs).filter(def => filterStates[def.id]).map(def => def.id)
  5011. const keys = {
  5012. }
  5013. types.forEach(type => {
  5014. const filterKeySelect = document.querySelector("#filter-" + type);
  5015. keys[type] = filterKeySelect.value;
  5016. })
  5017. clearFilter();
  5018. let current = document.querySelector(
  5019. ".entity-select.category-visible"
  5020. ).value;
  5021. let replace = current == "";
  5022. let first = null;
  5023. let count = 0;
  5024. const lowerSearchText = searchText !== "" ? searchText.toLowerCase() : null;
  5025. document
  5026. .querySelectorAll(".entity-select.category-visible > option")
  5027. .forEach((element) => {
  5028. let keep = true
  5029. types.forEach(type => {
  5030. if (
  5031. !(filterDefs[type]
  5032. .extract(availableEntities[category][element.value])
  5033. .indexOf(keys[type]) >= 0)
  5034. ) {
  5035. keep = false;
  5036. }
  5037. })
  5038. if (
  5039. searchText != "" &&
  5040. !availableEntities[category][element.value].name
  5041. .toLowerCase()
  5042. .includes(lowerSearchText)
  5043. ) {
  5044. keep = false;
  5045. }
  5046. if (!keep) {
  5047. element.classList.add("filtered");
  5048. element.disabled = true;
  5049. if (current == element.value) {
  5050. replace = true;
  5051. }
  5052. } else {
  5053. count += 1;
  5054. if (!first) {
  5055. first = element.value;
  5056. }
  5057. }
  5058. });
  5059. const button = document.querySelector("#spawn-all")
  5060. button.innerText = "Spawn " + count + " filtered " + (count == 1 ? "entity" : "entities") + ".";
  5061. if (replace) {
  5062. document.querySelector(".entity-select.category-visible").value = first;
  5063. document
  5064. .querySelector("#create-entity-" + category)
  5065. .dispatchEvent(new Event("change"));
  5066. }
  5067. }
  5068. function clearFilter() {
  5069. document
  5070. .querySelectorAll(".entity-select.category-visible > option")
  5071. .forEach((element) => {
  5072. element.classList.remove("filtered");
  5073. element.disabled = false;
  5074. });
  5075. }
  5076. function checkFitWorld() {
  5077. if (config.autoFit) {
  5078. fitWorld();
  5079. return true;
  5080. }
  5081. return false;
  5082. }
  5083. function fitWorld(manual = false, factor = 1.1) {
  5084. if (Object.keys(entities).length > 0) {
  5085. fitEntities(entities, factor);
  5086. }
  5087. }
  5088. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  5089. let minX = Infinity;
  5090. let maxX = -Infinity;
  5091. let minY = Infinity;
  5092. let maxY = -Infinity;
  5093. let count = 0;
  5094. const worldWidth =
  5095. (config.height.toNumber("meters") / canvasHeight) * canvasWidth;
  5096. const worldHeight = config.height.toNumber("meters");
  5097. Object.entries(targetEntities).forEach(([key, entity]) => {
  5098. const view = entity.view;
  5099. let extra = entity.views[view].image.extra;
  5100. extra = extra === undefined ? 1 : extra;
  5101. const image = document.querySelector(
  5102. "#entity-" + key + " > .entity-image"
  5103. );
  5104. const x = parseFloat(
  5105. document.querySelector("#entity-" + key).dataset.x
  5106. );
  5107. let width = image.width;
  5108. let height = image.height;
  5109. // only really relevant if the images haven't loaded in yet
  5110. if (height == 0) {
  5111. height = 100;
  5112. }
  5113. if (width == 0) {
  5114. width = height;
  5115. }
  5116. const xBottom =
  5117. x -
  5118. (entity.views[view].height.toNumber("meters") * width) / height / 2;
  5119. const xTop =
  5120. x +
  5121. (entity.views[view].height.toNumber("meters") * width) / height / 2;
  5122. const y = parseFloat(
  5123. document.querySelector("#entity-" + key).dataset.y
  5124. );
  5125. const yBottom = y;
  5126. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  5127. minX = Math.min(minX, xBottom);
  5128. maxX = Math.max(maxX, xTop);
  5129. minY = Math.min(minY, yBottom);
  5130. maxY = Math.max(maxY, yTop);
  5131. count += 1;
  5132. });
  5133. if (config.lockYAxis) {
  5134. minY = 0;
  5135. }
  5136. let ySize = (maxY - minY) * factor;
  5137. let xSize = (maxX - minX) * factor;
  5138. if (xSize / ySize > worldWidth / worldHeight) {
  5139. ySize *= xSize / ySize / (worldWidth / worldHeight);
  5140. }
  5141. config.x = (maxX + minX) / 2;
  5142. config.y = minY;
  5143. height = math.unit(ySize, "meter");
  5144. setWorldHeight(config.height, math.multiply(height, factor));
  5145. }
  5146. function updateWorldHeight() {
  5147. const unit = document.querySelector("#options-height-unit").value;
  5148. const rawValue = document.querySelector("#options-height-value").value;
  5149. var value;
  5150. try {
  5151. value = math.evaluate(rawValue);
  5152. if (typeof value !== "number") {
  5153. try {
  5154. value = value.toNumber(unit);
  5155. } catch {
  5156. toast(
  5157. "Invalid input: " +
  5158. rawValue +
  5159. " can't be converted to " +
  5160. unit
  5161. );
  5162. }
  5163. }
  5164. } catch {
  5165. toast("Invalid input: could not parse " + rawValue);
  5166. return;
  5167. }
  5168. const newHeight = Math.max(0.000000001, value);
  5169. const oldHeight = config.height;
  5170. setWorldHeight(oldHeight, math.unit(newHeight, unit), true);
  5171. }
  5172. function setWorldHeight(oldHeight, newHeight, keepUnit = false) {
  5173. worldSizeDirty = true;
  5174. config.height = newHeight.to(
  5175. document.querySelector("#options-height-unit").value
  5176. );
  5177. const unit = document.querySelector("#options-height-unit").value;
  5178. setNumericInput(
  5179. document.querySelector("#options-height-value"),
  5180. config.height.toNumber(unit)
  5181. );
  5182. Object.entries(entities).forEach(([key, entity]) => {
  5183. const element = document.querySelector("#entity-" + key);
  5184. let newPosition;
  5185. if (altHeld) {
  5186. newPosition = adjustAbs(
  5187. { x: element.dataset.x, y: element.dataset.y },
  5188. oldHeight,
  5189. config.height
  5190. );
  5191. } else {
  5192. newPosition = { x: element.dataset.x, y: element.dataset.y };
  5193. }
  5194. element.dataset.x = newPosition.x;
  5195. element.dataset.y = newPosition.y;
  5196. });
  5197. if (!keepUnit) {
  5198. pickUnit();
  5199. }
  5200. updateSizes();
  5201. }
  5202. function loadScene(name = "default") {
  5203. if (name === "") {
  5204. name = "default";
  5205. }
  5206. try {
  5207. const data = JSON.parse(
  5208. localStorage.getItem("macrovision-save-" + name), math.reviver
  5209. );
  5210. if (data === null) {
  5211. console.error("Couldn't load " + name);
  5212. return false;
  5213. }
  5214. importScene(data);
  5215. toast("Loaded " + name);
  5216. return true;
  5217. } catch (err) {
  5218. alert(
  5219. "Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error."
  5220. );
  5221. console.error(err);
  5222. return false;
  5223. }
  5224. }
  5225. function saveScene(name = "default") {
  5226. try {
  5227. const string = JSON.stringify(exportScene());
  5228. localStorage.setItem("macrovision-save-" + name, string);
  5229. toast("Saved as " + name);
  5230. } catch (err) {
  5231. alert(
  5232. "Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error."
  5233. );
  5234. console.error(err);
  5235. }
  5236. }
  5237. function deleteScene(name = "default") {
  5238. if (confirm("Really delete the " + name + " scene?")) {
  5239. try {
  5240. localStorage.removeItem("macrovision-save-" + name);
  5241. toast("Deleted " + name);
  5242. } catch (err) {
  5243. console.error(err);
  5244. }
  5245. }
  5246. updateSaveInfo();
  5247. }
  5248. function exportScene() {
  5249. const results = {};
  5250. results.entities = [];
  5251. Object.entries(entities)
  5252. .filter(([key, entity]) => entity.ephemeral !== true)
  5253. .forEach(([key, entity]) => {
  5254. const element = document.querySelector("#entity-" + key);
  5255. const entityData = {
  5256. name: entity.identifier,
  5257. customName: entity.name,
  5258. scale: entity.scale,
  5259. rotation: entity.rotation,
  5260. flipped: entity.flipped,
  5261. view: entity.view,
  5262. form: entity.form,
  5263. x: element.dataset.x,
  5264. y: element.dataset.y,
  5265. priority: entity.priority,
  5266. brightness: entity.brightness,
  5267. };
  5268. entityData.views = {};
  5269. Object.entries(entity.views).forEach(([viewId, viewData]) => {
  5270. Object.entries(viewData.attributes).forEach(([attrId, attrData]) => {
  5271. if (attrData.custom) {
  5272. if (entityData.views[viewId] === undefined) {
  5273. entityData.views[viewId] = {};
  5274. }
  5275. entityData.views[viewId][attrId] = attrData;
  5276. }
  5277. });
  5278. });
  5279. results.entities.push(entityData);
  5280. });
  5281. const unit = document.querySelector("#options-height-unit").value;
  5282. results.world = {
  5283. height: config.height.toNumber(unit),
  5284. unit: unit,
  5285. x: config.x,
  5286. y: config.y,
  5287. };
  5288. results.version = migrationDefs.length;
  5289. return results;
  5290. }
  5291. // btoa doesn't like anything that isn't ASCII
  5292. // great
  5293. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  5294. // for providing an alternative
  5295. function b64EncodeUnicode(str) {
  5296. // first we use encodeURIComponent to get percent-encoded UTF-8,
  5297. // then we convert the percent encodings into raw bytes which
  5298. // can be fed into btoa.
  5299. return btoa(
  5300. encodeURIComponent(str).replace(
  5301. /%([0-9A-F]{2})/g,
  5302. function toSolidBytes(match, p1) {
  5303. return String.fromCharCode("0x" + p1);
  5304. }
  5305. )
  5306. );
  5307. }
  5308. function b64DecodeUnicode(str) {
  5309. // Going backwards: from bytestream, to percent-encoding, to original string.
  5310. return decodeURIComponent(
  5311. atob(str)
  5312. .split("")
  5313. .map(function (c) {
  5314. return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
  5315. })
  5316. .join("")
  5317. );
  5318. }
  5319. function linkScene() {
  5320. loc = new URL(window.location);
  5321. const link =
  5322. loc.protocol +
  5323. "//" +
  5324. loc.host +
  5325. loc.pathname +
  5326. "#" +
  5327. b64EncodeUnicode(JSON.stringify(exportScene()));
  5328. window.history.replaceState(null, "Macrovision", link);
  5329. try {
  5330. navigator.clipboard.writeText(link);
  5331. toast("Copied permalink to clipboard");
  5332. } catch {
  5333. toast("Couldn't copy permalink");
  5334. }
  5335. }
  5336. function copyScene() {
  5337. const results = exportScene();
  5338. navigator.clipboard.writeText(JSON.stringify(results));
  5339. }
  5340. function pasteScene() {
  5341. try {
  5342. navigator.clipboard
  5343. .readText()
  5344. .then((text) => {
  5345. const data = JSON.parse(text, math.reviver);
  5346. if (data.entities === undefined) {
  5347. return;
  5348. }
  5349. if (data.world === undefined) {
  5350. return;
  5351. }
  5352. importScene(data);
  5353. })
  5354. .catch((err) => { toast("Something went wrong when importing: " + err), console.error(err) });
  5355. } catch (err) {
  5356. console.error(err);
  5357. // probably wasn't valid data
  5358. }
  5359. }
  5360. function findEntity(name) {
  5361. return availableEntitiesByName[name];
  5362. }
  5363. const migrationDefs = [
  5364. /*
  5365. Migration: 0 -> 1
  5366. Adds x and y coordinates for the camera
  5367. */
  5368. (data) => {
  5369. data.world.x = 0;
  5370. data.world.y = 0;
  5371. },
  5372. /*
  5373. Migration: 1 -> 2
  5374. Adds priority and brightness to each entity
  5375. */
  5376. (data) => {
  5377. data.entities.forEach((entity) => {
  5378. entity.priority = 0;
  5379. entity.brightness = 1;
  5380. });
  5381. },
  5382. /*
  5383. Migration: 2 -> 3
  5384. Custom names are exported
  5385. */
  5386. (data) => {
  5387. data.entities.forEach((entity) => {
  5388. entity.customName = entity.name;
  5389. });
  5390. },
  5391. /*
  5392. Migration: 3 -> 4
  5393. Rotation is now stored
  5394. */
  5395. (data) => {
  5396. data.entities.forEach((entity) => {
  5397. entity.rotation = 0;
  5398. });
  5399. },
  5400. /*
  5401. Migration: 4 -> 5
  5402. Flipping is now stored
  5403. */
  5404. (data) => {
  5405. data.entities.forEach((entity) => {
  5406. entity.flipped = false;
  5407. });
  5408. }
  5409. /*
  5410. Migration: 5 -> 6
  5411. Entities can now have custom attributes
  5412. */
  5413. ];
  5414. function migrateScene(data) {
  5415. if (data.version === undefined) {
  5416. alert(
  5417. "This save was created before save versions were tracked. The scene may import incorrectly."
  5418. );
  5419. console.trace();
  5420. data.version = 0;
  5421. } else if (data.version < migrationDefs.length) {
  5422. migrationDefs[data.version](data);
  5423. data.version += 1;
  5424. migrateScene(data);
  5425. }
  5426. }
  5427. function importScene(data) {
  5428. removeAllEntities();
  5429. migrateScene(data);
  5430. data.entities.forEach((entityInfo) => {
  5431. const entity = findEntity(entityInfo.name).constructor();
  5432. entity.name = entityInfo.customName;
  5433. entity.scale = entityInfo.scale;
  5434. entity.rotation = entityInfo.rotation;
  5435. entity.flipped = entityInfo.flipped;
  5436. entity.priority = entityInfo.priority;
  5437. entity.brightness = entityInfo.brightness;
  5438. entity.form = entityInfo.form;
  5439. Object.entries(entityInfo.views).forEach(([viewId, viewData]) => {
  5440. if (entityInfo.views[viewId] !== undefined) {
  5441. Object.entries(entityInfo.views[viewId]).forEach(([attrId, attrData]) => {
  5442. entity.views[viewId].attributes[attrId] = attrData;
  5443. });
  5444. }
  5445. });
  5446. Object.keys(entityInfo.views).forEach(key => defineAttributeGetters(entity.views[key]));
  5447. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  5448. });
  5449. config.height = math.unit(data.world.height, data.world.unit);
  5450. config.x = data.world.x;
  5451. config.y = data.world.y;
  5452. const height = math
  5453. .unit(data.world.height, data.world.unit)
  5454. .toNumber(defaultUnits.length[config.units]);
  5455. document.querySelector("#options-height-value").value = height;
  5456. document.querySelector("#options-height-unit").dataset.oldUnit =
  5457. defaultUnits.length[config.units];
  5458. document.querySelector("#options-height-unit").value =
  5459. defaultUnits.length[config.units];
  5460. if (data.canvasWidth) {
  5461. doHorizReposition(data.canvasWidth / canvasWidth);
  5462. }
  5463. updateSizes();
  5464. }
  5465. function renderToCanvas() {
  5466. const ctx = document.querySelector("#display").getContext("2d");
  5467. Object.entries(entities)
  5468. .sort((ent1, ent2) => {
  5469. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  5470. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  5471. return z1 - z2;
  5472. })
  5473. .forEach(([id, entity]) => {
  5474. element = document.querySelector("#entity-" + id);
  5475. img = element.querySelector("img");
  5476. let x = parseFloat(element.dataset.x);
  5477. let y = parseFloat(element.dataset.y);
  5478. let coords = pos2pix({ x: x, y: y });
  5479. let offset = img.style.getPropertyValue("--offset");
  5480. offset = parseFloat(offset.substring(0, offset.length - 1));
  5481. let xSize = img.width;
  5482. let ySize = img.height;
  5483. x = coords.x;
  5484. y = coords.y + ySize / 2 + (ySize * offset) / 100;
  5485. const oldFilter = ctx.filter;
  5486. const brightness =
  5487. getComputedStyle(element).getPropertyValue("--brightness");
  5488. ctx.filter = `brightness(${brightness})`;
  5489. ctx.save();
  5490. ctx.resetTransform();
  5491. ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
  5492. ctx.translate(x, y);
  5493. ctx.rotate(entity.rotation);
  5494. ctx.scale(entity.flipped ? -1 : 1, 1);
  5495. ctx.drawImage(img, -xSize / 2, -ySize / 2, xSize, ySize);
  5496. ctx.restore();
  5497. ctx.filter = oldFilter;
  5498. });
  5499. ctx.save();
  5500. ctx.resetTransform();
  5501. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  5502. ctx.restore();
  5503. }
  5504. function exportCanvas(callback) {
  5505. /** @type {CanvasRenderingContext2D} */
  5506. const ctx = document.querySelector("#display").getContext("2d");
  5507. ctx.canvas.toBlob(callback);
  5508. }
  5509. function generateScreenshot(callback) {
  5510. /** @type {CanvasRenderingContext2D} */
  5511. const ctx = document.querySelector("#display").getContext("2d");
  5512. if (config.groundKind !== "none") {
  5513. ctx.fillStyle = backgroundColors[config.groundKind];
  5514. ctx.fillRect(
  5515. 0,
  5516. pos2pix({ x: 0, y: 0 }).y,
  5517. canvasWidth + 100,
  5518. canvasHeight
  5519. );
  5520. }
  5521. renderToCanvas();
  5522. ctx.resetTransform();
  5523. ctx.fillStyle = "#999";
  5524. ctx.font = "normal normal lighter 16pt coda";
  5525. ctx.fillText("macrovision.crux.sexy", 10, 25);
  5526. exportCanvas((blob) => {
  5527. callback(blob);
  5528. });
  5529. }
  5530. function copyScreenshot() {
  5531. if (window.ClipboardItem === undefined) {
  5532. alert(
  5533. "Sorry, this browser doesn't yet support writing images to the clipboard."
  5534. );
  5535. return;
  5536. }
  5537. generateScreenshot((blob) => {
  5538. navigator.clipboard
  5539. .write([
  5540. new ClipboardItem({
  5541. "image/png": blob,
  5542. }),
  5543. ])
  5544. .then((e) => toast("Copied to clipboard!"))
  5545. .catch((e) => {
  5546. console.error(e);
  5547. toast(
  5548. "Couldn't write to the clipboard. Make sure the screenshot completes before switching tabs. Also, currently busted in Safari :("
  5549. );
  5550. });
  5551. });
  5552. drawScales(false);
  5553. }
  5554. function saveScreenshot() {
  5555. generateScreenshot((blob) => {
  5556. const a = document.createElement("a");
  5557. a.href = URL.createObjectURL(blob);
  5558. a.setAttribute("download", "macrovision.png");
  5559. a.click();
  5560. });
  5561. drawScales(false);
  5562. }
  5563. function openScreenshot() {
  5564. generateScreenshot((blob) => {
  5565. const a = document.createElement("a");
  5566. a.href = URL.createObjectURL(blob);
  5567. a.setAttribute("target", "_blank");
  5568. a.click();
  5569. });
  5570. drawScales(false);
  5571. }
  5572. const rateLimits = {};
  5573. function toast(msg) {
  5574. let div = document.createElement("div");
  5575. div.innerHTML = msg;
  5576. div.classList.add("toast");
  5577. document.body.appendChild(div);
  5578. setTimeout(() => {
  5579. document.body.removeChild(div);
  5580. }, 5000);
  5581. }
  5582. function toastRateLimit(msg, key, delay) {
  5583. if (!rateLimits[key]) {
  5584. toast(msg);
  5585. rateLimits[key] = setTimeout(() => {
  5586. delete rateLimits[key];
  5587. }, delay);
  5588. }
  5589. }
  5590. let lastTime = undefined;
  5591. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  5592. Object.keys(entities).forEach((key) => {
  5593. document.querySelector("#entity-" + key).classList.add("no-transition");
  5594. });
  5595. config.x = fromX;
  5596. config.y = fromY;
  5597. config.height = math.unit(fromHeight, "meters");
  5598. updateSizes();
  5599. lastTime = undefined;
  5600. requestAnimationFrame((timestamp) =>
  5601. panTo(
  5602. toX,
  5603. toY,
  5604. toHeight,
  5605. (toX - fromX) / duration,
  5606. (toY - fromY) / duration,
  5607. (toHeight - fromHeight) / duration,
  5608. timestamp,
  5609. duration
  5610. )
  5611. );
  5612. }
  5613. function panTo(
  5614. x,
  5615. y,
  5616. height,
  5617. xSpeed,
  5618. ySpeed,
  5619. heightSpeed,
  5620. timestamp,
  5621. remaining
  5622. ) {
  5623. if (lastTime === undefined) {
  5624. lastTime = timestamp;
  5625. }
  5626. dt = timestamp - lastTime;
  5627. remaining -= dt;
  5628. if (remaining < 0) {
  5629. dt += remaining;
  5630. }
  5631. let newX = config.x + xSpeed * dt;
  5632. let newY = config.y + ySpeed * dt;
  5633. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  5634. if (remaining > 0) {
  5635. requestAnimationFrame((timestamp) =>
  5636. panTo(
  5637. x,
  5638. y,
  5639. height,
  5640. xSpeed,
  5641. ySpeed,
  5642. heightSpeed,
  5643. timestamp,
  5644. remaining
  5645. )
  5646. );
  5647. } else {
  5648. Object.keys(entities).forEach((key) => {
  5649. document
  5650. .querySelector("#entity-" + key)
  5651. .classList.remove("no-transition");
  5652. });
  5653. }
  5654. config.x = newX;
  5655. config.y = newY;
  5656. config.height = math.unit(newHeight, "meters");
  5657. updateSizes();
  5658. }
  5659. function getVerticalOffset() {
  5660. if (config.groundPos === "very-high") {
  5661. return (config.height.toNumber("meters") / 12) * 5;
  5662. } else if (config.groundPos === "high") {
  5663. return (config.height.toNumber("meters") / 12) * 4;
  5664. } else if (config.groundPos === "medium") {
  5665. return (config.height.toNumber("meters") / 12) * 3;
  5666. } else if (config.groundPos === "low") {
  5667. return (config.height.toNumber("meters") / 12) * 2;
  5668. } else if (config.groundPos === "very-low") {
  5669. return config.height.toNumber("meters") / 12;
  5670. } else {
  5671. return 0;
  5672. }
  5673. }
  5674. function moveGround(down) {
  5675. const index = groundPosChoices.indexOf(config.groundPos);
  5676. if (down) {
  5677. if (index < groundPosChoices.length - 1) {
  5678. config.groundPos = groundPosChoices[index + 1];
  5679. }
  5680. } else {
  5681. if (index > 0) {
  5682. config.groundPos = groundPosChoices[index - 1];
  5683. }
  5684. }
  5685. updateScrollButtons();
  5686. updateSizes();
  5687. }
  5688. function updateScrollButtons() {
  5689. const up = document.querySelector("#scroll-up");
  5690. const down = document.querySelector("#scroll-down");
  5691. up.disabled = false;
  5692. down.disabled = false;
  5693. document.querySelector("#setting-ground-pos").value = config.groundPos;
  5694. if (config.lockYAxis) {
  5695. const index = groundPosChoices.indexOf(config.groundPos);
  5696. if (index == 0) {
  5697. down.disabled = true;
  5698. }
  5699. if (index == groundPosChoices.length - 1) {
  5700. up.disabled = true;
  5701. }
  5702. }
  5703. }