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.
 
 
 

5051 line
153 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.autoCaloricValue && view.attributes.weight !== undefined && view.attributes.energyWorth === undefined) {
  1020. view.attributes.energyNeed = {
  1021. name: "Caloric Value",
  1022. power: 3,
  1023. type: "energy",
  1024. base: math.unit(860 * view.attributes.weight.base.toNumber("lbs"), "kcal")
  1025. }
  1026. }
  1027. if (config.autoPreyCapacity !== "none" && view.attributes.weight !== undefined && view.attributes.capacity === undefined) {
  1028. view.attributes.capacity = {
  1029. name: "Capacity",
  1030. power: 3,
  1031. type: "volume",
  1032. base: math.unit((config.autoPreyCapacity == "same-size" ? 1 : 0.05) * view.attributes.weight.base.toNumber("lbs") / 150, "people")
  1033. }
  1034. }
  1035. Object.entries(view.attributes).forEach(([key, val]) => {
  1036. Object.defineProperty(
  1037. view,
  1038. key,
  1039. {
  1040. get: function () {
  1041. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  1042. },
  1043. set: function (value) {
  1044. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  1045. this.parent.scale = newScale;
  1046. }
  1047. }
  1048. );
  1049. });
  1050. });
  1051. this.sizes.forEach(size => {
  1052. if (size.default === true) {
  1053. if (Object.keys(forms).length > 0) {
  1054. if (this.defaultForm !== size.form) {
  1055. return;
  1056. }
  1057. }
  1058. this.views[this.defaultView].height = size.height;
  1059. this.size = size;
  1060. }
  1061. });
  1062. if (this.size === undefined && this.sizes.length > 0) {
  1063. this.views[this.defaultView].height = this.sizes[0].height;
  1064. this.size = this.sizes[0];
  1065. console.warn("No default size set for " + info.name);
  1066. } else if (this.sizes.length == 0) {
  1067. this.sizes = [
  1068. {
  1069. name: "Normal",
  1070. height: this.views[this.defaultView].height
  1071. }
  1072. ];
  1073. this.size = this.sizes[0];
  1074. }
  1075. this.desc = {};
  1076. Object.entries(this.info).forEach(([key, value]) => {
  1077. Object.defineProperty(
  1078. this.desc,
  1079. key,
  1080. {
  1081. get: function () {
  1082. let text = value.text;
  1083. if (entity.views[entity.view].info) {
  1084. if (entity.views[entity.view].info[key]) {
  1085. text = combineInfo(text, entity.views[entity.view].info[key]);
  1086. }
  1087. }
  1088. if (entity.size.info) {
  1089. if (entity.size.info[key]) {
  1090. text = combineInfo(text, entity.size.info[key]);
  1091. }
  1092. }
  1093. return { title: value.title, text: text };
  1094. }
  1095. }
  1096. )
  1097. });
  1098. Object.defineProperty(
  1099. this,
  1100. "currentView",
  1101. {
  1102. get: function() {
  1103. return entity.views[entity.view];
  1104. }
  1105. }
  1106. )
  1107. this.formViews = {};
  1108. this.formSizes = {}
  1109. Object.entries(views).forEach(([key, value]) => {
  1110. if (value.default) {
  1111. this.formViews[value.form] = key;
  1112. }
  1113. });
  1114. Object.entries(views).forEach(([key, value]) => {
  1115. if (this.formViews[value.form] === undefined) {
  1116. this.formViews[value.form] = key;
  1117. }
  1118. });
  1119. this.sizes.forEach(size => {
  1120. if (size.default) {
  1121. this.formSizes[size.form] = size;
  1122. }
  1123. })
  1124. this.sizes.forEach(size => {
  1125. if (this.formSizes[size.form] === undefined) {
  1126. this.formSizes[size.form] = size;
  1127. }
  1128. });
  1129. delete this.init;
  1130. return this;
  1131. }
  1132. }.init();
  1133. return entityTemplate;
  1134. }
  1135. function combineInfo(existing, next) {
  1136. switch (next.mode) {
  1137. case "replace":
  1138. return next.text;
  1139. case "prepend":
  1140. return next.text + existing;
  1141. case "append":
  1142. return existing + next.text;
  1143. }
  1144. return existing;
  1145. }
  1146. function clickDown(target, x, y) {
  1147. clicked = target;
  1148. movingInBounds = false;
  1149. const rect = target.getBoundingClientRect();
  1150. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1151. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1152. dragOffsetX = x - rect.left + entX;
  1153. dragOffsetY = y - rect.top + entY;
  1154. x = x - dragOffsetX;
  1155. y = y - dragOffsetY;
  1156. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  1157. movingInBounds = true;
  1158. }
  1159. clickTimeout = setTimeout(() => { dragging = true }, 200)
  1160. target.classList.add("no-transition");
  1161. }
  1162. // could we make this actually detect the menu area?
  1163. function hoveringInDeleteArea(e) {
  1164. return e.clientY < document.body.clientHeight / 10;
  1165. }
  1166. function clickUp(e) {
  1167. if (e.which != 1) {
  1168. return;
  1169. }
  1170. clearTimeout(clickTimeout);
  1171. if (clicked) {
  1172. clicked.classList.remove("no-transition");
  1173. if (dragging) {
  1174. dragging = false;
  1175. if (hoveringInDeleteArea(e)) {
  1176. removeEntity(clicked);
  1177. document.querySelector("#menubar").classList.remove("hover-delete");
  1178. }
  1179. } else {
  1180. select(clicked);
  1181. }
  1182. clicked = null;
  1183. }
  1184. }
  1185. function deselect(e) {
  1186. if (e !== undefined && e.which != 1) {
  1187. return;
  1188. }
  1189. if (selected) {
  1190. selected.classList.remove("selected");
  1191. }
  1192. if (prevSelected) {
  1193. prevSelected.classList.remove("prevSelected");
  1194. }
  1195. document.getElementById("options-selected-entity-none").selected = "selected";
  1196. clearAttribution();
  1197. selected = null;
  1198. clearViewList();
  1199. clearEntityOptions();
  1200. clearViewOptions();
  1201. document.querySelector("#delete-entity").disabled = true;
  1202. document.querySelector("#grow").disabled = true;
  1203. document.querySelector("#shrink").disabled = true;
  1204. document.querySelector("#fit").disabled = true;
  1205. }
  1206. function select(target) {
  1207. if (prevSelected !== null) {
  1208. prevSelected.classList.remove("prevSelected");
  1209. }
  1210. prevSelected = selected;
  1211. prevSelectedEntity = selectedEntity;
  1212. deselect();
  1213. selected = target;
  1214. selectedEntity = entities[target.dataset.key];
  1215. updateRatios();
  1216. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  1217. if (prevSelected !== null && config.showRatios && selected !== prevSelected) {
  1218. prevSelected.classList.add("prevSelected");
  1219. }
  1220. selected.classList.add("selected");
  1221. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  1222. configFormList(selectedEntity, selectedEntity.form);
  1223. configViewList(selectedEntity, selectedEntity.view);
  1224. configEntityOptions(selectedEntity, selectedEntity.view);
  1225. configViewOptions(selectedEntity, selectedEntity.view);
  1226. document.querySelector("#delete-entity").disabled = false;
  1227. document.querySelector("#grow").disabled = false;
  1228. document.querySelector("#shrink").disabled = false;
  1229. document.querySelector("#fit").disabled = false;
  1230. }
  1231. function configFormList(entity, selectedForm) {
  1232. const label = document.querySelector("#options-label-form");
  1233. const list = document.querySelector("#entity-form");
  1234. list.innerHTML = "";
  1235. if (selectedForm === undefined) {
  1236. label.style.display = "none";
  1237. list.style.display = "none";
  1238. return;
  1239. }
  1240. label.style.display = "block";
  1241. list.style.display = "block";
  1242. Object.keys(entity.forms).forEach(form => {
  1243. const option = document.createElement("option");
  1244. option.innerText = entity.forms[form].name;
  1245. option.value = form;
  1246. if (form === selectedForm) {
  1247. option.selected = true;
  1248. }
  1249. list.appendChild(option);
  1250. });
  1251. }
  1252. function configViewList(entity, selectedView) {
  1253. const list = document.querySelector("#entity-view");
  1254. list.innerHTML = "";
  1255. list.style.display = "block";
  1256. Object.keys(entity.views).forEach(view => {
  1257. if (Object.keys(entity.forms).length > 0) {
  1258. if (entity.views[view].form !== entity.form) {
  1259. return;
  1260. }
  1261. }
  1262. const option = document.createElement("option");
  1263. option.innerText = entity.views[view].name;
  1264. option.value = view;
  1265. if (isNsfw(entity.views[view].image.source)) {
  1266. option.classList.add("nsfw")
  1267. }
  1268. if (view === selectedView) {
  1269. option.selected = true;
  1270. if (option.classList.contains("nsfw")) {
  1271. list.classList.add("nsfw");
  1272. } else {
  1273. list.classList.remove("nsfw");
  1274. }
  1275. }
  1276. list.appendChild(option);
  1277. });
  1278. }
  1279. function clearViewList() {
  1280. const list = document.querySelector("#entity-view");
  1281. list.innerHTML = "";
  1282. list.style.display = "none";
  1283. }
  1284. function updateWorldOptions(entity, view) {
  1285. const heightInput = document.querySelector("#options-height-value");
  1286. const heightSelect = document.querySelector("#options-height-unit");
  1287. const converted = config.height.toNumber(heightSelect.value);
  1288. setNumericInput(heightInput, converted);
  1289. }
  1290. function configEntityOptions(entity, view) {
  1291. const holder = document.querySelector("#options-entity");
  1292. document.querySelector("#entity-category-header").style.display = "block";
  1293. document.querySelector("#entity-category").style.display = "block";
  1294. holder.innerHTML = "";
  1295. const scaleLabel = document.createElement("div");
  1296. scaleLabel.classList.add("options-label");
  1297. scaleLabel.innerText = "Scale";
  1298. const scaleRow = document.createElement("div");
  1299. scaleRow.classList.add("options-row");
  1300. const scaleInput = document.createElement("input");
  1301. scaleInput.classList.add("options-field-numeric");
  1302. scaleInput.id = "options-entity-scale";
  1303. scaleInput.addEventListener("change", e => {
  1304. try {
  1305. const newScale = e.target.value == 0 ? 1 : math.evaluate(e.target.value);
  1306. if (typeof(newScale) !== "number") {
  1307. toast("Invalid input: scale can't have any units!")
  1308. return;
  1309. }
  1310. entity.scale = newScale;
  1311. } catch {
  1312. toast("Invalid input: could not parse " + e.target.value)
  1313. }
  1314. entity.dirty = true;
  1315. if (config.autoFit) {
  1316. fitWorld();
  1317. } else {
  1318. updateSizes(true);
  1319. }
  1320. updateEntityOptions(entity, entity.view);
  1321. updateViewOptions(entity, entity.view);
  1322. });
  1323. scaleInput.addEventListener("keydown", e => {
  1324. e.stopPropagation();
  1325. })
  1326. setNumericInput(scaleInput, entity.scale);
  1327. scaleRow.appendChild(scaleInput);
  1328. holder.appendChild(scaleLabel);
  1329. holder.appendChild(scaleRow);
  1330. const nameLabel = document.createElement("div");
  1331. nameLabel.classList.add("options-label");
  1332. nameLabel.innerText = "Name";
  1333. const nameRow = document.createElement("div");
  1334. nameRow.classList.add("options-row");
  1335. const nameInput = document.createElement("input");
  1336. nameInput.classList.add("options-field-text");
  1337. nameInput.value = entity.name;
  1338. nameInput.addEventListener("input", e => {
  1339. entity.name = e.target.value;
  1340. entity.dirty = true;
  1341. updateSizes(true);
  1342. })
  1343. nameInput.addEventListener("keydown", e => {
  1344. e.stopPropagation();
  1345. })
  1346. nameRow.appendChild(nameInput);
  1347. holder.appendChild(nameLabel);
  1348. holder.appendChild(nameRow);
  1349. configSizeList(entity);
  1350. document.querySelector("#options-order-display").innerText = entity.priority;
  1351. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1352. document.querySelector("#options-ordering").style.display = "flex";
  1353. }
  1354. function configSizeList(entity) {
  1355. const defaultHolder = document.querySelector("#options-entity-defaults");
  1356. defaultHolder.innerHTML = "";
  1357. entity.sizes.forEach(defaultInfo => {
  1358. if (Object.keys(entity.forms).length > 0) {
  1359. if (defaultInfo.form !== entity.form) {
  1360. return;
  1361. }
  1362. }
  1363. const button = document.createElement("button");
  1364. button.classList.add("options-button");
  1365. button.innerText = defaultInfo.name;
  1366. button.addEventListener("click", e => {
  1367. if (Object.keys(entity.forms).length > 0) {
  1368. entity.views[entity.formViews[entity.form]].height = defaultInfo.height;
  1369. } else {
  1370. entity.views[entity.defaultView].height = defaultInfo.height;
  1371. }
  1372. entity.dirty = true;
  1373. updateEntityOptions(entity, entity.view);
  1374. updateViewOptions(entity, entity.view);
  1375. if (!checkFitWorld()) {
  1376. updateSizes(true);
  1377. }
  1378. if (config.autoFitSize) {
  1379. let targets = {};
  1380. targets[selected.dataset.key] = entities[selected.dataset.key];
  1381. fitEntities(targets);
  1382. }
  1383. });
  1384. defaultHolder.appendChild(button);
  1385. });
  1386. }
  1387. function updateEntityOptions(entity, view) {
  1388. const scaleInput = document.querySelector("#options-entity-scale");
  1389. setNumericInput(scaleInput, entity.scale);
  1390. document.querySelector("#options-order-display").innerText = entity.priority;
  1391. document.querySelector("#options-brightness-display").innerText = entity.brightness;
  1392. }
  1393. function clearEntityOptions() {
  1394. document.querySelector("#entity-category-header").style.display = "none";
  1395. document.querySelector("#entity-category").style.display = "none";
  1396. /*
  1397. const holder = document.querySelector("#options-entity");
  1398. holder.innerHTML = "";
  1399. document.querySelector("#options-entity-defaults").innerHTML = "";
  1400. document.querySelector("#options-ordering").style.display = "none";
  1401. document.querySelector("#options-ordering").style.display = "none";*/
  1402. }
  1403. function configViewOptions(entity, view) {
  1404. const holder = document.querySelector("#options-view");
  1405. document.querySelector("#view-category-header").style.display = "block";
  1406. document.querySelector("#view-category").style.display = "block";
  1407. holder.innerHTML = "";
  1408. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1409. const label = document.createElement("div");
  1410. label.classList.add("options-label");
  1411. label.innerText = val.name;
  1412. holder.appendChild(label);
  1413. const row = document.createElement("div");
  1414. row.classList.add("options-row");
  1415. holder.appendChild(row);
  1416. const input = document.createElement("input");
  1417. input.classList.add("options-field-numeric");
  1418. input.id = "options-view-" + key + "-input";
  1419. const select = document.createElement("select");
  1420. select.classList.add("options-field-unit");
  1421. select.id = "options-view-" + key + "-select"
  1422. Object.entries(unitChoices[val.type]).forEach(([group, entries]) => {
  1423. const optGroup = document.createElement("optgroup");
  1424. optGroup.label = group;
  1425. select.appendChild(optGroup);
  1426. entries.forEach(entry => {
  1427. const option = document.createElement("option");
  1428. option.innerText = entry;
  1429. if (entry == defaultUnits[val.type][config.units]) {
  1430. option.selected = true;
  1431. }
  1432. select.appendChild(option);
  1433. })
  1434. });
  1435. input.addEventListener("change", e => {
  1436. const raw_value = input.value == 0 ? 1 : input.value;
  1437. let value
  1438. try {
  1439. value = math.evaluate(raw_value).toNumber(select.value);
  1440. } catch {
  1441. try {
  1442. value = math.evaluate(input.value)
  1443. if (typeof(value) !== "number") {
  1444. toast("Invalid input: " + value.format() + " can't convert to " + select.value)
  1445. value = undefined
  1446. }
  1447. } catch {
  1448. toast("Invalid input: could not parse: " + input.value)
  1449. value = undefined
  1450. }
  1451. }
  1452. if (value === undefined) {
  1453. return;
  1454. }
  1455. input.value = value
  1456. entity.views[view][key] = math.unit(value, select.value);
  1457. entity.dirty = true;
  1458. if (config.autoFit) {
  1459. fitWorld();
  1460. } else {
  1461. updateSizes(true);
  1462. }
  1463. updateEntityOptions(entity, view);
  1464. updateViewOptions(entity, view, key);
  1465. });
  1466. input.addEventListener("keydown", e => {
  1467. e.stopPropagation();
  1468. })
  1469. if (entity.currentView.units[key]) {
  1470. select.value = entity.currentView.units[key];
  1471. } else {
  1472. entity.currentView.units[key] = select.value;
  1473. }
  1474. select.dataset.oldUnit = select.value;
  1475. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  1476. // TODO does this ever cause a change in the world?
  1477. select.addEventListener("input", e => {
  1478. const value = input.value == 0 ? 1 : input.value;
  1479. const oldUnit = select.dataset.oldUnit;
  1480. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  1481. entity.dirty = true;
  1482. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  1483. select.dataset.oldUnit = select.value;
  1484. entity.views[view].units[key] = select.value;
  1485. if (config.autoFit) {
  1486. fitWorld();
  1487. } else {
  1488. updateSizes(true);
  1489. }
  1490. updateEntityOptions(entity, view);
  1491. updateViewOptions(entity, view, key);
  1492. });
  1493. row.appendChild(input);
  1494. row.appendChild(select);
  1495. });
  1496. }
  1497. function updateViewOptions(entity, view, changed) {
  1498. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  1499. if (key != changed) {
  1500. const input = document.querySelector("#options-view-" + key + "-input");
  1501. const select = document.querySelector("#options-view-" + key + "-select");
  1502. const currentUnit = select.value;
  1503. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  1504. setNumericInput(input, convertedAmount);
  1505. }
  1506. });
  1507. }
  1508. function setNumericInput(input, value, round = 6) {
  1509. if (typeof value == "string") {
  1510. value = parseFloat(value)
  1511. }
  1512. input.value = value.toPrecision(round);
  1513. }
  1514. function getSortedEntities() {
  1515. return Object.keys(entities).sort((a, b) => {
  1516. const entA = entities[a];
  1517. const entB = entities[b];
  1518. const viewA = entA.view;
  1519. const viewB = entB.view;
  1520. const heightA = entA.views[viewA].height.to("meter").value;
  1521. const heightB = entB.views[viewB].height.to("meter").value;
  1522. return heightA - heightB;
  1523. });
  1524. }
  1525. function clearViewOptions() {
  1526. document.querySelector("#view-category-header").style.display = "none";
  1527. document.querySelector("#view-category").style.display = "none";
  1528. }
  1529. // this is a crime against humanity, and also stolen from
  1530. // stack overflow
  1531. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  1532. const testCanvas = document.createElement("canvas");
  1533. testCanvas.id = "test-canvas";
  1534. function rotate(point, angle) {
  1535. return [
  1536. point[0] * Math.cos(angle) - point[1] * Math.sin(angle),
  1537. point[0] * Math.sin(angle) + point[1] * Math.cos(angle)
  1538. ];
  1539. }
  1540. const testCtx = testCanvas.getContext("2d");
  1541. function testClick(event) {
  1542. testCtx.save();
  1543. const target = event.target;
  1544. if (rulerMode) {
  1545. return;
  1546. }
  1547. // Get click coordinates
  1548. let w = target.width;
  1549. let h = target.height;
  1550. let ratioW = 1, ratioH = 1;
  1551. // Limit the size of the canvas so that very large images don't cause problems)
  1552. if (w > 1000) {
  1553. ratioW = w / 1000;
  1554. w /= ratioW;
  1555. h /= ratioW;
  1556. }
  1557. if (h > 1000) {
  1558. ratioH = h / 1000;
  1559. w /= ratioH;
  1560. h /= ratioH;
  1561. }
  1562. // todo remove some of this unused stuff
  1563. const ratio = ratioW * ratioH;
  1564. const entity = entities[target.parentElement.dataset.key];
  1565. const angle = entity.rotation;
  1566. var x = event.clientX - target.getBoundingClientRect().x,
  1567. y = event.clientY - target.getBoundingClientRect().y,
  1568. alpha;
  1569. [xTarget,yTarget] = [x,y];
  1570. [actualW, actualH] = [target.getBoundingClientRect().width, target.getBoundingClientRect().height];
  1571. xTarget /= ratio;
  1572. yTarget /= ratio;
  1573. actualW /= ratio;
  1574. actualH /= ratio;
  1575. testCtx.canvas.width = actualW;
  1576. testCtx.canvas.height = actualH;
  1577. testCtx.save();
  1578. // dear future me: Sorry :(
  1579. testCtx.resetTransform();
  1580. testCtx.translate(actualW/2, actualH/2);
  1581. testCtx.rotate(angle);
  1582. testCtx.translate(-actualW/2, -actualH/2);
  1583. testCtx.drawImage(target, (actualW/2 - w/2), (actualH/2 - h/2), w, h);
  1584. testCtx.fillStyle = "red";
  1585. testCtx.fillRect(actualW/2,actualH/2,10,10);
  1586. testCtx.restore();
  1587. testCtx.fillStyle = "red";
  1588. alpha = testCtx.getImageData(xTarget, yTarget, 1, 1).data[3];
  1589. testCtx.fillRect(xTarget, yTarget, 3, 3);
  1590. // If the pixel is transparent,
  1591. // retrieve the element underneath and trigger its click event
  1592. if (alpha === 0) {
  1593. const oldDisplay = target.style.display;
  1594. target.style.display = "none";
  1595. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  1596. newTarget.dispatchEvent(new MouseEvent(event.type, {
  1597. "clientX": event.clientX,
  1598. "clientY": event.clientY
  1599. }));
  1600. target.style.display = oldDisplay;
  1601. } else {
  1602. clickDown(target.parentElement, event.clientX, event.clientY);
  1603. }
  1604. testCtx.restore();
  1605. }
  1606. function arrangeEntities(order) {
  1607. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1608. let sum = 0;
  1609. order.forEach(key => {
  1610. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1611. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1612. let height = image.height;
  1613. let width = image.width;
  1614. if (height == 0) {
  1615. height = 100;
  1616. }
  1617. if (width == 0) {
  1618. width = height;
  1619. }
  1620. sum += meters * width / height;
  1621. });
  1622. let x = config.x - sum / 2;
  1623. order.forEach(key => {
  1624. const image = document.querySelector("#entity-" + key + " > .entity-image");
  1625. const meters = entities[key].views[entities[key].view].height.toNumber("meters");
  1626. let height = image.height;
  1627. let width = image.width;
  1628. if (height == 0) {
  1629. height = 100;
  1630. }
  1631. if (width == 0) {
  1632. width = height;
  1633. }
  1634. x += meters * width / height / 2;
  1635. document.querySelector("#entity-" + key).dataset.x = x;
  1636. document.querySelector("#entity-" + key).dataset.y = config.y;
  1637. x += meters * width / height / 2;
  1638. })
  1639. fitWorld();
  1640. updateSizes();
  1641. }
  1642. function removeAllEntities() {
  1643. Object.keys(entities).forEach(key => {
  1644. removeEntity(document.querySelector("#entity-" + key));
  1645. });
  1646. }
  1647. function clearAttribution() {
  1648. document.querySelector("#attribution-category-header").style.display = "none";
  1649. document.querySelector("#options-attribution").style.display = "none";
  1650. }
  1651. function displayAttribution(file) {
  1652. document.querySelector("#attribution-category-header").style.display = "block";
  1653. document.querySelector("#options-attribution").style.display = "inline";
  1654. const authors = authorsOfFull(file);
  1655. const owners = ownersOfFull(file);
  1656. const citations = citationsOf(file);
  1657. const source = sourceOf(file);
  1658. const authorHolder = document.querySelector("#options-attribution-authors");
  1659. const ownerHolder = document.querySelector("#options-attribution-owners");
  1660. const citationHolder = document.querySelector("#options-attribution-citations");
  1661. const sourceHolder = document.querySelector("#options-attribution-source");
  1662. if (authors === []) {
  1663. const div = document.createElement("div");
  1664. div.innerText = "Unknown";
  1665. authorHolder.innerHTML = "";
  1666. authorHolder.appendChild(div);
  1667. } else if (authors === undefined) {
  1668. const div = document.createElement("div");
  1669. div.innerText = "Not yet entered";
  1670. authorHolder.innerHTML = "";
  1671. authorHolder.appendChild(div);
  1672. } else {
  1673. authorHolder.innerHTML = "";
  1674. const list = document.createElement("ul");
  1675. authorHolder.appendChild(list);
  1676. authors.forEach(author => {
  1677. const authorEntry = document.createElement("li");
  1678. if (author.url) {
  1679. const link = document.createElement("a");
  1680. link.href = author.url;
  1681. link.innerText = author.name;
  1682. link.rel = "noreferrer no opener";
  1683. link.target = "_blank";
  1684. authorEntry.appendChild(link);
  1685. } else {
  1686. const div = document.createElement("div");
  1687. div.innerText = author.name;
  1688. authorEntry.appendChild(div);
  1689. }
  1690. list.appendChild(authorEntry);
  1691. });
  1692. }
  1693. if (owners === []) {
  1694. const div = document.createElement("div");
  1695. div.innerText = "Unknown";
  1696. ownerHolder.innerHTML = "";
  1697. ownerHolder.appendChild(div);
  1698. } else if (owners === undefined) {
  1699. const div = document.createElement("div");
  1700. div.innerText = "Not yet entered";
  1701. ownerHolder.innerHTML = "";
  1702. ownerHolder.appendChild(div);
  1703. } else {
  1704. ownerHolder.innerHTML = "";
  1705. const list = document.createElement("ul");
  1706. ownerHolder.appendChild(list);
  1707. owners.forEach(owner => {
  1708. const ownerEntry = document.createElement("li");
  1709. if (owner.url) {
  1710. const link = document.createElement("a");
  1711. link.href = owner.url;
  1712. link.innerText = owner.name;
  1713. link.rel = "noreferrer no opener";
  1714. link.target = "_blank";
  1715. ownerEntry.appendChild(link);
  1716. } else {
  1717. const div = document.createElement("div");
  1718. div.innerText = owner.name;
  1719. ownerEntry.appendChild(div);
  1720. }
  1721. list.appendChild(ownerEntry);
  1722. });
  1723. }
  1724. if (citations === [] || citations === undefined) {
  1725. } else {
  1726. citationHolder.innerHTML = "";
  1727. const list = document.createElement("ul");
  1728. citationHolder.appendChild(list);
  1729. citations.forEach(citation => {
  1730. const citationEntry = document.createElement("li");
  1731. const link = document.createElement("a");
  1732. link.style.display = "block";
  1733. link.href = citation;
  1734. link.innerText = new URL(citation).host;
  1735. link.rel = "noreferrer no opener";
  1736. link.target = "_blank";
  1737. citationEntry.appendChild(link);
  1738. list.appendChild(citationEntry);
  1739. })
  1740. }
  1741. if (source === null) {
  1742. const div = document.createElement("div");
  1743. div.innerText = "No link";
  1744. sourceHolder.innerHTML = "";
  1745. sourceHolder.appendChild(div);
  1746. } else if (source === undefined) {
  1747. const div = document.createElement("div");
  1748. div.innerText = "Not yet entered";
  1749. sourceHolder.innerHTML = "";
  1750. sourceHolder.appendChild(div);
  1751. } else {
  1752. sourceHolder.innerHTML = "";
  1753. const link = document.createElement("a");
  1754. link.style.display = "block";
  1755. link.href = source;
  1756. link.innerText = new URL(source).host;
  1757. link.rel = "noreferrer no opener";
  1758. link.target = "_blank";
  1759. sourceHolder.appendChild(link);
  1760. }
  1761. }
  1762. function removeEntity(element) {
  1763. if (selected == element) {
  1764. deselect();
  1765. }
  1766. if (clicked == element) {
  1767. clicked = null;
  1768. }
  1769. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  1770. option.parentElement.removeChild(option);
  1771. delete entities[element.dataset.key];
  1772. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  1773. const topName = document.querySelector("#top-name-" + element.dataset.key);
  1774. bottomName.parentElement.removeChild(bottomName);
  1775. topName.parentElement.removeChild(topName);
  1776. element.parentElement.removeChild(element);
  1777. }
  1778. function checkEntity(entity) {
  1779. Object.values(entity.views).forEach(view => {
  1780. if (authorsOf(view.image.source) === undefined) {
  1781. console.warn("No authors: " + view.image.source);
  1782. }
  1783. });
  1784. }
  1785. function preloadViews(entity) {
  1786. Object.values(entity.views).forEach(view => {
  1787. if (Object.keys(entity.forms).length > 0) {
  1788. if (entity.form !== view.form){
  1789. return;
  1790. }
  1791. }
  1792. if (!preloaded.has(view.image.source)) {
  1793. let img = new Image();
  1794. img.src = view.image.source;
  1795. preloaded.add(view.image.source);
  1796. }
  1797. });
  1798. }
  1799. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  1800. checkEntity(entity);
  1801. // preload all of the entity's views
  1802. preloadViews(entity);
  1803. const box = document.createElement("div");
  1804. box.classList.add("entity-box");
  1805. const img = document.createElement("img");
  1806. img.classList.add("entity-image");
  1807. img.addEventListener("dragstart", e => {
  1808. e.preventDefault();
  1809. });
  1810. const nameTag = document.createElement("div");
  1811. nameTag.classList.add("entity-name");
  1812. nameTag.innerText = entity.name;
  1813. box.appendChild(img);
  1814. box.appendChild(nameTag);
  1815. const image = entity.views[view].image;
  1816. img.src = image.source;
  1817. if (image.bottom !== undefined) {
  1818. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1819. } else {
  1820. img.style.setProperty("--offset", ((-1) * 100) + "%")
  1821. }
  1822. img.style.setProperty("--rotation", (entity.rotation * 180 / Math.PI) + "deg")
  1823. box.dataset.x = x;
  1824. box.dataset.y = y;
  1825. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  1826. img.addEventListener("touchstart", e => {
  1827. const fakeEvent = {
  1828. target: e.target,
  1829. clientX: e.touches[0].clientX,
  1830. clientY: e.touches[0].clientY,
  1831. which: 1
  1832. };
  1833. testClick(fakeEvent);
  1834. if (clicked) { e.stopPropagation() }
  1835. });
  1836. const heightBar = document.createElement("div");
  1837. heightBar.classList.add("height-bar");
  1838. box.appendChild(heightBar);
  1839. box.id = "entity-" + entityIndex;
  1840. box.dataset.key = entityIndex;
  1841. entity.view = view;
  1842. if (entity.priority === undefined)
  1843. entity.priority = 0;
  1844. if (entity.brightness === undefined)
  1845. entity.brightness = 1;
  1846. entities[entityIndex] = entity;
  1847. entity.index = entityIndex;
  1848. const world = document.querySelector("#entities");
  1849. world.appendChild(box);
  1850. const bottomName = document.createElement("div");
  1851. bottomName.classList.add("bottom-name");
  1852. bottomName.id = "bottom-name-" + entityIndex;
  1853. bottomName.innerText = entity.name;
  1854. bottomName.addEventListener("click", () => select(box));
  1855. world.appendChild(bottomName);
  1856. const topName = document.createElement("div");
  1857. topName.classList.add("top-name");
  1858. topName.id = "top-name-" + entityIndex;
  1859. topName.innerText = entity.name;
  1860. topName.addEventListener("click", () => select(box));
  1861. world.appendChild(topName);
  1862. const entityOption = document.createElement("option");
  1863. entityOption.id = "options-selected-entity-" + entityIndex;
  1864. entityOption.value = entityIndex;
  1865. entityOption.innerText = entity.name;
  1866. document.getElementById("options-selected-entity").appendChild(entityOption);
  1867. entityIndex += 1;
  1868. if (config.autoFit) {
  1869. fitWorld();
  1870. }
  1871. if (selectEntity)
  1872. select(box);
  1873. entity.dirty = true;
  1874. if (refresh && config.autoFitAdd) {
  1875. let targets = {};
  1876. targets[entityIndex - 1] = entity;
  1877. fitEntities(targets);
  1878. }
  1879. if (refresh)
  1880. updateSizes(true);
  1881. }
  1882. window.onblur = function () {
  1883. altHeld = false;
  1884. shiftHeld = false;
  1885. }
  1886. window.onfocus = function () {
  1887. window.dispatchEvent(new Event("keydown"));
  1888. }
  1889. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1890. function toggleFullScreen() {
  1891. var doc = window.document;
  1892. var docEl = doc.documentElement;
  1893. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1894. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1895. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1896. requestFullScreen.call(docEl);
  1897. }
  1898. else {
  1899. cancelFullScreen.call(doc);
  1900. }
  1901. }
  1902. function handleResize() {
  1903. const oldCanvasWidth = canvasWidth;
  1904. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1905. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1906. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1907. const change = oldCanvasWidth / canvasWidth;
  1908. updateSizes();
  1909. }
  1910. function prepareSidebar() {
  1911. const menubar = document.querySelector("#sidebar-menu");
  1912. [
  1913. {
  1914. name: "Show/hide sidebar",
  1915. id: "menu-toggle-sidebar",
  1916. icon: "fas fa-chevron-circle-down",
  1917. rotates: true
  1918. },
  1919. {
  1920. name: "Fullscreen",
  1921. id: "menu-fullscreen",
  1922. icon: "fas fa-compress"
  1923. },
  1924. {
  1925. name: "Clear",
  1926. id: "menu-clear",
  1927. icon: "fas fa-file"
  1928. },
  1929. {
  1930. name: "Sort by height",
  1931. id: "menu-order-height",
  1932. icon: "fas fa-sort-numeric-up"
  1933. },
  1934. {
  1935. name: "Permalink",
  1936. id: "menu-permalink",
  1937. icon: "fas fa-link"
  1938. },
  1939. {
  1940. name: "Export to clipboard",
  1941. id: "menu-export",
  1942. icon: "fas fa-share"
  1943. },
  1944. {
  1945. name: "Import from clipboard",
  1946. id: "menu-import",
  1947. icon: "fas fa-share",
  1948. classes: ["flipped"]
  1949. },
  1950. {
  1951. name: "Save Scene",
  1952. id: "menu-save",
  1953. icon: "fas fa-download",
  1954. input: true
  1955. },
  1956. {
  1957. name: "Load Scene",
  1958. id: "menu-load",
  1959. icon: "fas fa-upload",
  1960. select: true
  1961. },
  1962. {
  1963. name: "Delete Scene",
  1964. id: "menu-delete",
  1965. icon: "fas fa-trash",
  1966. select: true
  1967. },
  1968. {
  1969. name: "Load Autosave",
  1970. id: "menu-load-autosave",
  1971. icon: "fas fa-redo"
  1972. },
  1973. {
  1974. name: "Add Image",
  1975. id: "menu-add-image",
  1976. icon: "fas fa-camera"
  1977. },
  1978. {
  1979. name: "Clear Rulers",
  1980. id: "menu-clear-rulers",
  1981. icon: "fas fa-ruler"
  1982. }
  1983. ].forEach(entry => {
  1984. const buttonHolder = document.createElement("div");
  1985. buttonHolder.classList.add("menu-button-holder");
  1986. const button = document.createElement("button");
  1987. button.id = entry.id;
  1988. button.classList.add("menu-button");
  1989. const icon = document.createElement("i");
  1990. icon.classList.add(...entry.icon.split(" "));
  1991. if (entry.rotates) {
  1992. icon.classList.add("rotate-backward", "transitions");
  1993. }
  1994. if (entry.classes) {
  1995. entry.classes.forEach(cls => icon.classList.add(cls));
  1996. }
  1997. const actionText = document.createElement("span");
  1998. actionText.innerText = entry.name;
  1999. actionText.classList.add("menu-text");
  2000. const srText = document.createElement("span");
  2001. srText.classList.add("sr-only");
  2002. srText.innerText = entry.name;
  2003. button.appendChild(icon);
  2004. button.appendChild(srText);
  2005. buttonHolder.appendChild(button);
  2006. buttonHolder.appendChild(actionText);
  2007. if (entry.input) {
  2008. const input = document.createElement("input");
  2009. buttonHolder.appendChild(input);
  2010. input.placeholder = "default";
  2011. input.addEventListener("keyup", e => {
  2012. if (e.key === "Enter") {
  2013. const name = document.querySelector("#menu-save ~ input").value;
  2014. if (/\S/.test(name)) {
  2015. saveScene(name);
  2016. }
  2017. updateSaveInfo();
  2018. e.preventDefault();
  2019. }
  2020. })
  2021. }
  2022. if (entry.select) {
  2023. const select = document.createElement("select");
  2024. buttonHolder.appendChild(select);
  2025. }
  2026. menubar.appendChild(buttonHolder);
  2027. });
  2028. }
  2029. function checkBodyClass(cls) {
  2030. return document.body.classList.contains(cls);
  2031. }
  2032. function toggleBodyClass(cls, setting) {
  2033. if (setting) {
  2034. document.body.classList.add(cls);
  2035. } else {
  2036. document.body.classList.remove(cls);
  2037. }
  2038. }
  2039. const settingsData = {
  2040. "show-vertical-scale": {
  2041. name: "Vertical Scale",
  2042. desc: "Draw vertical scale marks",
  2043. type: "toggle",
  2044. default: true,
  2045. get value() {
  2046. return config.drawYAxis;
  2047. },
  2048. set value(param) {
  2049. config.drawYAxis = param;
  2050. drawScales(false);
  2051. }
  2052. },
  2053. "show-horizontal-scale": {
  2054. name: "Horiziontal Scale",
  2055. desc: "Draw horizontal scale marks",
  2056. type: "toggle",
  2057. default: false,
  2058. get value() {
  2059. return config.drawXAxis;
  2060. },
  2061. set value(param) {
  2062. config.drawXAxis = param;
  2063. drawScales(false);
  2064. }
  2065. },
  2066. "show-altitudes": {
  2067. name: "Altitudes",
  2068. desc: "Draw interesting altitudes",
  2069. type: "select",
  2070. default: "none",
  2071. options: [
  2072. "none",
  2073. "all",
  2074. "atmosphere",
  2075. "orbits",
  2076. "weather",
  2077. "water",
  2078. "geology",
  2079. "thicknesses",
  2080. "airspaces",
  2081. "races",
  2082. "olympic-records",
  2083. ],
  2084. get value() {
  2085. return config.drawAltitudes;
  2086. },
  2087. set value(param) {
  2088. config.drawAltitudes = param;
  2089. drawScales(false);
  2090. }
  2091. },
  2092. "lock-y-axis": {
  2093. name: "Lock Y-Axis",
  2094. desc: "Keep the camera at ground-level",
  2095. type: "toggle",
  2096. default: true,
  2097. get value() {
  2098. return config.lockYAxis;
  2099. },
  2100. set value(param) {
  2101. config.lockYAxis = param;
  2102. if (param) {
  2103. config.y = 0;
  2104. updateSizes();
  2105. document.querySelector("#scroll-up").disabled = true;
  2106. document.querySelector("#scroll-down").disabled = true;
  2107. } else {
  2108. document.querySelector("#scroll-up").disabled = false;
  2109. document.querySelector("#scroll-down").disabled = false;
  2110. }
  2111. }
  2112. },
  2113. "axis-spacing": {
  2114. name: "Axis Spacing",
  2115. desc: "How frequent the axis lines are",
  2116. type: "select",
  2117. default: "standard",
  2118. options: [
  2119. "dense",
  2120. "standard",
  2121. "sparse"
  2122. ],
  2123. get value() {
  2124. return config.axisSpacing;
  2125. },
  2126. set value(param) {
  2127. config.axisSpacing = param;
  2128. const factor = {
  2129. "dense": 0.5,
  2130. "standard": 1,
  2131. "sparse": 2
  2132. }[param];
  2133. config.minLineSize = factor * 100;
  2134. config.maxLineSize = factor * 150;
  2135. updateSizes();
  2136. }
  2137. },
  2138. "solid-ground": {
  2139. name: "Ground",
  2140. desc: "Draw solid ground at the y=0 line",
  2141. type: "toggle",
  2142. default: true,
  2143. get value() {
  2144. return checkBodyClass("toggle-bottom-cover");
  2145. },
  2146. set value(param) {
  2147. toggleBodyClass("toggle-bottom-cover", param);
  2148. }
  2149. },
  2150. "ground-pos": {
  2151. name: "Ground Position",
  2152. desc: "How high the ground is if the y-axis is locked",
  2153. type: "select",
  2154. default: "bottom",
  2155. options: [
  2156. "very-high",
  2157. "high",
  2158. "medium",
  2159. "low",
  2160. "very-low",
  2161. "bottom",
  2162. ],
  2163. get value() {
  2164. return config.groundPos;
  2165. },
  2166. set value(param) {
  2167. config.groundPos = param;
  2168. updateSizes();
  2169. }
  2170. },
  2171. "auto-scale": {
  2172. name: "Auto-Size World",
  2173. desc: "Constantly zoom to fit the largest entity",
  2174. type: "toggle",
  2175. default: false,
  2176. get value() {
  2177. return config.autoFit;
  2178. },
  2179. set value(param) {
  2180. config.autoFit = param;
  2181. checkFitWorld();
  2182. }
  2183. },
  2184. "auto-units": {
  2185. name: "Auto-Select Units",
  2186. desc: "Automatically switch units when zooming in and out",
  2187. type: "toggle",
  2188. default: false,
  2189. get value() {
  2190. return config.autoUnits;
  2191. },
  2192. set value(param) {
  2193. config.autoUnits = param;
  2194. }
  2195. },
  2196. "zoom-when-adding": {
  2197. name: "Zoom On Add",
  2198. desc: "Zoom to fit when you add a new entity",
  2199. type: "toggle",
  2200. default: true,
  2201. get value() {
  2202. return config.autoFitAdd;
  2203. },
  2204. set value(param) {
  2205. config.autoFitAdd = param;
  2206. }
  2207. },
  2208. "zoom-when-sizing": {
  2209. name: "Zoom On Size",
  2210. desc: "Zoom to fit when you select an entity's size",
  2211. type: "toggle",
  2212. default: true,
  2213. get value() {
  2214. return config.autoFitSize;
  2215. },
  2216. set value(param) {
  2217. config.autoFitSize = param;
  2218. }
  2219. },
  2220. "show-ratios": {
  2221. name: "Show Ratios",
  2222. desc: "Show the proportions between the current selection and the most recent selection.",
  2223. type: "toggle",
  2224. default: true,
  2225. get value() {
  2226. return config.showRatios;
  2227. },
  2228. set value(param) {
  2229. config.showRatios = param;
  2230. if (param) {
  2231. document.body.querySelector(".ratio-info").style.display = "block";
  2232. } else {
  2233. document.body.querySelector(".ratio-info").style.display = "none";
  2234. }
  2235. }
  2236. },
  2237. "units": {
  2238. name: "Default Units",
  2239. desc: "Which kind of unit to use by default",
  2240. type: "select",
  2241. default: "metric",
  2242. options: [
  2243. "metric",
  2244. "customary",
  2245. "relative",
  2246. "quirky"
  2247. ],
  2248. get value() {
  2249. return config.units;
  2250. },
  2251. set value(param) {
  2252. config.units = param;
  2253. updateSizes();
  2254. }
  2255. },
  2256. "names": {
  2257. name: "Show Names",
  2258. desc: "Display names over entities",
  2259. type: "toggle",
  2260. default: true,
  2261. get value() {
  2262. return checkBodyClass("toggle-entity-name");
  2263. },
  2264. set value(param) {
  2265. toggleBodyClass("toggle-entity-name", param);
  2266. }
  2267. },
  2268. "bottom-names": {
  2269. name: "Bottom Names",
  2270. desc: "Display names at the bottom",
  2271. type: "toggle",
  2272. default: false,
  2273. get value() {
  2274. return checkBodyClass("toggle-bottom-name");
  2275. },
  2276. set value(param) {
  2277. toggleBodyClass("toggle-bottom-name", param);
  2278. }
  2279. },
  2280. "top-names": {
  2281. name: "Show Arrows",
  2282. desc: "Point to entities that are much larger than the current view",
  2283. type: "toggle",
  2284. default: false,
  2285. get value() {
  2286. return checkBodyClass("toggle-top-name");
  2287. },
  2288. set value(param) {
  2289. toggleBodyClass("toggle-top-name", param);
  2290. }
  2291. },
  2292. "height-bars": {
  2293. name: "Height Bars",
  2294. desc: "Draw dashed lines to the top of each entity",
  2295. type: "toggle",
  2296. default: false,
  2297. get value() {
  2298. return checkBodyClass("toggle-height-bars");
  2299. },
  2300. set value(param) {
  2301. toggleBodyClass("toggle-height-bars", param);
  2302. }
  2303. },
  2304. "glowing-entities": {
  2305. name: "Glowing Edges",
  2306. desc: "Makes all entities glow",
  2307. type: "toggle",
  2308. default: false,
  2309. get value() {
  2310. return checkBodyClass("toggle-entity-glow");
  2311. },
  2312. set value(param) {
  2313. toggleBodyClass("toggle-entity-glow", param);
  2314. }
  2315. },
  2316. "background-brightness": {
  2317. name: "Background Brightness",
  2318. desc: "How bright the background is",
  2319. type: "select",
  2320. default: "medium",
  2321. options: [
  2322. "black",
  2323. "dark",
  2324. "medium",
  2325. "light",
  2326. ],
  2327. get value() {
  2328. return config.background;
  2329. },
  2330. set value(param) {
  2331. config.background = param;
  2332. drawScales();
  2333. }
  2334. },
  2335. "smoothing": {
  2336. name: "Smoothing",
  2337. desc: "Smooth out movements and size changes. Disable for better performance.",
  2338. type: "toggle",
  2339. default: true,
  2340. get value() {
  2341. return checkBodyClass("smoothing");
  2342. },
  2343. set value(param) {
  2344. toggleBodyClass("smoothing", param);
  2345. }
  2346. },
  2347. "auto-food-intake": {
  2348. name: "Estimate Food Intake",
  2349. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  2350. type: "toggle",
  2351. default: false,
  2352. get value() {
  2353. return config.autoFoodIntake
  2354. },
  2355. set value(param) {
  2356. config.autoFoodIntake = param
  2357. }
  2358. },
  2359. "auto-caloric-value": {
  2360. name: "Estimate Caloric Value",
  2361. desc: "Guess how much food a creature is worth -- 860kcal per pound",
  2362. type: "toggle",
  2363. default: false,
  2364. get value() {
  2365. return config.autoCaloricValue
  2366. },
  2367. set value(param) {
  2368. config.autoCaloricValue = param
  2369. }
  2370. },
  2371. "auto-prey-capacity": {
  2372. name: "Estimate Prey Capacity",
  2373. desc: "Guess how much prey creatures can hold, based on their mass",
  2374. type: "select",
  2375. default: "none",
  2376. options: [
  2377. "none",
  2378. "realistic",
  2379. "same-size"
  2380. ],
  2381. get value() {
  2382. return config.autoPreyCapacity;
  2383. },
  2384. set value(param) {
  2385. config.autoPreyCapacity = param;
  2386. }
  2387. },
  2388. }
  2389. function getBoundingBox(entities, margin = 0.05) {
  2390. }
  2391. function prepareSettings(userSettings) {
  2392. const menubar = document.querySelector("#settings-menu");
  2393. Object.entries(settingsData).forEach(([id, entry]) => {
  2394. const holder = document.createElement("label");
  2395. holder.classList.add("settings-holder");
  2396. const input = document.createElement("input");
  2397. input.id = "setting-" + id;
  2398. const vertical = document.createElement("div");
  2399. vertical.classList.add("settings-vertical");
  2400. const name = document.createElement("label");
  2401. name.innerText = entry.name;
  2402. name.classList.add("settings-name");
  2403. name.setAttribute("for", input.id);
  2404. const desc = document.createElement("label");
  2405. desc.innerText = entry.desc;
  2406. desc.classList.add("settings-desc");
  2407. desc.setAttribute("for", input.id);
  2408. if (entry.type == "toggle") {
  2409. input.type = "checkbox";
  2410. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  2411. holder.setAttribute("for", input.id);
  2412. vertical.appendChild(name);
  2413. vertical.appendChild(desc);
  2414. holder.appendChild(vertical);
  2415. holder.appendChild(input);
  2416. menubar.appendChild(holder);
  2417. const update = () => {
  2418. if (input.checked) {
  2419. holder.classList.add("enabled");
  2420. holder.classList.remove("disabled");
  2421. } else {
  2422. holder.classList.remove("enabled");
  2423. holder.classList.add("disabled");
  2424. }
  2425. entry.value = input.checked;
  2426. }
  2427. update();
  2428. input.addEventListener("change", update);
  2429. } else if (entry.type == "select") {
  2430. // we don't use the input element we made!
  2431. const select = document.createElement("select");
  2432. select.id = "setting-" + id;
  2433. entry.options.forEach(choice => {
  2434. const option = document.createElement("option");
  2435. option.innerText = choice;
  2436. select.appendChild(option);
  2437. })
  2438. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  2439. vertical.appendChild(name);
  2440. vertical.appendChild(desc);
  2441. holder.appendChild(vertical);
  2442. holder.appendChild(select);
  2443. menubar.appendChild(holder);
  2444. holder.classList.add("enabled");
  2445. const update = () => {
  2446. entry.value = select.value;
  2447. }
  2448. update();
  2449. select.addEventListener("change", update);
  2450. }
  2451. })
  2452. }
  2453. function prepareMenu() {
  2454. prepareSidebar();
  2455. updateSaveInfo();
  2456. if (checkHelpDate()) {
  2457. document.querySelector("#open-help").classList.add("highlighted");
  2458. }
  2459. }
  2460. function updateSaveInfo() {
  2461. const saves = getSaves();
  2462. const load = document.querySelector("#menu-load ~ select");
  2463. load.innerHTML = "";
  2464. saves.forEach(save => {
  2465. const option = document.createElement("option");
  2466. option.innerText = save;
  2467. option.value = save;
  2468. load.appendChild(option);
  2469. });
  2470. const del = document.querySelector("#menu-delete ~ select");
  2471. del.innerHTML = "";
  2472. saves.forEach(save => {
  2473. const option = document.createElement("option");
  2474. option.innerText = save;
  2475. option.value = save;
  2476. del.appendChild(option);
  2477. });
  2478. }
  2479. function getSaves() {
  2480. try {
  2481. const results = [];
  2482. Object.keys(localStorage).forEach(key => {
  2483. if (key.startsWith("macrovision-save-")) {
  2484. results.push(key.replace("macrovision-save-", ""));
  2485. }
  2486. })
  2487. return results;
  2488. } catch (err) {
  2489. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2490. console.error(err);
  2491. return false;
  2492. }
  2493. }
  2494. function getUserSettings() {
  2495. try {
  2496. const settings = JSON.parse(localStorage.getItem("settings"));
  2497. return settings === null ? {} : settings;
  2498. } catch {
  2499. return {};
  2500. }
  2501. }
  2502. function exportUserSettings() {
  2503. const settings = {};
  2504. Object.entries(settingsData).forEach(([id, entry]) => {
  2505. settings[id] = entry.value;
  2506. });
  2507. return settings;
  2508. }
  2509. function setUserSettings(settings) {
  2510. try {
  2511. localStorage.setItem("settings", JSON.stringify(settings));
  2512. } catch {
  2513. // :(
  2514. }
  2515. }
  2516. const lastHelpChange = 1601955834693;
  2517. function checkHelpDate() {
  2518. // disabling this for now
  2519. return false;
  2520. try {
  2521. const old = localStorage.getItem("help-viewed");
  2522. if (old === null || old < lastHelpChange) {
  2523. return true;
  2524. }
  2525. return false;
  2526. } catch {
  2527. console.warn("Could not set the help-viewed date");
  2528. return false;
  2529. }
  2530. }
  2531. function setHelpDate() {
  2532. try {
  2533. localStorage.setItem("help-viewed", Date.now());
  2534. } catch {
  2535. console.warn("Could not set the help-viewed date");
  2536. }
  2537. }
  2538. function doYScroll() {
  2539. const worldHeight = config.height.toNumber("meters");
  2540. config.y += scrollDirection * worldHeight / 180;
  2541. updateSizes();
  2542. scrollDirection *= 1.05;
  2543. }
  2544. function doXScroll() {
  2545. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2546. config.x += scrollDirection * worldWidth / 180 ;
  2547. updateSizes();
  2548. scrollDirection *= 1.05;
  2549. }
  2550. function doZoom() {
  2551. const oldHeight = config.height;
  2552. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  2553. zoomDirection *= 1.05;
  2554. }
  2555. function doSize() {
  2556. if (selected) {
  2557. const entity = entities[selected.dataset.key];
  2558. const oldHeight = entity.views[entity.view].height;
  2559. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  2560. entity.dirty = true;
  2561. updateEntityOptions(entity, entity.view);
  2562. updateViewOptions(entity, entity.view);
  2563. updateSizes(true);
  2564. sizeDirection *= 1.01;
  2565. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  2566. let extra = entity.views[entity.view].image.extra;
  2567. extra = extra === undefined ? 1 : extra;
  2568. const worldHeight = config.height.toNumber("meters");
  2569. if (ownHeight * extra > worldHeight) {
  2570. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra));
  2571. } else if (ownHeight * extra * 10 < worldHeight) {
  2572. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra * 10));
  2573. }
  2574. }
  2575. }
  2576. function selectNewUnit() {
  2577. const unitSelector = document.querySelector("#options-height-unit");
  2578. checkFitWorld();
  2579. const scaleInput = document.querySelector("#options-height-value");
  2580. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(unitSelector.value);
  2581. setNumericInput(scaleInput, newVal);
  2582. updateWorldHeight();
  2583. unitSelector.dataset.oldUnit = unitSelector.value;
  2584. }
  2585. document.addEventListener("DOMContentLoaded", () => {
  2586. prepareMenu();
  2587. prepareEntities();
  2588. document.querySelector("#open-help").addEventListener("click", e => {
  2589. setHelpDate();
  2590. document.querySelector("#open-help").classList.remove("highlighted");
  2591. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  2592. });
  2593. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  2594. copyScreenshot();
  2595. toast("Copied to clipboard!");
  2596. });
  2597. document.querySelector("#save-screenshot").addEventListener("click", e => {
  2598. saveScreenshot();
  2599. });
  2600. document.querySelector("#open-screenshot").addEventListener("click", e => {
  2601. openScreenshot();
  2602. });
  2603. document.querySelector("#toggle-menu").addEventListener("click", e => {
  2604. const popoutMenu = document.querySelector("#sidebar-menu");
  2605. if (popoutMenu.classList.contains("visible")) {
  2606. popoutMenu.classList.remove("visible");
  2607. } else {
  2608. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2609. const rect = e.target.getBoundingClientRect();
  2610. popoutMenu.classList.add("visible");
  2611. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2612. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2613. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2614. let screenWidth = window.innerWidth;
  2615. if (menuWidth * 1.5 > screenWidth) {
  2616. popoutMenu.style.left = 25 + "px";
  2617. }
  2618. }
  2619. e.stopPropagation();
  2620. });
  2621. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  2622. e.stopPropagation();
  2623. });
  2624. document.addEventListener("click", e => {
  2625. document.querySelector("#sidebar-menu").classList.remove("visible");
  2626. });
  2627. document.querySelector("#toggle-settings").addEventListener("click", e => {
  2628. const popoutMenu = document.querySelector("#settings-menu");
  2629. if (popoutMenu.classList.contains("visible")) {
  2630. popoutMenu.classList.remove("visible");
  2631. } else {
  2632. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2633. const rect = e.target.getBoundingClientRect();
  2634. popoutMenu.classList.add("visible");
  2635. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2636. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2637. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2638. let screenWidth = window.innerWidth;
  2639. if (menuWidth * 1.5 > screenWidth) {
  2640. popoutMenu.style.left = 25 + "px";
  2641. }
  2642. }
  2643. e.stopPropagation();
  2644. });
  2645. document.querySelector("#settings-menu").addEventListener("click", e => {
  2646. e.stopPropagation();
  2647. });
  2648. document.addEventListener("click", e => {
  2649. document.querySelector("#settings-menu").classList.remove("visible");
  2650. });
  2651. window.addEventListener("unload", () => {
  2652. saveScene("autosave");
  2653. setUserSettings(exportUserSettings());
  2654. });
  2655. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  2656. if (e.target.value == "None") {
  2657. deselect()
  2658. } else {
  2659. select(document.querySelector("#entity-" + e.target.value));
  2660. }
  2661. });
  2662. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  2663. const sidebar = document.querySelector("#options");
  2664. if (sidebar.classList.contains("hidden")) {
  2665. sidebar.classList.remove("hidden");
  2666. e.target.classList.remove("rotate-forward");
  2667. e.target.classList.add("rotate-backward");
  2668. } else {
  2669. sidebar.classList.add("hidden");
  2670. e.target.classList.add("rotate-forward");
  2671. e.target.classList.remove("rotate-backward");
  2672. }
  2673. handleResize();
  2674. });
  2675. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2676. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2677. if (selected) {
  2678. entities[selected.dataset.key].priority += 1;
  2679. }
  2680. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2681. updateSizes();
  2682. });
  2683. document.querySelector("#options-order-back").addEventListener("click", e => {
  2684. if (selected) {
  2685. entities[selected.dataset.key].priority -= 1;
  2686. }
  2687. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2688. updateSizes();
  2689. });
  2690. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  2691. if (selected) {
  2692. entities[selected.dataset.key].brightness += 1;
  2693. }
  2694. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2695. updateSizes();
  2696. });
  2697. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  2698. if (selected) {
  2699. entities[selected.dataset.key].brightness -= 1;
  2700. }
  2701. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2702. updateSizes();
  2703. });
  2704. document.querySelector("#options-rotate-left").addEventListener("click", e => {
  2705. if (selected) {
  2706. entities[selected.dataset.key].rotation -= Math.PI/4;
  2707. }
  2708. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2709. updateSizes();
  2710. });
  2711. document.querySelector("#options-rotate-right").addEventListener("click", e => {
  2712. if (selected) {
  2713. entities[selected.dataset.key].rotation += Math.PI/4;
  2714. }
  2715. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2716. updateSizes();
  2717. });
  2718. document.querySelector("#options-flip").addEventListener("click", e => {
  2719. if (selected) {
  2720. selected.querySelector(".entity-image").classList.toggle("flipped");
  2721. }
  2722. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2723. updateSizes();
  2724. });
  2725. const sceneChoices = document.querySelector("#scene-choices");
  2726. Object.entries(scenes).forEach(([id, scene]) => {
  2727. const option = document.createElement("option");
  2728. option.innerText = id;
  2729. option.value = id;
  2730. sceneChoices.appendChild(option);
  2731. });
  2732. document.querySelector("#load-scene").addEventListener("click", e => {
  2733. const chosen = sceneChoices.value;
  2734. removeAllEntities();
  2735. scenes[chosen]();
  2736. });
  2737. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2738. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2739. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2740. document.querySelector("#options-height-value").addEventListener("change", e => {
  2741. updateWorldHeight();
  2742. })
  2743. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  2744. e.stopPropagation();
  2745. })
  2746. const unitSelector = document.querySelector("#options-height-unit");
  2747. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  2748. const optGroup = document.createElement("optgroup");
  2749. optGroup.label = group;
  2750. unitSelector.appendChild(optGroup);
  2751. entries.forEach(entry => {
  2752. const option = document.createElement("option");
  2753. option.innerText = entry;
  2754. // we haven't loaded user settings yet, so we can't choose the unit just yet
  2755. unitSelector.appendChild(option);
  2756. })
  2757. });
  2758. unitSelector.addEventListener("input", selectNewUnit);
  2759. param = window.location.hash;
  2760. // we now use the fragment for links, but we should still support old stuff:
  2761. if (param.length > 0) {
  2762. param = param.substring(1);
  2763. } else {
  2764. param = new URL(window.location.href).searchParams.get("scene");
  2765. }
  2766. document.querySelector("#world").addEventListener("mousedown", e => {
  2767. // only middle mouse clicks
  2768. if (e.which == 2) {
  2769. panning = true;
  2770. panOffsetX = e.clientX;
  2771. panOffsetY = e.clientY;
  2772. Object.keys(entities).forEach(key => {
  2773. document.querySelector("#entity-" + key).classList.add("no-transition");
  2774. });
  2775. }
  2776. });
  2777. document.addEventListener("mouseup", e => {
  2778. if (e.which == 2) {
  2779. panning = false;
  2780. Object.keys(entities).forEach(key => {
  2781. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2782. });
  2783. }
  2784. });
  2785. document.querySelector("#world").addEventListener("touchstart", e => {
  2786. if (!rulerMode) {
  2787. panning = true;
  2788. panOffsetX = e.touches[0].clientX;
  2789. panOffsetY = e.touches[0].clientY;
  2790. e.preventDefault();
  2791. Object.keys(entities).forEach(key => {
  2792. document.querySelector("#entity-" + key).classList.add("no-transition");
  2793. });
  2794. }
  2795. });
  2796. document.querySelector("#world").addEventListener("touchend", e => {
  2797. panning = false;
  2798. Object.keys(entities).forEach(key => {
  2799. document.querySelector("#entity-" + key).classList.remove("no-transition");
  2800. });
  2801. });
  2802. document.querySelector("#world").addEventListener("mousedown", e => {
  2803. // only left mouse clicks
  2804. if (e.which == 1 && rulerMode) {
  2805. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2806. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2807. const pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  2808. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y };
  2809. }
  2810. });
  2811. document.querySelector("#world").addEventListener("mouseup", e => {
  2812. // only left mouse clicks
  2813. if (e.which == 1 && currentRuler) {
  2814. rulers.push(currentRuler);
  2815. currentRuler = null;
  2816. rulerMode = false;
  2817. }
  2818. });
  2819. document.querySelector("#world").addEventListener("touchstart", e => {
  2820. if (rulerMode) {
  2821. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  2822. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  2823. const pos = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  2824. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y };
  2825. }
  2826. });
  2827. document.querySelector("#world").addEventListener("touchend", e => {
  2828. if (currentRuler) {
  2829. rulers.push(currentRuler);
  2830. currentRuler = null;
  2831. rulerMode = false;
  2832. }
  2833. });
  2834. document.querySelector("body").appendChild(testCtx.canvas);
  2835. world.addEventListener("mousedown", e => deselect(e));
  2836. world.addEventListener("touchstart", e => deselect({
  2837. which: 1,
  2838. }));
  2839. document.querySelector("#entities").addEventListener("mousedown", deselect);
  2840. document.querySelector("#display").addEventListener("mousedown", deselect);
  2841. document.addEventListener("mouseup", e => clickUp(e));
  2842. document.addEventListener("touchend", e => {
  2843. const fakeEvent = {
  2844. target: e.target,
  2845. clientX: e.changedTouches[0].clientX,
  2846. clientY: e.changedTouches[0].clientY,
  2847. which: 1
  2848. };
  2849. clickUp(fakeEvent);
  2850. });
  2851. const formList = document.querySelector("#entity-form");
  2852. formList.addEventListener("input", e => {
  2853. const entity = entities[selected.dataset.key];
  2854. entity.form = e.target.value;
  2855. entity.view = entity.formViews[entity.form];
  2856. if (Object.keys(entity.form).length > 0)
  2857. entity.views[entity.view].height = entity.formSizes[entity.form].height;
  2858. preloadViews(entity);
  2859. configViewList(entity, entity.view);
  2860. const image = entity.views[entity.view].image;
  2861. selected.querySelector(".entity-image").src = image.source;
  2862. configViewOptions(entity, entity.view);
  2863. displayAttribution(image.source);
  2864. if (image.bottom !== undefined) {
  2865. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  2866. } else {
  2867. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  2868. }
  2869. if (config.autoFitSize) {
  2870. let targets = {};
  2871. targets[selected.dataset.key] = entities[selected.dataset.key];
  2872. fitEntities(targets);
  2873. }
  2874. configSizeList(entity);
  2875. updateSizes();
  2876. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  2877. updateViewOptions(entities[selected.dataset.key], entity.view);
  2878. });
  2879. const viewList = document.querySelector("#entity-view");
  2880. document.querySelector("#entity-view").addEventListener("input", e => {
  2881. const entity = entities[selected.dataset.key];
  2882. entity.view = e.target.value;
  2883. preloadViews(entity);
  2884. const image = entities[selected.dataset.key].views[e.target.value].image;
  2885. selected.querySelector(".entity-image").src = image.source;
  2886. configViewOptions(entity, entity.view);
  2887. displayAttribution(image.source);
  2888. if (image.bottom !== undefined) {
  2889. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  2890. } else {
  2891. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  2892. }
  2893. updateSizes();
  2894. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  2895. updateViewOptions(entities[selected.dataset.key], e.target.value);
  2896. });
  2897. document.querySelector("#entity-view").addEventListener("input", e => {
  2898. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  2899. viewList.classList.add("nsfw");
  2900. } else {
  2901. viewList.classList.remove("nsfw");
  2902. }
  2903. })
  2904. clearViewList();
  2905. document.querySelector("#menu-clear").addEventListener("click", e => {
  2906. removeAllEntities();
  2907. });
  2908. document.querySelector("#delete-entity").disabled = true;
  2909. document.querySelector("#delete-entity").addEventListener("click", e => {
  2910. if (selected) {
  2911. removeEntity(selected);
  2912. selected = null;
  2913. }
  2914. });
  2915. document.querySelector("#menu-order-height").addEventListener("click", e => {
  2916. const order = Object.keys(entities).sort((a, b) => {
  2917. const entA = entities[a];
  2918. const entB = entities[b];
  2919. const viewA = entA.view;
  2920. const viewB = entB.view;
  2921. const heightA = entA.views[viewA].height.to("meter").value;
  2922. const heightB = entB.views[viewB].height.to("meter").value;
  2923. return heightA - heightB;
  2924. });
  2925. arrangeEntities(order);
  2926. });
  2927. // TODO: write some generic logic for this lol
  2928. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  2929. scrollDirection = -1;
  2930. clearInterval(scrollHandle);
  2931. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2932. e.stopPropagation();
  2933. });
  2934. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  2935. scrollDirection = 1;
  2936. clearInterval(scrollHandle);
  2937. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2938. e.stopPropagation();
  2939. });
  2940. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  2941. scrollDirection = -1;
  2942. clearInterval(scrollHandle);
  2943. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2944. e.stopPropagation();
  2945. });
  2946. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  2947. scrollDirection = 1;
  2948. clearInterval(scrollHandle);
  2949. scrollHandle = setInterval(doXScroll, 1000 / 20);
  2950. e.stopPropagation();
  2951. });
  2952. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  2953. scrollDirection = 1;
  2954. clearInterval(scrollHandle);
  2955. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2956. e.stopPropagation();
  2957. });
  2958. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  2959. scrollDirection = -1;
  2960. clearInterval(scrollHandle);
  2961. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2962. e.stopPropagation();
  2963. });
  2964. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  2965. scrollDirection = 1;
  2966. clearInterval(scrollHandle);
  2967. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2968. e.stopPropagation();
  2969. });
  2970. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  2971. scrollDirection = -1;
  2972. clearInterval(scrollHandle);
  2973. scrollHandle = setInterval(doYScroll, 1000 / 20);
  2974. e.stopPropagation();
  2975. });
  2976. document.addEventListener("mouseup", e => {
  2977. clearInterval(scrollHandle);
  2978. scrollHandle = null;
  2979. });
  2980. document.addEventListener("touchend", e => {
  2981. clearInterval(scrollHandle);
  2982. scrollHandle = null;
  2983. });
  2984. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  2985. zoomDirection = -1;
  2986. clearInterval(zoomHandle);
  2987. zoomHandle = setInterval(doZoom, 1000 / 20);
  2988. e.stopPropagation();
  2989. });
  2990. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  2991. zoomDirection = 1;
  2992. clearInterval(zoomHandle);
  2993. zoomHandle = setInterval(doZoom, 1000 / 20);
  2994. e.stopPropagation();
  2995. });
  2996. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  2997. zoomDirection = -1;
  2998. clearInterval(zoomHandle);
  2999. zoomHandle = setInterval(doZoom, 1000 / 20);
  3000. e.stopPropagation();
  3001. });
  3002. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  3003. zoomDirection = 1;
  3004. clearInterval(zoomHandle);
  3005. zoomHandle = setInterval(doZoom, 1000 / 20);
  3006. e.stopPropagation();
  3007. });
  3008. document.addEventListener("mouseup", e => {
  3009. clearInterval(zoomHandle);
  3010. zoomHandle = null;
  3011. });
  3012. document.addEventListener("touchend", e => {
  3013. clearInterval(zoomHandle);
  3014. zoomHandle = null;
  3015. });
  3016. document.querySelector("#shrink").addEventListener("mousedown", e => {
  3017. sizeDirection = -1;
  3018. clearInterval(sizeHandle);
  3019. sizeHandle = setInterval(doSize, 1000 / 20);
  3020. e.stopPropagation();
  3021. });
  3022. document.querySelector("#grow").addEventListener("mousedown", e => {
  3023. sizeDirection = 1;
  3024. clearInterval(sizeHandle);
  3025. sizeHandle = setInterval(doSize, 1000 / 20);
  3026. e.stopPropagation();
  3027. });
  3028. document.querySelector("#shrink").addEventListener("touchstart", e => {
  3029. sizeDirection = -1;
  3030. clearInterval(sizeHandle);
  3031. sizeHandle = setInterval(doSize, 1000 / 20);
  3032. e.stopPropagation();
  3033. });
  3034. document.querySelector("#grow").addEventListener("touchstart", e => {
  3035. sizeDirection = 1;
  3036. clearInterval(sizeHandle);
  3037. sizeHandle = setInterval(doSize, 1000 / 20);
  3038. e.stopPropagation();
  3039. });
  3040. document.addEventListener("mouseup", e => {
  3041. clearInterval(sizeHandle);
  3042. sizeHandle = null;
  3043. });
  3044. document.addEventListener("touchend", e => {
  3045. clearInterval(sizeHandle);
  3046. sizeHandle = null;
  3047. });
  3048. document.querySelector("#ruler").addEventListener("click", e => {
  3049. rulerMode = !rulerMode;
  3050. if (rulerMode) {
  3051. toast("Ready to draw a ruler mark");
  3052. } else {
  3053. toast("Cancelled ruler mode");
  3054. }
  3055. });
  3056. document.querySelector("#ruler").addEventListener("mousedown", e => {
  3057. e.stopPropagation();
  3058. });
  3059. document.querySelector("#ruler").addEventListener("touchstart", e => {
  3060. e.stopPropagation();
  3061. });
  3062. document.querySelector("#fit").addEventListener("click", e => {
  3063. if (selected) {
  3064. let targets = {};
  3065. targets[selected.dataset.key] = entities[selected.dataset.key];
  3066. fitEntities(targets);
  3067. }
  3068. });
  3069. document.querySelector("#fit").addEventListener("mousedown", e => {
  3070. e.stopPropagation();
  3071. });
  3072. document.querySelector("#fit").addEventListener("touchstart", e => {
  3073. e.stopPropagation();
  3074. });
  3075. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  3076. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  3077. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  3078. document.addEventListener("keydown", e => {
  3079. if (e.key == "Delete") {
  3080. if (selected) {
  3081. removeEntity(selected);
  3082. selected = null;
  3083. }
  3084. }
  3085. })
  3086. document.addEventListener("keydown", e => {
  3087. if (e.key == "Shift") {
  3088. shiftHeld = true;
  3089. e.preventDefault();
  3090. } else if (e.key == "Alt") {
  3091. altHeld = true;
  3092. movingInBounds = false; // don't snap the object back in bounds when we let go
  3093. e.preventDefault();
  3094. }
  3095. });
  3096. document.addEventListener("keyup", e => {
  3097. if (e.key == "Shift") {
  3098. shiftHeld = false;
  3099. e.preventDefault();
  3100. } else if (e.key == "Alt") {
  3101. altHeld = false;
  3102. e.preventDefault();
  3103. }
  3104. });
  3105. window.addEventListener("resize", handleResize);
  3106. // TODO: further investigate why the tool initially starts out with wrong
  3107. // values under certain circumstances (seems to be narrow aspect ratios -
  3108. // maybe the menu bar is animating when it shouldn't)
  3109. setTimeout(handleResize, 250);
  3110. setTimeout(handleResize, 500);
  3111. setTimeout(handleResize, 750);
  3112. setTimeout(handleResize, 1000);
  3113. document.querySelector("#menu-permalink").addEventListener("click", e => {
  3114. linkScene();
  3115. });
  3116. document.querySelector("#menu-export").addEventListener("click", e => {
  3117. copyScene();
  3118. });
  3119. document.querySelector("#menu-import").addEventListener("click", e => {
  3120. pasteScene();
  3121. });
  3122. document.querySelector("#menu-save").addEventListener("click", e => {
  3123. const name = document.querySelector("#menu-save ~ input").value;
  3124. if (/\S/.test(name)) {
  3125. saveScene(name);
  3126. }
  3127. updateSaveInfo();
  3128. });
  3129. document.querySelector("#menu-load").addEventListener("click", e => {
  3130. const name = document.querySelector("#menu-load ~ select").value;
  3131. if (/\S/.test(name)) {
  3132. loadScene(name);
  3133. }
  3134. });
  3135. document.querySelector("#menu-delete").addEventListener("click", e => {
  3136. const name = document.querySelector("#menu-delete ~ select").value;
  3137. if (/\S/.test(name)) {
  3138. deleteScene(name);
  3139. }
  3140. });
  3141. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  3142. loadScene("autosave");
  3143. });
  3144. document.querySelector("#menu-add-image").addEventListener("click", e => {
  3145. document.querySelector("#file-upload-picker").click();
  3146. });
  3147. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  3148. if (e.target.files.length > 0) {
  3149. for (let i=0; i<e.target.files.length; i++) {
  3150. customEntityFromFile(e.target.files[i]);
  3151. }
  3152. }
  3153. })
  3154. document.querySelector("#menu-clear-rulers").addEventListener("click", e => {
  3155. rulers = [];
  3156. drawRulers();
  3157. });
  3158. document.addEventListener("paste", e => {
  3159. let index = 0;
  3160. let item = null;
  3161. let found = false;
  3162. for (; index < e.clipboardData.items.length; index++) {
  3163. item = e.clipboardData.items[index];
  3164. if (item.type == "image/png") {
  3165. found = true;
  3166. break;
  3167. }
  3168. }
  3169. if (!found) {
  3170. return;
  3171. }
  3172. let url = null;
  3173. const file = item.getAsFile();
  3174. customEntityFromFile(file);
  3175. });
  3176. document.querySelector("#world").addEventListener("dragover", e => {
  3177. e.preventDefault();
  3178. })
  3179. document.querySelector("#world").addEventListener("drop", e => {
  3180. e.preventDefault();
  3181. if (e.dataTransfer.files.length > 0) {
  3182. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3183. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3184. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  3185. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  3186. }
  3187. })
  3188. clearEntityOptions();
  3189. clearViewOptions();
  3190. clearAttribution();
  3191. // we do this last because configuring settings can cause things
  3192. // to happen (e.g. auto-fit)
  3193. prepareSettings(getUserSettings());
  3194. // now that we have this loaded, we can set it
  3195. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  3196. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3197. // ...and then update the world height by setting off an input event
  3198. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  3199. }));
  3200. if (param === null) {
  3201. scenes["Empty"]();
  3202. }
  3203. else {
  3204. try {
  3205. const data = JSON.parse(b64DecodeUnicode(param));
  3206. if (data.entities === undefined) {
  3207. return;
  3208. }
  3209. if (data.world === undefined) {
  3210. return;
  3211. }
  3212. importScene(data);
  3213. } catch (err) {
  3214. console.error(err);
  3215. scenes["Empty"]();
  3216. // probably wasn't valid data
  3217. }
  3218. }
  3219. document.querySelector("#world").addEventListener("wheel", e => {
  3220. if (shiftHeld) {
  3221. if (selected) {
  3222. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  3223. const entity = entities[selected.dataset.key];
  3224. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  3225. entity.dirty = true;
  3226. updateEntityOptions(entity, entity.view);
  3227. updateViewOptions(entity, entity.view);
  3228. updateSizes(true);
  3229. } else {
  3230. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3231. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  3232. updateSizes();
  3233. updateSizes();
  3234. }
  3235. } else {
  3236. if (config.autoFit) {
  3237. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  3238. } else {
  3239. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  3240. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  3241. if (!config.lockYAxis) {
  3242. config.y += change / 2;
  3243. }
  3244. setWorldHeight(config.height, math.multiply(config.height, dir));
  3245. updateWorldOptions();
  3246. }
  3247. }
  3248. checkFitWorld();
  3249. })
  3250. updateWorldHeight();
  3251. document.querySelector("#search-box").addEventListener("change", e => doSearch(e.target.value));
  3252. });
  3253. let searchText = "";
  3254. function doSearch(value) {
  3255. searchText = value;
  3256. updateFilter();
  3257. }
  3258. function customEntityFromFile(file, x=0.5, y=0.5) {
  3259. file.arrayBuffer().then(buf => {
  3260. arr = new Uint8Array(buf);
  3261. blob = new Blob([arr], {type: file.type });
  3262. url = window.URL.createObjectURL(blob)
  3263. makeCustomEntity(url, x, y);
  3264. });
  3265. }
  3266. function makeCustomEntity(url, x=0.5, y=0.5) {
  3267. const maker = createEntityMaker(
  3268. {
  3269. name: "Custom Entity"
  3270. },
  3271. {
  3272. custom: {
  3273. attributes: {
  3274. height: {
  3275. name: "Height",
  3276. power: 1,
  3277. type: "length",
  3278. base: math.unit(6, "feet")
  3279. }
  3280. },
  3281. image: {
  3282. source: url
  3283. },
  3284. name: "Image",
  3285. info: {},
  3286. rename: false
  3287. }
  3288. },
  3289. []
  3290. );
  3291. const entity = maker.constructor();
  3292. entity.scale = config.height.toNumber("feet") / 20;
  3293. entity.ephemeral = true;
  3294. displayEntity(entity, "custom", x, y, true, true);
  3295. }
  3296. const filterDefs = {
  3297. none: {
  3298. id: "none",
  3299. name: "No Filter",
  3300. extract: maker => [],
  3301. render: name => name,
  3302. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3303. },
  3304. author: {
  3305. id: "author",
  3306. name: "Authors",
  3307. extract: maker => maker.authors ? maker.authors : [],
  3308. render: author => attributionData.people[author].name,
  3309. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3310. },
  3311. owner: {
  3312. id: "owner",
  3313. name: "Owners",
  3314. extract: maker => maker.owners ? maker.owners : [],
  3315. render: owner => attributionData.people[owner].name,
  3316. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3317. },
  3318. species: {
  3319. id: "species",
  3320. name: "Species",
  3321. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  3322. render: species => speciesData[species].name,
  3323. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3324. },
  3325. tags: {
  3326. id: "tags",
  3327. name: "Tags",
  3328. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  3329. render: tag => tagDefs[tag],
  3330. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3331. },
  3332. size: {
  3333. id: "size",
  3334. name: "Normal Size",
  3335. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  3336. if (result && !size.default) {
  3337. return result;
  3338. }
  3339. let meters = size.height.toNumber("meters");
  3340. if (meters < 1e-1) {
  3341. return ["micro"];
  3342. } else if (meters < 1e1) {
  3343. return ["moderate"];
  3344. } else {
  3345. return ["macro"];
  3346. }
  3347. }, null)) : [],
  3348. render: tag => { return {
  3349. "micro": "Micro",
  3350. "moderate": "Moderate",
  3351. "macro": "Macro"
  3352. }[tag]},
  3353. sort: (tag1, tag2) => {
  3354. const order = {
  3355. "micro": 0,
  3356. "moderate": 1,
  3357. "macro": 2
  3358. };
  3359. return order[tag1[0]] - order[tag2[0]];
  3360. }
  3361. },
  3362. allSizes: {
  3363. id: "allSizes",
  3364. name: "Possible Size",
  3365. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  3366. const height = size.height;
  3367. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  3368. if (result) {
  3369. return result;
  3370. } else {
  3371. if (math.compare(height, value) <= 0) {
  3372. return name;
  3373. }
  3374. }
  3375. }, null);
  3376. set.add(result ? result : "infinite");
  3377. return set;
  3378. }, new Set())) : [],
  3379. render: tag => tag[0].toUpperCase() + tag.slice(1),
  3380. sort: (tag1, tag2) => {
  3381. const order = [
  3382. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  3383. "galactic", "universal", "omniversal", "infinite"
  3384. ]
  3385. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  3386. }
  3387. }
  3388. }
  3389. const sizeCategories = {
  3390. "atomic": math.unit(100, "angstroms"),
  3391. "microscopic": math.unit(100, "micrometers"),
  3392. "tiny": math.unit(100, "millimeters"),
  3393. "small": math.unit(1, "meter"),
  3394. "moderate": math.unit(3, "meters"),
  3395. "large": math.unit(10, "meters"),
  3396. "macro": math.unit(300, "meters"),
  3397. "megamacro": math.unit(1000, "kilometers"),
  3398. "planetary": math.unit(10, "earths"),
  3399. "stellar": math.unit(10, "solarradii"),
  3400. "galactic": math.unit(10, "galaxies"),
  3401. "universal": math.unit(10, "universes"),
  3402. "omniversal": math.unit(10, "multiverses")
  3403. };
  3404. function prepareEntities() {
  3405. availableEntities["buildings"] = makeBuildings();
  3406. availableEntities["characters"] = makeCharacters();
  3407. availableEntities["clothing"] = makeClothing();
  3408. availableEntities["creatures"] = makeCreatures();
  3409. availableEntities["dildos"] = makeDildos();
  3410. availableEntities["fiction"] = makeFiction();
  3411. availableEntities["food"] = makeFood();
  3412. availableEntities["furniture"] = makeFurniture();
  3413. availableEntities["landmarks"] = makeLandmarks();
  3414. availableEntities["naturals"] = makeNaturals();
  3415. availableEntities["objects"] = makeObjects();
  3416. availableEntities["pokemon"] = makePokemon();
  3417. availableEntities["real-buildings"] = makeRealBuildings();
  3418. availableEntities["real-terrain"] = makeRealTerrains();
  3419. availableEntities["species"] = makeSpecies();
  3420. availableEntities["vehicles"] = makeVehicles();
  3421. availableEntities["species"].forEach(x => {
  3422. if (x.name == "Human") {
  3423. availableEntities["food"].push(x);
  3424. }
  3425. })
  3426. availableEntities["characters"].sort((x, y) => {
  3427. return x.name.localeCompare(y.name)
  3428. });
  3429. availableEntities["species"].sort((x, y) => {
  3430. return x.name.localeCompare(y.name)
  3431. });
  3432. availableEntities["objects"].sort((x, y) => {
  3433. return x.name.localeCompare(y.name)
  3434. });
  3435. const holder = document.querySelector("#spawners");
  3436. const filterHolder = document.querySelector("#filters");
  3437. const categorySelect = document.createElement("select");
  3438. categorySelect.id = "category-picker";
  3439. const filterSelect = document.createElement("select");
  3440. filterSelect.id = "filter-picker";
  3441. holder.appendChild(categorySelect);
  3442. filterHolder.appendChild(filterSelect);
  3443. const filterSets = {};
  3444. Object.values(filterDefs).forEach(filter => {
  3445. filterSets[filter.id] = new Set();
  3446. })
  3447. Object.entries(availableEntities).forEach(([category, entityList]) => {
  3448. const select = document.createElement("select");
  3449. select.id = "create-entity-" + category;
  3450. select.classList.add("entity-select");
  3451. for (let i = 0; i < entityList.length; i++) {
  3452. const entity = entityList[i];
  3453. const option = document.createElement("option");
  3454. option.value = i;
  3455. option.innerText = entity.name;
  3456. select.appendChild(option);
  3457. if (entity.nsfw) {
  3458. option.classList.add("nsfw");
  3459. }
  3460. Object.values(filterDefs).forEach(filter => {
  3461. filter.extract(entity).forEach(result => {
  3462. filterSets[filter.id].add(result);
  3463. });
  3464. });
  3465. availableEntitiesByName[entity.name] = entity;
  3466. };
  3467. select.addEventListener("change", e => {
  3468. if (select.options[select.selectedIndex]?.classList.contains("nsfw")) {
  3469. select.classList.add("nsfw");
  3470. } else {
  3471. select.classList.remove("nsfw");
  3472. }
  3473. // preload the entity's first image
  3474. const entity = entityList[select.selectedIndex]?.constructor();
  3475. if (entity)
  3476. {
  3477. let img = new Image();
  3478. img.src = entity.currentView.image.source;
  3479. }
  3480. })
  3481. const button = document.createElement("button");
  3482. button.id = "create-entity-" + category + "-button";
  3483. button.classList.add("entity-button");
  3484. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  3485. button.addEventListener("click", e => {
  3486. if (entityList[select.value] == null)
  3487. return;
  3488. const newEntity = entityList[select.value].constructor()
  3489. let yOffset = 0;
  3490. if (config.lockYAxis) {
  3491. if (config.groundPos === "very-high") {
  3492. yOffset = config.height.toNumber("meters") / 12 * 5;
  3493. }
  3494. else if (config.groundPos === "high") {
  3495. yOffset = config.height.toNumber("meters") / 12 * 4;
  3496. }
  3497. else if (config.groundPos === "medium") {
  3498. yOffset = config.height.toNumber("meters") / 12 * 3;
  3499. }
  3500. else if (config.groundPos === "low") {
  3501. yOffset = config.height.toNumber("meters") / 12 * 2;
  3502. }
  3503. else if (config.groundPos === "very-low") {
  3504. yOffset = config.height.toNumber("meters") / 12 * 1;
  3505. }
  3506. else if (config.groundPos === "bottom") {
  3507. yOffset = 0;
  3508. }
  3509. } else {
  3510. yOffset = (config.lockYAxis ? 0 : config.height.toNumber("meters")/2);
  3511. }
  3512. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + yOffset, true, true);
  3513. });
  3514. const categoryOption = document.createElement("option");
  3515. categoryOption.value = category
  3516. categoryOption.innerText = category;
  3517. if (category == "characters") {
  3518. categoryOption.selected = true;
  3519. select.classList.add("category-visible");
  3520. button.classList.add("category-visible");
  3521. }
  3522. categorySelect.appendChild(categoryOption);
  3523. holder.appendChild(select);
  3524. holder.appendChild(button);
  3525. });
  3526. Object.values(filterDefs).forEach(filter => {
  3527. const option = document.createElement("option");
  3528. option.innerText = filter.name;
  3529. option.value = filter.id;
  3530. filterSelect.appendChild(option);
  3531. const filterNameSelect = document.createElement("select");
  3532. filterNameSelect.classList.add("filter-select");
  3533. filterNameSelect.id = "filter-" + filter.id;
  3534. filterHolder.appendChild(filterNameSelect);
  3535. const button = document.createElement("button");
  3536. button.classList.add("filter-button");
  3537. button.id = "create-filtered-" + filter.id + "-button";
  3538. filterHolder.appendChild(button);
  3539. const counter = document.createElement("div");
  3540. counter.classList.add("button-counter");
  3541. counter.innerText = "10";
  3542. button.appendChild(counter);
  3543. const i = document.createElement("i");
  3544. i.classList.add("fas");
  3545. i.classList.add("fa-plus");
  3546. button.appendChild(i);
  3547. button.addEventListener("click", e => {
  3548. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  3549. const count = makers.length + 2;
  3550. let index = 1;
  3551. if (makers.length > 50) {
  3552. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  3553. return;
  3554. }
  3555. }
  3556. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3557. const spawned = makers.map(element => {
  3558. const category = document.querySelector("#category-picker").value;
  3559. const maker = availableEntities[category][element.value];
  3560. const entity = maker.constructor()
  3561. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  3562. index += 1;
  3563. return entityIndex - 1;
  3564. });
  3565. updateSizes(true);
  3566. if (config.autoFitAdd) {
  3567. let targets = {};
  3568. spawned.forEach(key => {
  3569. targets[key] = entities[key];
  3570. })
  3571. fitEntities(targets);
  3572. }
  3573. });
  3574. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  3575. const option = document.createElement("option");
  3576. option.innerText = name[1];
  3577. option.value = name[0];
  3578. filterNameSelect.appendChild(option);
  3579. });
  3580. filterNameSelect.addEventListener("change", e => {
  3581. updateFilter();
  3582. });
  3583. });
  3584. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  3585. categorySelect.addEventListener("input", e => {
  3586. const oldSelect = document.querySelector(".entity-select.category-visible");
  3587. oldSelect.classList.remove("category-visible");
  3588. const oldButton = document.querySelector(".entity-button.category-visible");
  3589. oldButton.classList.remove("category-visible");
  3590. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  3591. newSelect.classList.add("category-visible");
  3592. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  3593. newButton.classList.add("category-visible");
  3594. recomputeFilters();
  3595. updateFilter();
  3596. });
  3597. recomputeFilters();
  3598. filterSelect.addEventListener("input", e => {
  3599. const oldSelect = document.querySelector(".filter-select.category-visible");
  3600. if (oldSelect)
  3601. oldSelect.classList.remove("category-visible");
  3602. const newSelect = document.querySelector("#filter-" + e.target.value);
  3603. if (newSelect && e.target.value != "none")
  3604. newSelect.classList.add("category-visible");
  3605. updateFilter();
  3606. });
  3607. ratioInfo = document.body.querySelector(".ratio-info")
  3608. }
  3609. // Only display authors and owners if they appear
  3610. // somewhere in the current entity list
  3611. function recomputeFilters() {
  3612. const category = document.querySelector("#category-picker").value;
  3613. const filterSets = {};
  3614. Object.values(filterDefs).forEach(filter => {
  3615. filterSets[filter.id] = new Set();
  3616. });
  3617. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3618. const entity = availableEntities[category][element.value];
  3619. Object.values(filterDefs).forEach(filter => {
  3620. filter.extract(entity).forEach(result => {
  3621. filterSets[filter.id].add(result);
  3622. });
  3623. });
  3624. });
  3625. Object.values(filterDefs).forEach(filter => {
  3626. // always show the "none" option
  3627. let found = filter.id == "none";
  3628. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  3629. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  3630. element.classList.remove("filtered");
  3631. element.disabled = false;
  3632. found = true;
  3633. } else {
  3634. element.classList.add("filtered");
  3635. element.disabled = true;
  3636. }
  3637. });
  3638. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  3639. if (found) {
  3640. filterOption.classList.remove("filtered");
  3641. filterOption.disabled = false;
  3642. } else {
  3643. filterOption.classList.add("filtered");
  3644. filterOption.disabled = true;
  3645. }
  3646. });
  3647. document.querySelector("#filter-picker").value = "none";
  3648. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  3649. }
  3650. function updateFilter() {
  3651. const category = document.querySelector("#category-picker").value;
  3652. const type = document.querySelector("#filter-picker").value;
  3653. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  3654. clearFilter();
  3655. const noFilter = !filterKeySelect;
  3656. let key;
  3657. let current = document.querySelector(".entity-select.category-visible").value;
  3658. if (!noFilter)
  3659. {
  3660. key = filterKeySelect.value;
  3661. current
  3662. }
  3663. let replace = current == "";
  3664. let first = null;
  3665. let count = 0;
  3666. const lowerSearchText = searchText !== "" ? searchText.toLowerCase() : null;
  3667. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3668. let keep = noFilter;
  3669. if (!noFilter && filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  3670. keep = true;
  3671. }
  3672. if (searchText != "" && !availableEntities[category][element.value].name.toLowerCase().includes(lowerSearchText))
  3673. {
  3674. keep = false;
  3675. }
  3676. if (!keep) {
  3677. element.classList.add("filtered");
  3678. element.disabled = true;
  3679. if (current == element.value) {
  3680. replace = true;
  3681. }
  3682. } else {
  3683. count += 1;
  3684. if (!first) {
  3685. first = element.value;
  3686. }
  3687. }
  3688. });
  3689. const button = document.querySelector(".filter-select.category-visible + button");
  3690. if (button) {
  3691. button.querySelector(".button-counter").innerText = count;
  3692. }
  3693. if (replace) {
  3694. document.querySelector(".entity-select.category-visible").value = first;
  3695. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  3696. }
  3697. }
  3698. function clearFilter() {
  3699. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3700. element.classList.remove("filtered");
  3701. element.disabled = false;
  3702. });
  3703. }
  3704. document.addEventListener("mousemove", (e) => {
  3705. if (currentRuler) {
  3706. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3707. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3708. let position = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3709. currentRuler.x1 = position.x;
  3710. currentRuler.y1 = position.y;
  3711. }
  3712. drawRulers();
  3713. });
  3714. document.addEventListener("touchmove", (e) => {
  3715. if (currentRuler) {
  3716. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3717. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3718. let position = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3719. currentRuler.x1 = position.x;
  3720. currentRuler.y1 = position.y;
  3721. }
  3722. drawRulers();
  3723. });
  3724. document.addEventListener("mousemove", (e) => {
  3725. if (clicked) {
  3726. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  3727. if (movingInBounds) {
  3728. position = snapPos(position);
  3729. } else {
  3730. let x = e.clientX - dragOffsetX;
  3731. let y = e.clientY - dragOffsetY;
  3732. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  3733. movingInBounds = true;
  3734. }
  3735. }
  3736. clicked.dataset.x = position.x;
  3737. clicked.dataset.y = position.y;
  3738. updateEntityElement(entities[clicked.dataset.key], clicked);
  3739. if (hoveringInDeleteArea(e)) {
  3740. document.querySelector("#menubar").classList.add("hover-delete");
  3741. } else {
  3742. document.querySelector("#menubar").classList.remove("hover-delete");
  3743. }
  3744. }
  3745. if (panning && panReady) {
  3746. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3747. const worldHeight = config.height.toNumber("meters");
  3748. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  3749. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  3750. panOffsetX = e.clientX;
  3751. panOffsetY = e.clientY;
  3752. updateSizes();
  3753. panReady = false;
  3754. setTimeout(() => panReady=true, 1000/120);
  3755. }
  3756. });
  3757. document.addEventListener("touchmove", (e) => {
  3758. if (clicked) {
  3759. e.preventDefault();
  3760. let x = e.touches[0].clientX;
  3761. let y = e.touches[0].clientY;
  3762. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  3763. clicked.dataset.x = position.x;
  3764. clicked.dataset.y = position.y;
  3765. updateEntityElement(entities[clicked.dataset.key], clicked);
  3766. // what a hack
  3767. // I should centralize this 'fake event' creation...
  3768. if (hoveringInDeleteArea({ clientY: y })) {
  3769. document.querySelector("#menubar").classList.add("hover-delete");
  3770. } else {
  3771. document.querySelector("#menubar").classList.remove("hover-delete");
  3772. }
  3773. }
  3774. if (panning && panReady) {
  3775. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3776. const worldHeight = config.height.toNumber("meters");
  3777. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  3778. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  3779. panOffsetX = e.touches[0].clientX;
  3780. panOffsetY = e.touches[0].clientY;
  3781. updateSizes();
  3782. panReady = false;
  3783. setTimeout(() => panReady=true, 1000/60);
  3784. }
  3785. }, { passive: false });
  3786. function checkFitWorld() {
  3787. if (config.autoFit) {
  3788. fitWorld();
  3789. return true;
  3790. }
  3791. return false;
  3792. }
  3793. function fitWorld(manual = false, factor = 1.1) {
  3794. if (Object.keys(entities).length > 0) {
  3795. fitEntities(entities, factor);
  3796. }
  3797. }
  3798. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  3799. let minX = Infinity;
  3800. let maxX = -Infinity;
  3801. let minY = Infinity;
  3802. let maxY = -Infinity;
  3803. let count = 0;
  3804. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3805. const worldHeight = config.height.toNumber("meters");
  3806. Object.entries(targetEntities).forEach(([key, entity]) => {
  3807. const view = entity.view;
  3808. let extra = entity.views[view].image.extra;
  3809. extra = extra === undefined ? 1 : extra;
  3810. const image = document.querySelector("#entity-" + key + " > .entity-image");
  3811. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  3812. let width = image.width;
  3813. let height = image.height;
  3814. // only really relevant if the images haven't loaded in yet
  3815. if (height == 0) {
  3816. height = 100;
  3817. }
  3818. if (width == 0) {
  3819. width = height;
  3820. }
  3821. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  3822. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  3823. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  3824. const yBottom = y;
  3825. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  3826. minX = Math.min(minX, xBottom);
  3827. maxX = Math.max(maxX, xTop);
  3828. minY = Math.min(minY, yBottom);
  3829. maxY = Math.max(maxY, yTop);
  3830. count += 1;
  3831. });
  3832. if (config.lockYAxis) {
  3833. minY = 0;
  3834. }
  3835. let ySize = (maxY - minY) * factor;
  3836. let xSize = (maxX - minX) * factor;
  3837. if (xSize / ySize > worldWidth / worldHeight) {
  3838. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  3839. }
  3840. config.x = (maxX + minX) / 2;
  3841. config.y = minY;
  3842. height = math.unit(ySize, "meter")
  3843. setWorldHeight(config.height, math.multiply(height, factor));
  3844. }
  3845. function updateWorldHeight() {
  3846. const unit = document.querySelector("#options-height-unit").value;
  3847. const rawValue = document.querySelector("#options-height-value").value;
  3848. var value
  3849. try {
  3850. value = math.evaluate(rawValue)
  3851. if (typeof(value) !== "number") {
  3852. try {
  3853. value = value.toNumber(unit)
  3854. } catch {
  3855. toast("Invalid input: " + rawValue + " can't be converted to " + unit)
  3856. }
  3857. }
  3858. } catch {
  3859. toast("Invalid input: could not parse " + rawValue)
  3860. return;
  3861. }
  3862. const newHeight = Math.max(0.000000001, value);
  3863. const oldHeight = config.height;
  3864. setWorldHeight(oldHeight, math.unit(newHeight, unit), true);
  3865. }
  3866. function setWorldHeight(oldHeight, newHeight, keepUnit=false) {
  3867. worldSizeDirty = true;
  3868. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  3869. const unit = document.querySelector("#options-height-unit").value;
  3870. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  3871. Object.entries(entities).forEach(([key, entity]) => {
  3872. const element = document.querySelector("#entity-" + key);
  3873. let newPosition;
  3874. if (altHeld) {
  3875. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  3876. } else {
  3877. newPosition = { x: element.dataset.x, y: element.dataset.y };
  3878. }
  3879. element.dataset.x = newPosition.x;
  3880. element.dataset.y = newPosition.y;
  3881. });
  3882. if (!keepUnit) {
  3883. pickUnit()
  3884. }
  3885. updateSizes();
  3886. }
  3887. function loadScene(name = "default") {
  3888. if (name === "") {
  3889. name = "default"
  3890. }
  3891. try {
  3892. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  3893. if (data === null) {
  3894. console.error("Couldn't load " + name)
  3895. return false;
  3896. }
  3897. importScene(data);
  3898. toast("Loaded " + name);
  3899. return true;
  3900. } catch (err) {
  3901. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  3902. console.error(err);
  3903. return false;
  3904. }
  3905. }
  3906. function saveScene(name = "default") {
  3907. try {
  3908. const string = JSON.stringify(exportScene());
  3909. localStorage.setItem("macrovision-save-" + name, string);
  3910. toast("Saved as " + name);
  3911. } catch (err) {
  3912. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  3913. console.error(err);
  3914. }
  3915. }
  3916. function deleteScene(name = "default") {
  3917. if (confirm("Really delete the " + name + " scene?")) {
  3918. try {
  3919. localStorage.removeItem("macrovision-save-" + name)
  3920. toast("Deleted " + name);
  3921. } catch (err) {
  3922. console.error(err);
  3923. }
  3924. }
  3925. updateSaveInfo();
  3926. }
  3927. function exportScene() {
  3928. const results = {};
  3929. results.entities = [];
  3930. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  3931. const element = document.querySelector("#entity-" + key);
  3932. results.entities.push({
  3933. name: entity.identifier,
  3934. customName: entity.name,
  3935. scale: entity.scale,
  3936. rotation: entity.rotation,
  3937. view: entity.view,
  3938. form: entity.form,
  3939. x: element.dataset.x,
  3940. y: element.dataset.y,
  3941. priority: entity.priority,
  3942. brightness: entity.brightness
  3943. });
  3944. });
  3945. const unit = document.querySelector("#options-height-unit").value;
  3946. results.world = {
  3947. height: config.height.toNumber(unit),
  3948. unit: unit,
  3949. x: config.x,
  3950. y: config.y
  3951. }
  3952. results.version = migrationDefs.length;
  3953. return results;
  3954. }
  3955. // btoa doesn't like anything that isn't ASCII
  3956. // great
  3957. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  3958. // for providing an alternative
  3959. function b64EncodeUnicode(str) {
  3960. // first we use encodeURIComponent to get percent-encoded UTF-8,
  3961. // then we convert the percent encodings into raw bytes which
  3962. // can be fed into btoa.
  3963. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  3964. function toSolidBytes(match, p1) {
  3965. return String.fromCharCode('0x' + p1);
  3966. }));
  3967. }
  3968. function b64DecodeUnicode(str) {
  3969. // Going backwards: from bytestream, to percent-encoding, to original string.
  3970. return decodeURIComponent(atob(str).split('').map(function (c) {
  3971. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  3972. }).join(''));
  3973. }
  3974. function linkScene() {
  3975. loc = new URL(window.location);
  3976. const link = loc.protocol + "//" + loc.host + loc.pathname + "#" + b64EncodeUnicode(JSON.stringify(exportScene()));
  3977. window.history.replaceState(null, "Macrovision", link);
  3978. try {
  3979. navigator.clipboard.writeText(link);
  3980. toast("Copied permalink to clipboard");
  3981. } catch {
  3982. toast("Couldn't copy permalink");
  3983. }
  3984. }
  3985. function copyScene() {
  3986. const results = exportScene();
  3987. navigator.clipboard.writeText(JSON.stringify(results));
  3988. }
  3989. function pasteScene() {
  3990. try {
  3991. navigator.clipboard.readText().then(text => {
  3992. const data = JSON.parse(text);
  3993. if (data.entities === undefined) {
  3994. return;
  3995. }
  3996. if (data.world === undefined) {
  3997. return;
  3998. }
  3999. importScene(data);
  4000. }).catch(err => alert(err));
  4001. } catch (err) {
  4002. console.error(err);
  4003. // probably wasn't valid data
  4004. }
  4005. }
  4006. // TODO - don't just search through every single entity
  4007. // probably just have a way to do lookups directly
  4008. function findEntity(name) {
  4009. return availableEntitiesByName[name];
  4010. }
  4011. const migrationDefs = [
  4012. /*
  4013. Migration: 0 -> 1
  4014. Adds x and y coordinates for the camera
  4015. */
  4016. data => {
  4017. data.world.x = 0;
  4018. data.world.y = 0;
  4019. },
  4020. /*
  4021. Migration: 1 -> 2
  4022. Adds priority and brightness to each entity
  4023. */
  4024. data => {
  4025. data.entities.forEach(entity => {
  4026. entity.priority = 0;
  4027. entity.brightness = 1;
  4028. });
  4029. },
  4030. /*
  4031. Migration: 2 -> 3
  4032. Custom names are exported
  4033. */
  4034. data => {
  4035. data.entities.forEach(entity => {
  4036. entity.customName = entity.name
  4037. });
  4038. },
  4039. /*
  4040. Migration: 3 -> $
  4041. Rotation is now stored
  4042. */
  4043. data => {
  4044. data.entities.forEach(entity => {
  4045. entity.rotation = 0
  4046. });
  4047. }
  4048. ]
  4049. function migrateScene(data) {
  4050. if (data.version === undefined) {
  4051. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  4052. console.trace()
  4053. data.version = 0;
  4054. } else if (data.version < migrationDefs.length) {
  4055. migrationDefs[data.version](data);
  4056. data.version += 1;
  4057. migrateScene(data);
  4058. }
  4059. }
  4060. function importScene(data) {
  4061. removeAllEntities();
  4062. migrateScene(data);
  4063. data.entities.forEach(entityInfo => {
  4064. const entity = findEntity(entityInfo.name).constructor();
  4065. entity.name = entityInfo.customName;
  4066. entity.scale = entityInfo.scale;
  4067. entity.rotation = entityInfo.rotation;
  4068. entity.priority = entityInfo.priority;
  4069. entity.brightness = entityInfo.brightness;
  4070. entity.form = entityInfo.form;
  4071. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  4072. });
  4073. config.height = math.unit(data.world.height, data.world.unit);
  4074. config.x = data.world.x;
  4075. config.y = data.world.y;
  4076. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  4077. document.querySelector("#options-height-value").value = height;
  4078. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  4079. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  4080. if (data.canvasWidth) {
  4081. doHorizReposition(data.canvasWidth / canvasWidth);
  4082. }
  4083. updateSizes();
  4084. }
  4085. function renderToCanvas() {
  4086. const ctx = document.querySelector("#display").getContext("2d");
  4087. Object.entries(entities).sort((ent1, ent2) => {
  4088. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  4089. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  4090. return z1 - z2;
  4091. }).forEach(([id, entity]) => {
  4092. element = document.querySelector("#entity-" + id);
  4093. img = element.querySelector("img");
  4094. let x = parseFloat(element.dataset.x);
  4095. let y = parseFloat(element.dataset.y);
  4096. let coords = pos2pix({x: x, y: y});
  4097. let offset = img.style.getPropertyValue("--offset");
  4098. offset = parseFloat(offset.substring(0, offset.length-1))
  4099. let xSize = img.width;
  4100. let ySize = img.height;
  4101. x = coords.x
  4102. y = coords.y + ySize/2 + ySize * offset / 100;
  4103. const oldFilter = ctx.filter
  4104. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  4105. ctx.filter = `brightness(${brightness})`;
  4106. ctx.save();
  4107. ctx.resetTransform();
  4108. ctx.scale(window.devicePixelRatio, window.devicePixelRatio)
  4109. ctx.translate(x, y);
  4110. ctx.rotate(entity.rotation);
  4111. ctx.drawImage(img, -xSize/2, -ySize/2, xSize, ySize);
  4112. ctx.restore();
  4113. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  4114. ctx.translate(-xSize/2, -ySize/2);
  4115. ctx.filter = oldFilter
  4116. });
  4117. }
  4118. function exportCanvas(callback) {
  4119. /** @type {CanvasRenderingContext2D} */
  4120. const ctx = document.querySelector("#display").getContext("2d");
  4121. const blob = ctx.canvas.toBlob(callback);
  4122. }
  4123. function generateScreenshot(callback) {
  4124. /** @type {CanvasRenderingContext2D} */
  4125. const ctx = document.querySelector("#display").getContext("2d");
  4126. if (checkBodyClass("toggle-bottom-cover")) {
  4127. ctx.fillStyle = "#000";
  4128. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  4129. }
  4130. renderToCanvas();
  4131. ctx.resetTransform();
  4132. ctx.fillStyle = "#777";
  4133. ctx.font = "normal normal lighter 16pt coda";
  4134. ctx.fillText("macrovision.crux.sexy", 10, 25);
  4135. exportCanvas(blob => {
  4136. callback(blob);
  4137. });
  4138. }
  4139. function copyScreenshot() {
  4140. if (window.ClipboardItem === undefined) {
  4141. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  4142. return;
  4143. }
  4144. generateScreenshot(blob => {
  4145. navigator.clipboard.write([
  4146. new ClipboardItem({
  4147. "image/png": blob
  4148. })
  4149. ]);
  4150. });
  4151. drawScales(false);
  4152. }
  4153. function saveScreenshot() {
  4154. generateScreenshot(blob => {
  4155. const a = document.createElement("a");
  4156. a.href = URL.createObjectURL(blob);
  4157. a.setAttribute("download", "macrovision.png");
  4158. a.click();
  4159. });
  4160. drawScales(false);
  4161. }
  4162. function openScreenshot() {
  4163. generateScreenshot(blob => {
  4164. const a = document.createElement("a");
  4165. a.href = URL.createObjectURL(blob);
  4166. a.setAttribute("target", "_blank");
  4167. a.click();
  4168. });
  4169. drawScales(false);
  4170. }
  4171. const rateLimits = {};
  4172. function toast(msg) {
  4173. let div = document.createElement("div");
  4174. div.innerHTML = msg;
  4175. div.classList.add("toast");
  4176. document.body.appendChild(div);
  4177. setTimeout(() => {
  4178. document.body.removeChild(div);
  4179. }, 5000)
  4180. }
  4181. function toastRateLimit(msg, key, delay) {
  4182. if (!rateLimits[key]) {
  4183. toast(msg);
  4184. rateLimits[key] = setTimeout(() => {
  4185. delete rateLimits[key]
  4186. }, delay);
  4187. }
  4188. }
  4189. let lastTime = undefined;
  4190. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  4191. Object.keys(entities).forEach(key => {
  4192. document.querySelector("#entity-" + key).classList.add("no-transition");
  4193. });
  4194. config.x = fromX;
  4195. config.y = fromY;
  4196. config.height = math.unit(fromHeight, "meters")
  4197. updateSizes();
  4198. lastTime = undefined;
  4199. requestAnimationFrame((timestamp) => panTo(toX, toY, toHeight, (toX - fromX) / duration, (toY - fromY) / duration, (toHeight - fromHeight) / duration, timestamp, duration));
  4200. }
  4201. function panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining) {
  4202. if (lastTime === undefined) {
  4203. lastTime = timestamp;
  4204. }
  4205. dt = timestamp - lastTime;
  4206. remaining -= dt;
  4207. if (remaining < 0) {
  4208. dt += remaining
  4209. }
  4210. let newX = config.x + xSpeed * dt;
  4211. let newY = config.y + ySpeed * dt;
  4212. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  4213. if (remaining > 0) {
  4214. requestAnimationFrame((timestamp) => panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining))
  4215. } else {
  4216. Object.keys(entities).forEach(key => {
  4217. document.querySelector("#entity-" + key).classList.remove("no-transition");
  4218. });
  4219. }
  4220. config.x = newX;
  4221. config.y = newY;
  4222. config.height = math.unit(newHeight, "meters");
  4223. updateSizes();
  4224. }