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

4239 строки
128 KiB

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