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

5390 lines
164 KiB

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