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

4805 lines
145 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. rotation: 0,
  926. info: JSON.parse(JSON.stringify(info)),
  927. views: JSON.parse(JSON.stringify(views), math.reviver),
  928. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  929. init: function () {
  930. const entity = this;
  931. Object.entries(this.views).forEach(([viewKey, view]) => {
  932. view.parent = this;
  933. if (this.defaultView === undefined) {
  934. this.defaultView = viewKey;
  935. this.view = viewKey;
  936. }
  937. if (view.default) {
  938. this.defaultView = viewKey;
  939. this.view = viewKey;
  940. }
  941. // to remember the units the user last picked
  942. view.units = {};
  943. if (config.autoFoodIntake && view.attributes.weight !== undefined && view.attributes.energyNeed === undefined) {
  944. view.attributes.energyNeed = {
  945. name: "Food Intake",
  946. power: 3,
  947. type: "energy",
  948. base: math.unit(2000 * view.attributes.weight.base.toNumber("lbs") / 150, "kcal")
  949. }
  950. }
  951. if (config.autoPreyCapacity !== "none" && view.attributes.weight !== undefined && view.attributes.capacity === undefined) {
  952. view.attributes.capacity = {
  953. name: "Capacity",
  954. power: 3,
  955. type: "volume",
  956. base: math.unit((config.autoPreyCapacity == "same-size" ? 1 : 0.05) * view.attributes.weight.base.toNumber("lbs") / 150, "people")
  957. }
  958. }
  959. Object.entries(view.attributes).forEach(([key, val]) => {
  960. Object.defineProperty(
  961. view,
  962. key,
  963. {
  964. get: function () {
  965. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  966. },
  967. set: function (value) {
  968. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  969. this.parent.scale = newScale;
  970. }
  971. }
  972. );
  973. });
  974. });
  975. this.sizes.forEach(size => {
  976. if (size.default === true) {
  977. this.views[this.defaultView].height = size.height;
  978. this.size = size;
  979. }
  980. });
  981. if (this.size === undefined && this.sizes.length > 0) {
  982. this.views[this.defaultView].height = this.sizes[0].height;
  983. this.size = this.sizes[0];
  984. console.warn("No default size set for " + info.name);
  985. } else if (this.sizes.length == 0) {
  986. this.sizes = [
  987. {
  988. name: "Normal",
  989. height: this.views[this.defaultView].height
  990. }
  991. ];
  992. this.size = this.sizes[0];
  993. }
  994. this.desc = {};
  995. Object.entries(this.info).forEach(([key, value]) => {
  996. Object.defineProperty(
  997. this.desc,
  998. key,
  999. {
  1000. get: function () {
  1001. let text = value.text;
  1002. if (entity.views[entity.view].info) {
  1003. if (entity.views[entity.view].info[key]) {
  1004. text = combineInfo(text, entity.views[entity.view].info[key]);
  1005. }
  1006. }
  1007. if (entity.size.info) {
  1008. if (entity.size.info[key]) {
  1009. text = combineInfo(text, entity.size.info[key]);
  1010. }
  1011. }
  1012. return { title: value.title, text: text };
  1013. }
  1014. }
  1015. )
  1016. });
  1017. Object.defineProperty(
  1018. this,
  1019. "currentView",
  1020. {
  1021. get: function() {
  1022. return entity.views[entity.view];
  1023. }
  1024. }
  1025. )
  1026. delete this.init;
  1027. return this;
  1028. }
  1029. }.init();
  1030. return entityTemplate;
  1031. }
  1032. function combineInfo(existing, next) {
  1033. switch (next.mode) {
  1034. case "replace":
  1035. return next.text;
  1036. case "prepend":
  1037. return next.text + existing;
  1038. case "append":
  1039. return existing + next.text;
  1040. }
  1041. return existing;
  1042. }
  1043. function clickDown(target, x, y) {
  1044. clicked = target;
  1045. movingInBounds = false;
  1046. const rect = target.getBoundingClientRect();
  1047. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1048. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1049. dragOffsetX = x - rect.left + entX;
  1050. dragOffsetY = y - rect.top + entY;
  1051. x = x - dragOffsetX;
  1052. y = y - dragOffsetY;
  1053. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  1054. movingInBounds = true;
  1055. }
  1056. clickTimeout = setTimeout(() => { dragging = true }, 200)
  1057. target.classList.add("no-transition");
  1058. }
  1059. // could we make this actually detect the menu area?
  1060. function hoveringInDeleteArea(e) {
  1061. return e.clientY < document.body.clientHeight / 10;
  1062. }
  1063. function clickUp(e) {
  1064. if (e.which != 1) {
  1065. return;
  1066. }
  1067. clearTimeout(clickTimeout);
  1068. if (clicked) {
  1069. clicked.classList.remove("no-transition");
  1070. if (dragging) {
  1071. dragging = false;
  1072. if (hoveringInDeleteArea(e)) {
  1073. removeEntity(clicked);
  1074. document.querySelector("#menubar").classList.remove("hover-delete");
  1075. }
  1076. } else {
  1077. select(clicked);
  1078. }
  1079. clicked = null;
  1080. }
  1081. }
  1082. function deselect(e) {
  1083. if (e !== undefined && e.which != 1) {
  1084. return;
  1085. }
  1086. if (selected) {
  1087. selected.classList.remove("selected");
  1088. }
  1089. if (prevSelected) {
  1090. prevSelected.classList.remove("prevSelected");
  1091. }
  1092. document.getElementById("options-selected-entity-none").selected = "selected";
  1093. clearAttribution();
  1094. selected = null;
  1095. clearViewList();
  1096. clearEntityOptions();
  1097. clearViewOptions();
  1098. document.querySelector("#delete-entity").disabled = true;
  1099. document.querySelector("#grow").disabled = true;
  1100. document.querySelector("#shrink").disabled = true;
  1101. document.querySelector("#fit").disabled = true;
  1102. }
  1103. function select(target) {
  1104. if (prevSelected !== null) {
  1105. prevSelected.classList.remove("prevSelected");
  1106. }
  1107. prevSelected = selected;
  1108. prevSelectedEntity = selectedEntity;
  1109. deselect();
  1110. selected = target;
  1111. selectedEntity = entities[target.dataset.key];
  1112. updateRatios();
  1113. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  1114. if (prevSelected !== null && config.showRatios && selected !== prevSelected) {
  1115. prevSelected.classList.add("prevSelected");
  1116. }
  1117. selected.classList.add("selected");
  1118. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  1119. configViewList(selectedEntity, selectedEntity.view);
  1120. configEntityOptions(selectedEntity, selectedEntity.view);
  1121. configViewOptions(selectedEntity, selectedEntity.view);
  1122. document.querySelector("#delete-entity").disabled = false;
  1123. document.querySelector("#grow").disabled = false;
  1124. document.querySelector("#shrink").disabled = false;
  1125. document.querySelector("#fit").disabled = false;
  1126. }
  1127. function configViewList(entity, selectedView) {
  1128. const list = document.querySelector("#entity-view");
  1129. list.innerHTML = "";
  1130. list.style.display = "block";
  1131. Object.keys(entity.views).forEach(view => {
  1132. const option = document.createElement("option");
  1133. option.innerText = entity.views[view].name;
  1134. option.value = view;
  1135. if (isNsfw(entity.views[view].image.source)) {
  1136. option.classList.add("nsfw")
  1137. }
  1138. if (view === selectedView) {
  1139. option.selected = true;
  1140. if (option.classList.contains("nsfw")) {
  1141. list.classList.add("nsfw");
  1142. } else {
  1143. list.classList.remove("nsfw");
  1144. }
  1145. }
  1146. list.appendChild(option);
  1147. });
  1148. }
  1149. function clearViewList() {
  1150. const list = document.querySelector("#entity-view");
  1151. list.innerHTML = "";
  1152. list.style.display = "none";
  1153. }
  1154. function updateWorldOptions(entity, view) {
  1155. const heightInput = document.querySelector("#options-height-value");
  1156. const heightSelect = document.querySelector("#options-height-unit");
  1157. const converted = config.height.toNumber(heightSelect.value);
  1158. setNumericInput(heightInput, converted);
  1159. }
  1160. function configEntityOptions(entity, view) {
  1161. const holder = document.querySelector("#options-entity");
  1162. document.querySelector("#entity-category-header").style.display = "block";
  1163. document.querySelector("#entity-category").style.display = "block";
  1164. holder.innerHTML = "";
  1165. const scaleLabel = document.createElement("div");
  1166. scaleLabel.classList.add("options-label");
  1167. scaleLabel.innerText = "Scale";
  1168. const scaleRow = document.createElement("div");
  1169. scaleRow.classList.add("options-row");
  1170. const scaleInput = document.createElement("input");
  1171. scaleInput.classList.add("options-field-numeric");
  1172. scaleInput.id = "options-entity-scale";
  1173. scaleInput.addEventListener("change", e => {
  1174. try {
  1175. const newScale = e.target.value == 0 ? 1 : math.evaluate(e.target.value);
  1176. if (typeof(newScale) !== "number") {
  1177. toast("Invalid input: scale can't have any units!")
  1178. return;
  1179. }
  1180. entity.scale = newScale;
  1181. } catch {
  1182. toast("Invalid input: could not parse " + e.target.value)
  1183. }
  1184. entity.dirty = true;
  1185. if (config.autoFit) {
  1186. fitWorld();
  1187. } else {
  1188. updateSizes(true);
  1189. }
  1190. updateEntityOptions(entity, entity.view);
  1191. updateViewOptions(entity, entity.view);
  1192. });
  1193. scaleInput.addEventListener("keydown", e => {
  1194. e.stopPropagation();
  1195. })
  1196. setNumericInput(scaleInput, entity.scale);
  1197. scaleRow.appendChild(scaleInput);
  1198. holder.appendChild(scaleLabel);
  1199. holder.appendChild(scaleRow);
  1200. const nameLabel = document.createElement("div");
  1201. nameLabel.classList.add("options-label");
  1202. nameLabel.innerText = "Name";
  1203. const nameRow = document.createElement("div");
  1204. nameRow.classList.add("options-row");
  1205. const nameInput = document.createElement("input");
  1206. nameInput.classList.add("options-field-text");
  1207. nameInput.value = entity.name;
  1208. nameInput.addEventListener("input", e => {
  1209. entity.name = e.target.value;
  1210. entity.dirty = true;
  1211. updateSizes(true);
  1212. })
  1213. nameInput.addEventListener("keydown", e => {
  1214. e.stopPropagation();
  1215. })
  1216. nameRow.appendChild(nameInput);
  1217. holder.appendChild(nameLabel);
  1218. holder.appendChild(nameRow);
  1219. const defaultHolder = document.querySelector("#options-entity-defaults");
  1220. defaultHolder.innerHTML = "";
  1221. entity.sizes.forEach(defaultInfo => {
  1222. const button = document.createElement("button");
  1223. button.classList.add("options-button");
  1224. button.innerText = defaultInfo.name;
  1225. button.addEventListener("click", e => {
  1226. entity.views[entity.defaultView].height = defaultInfo.height;
  1227. entity.dirty = true;
  1228. updateEntityOptions(entity, entity.view);
  1229. updateViewOptions(entity, entity.view);
  1230. if (!checkFitWorld()) {
  1231. updateSizes(true);
  1232. }
  1233. if (config.autoFitSize) {
  1234. let targets = {};
  1235. targets[selected.dataset.key] = entities[selected.dataset.key];
  1236. fitEntities(targets);
  1237. }
  1238. });
  1239. defaultHolder.appendChild(button);
  1240. });
  1241. document.querySelector("#options-order-display").innerText = entity.priority;
  1242. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1243. document.querySelector("#options-ordering").style.display = "flex";
  1244. }
  1245. function updateEntityOptions(entity, view) {
  1246. const scaleInput = document.querySelector("#options-entity-scale");
  1247. setNumericInput(scaleInput, entity.scale);
  1248. document.querySelector("#options-order-display").innerText = entity.priority;
  1249. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1250. }
  1251. function clearEntityOptions() {
  1252. document.querySelector("#entity-category-header").style.display = "none";
  1253. document.querySelector("#entity-category").style.display = "none";
  1254. /*
  1255. const holder = document.querySelector("#options-entity");
  1256. holder.innerHTML = "";
  1257. document.querySelector("#options-entity-defaults").innerHTML = "";
  1258. document.querySelector("#options-ordering").style.display = "none";
  1259. document.querySelector("#options-ordering").style.display = "none";*/
  1260. }
  1261. function configViewOptions(entity, view) {
  1262. const holder = document.querySelector("#options-view");
  1263. document.querySelector("#view-category-header").style.display = "block";
  1264. document.querySelector("#view-category").style.display = "block";
  1265. holder.innerHTML = "";
  1266. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1267. const label = document.createElement("div");
  1268. label.classList.add("options-label");
  1269. label.innerText = val.name;
  1270. holder.appendChild(label);
  1271. const row = document.createElement("div");
  1272. row.classList.add("options-row");
  1273. holder.appendChild(row);
  1274. const input = document.createElement("input");
  1275. input.classList.add("options-field-numeric");
  1276. input.id = "options-view-" + key + "-input";
  1277. const select = document.createElement("select");
  1278. select.classList.add("options-field-unit");
  1279. select.id = "options-view-" + key + "-select"
  1280. Object.entries(unitChoices[val.type]).forEach(([group, entries]) => {
  1281. const optGroup = document.createElement("optgroup");
  1282. optGroup.label = group;
  1283. select.appendChild(optGroup);
  1284. entries.forEach(entry => {
  1285. const option = document.createElement("option");
  1286. option.innerText = entry;
  1287. if (entry == defaultUnits[val.type][config.units]) {
  1288. option.selected = true;
  1289. }
  1290. select.appendChild(option);
  1291. })
  1292. });
  1293. input.addEventListener("change", e => {
  1294. const raw_value = input.value == 0 ? 1 : input.value;
  1295. let value
  1296. try {
  1297. value = math.evaluate(raw_value).toNumber(select.value);
  1298. } catch {
  1299. try {
  1300. value = math.evaluate(input.value)
  1301. if (typeof(value) !== "number") {
  1302. toast("Invalid input: " + value.format() + " can't convert to " + select.value)
  1303. value = undefined
  1304. }
  1305. } catch {
  1306. toast("Invalid input: could not parse: " + input.value)
  1307. value = undefined
  1308. }
  1309. }
  1310. if (value === undefined) {
  1311. return;
  1312. }
  1313. input.value = value
  1314. entity.views[view][key] = math.unit(value, select.value);
  1315. entity.dirty = true;
  1316. if (config.autoFit) {
  1317. fitWorld();
  1318. } else {
  1319. updateSizes(true);
  1320. }
  1321. updateEntityOptions(entity, view);
  1322. updateViewOptions(entity, view, key);
  1323. });
  1324. input.addEventListener("keydown", e => {
  1325. e.stopPropagation();
  1326. })
  1327. if (entity.currentView.units[key]) {
  1328. select.value = entity.currentView.units[key];
  1329. } else {
  1330. entity.currentView.units[key] = select.value;
  1331. }
  1332. select.dataset.oldUnit = select.value;
  1333. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  1334. // TODO does this ever cause a change in the world?
  1335. select.addEventListener("input", e => {
  1336. const value = input.value == 0 ? 1 : input.value;
  1337. const oldUnit = select.dataset.oldUnit;
  1338. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  1339. entity.dirty = true;
  1340. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  1341. select.dataset.oldUnit = select.value;
  1342. entity.views[view].units[key] = select.value;
  1343. if (config.autoFit) {
  1344. fitWorld();
  1345. } else {
  1346. updateSizes(true);
  1347. }
  1348. updateEntityOptions(entity, view);
  1349. updateViewOptions(entity, view, key);
  1350. });
  1351. row.appendChild(input);
  1352. row.appendChild(select);
  1353. });
  1354. }
  1355. function updateViewOptions(entity, view, changed) {
  1356. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1357. if (key != changed) {
  1358. const input = document.querySelector("#options-view-" + key + "-input");
  1359. const select = document.querySelector("#options-view-" + key + "-select");
  1360. const currentUnit = select.value;
  1361. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  1362. setNumericInput(input, convertedAmount);
  1363. }
  1364. });
  1365. }
  1366. function setNumericInput(input, value, round = 6) {
  1367. if (typeof value == "string") {
  1368. value = parseFloat(value)
  1369. }
  1370. input.value = value.toPrecision(round);
  1371. }
  1372. function getSortedEntities() {
  1373. return Object.keys(entities).sort((a, b) => {
  1374. const entA = entities[a];
  1375. const entB = entities[b];
  1376. const viewA = entA.view;
  1377. const viewB = entB.view;
  1378. const heightA = entA.views[viewA].height.to("meter").value;
  1379. const heightB = entB.views[viewB].height.to("meter").value;
  1380. return heightA - heightB;
  1381. });
  1382. }
  1383. function clearViewOptions() {
  1384. document.querySelector("#view-category-header").style.display = "none";
  1385. document.querySelector("#view-category").style.display = "none";
  1386. }
  1387. // this is a crime against humanity, and also stolen from
  1388. // stack overflow
  1389. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  1390. const testCanvas = document.createElement("canvas");
  1391. testCanvas.id = "test-canvas";
  1392. function rotate(point, angle) {
  1393. return [
  1394. point[0] * Math.cos(angle) - point[1] * Math.sin(angle),
  1395. point[0] * Math.sin(angle) + point[1] * Math.cos(angle)
  1396. ];
  1397. }
  1398. const testCtx = testCanvas.getContext("2d");
  1399. function testClick(event) {
  1400. testCtx.save();
  1401. const target = event.target;
  1402. if (rulerMode) {
  1403. return;
  1404. }
  1405. // Get click coordinates
  1406. let w = target.width;
  1407. let h = target.height;
  1408. let ratioW = 1, ratioH = 1;
  1409. // Limit the size of the canvas so that very large images don't cause problems)
  1410. if (w > 1000) {
  1411. ratioW = w / 1000;
  1412. w /= ratioW;
  1413. h /= ratioW;
  1414. }
  1415. if (h > 1000) {
  1416. ratioH = h / 1000;
  1417. w /= ratioH;
  1418. h /= ratioH;
  1419. }
  1420. // todo remove some of this unused stuff
  1421. const ratio = ratioW * ratioH;
  1422. const entity = entities[target.parentElement.dataset.key];
  1423. const angle = entity.rotation;
  1424. var x = event.clientX - target.getBoundingClientRect().x,
  1425. y = event.clientY - target.getBoundingClientRect().y,
  1426. alpha;
  1427. [xTarget,yTarget] = [x,y];
  1428. [actualW, actualH] = [target.getBoundingClientRect().width, target.getBoundingClientRect().height];
  1429. xTarget /= ratio;
  1430. yTarget /= ratio;
  1431. actualW /= ratio;
  1432. actualH /= ratio;
  1433. testCtx.canvas.width = actualW;
  1434. testCtx.canvas.height = actualH;
  1435. testCtx.save();
  1436. // dear future me: Sorry :(
  1437. testCtx.resetTransform();
  1438. testCtx.translate(actualW/2, actualH/2);
  1439. testCtx.rotate(angle);
  1440. testCtx.translate(-actualW/2, -actualH/2);
  1441. testCtx.drawImage(target, (actualW/2 - w/2), (actualH/2 - h/2), w, h);
  1442. testCtx.fillStyle = "red";
  1443. testCtx.fillRect(actualW/2,actualH/2,10,10);
  1444. testCtx.restore();
  1445. testCtx.fillStyle = "red";
  1446. alpha = testCtx.getImageData(xTarget, yTarget, 1, 1).data[3];
  1447. testCtx.fillRect(xTarget, yTarget, 3, 3);
  1448. // If the pixel is transparent,
  1449. // retrieve the element underneath and trigger its click event
  1450. if (alpha === 0) {
  1451. const oldDisplay = target.style.display;
  1452. target.style.display = "none";
  1453. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  1454. newTarget.dispatchEvent(new MouseEvent(event.type, {
  1455. "clientX": event.clientX,
  1456. "clientY": event.clientY
  1457. }));
  1458. target.style.display = oldDisplay;
  1459. } else {
  1460. clickDown(target.parentElement, event.clientX, event.clientY);
  1461. }
  1462. testCtx.restore();
  1463. }
  1464. function arrangeEntities(order) {
  1465. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1466. let sum = 0;
  1467. order.forEach(key => {
  1468. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1469. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1470. let height = image.height;
  1471. let width = image.width;
  1472. if (height == 0) {
  1473. height = 100;
  1474. }
  1475. if (width == 0) {
  1476. width = height;
  1477. }
  1478. sum += meters * width / height;
  1479. });
  1480. let x = config.x - sum / 2;
  1481. order.forEach(key => {
  1482. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1483. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1484. let height = image.height;
  1485. let width = image.width;
  1486. if (height == 0) {
  1487. height = 100;
  1488. }
  1489. if (width == 0) {
  1490. width = height;
  1491. }
  1492. x += meters * width / height / 2;
  1493. document.querySelector("#entity-" + key).dataset.x = x;
  1494. document.querySelector("#entity-" + key).dataset.y = config.y;
  1495. x += meters * width / height / 2;
  1496. })
  1497. fitWorld();
  1498. updateSizes();
  1499. }
  1500. function removeAllEntities() {
  1501. Object.keys(entities).forEach(key => {
  1502. removeEntity(document.querySelector("#entity-" + key));
  1503. });
  1504. }
  1505. function clearAttribution() {
  1506. document.querySelector("#attribution-category-header").style.display = "none";
  1507. document.querySelector("#options-attribution").style.display = "none";
  1508. }
  1509. function displayAttribution(file) {
  1510. document.querySelector("#attribution-category-header").style.display = "block";
  1511. document.querySelector("#options-attribution").style.display = "inline";
  1512. const authors = authorsOfFull(file);
  1513. const owners = ownersOfFull(file);
  1514. const citations = citationsOf(file);
  1515. const source = sourceOf(file);
  1516. const authorHolder = document.querySelector("#options-attribution-authors");
  1517. const ownerHolder = document.querySelector("#options-attribution-owners");
  1518. const citationHolder = document.querySelector("#options-attribution-citations");
  1519. const sourceHolder = document.querySelector("#options-attribution-source");
  1520. if (authors === []) {
  1521. const div = document.createElement("div");
  1522. div.innerText = "Unknown";
  1523. authorHolder.innerHTML = "";
  1524. authorHolder.appendChild(div);
  1525. } else if (authors === undefined) {
  1526. const div = document.createElement("div");
  1527. div.innerText = "Not yet entered";
  1528. authorHolder.innerHTML = "";
  1529. authorHolder.appendChild(div);
  1530. } else {
  1531. authorHolder.innerHTML = "";
  1532. const list = document.createElement("ul");
  1533. authorHolder.appendChild(list);
  1534. authors.forEach(author => {
  1535. const authorEntry = document.createElement("li");
  1536. if (author.url) {
  1537. const link = document.createElement("a");
  1538. link.href = author.url;
  1539. link.innerText = author.name;
  1540. link.rel = "noreferrer no opener";
  1541. link.target = "_blank";
  1542. authorEntry.appendChild(link);
  1543. } else {
  1544. const div = document.createElement("div");
  1545. div.innerText = author.name;
  1546. authorEntry.appendChild(div);
  1547. }
  1548. list.appendChild(authorEntry);
  1549. });
  1550. }
  1551. if (owners === []) {
  1552. const div = document.createElement("div");
  1553. div.innerText = "Unknown";
  1554. ownerHolder.innerHTML = "";
  1555. ownerHolder.appendChild(div);
  1556. } else if (owners === undefined) {
  1557. const div = document.createElement("div");
  1558. div.innerText = "Not yet entered";
  1559. ownerHolder.innerHTML = "";
  1560. ownerHolder.appendChild(div);
  1561. } else {
  1562. ownerHolder.innerHTML = "";
  1563. const list = document.createElement("ul");
  1564. ownerHolder.appendChild(list);
  1565. owners.forEach(owner => {
  1566. const ownerEntry = document.createElement("li");
  1567. if (owner.url) {
  1568. const link = document.createElement("a");
  1569. link.href = owner.url;
  1570. link.innerText = owner.name;
  1571. link.rel = "noreferrer no opener";
  1572. link.target = "_blank";
  1573. ownerEntry.appendChild(link);
  1574. } else {
  1575. const div = document.createElement("div");
  1576. div.innerText = owner.name;
  1577. ownerEntry.appendChild(div);
  1578. }
  1579. list.appendChild(ownerEntry);
  1580. });
  1581. }
  1582. if (citations === [] || citations === undefined) {
  1583. } else {
  1584. citationHolder.innerHTML = "";
  1585. const list = document.createElement("ul");
  1586. citationHolder.appendChild(list);
  1587. citations.forEach(citation => {
  1588. const citationEntry = document.createElement("li");
  1589. const link = document.createElement("a");
  1590. link.style.display = "block";
  1591. link.href = citation;
  1592. link.innerText = new URL(citation).host;
  1593. link.rel = "noreferrer no opener";
  1594. link.target = "_blank";
  1595. citationEntry.appendChild(link);
  1596. list.appendChild(citationEntry);
  1597. })
  1598. }
  1599. if (source === null) {
  1600. const div = document.createElement("div");
  1601. div.innerText = "No link";
  1602. sourceHolder.innerHTML = "";
  1603. sourceHolder.appendChild(div);
  1604. } else if (source === undefined) {
  1605. const div = document.createElement("div");
  1606. div.innerText = "Not yet entered";
  1607. sourceHolder.innerHTML = "";
  1608. sourceHolder.appendChild(div);
  1609. } else {
  1610. sourceHolder.innerHTML = "";
  1611. const link = document.createElement("a");
  1612. link.style.display = "block";
  1613. link.href = source;
  1614. link.innerText = new URL(source).host;
  1615. link.rel = "noreferrer no opener";
  1616. link.target = "_blank";
  1617. sourceHolder.appendChild(link);
  1618. }
  1619. }
  1620. function removeEntity(element) {
  1621. if (selected == element) {
  1622. deselect();
  1623. }
  1624. if (clicked == element) {
  1625. clicked = null;
  1626. }
  1627. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  1628. option.parentElement.removeChild(option);
  1629. delete entities[element.dataset.key];
  1630. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  1631. const topName = document.querySelector("#top-name-" + element.dataset.key);
  1632. bottomName.parentElement.removeChild(bottomName);
  1633. topName.parentElement.removeChild(topName);
  1634. element.parentElement.removeChild(element);
  1635. }
  1636. function checkEntity(entity) {
  1637. Object.values(entity.views).forEach(view => {
  1638. if (authorsOf(view.image.source) === undefined) {
  1639. console.warn("No authors: " + view.image.source);
  1640. }
  1641. });
  1642. }
  1643. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  1644. checkEntity(entity);
  1645. // preload all of the entity's views
  1646. Object.values(entity.views).forEach(view => {
  1647. if (!preloaded.has(view.image.source)) {
  1648. let img = new Image();
  1649. img.src = view.image.source;
  1650. preloaded.add(view.image.source);
  1651. }
  1652. });
  1653. const box = document.createElement("div");
  1654. box.classList.add("entity-box");
  1655. const img = document.createElement("img");
  1656. img.classList.add("entity-image");
  1657. img.addEventListener("dragstart", e => {
  1658. e.preventDefault();
  1659. });
  1660. const nameTag = document.createElement("div");
  1661. nameTag.classList.add("entity-name");
  1662. nameTag.innerText = entity.name;
  1663. box.appendChild(img);
  1664. box.appendChild(nameTag);
  1665. const image = entity.views[view].image;
  1666. img.src = image.source;
  1667. if (image.bottom !== undefined) {
  1668. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1669. } else {
  1670. img.style.setProperty("--offset", ((-1) * 100) + "%")
  1671. }
  1672. img.style.setProperty("--rotation", (entity.rotation * 180 / Math.PI) + "deg")
  1673. box.dataset.x = x;
  1674. box.dataset.y = y;
  1675. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  1676. img.addEventListener("touchstart", e => {
  1677. const fakeEvent = {
  1678. target: e.target,
  1679. clientX: e.touches[0].clientX,
  1680. clientY: e.touches[0].clientY,
  1681. which: 1
  1682. };
  1683. testClick(fakeEvent);
  1684. if (clicked) { e.stopPropagation() }
  1685. });
  1686. const heightBar = document.createElement("div");
  1687. heightBar.classList.add("height-bar");
  1688. box.appendChild(heightBar);
  1689. box.id = "entity-" + entityIndex;
  1690. box.dataset.key = entityIndex;
  1691. entity.view = view;
  1692. if (entity.priority === undefined)
  1693. entity.priority = 0;
  1694. if (entity.brightness === undefined)
  1695. entity.brightness = 1;
  1696. entities[entityIndex] = entity;
  1697. entity.index = entityIndex;
  1698. const world = document.querySelector("#entities");
  1699. world.appendChild(box);
  1700. const bottomName = document.createElement("div");
  1701. bottomName.classList.add("bottom-name");
  1702. bottomName.id = "bottom-name-" + entityIndex;
  1703. bottomName.innerText = entity.name;
  1704. bottomName.addEventListener("click", () => select(box));
  1705. world.appendChild(bottomName);
  1706. const topName = document.createElement("div");
  1707. topName.classList.add("top-name");
  1708. topName.id = "top-name-" + entityIndex;
  1709. topName.innerText = entity.name;
  1710. topName.addEventListener("click", () => select(box));
  1711. world.appendChild(topName);
  1712. const entityOption = document.createElement("option");
  1713. entityOption.id = "options-selected-entity-" + entityIndex;
  1714. entityOption.value = entityIndex;
  1715. entityOption.innerText = entity.name;
  1716. document.getElementById("options-selected-entity").appendChild(entityOption);
  1717. entityIndex += 1;
  1718. if (config.autoFit) {
  1719. fitWorld();
  1720. }
  1721. if (selectEntity)
  1722. select(box);
  1723. entity.dirty = true;
  1724. if (refresh && config.autoFitAdd) {
  1725. let targets = {};
  1726. targets[entityIndex - 1] = entity;
  1727. fitEntities(targets);
  1728. }
  1729. if (refresh)
  1730. updateSizes(true);
  1731. }
  1732. window.onblur = function () {
  1733. altHeld = false;
  1734. shiftHeld = false;
  1735. }
  1736. window.onfocus = function () {
  1737. window.dispatchEvent(new Event("keydown"));
  1738. }
  1739. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1740. function toggleFullScreen() {
  1741. var doc = window.document;
  1742. var docEl = doc.documentElement;
  1743. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1744. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1745. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1746. requestFullScreen.call(docEl);
  1747. }
  1748. else {
  1749. cancelFullScreen.call(doc);
  1750. }
  1751. }
  1752. function handleResize() {
  1753. const oldCanvasWidth = canvasWidth;
  1754. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1755. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1756. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1757. const change = oldCanvasWidth / canvasWidth;
  1758. updateSizes();
  1759. }
  1760. function prepareSidebar() {
  1761. const menubar = document.querySelector("#sidebar-menu");
  1762. [
  1763. {
  1764. name: "Show/hide sidebar",
  1765. id: "menu-toggle-sidebar",
  1766. icon: "fas fa-chevron-circle-down",
  1767. rotates: true
  1768. },
  1769. {
  1770. name: "Fullscreen",
  1771. id: "menu-fullscreen",
  1772. icon: "fas fa-compress"
  1773. },
  1774. {
  1775. name: "Clear",
  1776. id: "menu-clear",
  1777. icon: "fas fa-file"
  1778. },
  1779. {
  1780. name: "Sort by height",
  1781. id: "menu-order-height",
  1782. icon: "fas fa-sort-numeric-up"
  1783. },
  1784. {
  1785. name: "Permalink",
  1786. id: "menu-permalink",
  1787. icon: "fas fa-link"
  1788. },
  1789. {
  1790. name: "Export to clipboard",
  1791. id: "menu-export",
  1792. icon: "fas fa-share"
  1793. },
  1794. {
  1795. name: "Import from clipboard",
  1796. id: "menu-import",
  1797. icon: "fas fa-share",
  1798. classes: ["flipped"]
  1799. },
  1800. {
  1801. name: "Save Scene",
  1802. id: "menu-save",
  1803. icon: "fas fa-download",
  1804. input: true
  1805. },
  1806. {
  1807. name: "Load Scene",
  1808. id: "menu-load",
  1809. icon: "fas fa-upload",
  1810. select: true
  1811. },
  1812. {
  1813. name: "Delete Scene",
  1814. id: "menu-delete",
  1815. icon: "fas fa-trash",
  1816. select: true
  1817. },
  1818. {
  1819. name: "Load Autosave",
  1820. id: "menu-load-autosave",
  1821. icon: "fas fa-redo"
  1822. },
  1823. {
  1824. name: "Add Image",
  1825. id: "menu-add-image",
  1826. icon: "fas fa-camera"
  1827. },
  1828. {
  1829. name: "Clear Rulers",
  1830. id: "menu-clear-rulers",
  1831. icon: "fas fa-ruler"
  1832. }
  1833. ].forEach(entry => {
  1834. const buttonHolder = document.createElement("div");
  1835. buttonHolder.classList.add("menu-button-holder");
  1836. const button = document.createElement("button");
  1837. button.id = entry.id;
  1838. button.classList.add("menu-button");
  1839. const icon = document.createElement("i");
  1840. icon.classList.add(...entry.icon.split(" "));
  1841. if (entry.rotates) {
  1842. icon.classList.add("rotate-backward", "transitions");
  1843. }
  1844. if (entry.classes) {
  1845. entry.classes.forEach(cls => icon.classList.add(cls));
  1846. }
  1847. const actionText = document.createElement("span");
  1848. actionText.innerText = entry.name;
  1849. actionText.classList.add("menu-text");
  1850. const srText = document.createElement("span");
  1851. srText.classList.add("sr-only");
  1852. srText.innerText = entry.name;
  1853. button.appendChild(icon);
  1854. button.appendChild(srText);
  1855. buttonHolder.appendChild(button);
  1856. buttonHolder.appendChild(actionText);
  1857. if (entry.input) {
  1858. const input = document.createElement("input");
  1859. buttonHolder.appendChild(input);
  1860. input.placeholder = "default";
  1861. input.addEventListener("keyup", e => {
  1862. if (e.key === "Enter") {
  1863. const name = document.querySelector("#menu-save ~ input").value;
  1864. if (/\S/.test(name)) {
  1865. saveScene(name);
  1866. }
  1867. updateSaveInfo();
  1868. e.preventDefault();
  1869. }
  1870. })
  1871. }
  1872. if (entry.select) {
  1873. const select = document.createElement("select");
  1874. buttonHolder.appendChild(select);
  1875. }
  1876. menubar.appendChild(buttonHolder);
  1877. });
  1878. }
  1879. function checkBodyClass(cls) {
  1880. return document.body.classList.contains(cls);
  1881. }
  1882. function toggleBodyClass(cls, setting) {
  1883. if (setting) {
  1884. document.body.classList.add(cls);
  1885. } else {
  1886. document.body.classList.remove(cls);
  1887. }
  1888. }
  1889. const settingsData = {
  1890. "show-vertical-scale": {
  1891. name: "Vertical Scale",
  1892. desc: "Draw vertical scale marks",
  1893. type: "toggle",
  1894. default: true,
  1895. get value() {
  1896. return config.drawYAxis;
  1897. },
  1898. set value(param) {
  1899. config.drawYAxis = param;
  1900. drawScales(false);
  1901. }
  1902. },
  1903. "show-horizontal-scale": {
  1904. name: "Horiziontal Scale",
  1905. desc: "Draw horizontal scale marks",
  1906. type: "toggle",
  1907. default: false,
  1908. get value() {
  1909. return config.drawXAxis;
  1910. },
  1911. set value(param) {
  1912. config.drawXAxis = param;
  1913. drawScales(false);
  1914. }
  1915. },
  1916. "show-altitudes": {
  1917. name: "Altitudes",
  1918. desc: "Draw interesting altitudes",
  1919. type: "select",
  1920. default: "none",
  1921. options: [
  1922. "none",
  1923. "all",
  1924. "atmosphere",
  1925. "orbits",
  1926. "weather",
  1927. "water",
  1928. "geology",
  1929. "thicknesses"
  1930. ],
  1931. get value() {
  1932. return config.drawAltitudes;
  1933. },
  1934. set value(param) {
  1935. config.drawAltitudes = param;
  1936. drawScales(false);
  1937. }
  1938. },
  1939. "lock-y-axis": {
  1940. name: "Lock Y-Axis",
  1941. desc: "Keep the camera at ground-level",
  1942. type: "toggle",
  1943. default: true,
  1944. get value() {
  1945. return config.lockYAxis;
  1946. },
  1947. set value(param) {
  1948. config.lockYAxis = param;
  1949. if (param) {
  1950. config.y = 0;
  1951. updateSizes();
  1952. document.querySelector("#scroll-up").disabled = true;
  1953. document.querySelector("#scroll-down").disabled = true;
  1954. } else {
  1955. document.querySelector("#scroll-up").disabled = false;
  1956. document.querySelector("#scroll-down").disabled = false;
  1957. }
  1958. }
  1959. },
  1960. "axis-spacing": {
  1961. name: "Axis Spacing",
  1962. desc: "How frequent the axis lines are",
  1963. type: "select",
  1964. default: "standard",
  1965. options: [
  1966. "dense",
  1967. "standard",
  1968. "sparse"
  1969. ],
  1970. get value() {
  1971. return config.axisSpacing;
  1972. },
  1973. set value(param) {
  1974. config.axisSpacing = param;
  1975. const factor = {
  1976. "dense": 0.5,
  1977. "standard": 1,
  1978. "sparse": 2
  1979. }[param];
  1980. config.minLineSize = factor * 100;
  1981. config.maxLineSize = factor * 150;
  1982. updateSizes();
  1983. }
  1984. },
  1985. "solid-ground": {
  1986. name: "Ground",
  1987. desc: "Draw solid ground at the y=0 line",
  1988. type: "toggle",
  1989. default: true,
  1990. get value() {
  1991. return checkBodyClass("toggle-bottom-cover");
  1992. },
  1993. set value(param) {
  1994. toggleBodyClass("toggle-bottom-cover", param);
  1995. }
  1996. },
  1997. "ground-pos": {
  1998. name: "Ground Position",
  1999. desc: "How high the ground is if the y-axis is locked",
  2000. type: "select",
  2001. default: "bottom",
  2002. options: [
  2003. "high",
  2004. "medium",
  2005. "low",
  2006. "bottom",
  2007. ],
  2008. get value() {
  2009. return config.groundPos;
  2010. },
  2011. set value(param) {
  2012. config.groundPos = param;
  2013. updateSizes();
  2014. }
  2015. },
  2016. "auto-scale": {
  2017. name: "Auto-Size World",
  2018. desc: "Constantly zoom to fit the largest entity",
  2019. type: "toggle",
  2020. default: false,
  2021. get value() {
  2022. return config.autoFit;
  2023. },
  2024. set value(param) {
  2025. config.autoFit = param;
  2026. checkFitWorld();
  2027. }
  2028. },
  2029. "auto-units": {
  2030. name: "Auto-Select Units",
  2031. desc: "Automatically switch units when zooming in and out",
  2032. type: "toggle",
  2033. default: false,
  2034. get value() {
  2035. return config.autoUnits;
  2036. },
  2037. set value(param) {
  2038. config.autoUnits = param;
  2039. }
  2040. },
  2041. "zoom-when-adding": {
  2042. name: "Zoom On Add",
  2043. desc: "Zoom to fit when you add a new entity",
  2044. type: "toggle",
  2045. default: true,
  2046. get value() {
  2047. return config.autoFitAdd;
  2048. },
  2049. set value(param) {
  2050. config.autoFitAdd = param;
  2051. }
  2052. },
  2053. "zoom-when-sizing": {
  2054. name: "Zoom On Size",
  2055. desc: "Zoom to fit when you select an entity's size",
  2056. type: "toggle",
  2057. default: true,
  2058. get value() {
  2059. return config.autoFitSize;
  2060. },
  2061. set value(param) {
  2062. config.autoFitSize = param;
  2063. }
  2064. },
  2065. "show-ratios": {
  2066. name: "Show Ratios",
  2067. desc: "Show the proportions between the current selection and the most recent selection.",
  2068. type: "toggle",
  2069. default: true,
  2070. get value() {
  2071. return config.showRatios;
  2072. },
  2073. set value(param) {
  2074. config.showRatios = param;
  2075. if (param) {
  2076. document.body.querySelector(".ratio-info").style.display = "block";
  2077. } else {
  2078. document.body.querySelector(".ratio-info").style.display = "none";
  2079. }
  2080. }
  2081. },
  2082. "units": {
  2083. name: "Default Units",
  2084. desc: "Which kind of unit to use by default",
  2085. type: "select",
  2086. default: "metric",
  2087. options: [
  2088. "metric",
  2089. "customary",
  2090. "relative",
  2091. "quirky"
  2092. ],
  2093. get value() {
  2094. return config.units;
  2095. },
  2096. set value(param) {
  2097. config.units = param;
  2098. updateSizes();
  2099. }
  2100. },
  2101. "names": {
  2102. name: "Show Names",
  2103. desc: "Display names over entities",
  2104. type: "toggle",
  2105. default: true,
  2106. get value() {
  2107. return checkBodyClass("toggle-entity-name");
  2108. },
  2109. set value(param) {
  2110. toggleBodyClass("toggle-entity-name", param);
  2111. }
  2112. },
  2113. "bottom-names": {
  2114. name: "Bottom Names",
  2115. desc: "Display names at the bottom",
  2116. type: "toggle",
  2117. default: false,
  2118. get value() {
  2119. return checkBodyClass("toggle-bottom-name");
  2120. },
  2121. set value(param) {
  2122. toggleBodyClass("toggle-bottom-name", param);
  2123. }
  2124. },
  2125. "top-names": {
  2126. name: "Show Arrows",
  2127. desc: "Point to entities that are much larger than the current view",
  2128. type: "toggle",
  2129. default: false,
  2130. get value() {
  2131. return checkBodyClass("toggle-top-name");
  2132. },
  2133. set value(param) {
  2134. toggleBodyClass("toggle-top-name", param);
  2135. }
  2136. },
  2137. "height-bars": {
  2138. name: "Height Bars",
  2139. desc: "Draw dashed lines to the top of each entity",
  2140. type: "toggle",
  2141. default: false,
  2142. get value() {
  2143. return checkBodyClass("toggle-height-bars");
  2144. },
  2145. set value(param) {
  2146. toggleBodyClass("toggle-height-bars", param);
  2147. }
  2148. },
  2149. "glowing-entities": {
  2150. name: "Glowing Edges",
  2151. desc: "Makes all entities glow",
  2152. type: "toggle",
  2153. default: false,
  2154. get value() {
  2155. return checkBodyClass("toggle-entity-glow");
  2156. },
  2157. set value(param) {
  2158. toggleBodyClass("toggle-entity-glow", param);
  2159. }
  2160. },
  2161. "background-brightness": {
  2162. name: "Background Brightness",
  2163. desc: "How bright the background is",
  2164. type: "select",
  2165. default: "medium",
  2166. options: [
  2167. "black",
  2168. "dark",
  2169. "medium",
  2170. "light",
  2171. ],
  2172. get value() {
  2173. return config.background;
  2174. },
  2175. set value(param) {
  2176. config.background = param;
  2177. drawScales();
  2178. }
  2179. },
  2180. "smoothing": {
  2181. name: "Smoothing",
  2182. desc: "Smooth out movements and size changes. Disable for better performance.",
  2183. type: "toggle",
  2184. default: true,
  2185. get value() {
  2186. return checkBodyClass("smoothing");
  2187. },
  2188. set value(param) {
  2189. toggleBodyClass("smoothing", param);
  2190. }
  2191. },
  2192. "auto-food-intake": {
  2193. name: "Estimate Food Intake",
  2194. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  2195. type: "toggle",
  2196. default: false,
  2197. get value() {
  2198. return config.autoFoodIntake
  2199. },
  2200. set value(param) {
  2201. config.autoFoodIntake = param
  2202. }
  2203. },
  2204. "auto-prey-capacity": {
  2205. name: "Estimate Prey Capacity",
  2206. desc: "Guess how much prey creatures can hold, based on their mass",
  2207. type: "select",
  2208. default: "none",
  2209. options: [
  2210. "none",
  2211. "realistic",
  2212. "same-size"
  2213. ],
  2214. get value() {
  2215. return config.autoPreyCapacity;
  2216. },
  2217. set value(param) {
  2218. config.autoPreyCapacity = param;
  2219. }
  2220. },
  2221. }
  2222. function getBoundingBox(entities, margin = 0.05) {
  2223. }
  2224. function prepareSettings(userSettings) {
  2225. const menubar = document.querySelector("#settings-menu");
  2226. Object.entries(settingsData).forEach(([id, entry]) => {
  2227. const holder = document.createElement("label");
  2228. holder.classList.add("settings-holder");
  2229. const input = document.createElement("input");
  2230. input.id = "setting-" + id;
  2231. const vertical = document.createElement("div");
  2232. vertical.classList.add("settings-vertical");
  2233. const name = document.createElement("label");
  2234. name.innerText = entry.name;
  2235. name.classList.add("settings-name");
  2236. name.setAttribute("for", input.id);
  2237. const desc = document.createElement("label");
  2238. desc.innerText = entry.desc;
  2239. desc.classList.add("settings-desc");
  2240. desc.setAttribute("for", input.id);
  2241. if (entry.type == "toggle") {
  2242. input.type = "checkbox";
  2243. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  2244. holder.setAttribute("for", input.id);
  2245. vertical.appendChild(name);
  2246. vertical.appendChild(desc);
  2247. holder.appendChild(vertical);
  2248. holder.appendChild(input);
  2249. menubar.appendChild(holder);
  2250. const update = () => {
  2251. if (input.checked) {
  2252. holder.classList.add("enabled");
  2253. holder.classList.remove("disabled");
  2254. } else {
  2255. holder.classList.remove("enabled");
  2256. holder.classList.add("disabled");
  2257. }
  2258. entry.value = input.checked;
  2259. }
  2260. update();
  2261. input.addEventListener("change", update);
  2262. } else if (entry.type == "select") {
  2263. // we don't use the input element we made!
  2264. const select = document.createElement("select");
  2265. select.id = "setting-" + id;
  2266. entry.options.forEach(choice => {
  2267. const option = document.createElement("option");
  2268. option.innerText = choice;
  2269. select.appendChild(option);
  2270. })
  2271. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  2272. vertical.appendChild(name);
  2273. vertical.appendChild(desc);
  2274. holder.appendChild(vertical);
  2275. holder.appendChild(select);
  2276. menubar.appendChild(holder);
  2277. holder.classList.add("enabled");
  2278. const update = () => {
  2279. entry.value = select.value;
  2280. }
  2281. update();
  2282. select.addEventListener("change", update);
  2283. }
  2284. })
  2285. }
  2286. function prepareMenu() {
  2287. prepareSidebar();
  2288. updateSaveInfo();
  2289. if (checkHelpDate()) {
  2290. document.querySelector("#open-help").classList.add("highlighted");
  2291. }
  2292. }
  2293. function updateSaveInfo() {
  2294. const saves = getSaves();
  2295. const load = document.querySelector("#menu-load ~ select");
  2296. load.innerHTML = "";
  2297. saves.forEach(save => {
  2298. const option = document.createElement("option");
  2299. option.innerText = save;
  2300. option.value = save;
  2301. load.appendChild(option);
  2302. });
  2303. const del = document.querySelector("#menu-delete ~ select");
  2304. del.innerHTML = "";
  2305. saves.forEach(save => {
  2306. const option = document.createElement("option");
  2307. option.innerText = save;
  2308. option.value = save;
  2309. del.appendChild(option);
  2310. });
  2311. }
  2312. function getSaves() {
  2313. try {
  2314. const results = [];
  2315. Object.keys(localStorage).forEach(key => {
  2316. if (key.startsWith("macrovision-save-")) {
  2317. results.push(key.replace("macrovision-save-", ""));
  2318. }
  2319. })
  2320. return results;
  2321. } catch (err) {
  2322. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2323. console.error(err);
  2324. return false;
  2325. }
  2326. }
  2327. function getUserSettings() {
  2328. try {
  2329. const settings = JSON.parse(localStorage.getItem("settings"));
  2330. return settings === null ? {} : settings;
  2331. } catch {
  2332. return {};
  2333. }
  2334. }
  2335. function exportUserSettings() {
  2336. const settings = {};
  2337. Object.entries(settingsData).forEach(([id, entry]) => {
  2338. settings[id] = entry.value;
  2339. });
  2340. return settings;
  2341. }
  2342. function setUserSettings(settings) {
  2343. try {
  2344. localStorage.setItem("settings", JSON.stringify(settings));
  2345. } catch {
  2346. // :(
  2347. }
  2348. }
  2349. const lastHelpChange = 1601955834693;
  2350. function checkHelpDate() {
  2351. // disabling this for now
  2352. return false;
  2353. try {
  2354. const old = localStorage.getItem("help-viewed");
  2355. if (old === null || old < lastHelpChange) {
  2356. return true;
  2357. }
  2358. return false;
  2359. } catch {
  2360. console.warn("Could not set the help-viewed date");
  2361. return false;
  2362. }
  2363. }
  2364. function setHelpDate() {
  2365. try {
  2366. localStorage.setItem("help-viewed", Date.now());
  2367. } catch {
  2368. console.warn("Could not set the help-viewed date");
  2369. }
  2370. }
  2371. function doYScroll() {
  2372. const worldHeight = config.height.toNumber("meters");
  2373. config.y += scrollDirection * worldHeight / 180;
  2374. updateSizes();
  2375. scrollDirection *= 1.05;
  2376. }
  2377. function doXScroll() {
  2378. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2379. config.x += scrollDirection * worldWidth / 180 ;
  2380. updateSizes();
  2381. scrollDirection *= 1.05;
  2382. }
  2383. function doZoom() {
  2384. const oldHeight = config.height;
  2385. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  2386. zoomDirection *= 1.05;
  2387. }
  2388. function doSize() {
  2389. if (selected) {
  2390. const entity = entities[selected.dataset.key];
  2391. const oldHeight = entity.views[entity.view].height;
  2392. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  2393. entity.dirty = true;
  2394. updateEntityOptions(entity, entity.view);
  2395. updateViewOptions(entity, entity.view);
  2396. updateSizes(true);
  2397. sizeDirection *= 1.01;
  2398. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  2399. let extra = entity.views[entity.view].image.extra;
  2400. extra = extra === undefined ? 1 : extra;
  2401. const worldHeight = config.height.toNumber("meters");
  2402. if (ownHeight * extra > worldHeight) {
  2403. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra));
  2404. } else if (ownHeight * extra * 10 < worldHeight) {
  2405. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra * 10));
  2406. }
  2407. }
  2408. }
  2409. function selectNewUnit() {
  2410. const unitSelector = document.querySelector("#options-height-unit");
  2411. checkFitWorld();
  2412. const scaleInput = document.querySelector("#options-height-value");
  2413. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(unitSelector.value);
  2414. setNumericInput(scaleInput, newVal);
  2415. updateWorldHeight();
  2416. unitSelector.dataset.oldUnit = unitSelector.value;
  2417. }
  2418. document.addEventListener("DOMContentLoaded", () => {
  2419. prepareMenu();
  2420. prepareEntities();
  2421. document.querySelector("#open-help").addEventListener("click", e => {
  2422. setHelpDate();
  2423. document.querySelector("#open-help").classList.remove("highlighted");
  2424. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  2425. });
  2426. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  2427. copyScreenshot();
  2428. toast("Copied to clipboard!");
  2429. });
  2430. document.querySelector("#save-screenshot").addEventListener("click", e => {
  2431. saveScreenshot();
  2432. });
  2433. document.querySelector("#open-screenshot").addEventListener("click", e => {
  2434. openScreenshot();
  2435. });
  2436. document.querySelector("#toggle-menu").addEventListener("click", e => {
  2437. const popoutMenu = document.querySelector("#sidebar-menu");
  2438. if (popoutMenu.classList.contains("visible")) {
  2439. popoutMenu.classList.remove("visible");
  2440. } else {
  2441. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2442. const rect = e.target.getBoundingClientRect();
  2443. popoutMenu.classList.add("visible");
  2444. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2445. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2446. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2447. let screenWidth = window.innerWidth;
  2448. if (menuWidth * 1.5 > screenWidth) {
  2449. popoutMenu.style.left = 25 + "px";
  2450. }
  2451. }
  2452. e.stopPropagation();
  2453. });
  2454. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  2455. e.stopPropagation();
  2456. });
  2457. document.addEventListener("click", e => {
  2458. document.querySelector("#sidebar-menu").classList.remove("visible");
  2459. });
  2460. document.querySelector("#toggle-settings").addEventListener("click", e => {
  2461. const popoutMenu = document.querySelector("#settings-menu");
  2462. if (popoutMenu.classList.contains("visible")) {
  2463. popoutMenu.classList.remove("visible");
  2464. } else {
  2465. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2466. const rect = e.target.getBoundingClientRect();
  2467. popoutMenu.classList.add("visible");
  2468. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2469. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2470. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2471. let screenWidth = window.innerWidth;
  2472. if (menuWidth * 1.5 > screenWidth) {
  2473. popoutMenu.style.left = 25 + "px";
  2474. }
  2475. }
  2476. e.stopPropagation();
  2477. });
  2478. document.querySelector("#settings-menu").addEventListener("click", e => {
  2479. e.stopPropagation();
  2480. });
  2481. document.addEventListener("click", e => {
  2482. document.querySelector("#settings-menu").classList.remove("visible");
  2483. });
  2484. window.addEventListener("unload", () => {
  2485. saveScene("autosave");
  2486. setUserSettings(exportUserSettings());
  2487. });
  2488. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  2489. if (e.target.value == "None") {
  2490. deselect()
  2491. } else {
  2492. select(document.querySelector("#entity-" + e.target.value));
  2493. }
  2494. });
  2495. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  2496. const sidebar = document.querySelector("#options");
  2497. if (sidebar.classList.contains("hidden")) {
  2498. sidebar.classList.remove("hidden");
  2499. e.target.classList.remove("rotate-forward");
  2500. e.target.classList.add("rotate-backward");
  2501. } else {
  2502. sidebar.classList.add("hidden");
  2503. e.target.classList.add("rotate-forward");
  2504. e.target.classList.remove("rotate-backward");
  2505. }
  2506. handleResize();
  2507. });
  2508. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2509. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2510. if (selected) {
  2511. entities[selected.dataset.key].priority += 1;
  2512. }
  2513. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2514. updateSizes();
  2515. });
  2516. document.querySelector("#options-order-back").addEventListener("click", e => {
  2517. if (selected) {
  2518. entities[selected.dataset.key].priority -= 1;
  2519. }
  2520. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2521. updateSizes();
  2522. });
  2523. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  2524. if (selected) {
  2525. entities[selected.dataset.key].brightness += 1;
  2526. }
  2527. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2528. updateSizes();
  2529. });
  2530. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  2531. if (selected) {
  2532. entities[selected.dataset.key].brightness -= 1;
  2533. }
  2534. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2535. updateSizes();
  2536. });
  2537. document.querySelector("#options-rotate-left").addEventListener("click", e => {
  2538. if (selected) {
  2539. entities[selected.dataset.key].rotation -= Math.PI/4;
  2540. }
  2541. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2542. updateSizes();
  2543. });
  2544. document.querySelector("#options-rotate-right").addEventListener("click", e => {
  2545. if (selected) {
  2546. entities[selected.dataset.key].rotation += Math.PI/4;
  2547. }
  2548. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2549. updateSizes();
  2550. });
  2551. document.querySelector("#options-flip").addEventListener("click", e => {
  2552. if (selected) {
  2553. selected.querySelector(".entity-image").classList.toggle("flipped");
  2554. }
  2555. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2556. updateSizes();
  2557. });
  2558. const sceneChoices = document.querySelector("#scene-choices");
  2559. Object.entries(scenes).forEach(([id, scene]) => {
  2560. const option = document.createElement("option");
  2561. option.innerText = id;
  2562. option.value = id;
  2563. sceneChoices.appendChild(option);
  2564. });
  2565. document.querySelector("#load-scene").addEventListener("click", e => {
  2566. const chosen = sceneChoices.value;
  2567. removeAllEntities();
  2568. scenes[chosen]();
  2569. });
  2570. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2571. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2572. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2573. document.querySelector("#options-height-value").addEventListener("change", e => {
  2574. updateWorldHeight();
  2575. })
  2576. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  2577. e.stopPropagation();
  2578. })
  2579. const unitSelector = document.querySelector("#options-height-unit");
  2580. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  2581. const optGroup = document.createElement("optgroup");
  2582. optGroup.label = group;
  2583. unitSelector.appendChild(optGroup);
  2584. entries.forEach(entry => {
  2585. const option = document.createElement("option");
  2586. option.innerText = entry;
  2587. // we haven't loaded user settings yet, so we can't choose the unit just yet
  2588. unitSelector.appendChild(option);
  2589. })
  2590. });
  2591. unitSelector.addEventListener("input", selectNewUnit);
  2592. param = window.location.hash;
  2593. // we now use the fragment for links, but we should still support old stuff:
  2594. if (param.length > 0) {
  2595. param = param.substring(1);
  2596. } else {
  2597. param = new URL(window.location.href).searchParams.get("scene");
  2598. }
  2599. document.querySelector("#world").addEventListener("mousedown", e => {
  2600. // only middle mouse clicks
  2601. if (e.which == 2) {
  2602. panning = true;
  2603. panOffsetX = e.clientX;
  2604. panOffsetY = e.clientY;
  2605. Object.keys(entities).forEach(key => {
  2606. document.querySelector("#entity-" + key).classList.add("no-transition");
  2607. });
  2608. }
  2609. });
  2610. document.addEventListener("mouseup", e => {
  2611. if (e.which == 2) {
  2612. panning = false;
  2613. Object.keys(entities).forEach(key => {
  2614. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2615. });
  2616. }
  2617. });
  2618. document.querySelector("#world").addEventListener("touchstart", e => {
  2619. if (!rulerMode) {
  2620. panning = true;
  2621. panOffsetX = e.touches[0].clientX;
  2622. panOffsetY = e.touches[0].clientY;
  2623. e.preventDefault();
  2624. Object.keys(entities).forEach(key => {
  2625. document.querySelector("#entity-" + key).classList.add("no-transition");
  2626. });
  2627. }
  2628. });
  2629. document.querySelector("#world").addEventListener("touchend", e => {
  2630. panning = false;
  2631. Object.keys(entities).forEach(key => {
  2632. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2633. });
  2634. });
  2635. document.querySelector("#world").addEventListener("mousedown", e => {
  2636. // only left mouse clicks
  2637. if (e.which == 1 && rulerMode) {
  2638. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2639. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2640. const pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  2641. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y };
  2642. }
  2643. });
  2644. document.querySelector("#world").addEventListener("mouseup", e => {
  2645. // only left mouse clicks
  2646. if (e.which == 1 && currentRuler) {
  2647. rulers.push(currentRuler);
  2648. currentRuler = null;
  2649. rulerMode = false;
  2650. }
  2651. });
  2652. document.querySelector("#world").addEventListener("touchstart", e => {
  2653. if (rulerMode) {
  2654. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2655. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2656. const pos = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  2657. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y };
  2658. }
  2659. });
  2660. document.querySelector("#world").addEventListener("touchend", e => {
  2661. if (currentRuler) {
  2662. rulers.push(currentRuler);
  2663. currentRuler = null;
  2664. rulerMode = false;
  2665. }
  2666. });
  2667. document.querySelector("body").appendChild(testCtx.canvas);
  2668. world.addEventListener("mousedown", e => deselect(e));
  2669. world.addEventListener("touchstart", e => deselect({
  2670. which: 1,
  2671. }));
  2672. document.querySelector("#entities").addEventListener("mousedown", deselect);
  2673. document.querySelector("#display").addEventListener("mousedown", deselect);
  2674. document.addEventListener("mouseup", e => clickUp(e));
  2675. document.addEventListener("touchend", e => {
  2676. const fakeEvent = {
  2677. target: e.target,
  2678. clientX: e.changedTouches[0].clientX,
  2679. clientY: e.changedTouches[0].clientY,
  2680. which: 1
  2681. };
  2682. clickUp(fakeEvent);
  2683. });
  2684. const viewList = document.querySelector("#entity-view");
  2685. document.querySelector("#entity-view").addEventListener("input", e => {
  2686. const entity = entities[selected.dataset.key];
  2687. entity.view = e.target.value;
  2688. const image = entities[selected.dataset.key].views[e.target.value].image;
  2689. selected.querySelector(".entity-image").src = image.source;
  2690. configViewOptions(entity, entity.view);
  2691. displayAttribution(image.source);
  2692. if (image.bottom !== undefined) {
  2693. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  2694. } else {
  2695. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  2696. }
  2697. updateSizes();
  2698. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  2699. updateViewOptions(entities[selected.dataset.key], e.target.value);
  2700. });
  2701. document.querySelector("#entity-view").addEventListener("input", e => {
  2702. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  2703. viewList.classList.add("nsfw");
  2704. } else {
  2705. viewList.classList.remove("nsfw");
  2706. }
  2707. })
  2708. clearViewList();
  2709. document.querySelector("#menu-clear").addEventListener("click", e => {
  2710. removeAllEntities();
  2711. });
  2712. document.querySelector("#delete-entity").disabled = true;
  2713. document.querySelector("#delete-entity").addEventListener("click", e => {
  2714. if (selected) {
  2715. removeEntity(selected);
  2716. selected = null;
  2717. }
  2718. });
  2719. document.querySelector("#menu-order-height").addEventListener("click", e => {
  2720. const order = Object.keys(entities).sort((a, b) => {
  2721. const entA = entities[a];
  2722. const entB = entities[b];
  2723. const viewA = entA.view;
  2724. const viewB = entB.view;
  2725. const heightA = entA.views[viewA].height.to("meter").value;
  2726. const heightB = entB.views[viewB].height.to("meter").value;
  2727. return heightA - heightB;
  2728. });
  2729. arrangeEntities(order);
  2730. });
  2731. // TODO: write some generic logic for this lol
  2732. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  2733. scrollDirection = -1;
  2734. clearInterval(scrollHandle);
  2735. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2736. e.stopPropagation();
  2737. });
  2738. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  2739. scrollDirection = 1;
  2740. clearInterval(scrollHandle);
  2741. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2742. e.stopPropagation();
  2743. });
  2744. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  2745. scrollDirection = -1;
  2746. clearInterval(scrollHandle);
  2747. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2748. e.stopPropagation();
  2749. });
  2750. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  2751. scrollDirection = 1;
  2752. clearInterval(scrollHandle);
  2753. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2754. e.stopPropagation();
  2755. });
  2756. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  2757. scrollDirection = 1;
  2758. clearInterval(scrollHandle);
  2759. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2760. e.stopPropagation();
  2761. });
  2762. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  2763. scrollDirection = -1;
  2764. clearInterval(scrollHandle);
  2765. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2766. e.stopPropagation();
  2767. });
  2768. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  2769. scrollDirection = 1;
  2770. clearInterval(scrollHandle);
  2771. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2772. e.stopPropagation();
  2773. });
  2774. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  2775. scrollDirection = -1;
  2776. clearInterval(scrollHandle);
  2777. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2778. e.stopPropagation();
  2779. });
  2780. document.addEventListener("mouseup", e => {
  2781. clearInterval(scrollHandle);
  2782. scrollHandle = null;
  2783. });
  2784. document.addEventListener("touchend", e => {
  2785. clearInterval(scrollHandle);
  2786. scrollHandle = null;
  2787. });
  2788. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  2789. zoomDirection = -1;
  2790. clearInterval(zoomHandle);
  2791. zoomHandle = setInterval(doZoom, 1000 / 20);
  2792. e.stopPropagation();
  2793. });
  2794. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  2795. zoomDirection = 1;
  2796. clearInterval(zoomHandle);
  2797. zoomHandle = setInterval(doZoom, 1000 / 20);
  2798. e.stopPropagation();
  2799. });
  2800. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  2801. zoomDirection = -1;
  2802. clearInterval(zoomHandle);
  2803. zoomHandle = setInterval(doZoom, 1000 / 20);
  2804. e.stopPropagation();
  2805. });
  2806. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  2807. zoomDirection = 1;
  2808. clearInterval(zoomHandle);
  2809. zoomHandle = setInterval(doZoom, 1000 / 20);
  2810. e.stopPropagation();
  2811. });
  2812. document.addEventListener("mouseup", e => {
  2813. clearInterval(zoomHandle);
  2814. zoomHandle = null;
  2815. });
  2816. document.addEventListener("touchend", e => {
  2817. clearInterval(zoomHandle);
  2818. zoomHandle = null;
  2819. });
  2820. document.querySelector("#shrink").addEventListener("mousedown", e => {
  2821. sizeDirection = -1;
  2822. clearInterval(sizeHandle);
  2823. sizeHandle = setInterval(doSize, 1000 / 20);
  2824. e.stopPropagation();
  2825. });
  2826. document.querySelector("#grow").addEventListener("mousedown", e => {
  2827. sizeDirection = 1;
  2828. clearInterval(sizeHandle);
  2829. sizeHandle = setInterval(doSize, 1000 / 20);
  2830. e.stopPropagation();
  2831. });
  2832. document.querySelector("#shrink").addEventListener("touchstart", e => {
  2833. sizeDirection = -1;
  2834. clearInterval(sizeHandle);
  2835. sizeHandle = setInterval(doSize, 1000 / 20);
  2836. e.stopPropagation();
  2837. });
  2838. document.querySelector("#grow").addEventListener("touchstart", e => {
  2839. sizeDirection = 1;
  2840. clearInterval(sizeHandle);
  2841. sizeHandle = setInterval(doSize, 1000 / 20);
  2842. e.stopPropagation();
  2843. });
  2844. document.addEventListener("mouseup", e => {
  2845. clearInterval(sizeHandle);
  2846. sizeHandle = null;
  2847. });
  2848. document.addEventListener("touchend", e => {
  2849. clearInterval(sizeHandle);
  2850. sizeHandle = null;
  2851. });
  2852. document.querySelector("#ruler").addEventListener("click", e => {
  2853. rulerMode = !rulerMode;
  2854. if (rulerMode) {
  2855. toast("Ready to draw a ruler mark");
  2856. } else {
  2857. toast("Cancelled ruler mode");
  2858. }
  2859. });
  2860. document.querySelector("#ruler").addEventListener("mousedown", e => {
  2861. e.stopPropagation();
  2862. });
  2863. document.querySelector("#ruler").addEventListener("touchstart", e => {
  2864. e.stopPropagation();
  2865. });
  2866. document.querySelector("#fit").addEventListener("click", e => {
  2867. if (selected) {
  2868. let targets = {};
  2869. targets[selected.dataset.key] = entities[selected.dataset.key];
  2870. fitEntities(targets);
  2871. }
  2872. });
  2873. document.querySelector("#fit").addEventListener("mousedown", e => {
  2874. e.stopPropagation();
  2875. });
  2876. document.querySelector("#fit").addEventListener("touchstart", e => {
  2877. e.stopPropagation();
  2878. });
  2879. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  2880. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  2881. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  2882. document.addEventListener("keydown", e => {
  2883. if (e.key == "Delete") {
  2884. if (selected) {
  2885. removeEntity(selected);
  2886. selected = null;
  2887. }
  2888. }
  2889. })
  2890. document.addEventListener("keydown", e => {
  2891. if (e.key == "Shift") {
  2892. shiftHeld = true;
  2893. e.preventDefault();
  2894. } else if (e.key == "Alt") {
  2895. altHeld = true;
  2896. movingInBounds = false; // don't snap the object back in bounds when we let go
  2897. e.preventDefault();
  2898. }
  2899. });
  2900. document.addEventListener("keyup", e => {
  2901. if (e.key == "Shift") {
  2902. shiftHeld = false;
  2903. e.preventDefault();
  2904. } else if (e.key == "Alt") {
  2905. altHeld = false;
  2906. e.preventDefault();
  2907. }
  2908. });
  2909. window.addEventListener("resize", handleResize);
  2910. // TODO: further investigate why the tool initially starts out with wrong
  2911. // values under certain circumstances (seems to be narrow aspect ratios -
  2912. // maybe the menu bar is animating when it shouldn't)
  2913. setTimeout(handleResize, 250);
  2914. setTimeout(handleResize, 500);
  2915. setTimeout(handleResize, 750);
  2916. setTimeout(handleResize, 1000);
  2917. document.querySelector("#menu-permalink").addEventListener("click", e => {
  2918. linkScene();
  2919. });
  2920. document.querySelector("#menu-export").addEventListener("click", e => {
  2921. copyScene();
  2922. });
  2923. document.querySelector("#menu-import").addEventListener("click", e => {
  2924. pasteScene();
  2925. });
  2926. document.querySelector("#menu-save").addEventListener("click", e => {
  2927. const name = document.querySelector("#menu-save ~ input").value;
  2928. if (/\S/.test(name)) {
  2929. saveScene(name);
  2930. }
  2931. updateSaveInfo();
  2932. });
  2933. document.querySelector("#menu-load").addEventListener("click", e => {
  2934. const name = document.querySelector("#menu-load ~ select").value;
  2935. if (/\S/.test(name)) {
  2936. loadScene(name);
  2937. }
  2938. });
  2939. document.querySelector("#menu-delete").addEventListener("click", e => {
  2940. const name = document.querySelector("#menu-delete ~ select").value;
  2941. if (/\S/.test(name)) {
  2942. deleteScene(name);
  2943. }
  2944. });
  2945. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  2946. loadScene("autosave");
  2947. });
  2948. document.querySelector("#menu-add-image").addEventListener("click", e => {
  2949. document.querySelector("#file-upload-picker").click();
  2950. });
  2951. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  2952. if (e.target.files.length > 0) {
  2953. for (let i=0; i<e.target.files.length; i++) {
  2954. customEntityFromFile(e.target.files[i]);
  2955. }
  2956. }
  2957. })
  2958. document.querySelector("#menu-clear-rulers").addEventListener("click", e => {
  2959. rulers = [];
  2960. drawRulers();
  2961. });
  2962. document.addEventListener("paste", e => {
  2963. let index = 0;
  2964. let item = null;
  2965. let found = false;
  2966. for (; index < e.clipboardData.items.length; index++) {
  2967. item = e.clipboardData.items[index];
  2968. if (item.type == "image/png") {
  2969. found = true;
  2970. break;
  2971. }
  2972. }
  2973. if (!found) {
  2974. return;
  2975. }
  2976. let url = null;
  2977. const file = item.getAsFile();
  2978. customEntityFromFile(file);
  2979. });
  2980. document.querySelector("#world").addEventListener("dragover", e => {
  2981. e.preventDefault();
  2982. })
  2983. document.querySelector("#world").addEventListener("drop", e => {
  2984. e.preventDefault();
  2985. if (e.dataTransfer.files.length > 0) {
  2986. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2987. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2988. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  2989. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  2990. }
  2991. })
  2992. clearEntityOptions();
  2993. clearViewOptions();
  2994. clearAttribution();
  2995. // we do this last because configuring settings can cause things
  2996. // to happen (e.g. auto-fit)
  2997. prepareSettings(getUserSettings());
  2998. // now that we have this loaded, we can set it
  2999. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  3000. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3001. // ...and then update the world height by setting off an input event
  3002. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  3003. }));
  3004. if (param === null) {
  3005. scenes["Empty"]();
  3006. }
  3007. else {
  3008. try {
  3009. const data = JSON.parse(b64DecodeUnicode(param));
  3010. if (data.entities === undefined) {
  3011. return;
  3012. }
  3013. if (data.world === undefined) {
  3014. return;
  3015. }
  3016. importScene(data);
  3017. } catch (err) {
  3018. console.error(err);
  3019. scenes["Empty"]();
  3020. // probably wasn't valid data
  3021. }
  3022. }
  3023. document.querySelector("#world").addEventListener("wheel", e => {
  3024. if (shiftHeld) {
  3025. if (selected) {
  3026. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  3027. const entity = entities[selected.dataset.key];
  3028. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  3029. entity.dirty = true;
  3030. updateEntityOptions(entity, entity.view);
  3031. updateViewOptions(entity, entity.view);
  3032. updateSizes(true);
  3033. } else {
  3034. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3035. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  3036. updateSizes();
  3037. updateSizes();
  3038. }
  3039. } else {
  3040. if (config.autoFit) {
  3041. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  3042. } else {
  3043. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  3044. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  3045. if (!config.lockYAxis) {
  3046. config.y += change / 2;
  3047. }
  3048. setWorldHeight(config.height, math.multiply(config.height, dir));
  3049. updateWorldOptions();
  3050. }
  3051. }
  3052. checkFitWorld();
  3053. })
  3054. updateWorldHeight();
  3055. document.querySelector("#search-box").addEventListener("change", e => doSearch(e.target.value));
  3056. });
  3057. let searchText = "";
  3058. function doSearch(value) {
  3059. searchText = value;
  3060. updateFilter();
  3061. }
  3062. function customEntityFromFile(file, x=0.5, y=0.5) {
  3063. file.arrayBuffer().then(buf => {
  3064. arr = new Uint8Array(buf);
  3065. blob = new Blob([arr], {type: file.type });
  3066. url = window.URL.createObjectURL(blob)
  3067. makeCustomEntity(url, x, y);
  3068. });
  3069. }
  3070. function makeCustomEntity(url, x=0.5, y=0.5) {
  3071. const maker = createEntityMaker(
  3072. {
  3073. name: "Custom Entity"
  3074. },
  3075. {
  3076. custom: {
  3077. attributes: {
  3078. height: {
  3079. name: "Height",
  3080. power: 1,
  3081. type: "length",
  3082. base: math.unit(6, "feet")
  3083. }
  3084. },
  3085. image: {
  3086. source: url
  3087. },
  3088. name: "Image",
  3089. info: {},
  3090. rename: false
  3091. }
  3092. },
  3093. []
  3094. );
  3095. const entity = maker.constructor();
  3096. entity.scale = config.height.toNumber("feet") / 20;
  3097. entity.ephemeral = true;
  3098. displayEntity(entity, "custom", x, y, true, true);
  3099. }
  3100. const filterDefs = {
  3101. none: {
  3102. id: "none",
  3103. name: "No Filter",
  3104. extract: maker => [],
  3105. render: name => name,
  3106. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3107. },
  3108. author: {
  3109. id: "author",
  3110. name: "Authors",
  3111. extract: maker => maker.authors ? maker.authors : [],
  3112. render: author => attributionData.people[author].name,
  3113. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3114. },
  3115. owner: {
  3116. id: "owner",
  3117. name: "Owners",
  3118. extract: maker => maker.owners ? maker.owners : [],
  3119. render: owner => attributionData.people[owner].name,
  3120. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3121. },
  3122. species: {
  3123. id: "species",
  3124. name: "Species",
  3125. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  3126. render: species => speciesData[species].name,
  3127. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3128. },
  3129. tags: {
  3130. id: "tags",
  3131. name: "Tags",
  3132. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  3133. render: tag => tagDefs[tag],
  3134. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3135. },
  3136. size: {
  3137. id: "size",
  3138. name: "Normal Size",
  3139. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  3140. if (result && !size.default) {
  3141. return result;
  3142. }
  3143. let meters = size.height.toNumber("meters");
  3144. if (meters < 1e-1) {
  3145. return ["micro"];
  3146. } else if (meters < 1e1) {
  3147. return ["moderate"];
  3148. } else {
  3149. return ["macro"];
  3150. }
  3151. }, null)) : [],
  3152. render: tag => { return {
  3153. "micro": "Micro",
  3154. "moderate": "Moderate",
  3155. "macro": "Macro"
  3156. }[tag]},
  3157. sort: (tag1, tag2) => {
  3158. const order = {
  3159. "micro": 0,
  3160. "moderate": 1,
  3161. "macro": 2
  3162. };
  3163. return order[tag1[0]] - order[tag2[0]];
  3164. }
  3165. },
  3166. allSizes: {
  3167. id: "allSizes",
  3168. name: "Possible Size",
  3169. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  3170. const height = size.height;
  3171. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  3172. if (result) {
  3173. return result;
  3174. } else {
  3175. if (math.compare(height, value) <= 0) {
  3176. return name;
  3177. }
  3178. }
  3179. }, null);
  3180. set.add(result ? result : "infinite");
  3181. return set;
  3182. }, new Set())) : [],
  3183. render: tag => tag[0].toUpperCase() + tag.slice(1),
  3184. sort: (tag1, tag2) => {
  3185. const order = [
  3186. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  3187. "galactic", "universal", "omniversal", "infinite"
  3188. ]
  3189. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  3190. }
  3191. }
  3192. }
  3193. const sizeCategories = {
  3194. "atomic": math.unit(100, "angstroms"),
  3195. "microscopic": math.unit(100, "micrometers"),
  3196. "tiny": math.unit(100, "millimeters"),
  3197. "small": math.unit(1, "meter"),
  3198. "moderate": math.unit(3, "meters"),
  3199. "large": math.unit(10, "meters"),
  3200. "macro": math.unit(300, "meters"),
  3201. "megamacro": math.unit(1000, "kilometers"),
  3202. "planetary": math.unit(10, "earths"),
  3203. "stellar": math.unit(10, "solarradii"),
  3204. "galactic": math.unit(10, "galaxies"),
  3205. "universal": math.unit(10, "universes"),
  3206. "omniversal": math.unit(10, "multiverses")
  3207. };
  3208. function prepareEntities() {
  3209. availableEntities["buildings"] = makeBuildings();
  3210. availableEntities["characters"] = makeCharacters();
  3211. availableEntities["clothing"] = makeClothing();
  3212. availableEntities["creatures"] = makeCreatures();
  3213. availableEntities["dildos"] = makeDildos();
  3214. availableEntities["fiction"] = makeFiction();
  3215. availableEntities["food"] = makeFood();
  3216. availableEntities["furniture"] = makeFurniture();
  3217. availableEntities["landmarks"] = makeLandmarks();
  3218. availableEntities["naturals"] = makeNaturals();
  3219. availableEntities["objects"] = makeObjects();
  3220. availableEntities["pokemon"] = makePokemon();
  3221. availableEntities["real-buildings"] = makeRealBuildings();
  3222. availableEntities["real-terrain"] = makeRealTerrains();
  3223. availableEntities["species"] = makeSpecies();
  3224. availableEntities["vehicles"] = makeVehicles();
  3225. availableEntities["species"].forEach(x => {
  3226. if (x.name == "Human") {
  3227. availableEntities["food"].push(x);
  3228. }
  3229. })
  3230. availableEntities["characters"].sort((x, y) => {
  3231. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  3232. });
  3233. availableEntities["species"].sort((x, y) => {
  3234. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  3235. });
  3236. const holder = document.querySelector("#spawners");
  3237. const filterHolder = document.querySelector("#filters");
  3238. const categorySelect = document.createElement("select");
  3239. categorySelect.id = "category-picker";
  3240. const filterSelect = document.createElement("select");
  3241. filterSelect.id = "filter-picker";
  3242. holder.appendChild(categorySelect);
  3243. filterHolder.appendChild(filterSelect);
  3244. const filterSets = {};
  3245. Object.values(filterDefs).forEach(filter => {
  3246. filterSets[filter.id] = new Set();
  3247. })
  3248. Object.entries(availableEntities).forEach(([category, entityList]) => {
  3249. const select = document.createElement("select");
  3250. select.id = "create-entity-" + category;
  3251. select.classList.add("entity-select");
  3252. for (let i = 0; i < entityList.length; i++) {
  3253. const entity = entityList[i];
  3254. const option = document.createElement("option");
  3255. option.value = i;
  3256. option.innerText = entity.name;
  3257. select.appendChild(option);
  3258. if (entity.nsfw) {
  3259. option.classList.add("nsfw");
  3260. }
  3261. Object.values(filterDefs).forEach(filter => {
  3262. filter.extract(entity).forEach(result => {
  3263. filterSets[filter.id].add(result);
  3264. });
  3265. });
  3266. availableEntitiesByName[entity.name] = entity;
  3267. };
  3268. select.addEventListener("change", e => {
  3269. if (select.options[select.selectedIndex]?.classList.contains("nsfw")) {
  3270. select.classList.add("nsfw");
  3271. } else {
  3272. select.classList.remove("nsfw");
  3273. }
  3274. // preload the entity's first image
  3275. const entity = entityList[select.selectedIndex]?.constructor();
  3276. if (entity)
  3277. {
  3278. let img = new Image();
  3279. img.src = entity.currentView.image.source;
  3280. }
  3281. })
  3282. const button = document.createElement("button");
  3283. button.id = "create-entity-" + category + "-button";
  3284. button.classList.add("entity-button");
  3285. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  3286. button.addEventListener("click", e => {
  3287. if (entityList[select.value] == null)
  3288. return;
  3289. const newEntity = entityList[select.value].constructor()
  3290. let yOffset = 0;
  3291. if (config.lockYAxis) {
  3292. if (config.groundPos === "high") {
  3293. yOffset = config.height.toNumber("meters")/2;
  3294. }
  3295. else if (config.groundPos === "medium") {
  3296. yOffset = config.height.toNumber("meters")/4;
  3297. }
  3298. else if (config.groundPos === "low") {
  3299. yOffset = config.height.toNumber("meters")/6;
  3300. }
  3301. else if (config.groundPos === "bottom") {
  3302. yOffset = 0;
  3303. }
  3304. } else {
  3305. yOffset = (config.lockYAxis ? 0 : config.height.toNumber("meters")/2);
  3306. }
  3307. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + yOffset, true, true);
  3308. });
  3309. const categoryOption = document.createElement("option");
  3310. categoryOption.value = category
  3311. categoryOption.innerText = category;
  3312. if (category == "characters") {
  3313. categoryOption.selected = true;
  3314. select.classList.add("category-visible");
  3315. button.classList.add("category-visible");
  3316. }
  3317. categorySelect.appendChild(categoryOption);
  3318. holder.appendChild(select);
  3319. holder.appendChild(button);
  3320. });
  3321. Object.values(filterDefs).forEach(filter => {
  3322. const option = document.createElement("option");
  3323. option.innerText = filter.name;
  3324. option.value = filter.id;
  3325. filterSelect.appendChild(option);
  3326. const filterNameSelect = document.createElement("select");
  3327. filterNameSelect.classList.add("filter-select");
  3328. filterNameSelect.id = "filter-" + filter.id;
  3329. filterHolder.appendChild(filterNameSelect);
  3330. const button = document.createElement("button");
  3331. button.classList.add("filter-button");
  3332. button.id = "create-filtered-" + filter.id + "-button";
  3333. filterHolder.appendChild(button);
  3334. const counter = document.createElement("div");
  3335. counter.classList.add("button-counter");
  3336. counter.innerText = "10";
  3337. button.appendChild(counter);
  3338. const i = document.createElement("i");
  3339. i.classList.add("fas");
  3340. i.classList.add("fa-plus");
  3341. button.appendChild(i);
  3342. button.addEventListener("click", e => {
  3343. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  3344. const count = makers.length + 2;
  3345. let index = 1;
  3346. if (makers.length > 50) {
  3347. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  3348. return;
  3349. }
  3350. }
  3351. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3352. const spawned = makers.map(element => {
  3353. const category = document.querySelector("#category-picker").value;
  3354. const maker = availableEntities[category][element.value];
  3355. const entity = maker.constructor()
  3356. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  3357. index += 1;
  3358. return entityIndex - 1;
  3359. });
  3360. updateSizes(true);
  3361. if (config.autoFitAdd) {
  3362. let targets = {};
  3363. spawned.forEach(key => {
  3364. targets[key] = entities[key];
  3365. })
  3366. fitEntities(targets);
  3367. }
  3368. });
  3369. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  3370. const option = document.createElement("option");
  3371. option.innerText = name[1];
  3372. option.value = name[0];
  3373. filterNameSelect.appendChild(option);
  3374. });
  3375. filterNameSelect.addEventListener("change", e => {
  3376. updateFilter();
  3377. });
  3378. });
  3379. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  3380. categorySelect.addEventListener("input", e => {
  3381. const oldSelect = document.querySelector(".entity-select.category-visible");
  3382. oldSelect.classList.remove("category-visible");
  3383. const oldButton = document.querySelector(".entity-button.category-visible");
  3384. oldButton.classList.remove("category-visible");
  3385. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  3386. newSelect.classList.add("category-visible");
  3387. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  3388. newButton.classList.add("category-visible");
  3389. recomputeFilters();
  3390. updateFilter();
  3391. });
  3392. recomputeFilters();
  3393. filterSelect.addEventListener("input", e => {
  3394. const oldSelect = document.querySelector(".filter-select.category-visible");
  3395. if (oldSelect)
  3396. oldSelect.classList.remove("category-visible");
  3397. const newSelect = document.querySelector("#filter-" + e.target.value);
  3398. if (newSelect && e.target.value != "none")
  3399. newSelect.classList.add("category-visible");
  3400. updateFilter();
  3401. });
  3402. ratioInfo = document.body.querySelector(".ratio-info")
  3403. }
  3404. // Only display authors and owners if they appear
  3405. // somewhere in the current entity list
  3406. function recomputeFilters() {
  3407. const category = document.querySelector("#category-picker").value;
  3408. const filterSets = {};
  3409. Object.values(filterDefs).forEach(filter => {
  3410. filterSets[filter.id] = new Set();
  3411. });
  3412. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3413. const entity = availableEntities[category][element.value];
  3414. Object.values(filterDefs).forEach(filter => {
  3415. filter.extract(entity).forEach(result => {
  3416. filterSets[filter.id].add(result);
  3417. });
  3418. });
  3419. });
  3420. Object.values(filterDefs).forEach(filter => {
  3421. // always show the "none" option
  3422. let found = filter.id == "none";
  3423. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  3424. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  3425. element.classList.remove("filtered");
  3426. element.disabled = false;
  3427. found = true;
  3428. } else {
  3429. element.classList.add("filtered");
  3430. element.disabled = true;
  3431. }
  3432. });
  3433. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  3434. if (found) {
  3435. filterOption.classList.remove("filtered");
  3436. filterOption.disabled = false;
  3437. } else {
  3438. filterOption.classList.add("filtered");
  3439. filterOption.disabled = true;
  3440. }
  3441. });
  3442. document.querySelector("#filter-picker").value = "none";
  3443. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  3444. }
  3445. function updateFilter() {
  3446. const category = document.querySelector("#category-picker").value;
  3447. const type = document.querySelector("#filter-picker").value;
  3448. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  3449. clearFilter();
  3450. const noFilter = !filterKeySelect;
  3451. let key;
  3452. let current = document.querySelector(".entity-select.category-visible").value;
  3453. if (!noFilter)
  3454. {
  3455. key = filterKeySelect.value;
  3456. current
  3457. }
  3458. let replace = current == "";
  3459. let first = null;
  3460. let count = 0;
  3461. const lowerSearchText = searchText !== "" ? searchText.toLowerCase() : null;
  3462. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3463. let keep = noFilter;
  3464. if (!noFilter && filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  3465. keep = true;
  3466. }
  3467. if (searchText != "" && !availableEntities[category][element.value].name.toLowerCase().includes(lowerSearchText))
  3468. {
  3469. keep = false;
  3470. }
  3471. if (!keep) {
  3472. element.classList.add("filtered");
  3473. element.disabled = true;
  3474. if (current == element.value) {
  3475. replace = true;
  3476. }
  3477. } else {
  3478. count += 1;
  3479. if (!first) {
  3480. first = element.value;
  3481. }
  3482. }
  3483. });
  3484. const button = document.querySelector(".filter-select.category-visible + button");
  3485. if (button) {
  3486. button.querySelector(".button-counter").innerText = count;
  3487. }
  3488. if (replace) {
  3489. document.querySelector(".entity-select.category-visible").value = first;
  3490. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  3491. }
  3492. }
  3493. function clearFilter() {
  3494. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3495. element.classList.remove("filtered");
  3496. element.disabled = false;
  3497. });
  3498. }
  3499. document.addEventListener("mousemove", (e) => {
  3500. if (currentRuler) {
  3501. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3502. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3503. let position = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3504. currentRuler.x1 = position.x;
  3505. currentRuler.y1 = position.y;
  3506. }
  3507. drawRulers();
  3508. });
  3509. document.addEventListener("touchmove", (e) => {
  3510. if (currentRuler) {
  3511. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3512. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3513. let position = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3514. currentRuler.x1 = position.x;
  3515. currentRuler.y1 = position.y;
  3516. }
  3517. drawRulers();
  3518. });
  3519. document.addEventListener("mousemove", (e) => {
  3520. if (clicked) {
  3521. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  3522. if (movingInBounds) {
  3523. position = snapPos(position);
  3524. } else {
  3525. let x = e.clientX - dragOffsetX;
  3526. let y = e.clientY - dragOffsetY;
  3527. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  3528. movingInBounds = true;
  3529. }
  3530. }
  3531. clicked.dataset.x = position.x;
  3532. clicked.dataset.y = position.y;
  3533. updateEntityElement(entities[clicked.dataset.key], clicked);
  3534. if (hoveringInDeleteArea(e)) {
  3535. document.querySelector("#menubar").classList.add("hover-delete");
  3536. } else {
  3537. document.querySelector("#menubar").classList.remove("hover-delete");
  3538. }
  3539. }
  3540. if (panning && panReady) {
  3541. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3542. const worldHeight = config.height.toNumber("meters");
  3543. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  3544. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  3545. panOffsetX = e.clientX;
  3546. panOffsetY = e.clientY;
  3547. updateSizes();
  3548. panReady = false;
  3549. setTimeout(() => panReady=true, 1000/120);
  3550. }
  3551. });
  3552. document.addEventListener("touchmove", (e) => {
  3553. if (clicked) {
  3554. e.preventDefault();
  3555. let x = e.touches[0].clientX;
  3556. let y = e.touches[0].clientY;
  3557. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  3558. clicked.dataset.x = position.x;
  3559. clicked.dataset.y = position.y;
  3560. updateEntityElement(entities[clicked.dataset.key], clicked);
  3561. // what a hack
  3562. // I should centralize this 'fake event' creation...
  3563. if (hoveringInDeleteArea({ clientY: y })) {
  3564. document.querySelector("#menubar").classList.add("hover-delete");
  3565. } else {
  3566. document.querySelector("#menubar").classList.remove("hover-delete");
  3567. }
  3568. }
  3569. if (panning && panReady) {
  3570. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3571. const worldHeight = config.height.toNumber("meters");
  3572. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  3573. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  3574. panOffsetX = e.touches[0].clientX;
  3575. panOffsetY = e.touches[0].clientY;
  3576. updateSizes();
  3577. panReady = false;
  3578. setTimeout(() => panReady=true, 1000/60);
  3579. }
  3580. }, { passive: false });
  3581. function checkFitWorld() {
  3582. if (config.autoFit) {
  3583. fitWorld();
  3584. return true;
  3585. }
  3586. return false;
  3587. }
  3588. function fitWorld(manual = false, factor = 1.1) {
  3589. if (Object.keys(entities).length > 0) {
  3590. fitEntities(entities, factor);
  3591. }
  3592. }
  3593. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  3594. let minX = Infinity;
  3595. let maxX = -Infinity;
  3596. let minY = Infinity;
  3597. let maxY = -Infinity;
  3598. let count = 0;
  3599. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3600. const worldHeight = config.height.toNumber("meters");
  3601. Object.entries(targetEntities).forEach(([key, entity]) => {
  3602. const view = entity.view;
  3603. let extra = entity.views[view].image.extra;
  3604. extra = extra === undefined ? 1 : extra;
  3605. const image = document.querySelector("#entity-" + key + " > .entity-image");
  3606. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  3607. let width = image.width;
  3608. let height = image.height;
  3609. // only really relevant if the images haven't loaded in yet
  3610. if (height == 0) {
  3611. height = 100;
  3612. }
  3613. if (width == 0) {
  3614. width = height;
  3615. }
  3616. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  3617. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  3618. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  3619. const yBottom = y;
  3620. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  3621. minX = Math.min(minX, xBottom);
  3622. maxX = Math.max(maxX, xTop);
  3623. minY = Math.min(minY, yBottom);
  3624. maxY = Math.max(maxY, yTop);
  3625. count += 1;
  3626. });
  3627. if (config.lockYAxis) {
  3628. minY = 0;
  3629. }
  3630. let ySize = (maxY - minY) * factor;
  3631. let xSize = (maxX - minX) * factor;
  3632. if (xSize / ySize > worldWidth / worldHeight) {
  3633. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  3634. }
  3635. config.x = (maxX + minX) / 2;
  3636. config.y = minY;
  3637. height = math.unit(ySize, "meter")
  3638. setWorldHeight(config.height, math.multiply(height, factor));
  3639. }
  3640. function updateWorldHeight() {
  3641. const unit = document.querySelector("#options-height-unit").value;
  3642. const rawValue = document.querySelector("#options-height-value").value;
  3643. var value
  3644. try {
  3645. value = math.evaluate(rawValue)
  3646. if (typeof(value) !== "number") {
  3647. try {
  3648. value = value.toNumber(unit)
  3649. } catch {
  3650. toast("Invalid input: " + rawValue + " can't be converted to " + unit)
  3651. }
  3652. }
  3653. } catch {
  3654. toast("Invalid input: could not parse " + rawValue)
  3655. return;
  3656. }
  3657. const newHeight = Math.max(0.000000001, value);
  3658. const oldHeight = config.height;
  3659. setWorldHeight(oldHeight, math.unit(newHeight, unit), true);
  3660. }
  3661. function setWorldHeight(oldHeight, newHeight, keepUnit=false) {
  3662. worldSizeDirty = true;
  3663. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  3664. const unit = document.querySelector("#options-height-unit").value;
  3665. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  3666. Object.entries(entities).forEach(([key, entity]) => {
  3667. const element = document.querySelector("#entity-" + key);
  3668. let newPosition;
  3669. if (altHeld) {
  3670. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  3671. } else {
  3672. newPosition = { x: element.dataset.x, y: element.dataset.y };
  3673. }
  3674. element.dataset.x = newPosition.x;
  3675. element.dataset.y = newPosition.y;
  3676. });
  3677. if (!keepUnit) {
  3678. pickUnit()
  3679. }
  3680. updateSizes();
  3681. }
  3682. function loadScene(name = "default") {
  3683. if (name === "") {
  3684. name = "default"
  3685. }
  3686. try {
  3687. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  3688. if (data === null) {
  3689. console.error("Couldn't load " + name)
  3690. return false;
  3691. }
  3692. importScene(data);
  3693. toast("Loaded " + name);
  3694. return true;
  3695. } catch (err) {
  3696. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  3697. console.error(err);
  3698. return false;
  3699. }
  3700. }
  3701. function saveScene(name = "default") {
  3702. try {
  3703. const string = JSON.stringify(exportScene());
  3704. localStorage.setItem("macrovision-save-" + name, string);
  3705. toast("Saved as " + name);
  3706. } catch (err) {
  3707. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  3708. console.error(err);
  3709. }
  3710. }
  3711. function deleteScene(name = "default") {
  3712. if (confirm("Really delete the " + name + " scene?")) {
  3713. try {
  3714. localStorage.removeItem("macrovision-save-" + name)
  3715. toast("Deleted " + name);
  3716. } catch (err) {
  3717. console.error(err);
  3718. }
  3719. }
  3720. updateSaveInfo();
  3721. }
  3722. function exportScene() {
  3723. const results = {};
  3724. results.entities = [];
  3725. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  3726. const element = document.querySelector("#entity-" + key);
  3727. results.entities.push({
  3728. name: entity.identifier,
  3729. customName: entity.name,
  3730. scale: entity.scale,
  3731. rotation: entity.rotation,
  3732. view: entity.view,
  3733. x: element.dataset.x,
  3734. y: element.dataset.y,
  3735. priority: entity.priority,
  3736. brightness: entity.brightness
  3737. });
  3738. });
  3739. const unit = document.querySelector("#options-height-unit").value;
  3740. results.world = {
  3741. height: config.height.toNumber(unit),
  3742. unit: unit,
  3743. x: config.x,
  3744. y: config.y
  3745. }
  3746. results.version = migrationDefs.length;
  3747. return results;
  3748. }
  3749. // btoa doesn't like anything that isn't ASCII
  3750. // great
  3751. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  3752. // for providing an alternative
  3753. function b64EncodeUnicode(str) {
  3754. // first we use encodeURIComponent to get percent-encoded UTF-8,
  3755. // then we convert the percent encodings into raw bytes which
  3756. // can be fed into btoa.
  3757. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  3758. function toSolidBytes(match, p1) {
  3759. return String.fromCharCode('0x' + p1);
  3760. }));
  3761. }
  3762. function b64DecodeUnicode(str) {
  3763. // Going backwards: from bytestream, to percent-encoding, to original string.
  3764. return decodeURIComponent(atob(str).split('').map(function (c) {
  3765. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  3766. }).join(''));
  3767. }
  3768. function linkScene() {
  3769. loc = new URL(window.location);
  3770. const link = loc.protocol + "//" + loc.host + loc.pathname + "#" + b64EncodeUnicode(JSON.stringify(exportScene()));
  3771. window.history.replaceState(null, "Macrovision", link);
  3772. try {
  3773. navigator.clipboard.writeText(link);
  3774. toast("Copied permalink to clipboard");
  3775. } catch {
  3776. toast("Couldn't copy permalink");
  3777. }
  3778. }
  3779. function copyScene() {
  3780. const results = exportScene();
  3781. navigator.clipboard.writeText(JSON.stringify(results));
  3782. }
  3783. function pasteScene() {
  3784. try {
  3785. navigator.clipboard.readText().then(text => {
  3786. const data = JSON.parse(text);
  3787. if (data.entities === undefined) {
  3788. return;
  3789. }
  3790. if (data.world === undefined) {
  3791. return;
  3792. }
  3793. importScene(data);
  3794. }).catch(err => alert(err));
  3795. } catch (err) {
  3796. console.error(err);
  3797. // probably wasn't valid data
  3798. }
  3799. }
  3800. // TODO - don't just search through every single entity
  3801. // probably just have a way to do lookups directly
  3802. function findEntity(name) {
  3803. return availableEntitiesByName[name];
  3804. }
  3805. const migrationDefs = [
  3806. /*
  3807. Migration: 0 -> 1
  3808. Adds x and y coordinates for the camera
  3809. */
  3810. data => {
  3811. data.world.x = 0;
  3812. data.world.y = 0;
  3813. },
  3814. /*
  3815. Migration: 1 -> 2
  3816. Adds priority and brightness to each entity
  3817. */
  3818. data => {
  3819. data.entities.forEach(entity => {
  3820. entity.priority = 0;
  3821. entity.brightness = 1;
  3822. });
  3823. },
  3824. /*
  3825. Migration: 2 -> 3
  3826. Custom names are exported
  3827. */
  3828. data => {
  3829. data.entities.forEach(entity => {
  3830. entity.customName = entity.name
  3831. });
  3832. },
  3833. /*
  3834. Migration: 3 -> $
  3835. Rotation is now stored
  3836. */
  3837. data => {
  3838. data.entities.forEach(entity => {
  3839. entity.rotation = 0
  3840. });
  3841. }
  3842. ]
  3843. function migrateScene(data) {
  3844. if (data.version === undefined) {
  3845. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  3846. console.trace()
  3847. data.version = 0;
  3848. } else if (data.version < migrationDefs.length) {
  3849. migrationDefs[data.version](data);
  3850. data.version += 1;
  3851. migrateScene(data);
  3852. }
  3853. }
  3854. function importScene(data) {
  3855. removeAllEntities();
  3856. migrateScene(data);
  3857. data.entities.forEach(entityInfo => {
  3858. const entity = findEntity(entityInfo.name).constructor();
  3859. entity.name = entityInfo.customName;
  3860. entity.scale = entityInfo.scale;
  3861. entity.rotation = entityInfo.rotation;
  3862. entity.priority = entityInfo.priority;
  3863. entity.brightness = entityInfo.brightness;
  3864. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  3865. });
  3866. config.height = math.unit(data.world.height, data.world.unit);
  3867. config.x = data.world.x;
  3868. config.y = data.world.y;
  3869. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  3870. document.querySelector("#options-height-value").value = height;
  3871. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  3872. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3873. if (data.canvasWidth) {
  3874. doHorizReposition(data.canvasWidth / canvasWidth);
  3875. }
  3876. updateSizes();
  3877. }
  3878. function renderToCanvas() {
  3879. const ctx = document.querySelector("#display").getContext("2d");
  3880. Object.entries(entities).sort((ent1, ent2) => {
  3881. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  3882. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  3883. return z1 - z2;
  3884. }).forEach(([id, entity]) => {
  3885. element = document.querySelector("#entity-" + id);
  3886. img = element.querySelector("img");
  3887. let x = parseFloat(element.dataset.x);
  3888. let y = parseFloat(element.dataset.y);
  3889. let coords = pos2pix({x: x, y: y});
  3890. let offset = img.style.getPropertyValue("--offset");
  3891. offset = parseFloat(offset.substring(0, offset.length-1))
  3892. let xSize = img.width;
  3893. let ySize = img.height;
  3894. x = coords.x
  3895. y = coords.y + ySize/2 + ySize * offset / 100;
  3896. const oldFilter = ctx.filter
  3897. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  3898. ctx.filter = `brightness(${brightness})`;
  3899. ctx.save();
  3900. ctx.resetTransform();
  3901. ctx.translate(x, y);
  3902. ctx.rotate(entity.rotation);
  3903. ctx.drawImage(img, -xSize/2, -ySize/2, xSize, ySize);
  3904. ctx.restore();
  3905. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  3906. ctx.translate(-xSize/2, -ySize/2);
  3907. ctx.filter = oldFilter
  3908. });
  3909. }
  3910. function exportCanvas(callback) {
  3911. /** @type {CanvasRenderingContext2D} */
  3912. const ctx = document.querySelector("#display").getContext("2d");
  3913. const blob = ctx.canvas.toBlob(callback);
  3914. }
  3915. function generateScreenshot(callback) {
  3916. /** @type {CanvasRenderingContext2D} */
  3917. const ctx = document.querySelector("#display").getContext("2d");
  3918. if (checkBodyClass("toggle-bottom-cover")) {
  3919. ctx.fillStyle = "#000";
  3920. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  3921. }
  3922. renderToCanvas();
  3923. ctx.fillStyle = "#777";
  3924. ctx.font = "normal normal lighter 16pt coda";
  3925. ctx.fillText("macrovision.crux.sexy", 10, 25);
  3926. exportCanvas(blob => {
  3927. callback(blob);
  3928. });
  3929. }
  3930. function copyScreenshot() {
  3931. if (window.ClipboardItem === undefined) {
  3932. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  3933. return;
  3934. }
  3935. generateScreenshot(blob => {
  3936. navigator.clipboard.write([
  3937. new ClipboardItem({
  3938. "image/png": blob
  3939. })
  3940. ]);
  3941. });
  3942. drawScales(false);
  3943. }
  3944. function saveScreenshot() {
  3945. generateScreenshot(blob => {
  3946. const a = document.createElement("a");
  3947. a.href = URL.createObjectURL(blob);
  3948. a.setAttribute("download", "macrovision.png");
  3949. a.click();
  3950. });
  3951. drawScales(false);
  3952. }
  3953. function openScreenshot() {
  3954. generateScreenshot(blob => {
  3955. const a = document.createElement("a");
  3956. a.href = URL.createObjectURL(blob);
  3957. a.setAttribute("target", "_blank");
  3958. a.click();
  3959. });
  3960. drawScales(false);
  3961. }
  3962. const rateLimits = {};
  3963. function toast(msg) {
  3964. let div = document.createElement("div");
  3965. div.innerHTML = msg;
  3966. div.classList.add("toast");
  3967. document.body.appendChild(div);
  3968. setTimeout(() => {
  3969. document.body.removeChild(div);
  3970. }, 5000)
  3971. }
  3972. function toastRateLimit(msg, key, delay) {
  3973. if (!rateLimits[key]) {
  3974. toast(msg);
  3975. rateLimits[key] = setTimeout(() => {
  3976. delete rateLimits[key]
  3977. }, delay);
  3978. }
  3979. }
  3980. let lastTime = undefined;
  3981. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  3982. Object.keys(entities).forEach(key => {
  3983. document.querySelector("#entity-" + key).classList.add("no-transition");
  3984. });
  3985. config.x = fromX;
  3986. config.y = fromY;
  3987. config.height = math.unit(fromHeight, "meters")
  3988. updateSizes();
  3989. lastTime = undefined;
  3990. requestAnimationFrame((timestamp) => panTo(toX, toY, toHeight, (toX - fromX) / duration, (toY - fromY) / duration, (toHeight - fromHeight) / duration, timestamp, duration));
  3991. }
  3992. function panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining) {
  3993. if (lastTime === undefined) {
  3994. lastTime = timestamp;
  3995. }
  3996. dt = timestamp - lastTime;
  3997. remaining -= dt;
  3998. if (remaining < 0) {
  3999. dt += remaining
  4000. }
  4001. let newX = config.x + xSpeed * dt;
  4002. let newY = config.y + ySpeed * dt;
  4003. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  4004. if (remaining > 0) {
  4005. requestAnimationFrame((timestamp) => panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining))
  4006. } else {
  4007. Object.keys(entities).forEach(key => {
  4008. document.querySelector("#entity-" + key).classList.remove("no-transition");
  4009. });
  4010. }
  4011. config.x = newX;
  4012. config.y = newY;
  4013. config.height = math.unit(newHeight, "meters");
  4014. updateSizes();
  4015. }