less copy protection, more size visualization
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

4273 行
130 KiB

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