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

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