less copy protection, more size visualization
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

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