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

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