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

5184 строки
158 KiB

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