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.
 
 
 

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