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

5030 lines
152 KiB

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