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

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