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

4648 lines
141 KiB

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