less copy protection, more size visualization
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

4571 lines
139 KiB

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