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

5213 строки
159 KiB

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