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

4714 строки
142 KiB

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