less copy protection, more size visualization
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

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