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

5371 lines
163 KiB

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