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.
 
 
 

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