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.
 
 
 

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