less copy protection, more size visualization
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

4825 satır
146 KiB

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