less copy protection, more size visualization
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

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