less copy protection, more size visualization
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

4268 líneas
130 KiB

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