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

4260 строки
129 KiB

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