less copy protection, more size visualization
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

5319 行
162 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 settingsData = {
  2176. "show-vertical-scale": {
  2177. name: "Vertical Scale",
  2178. desc: "Draw vertical scale marks",
  2179. type: "toggle",
  2180. default: true,
  2181. get value() {
  2182. return config.drawYAxis;
  2183. },
  2184. set value(param) {
  2185. config.drawYAxis = param;
  2186. drawScales(false);
  2187. }
  2188. },
  2189. "show-horizontal-scale": {
  2190. name: "Horiziontal Scale",
  2191. desc: "Draw horizontal scale marks",
  2192. type: "toggle",
  2193. default: false,
  2194. get value() {
  2195. return config.drawXAxis;
  2196. },
  2197. set value(param) {
  2198. config.drawXAxis = param;
  2199. drawScales(false);
  2200. }
  2201. },
  2202. "show-altitudes": {
  2203. name: "Altitudes",
  2204. desc: "Draw interesting altitudes",
  2205. type: "select",
  2206. default: "none",
  2207. disabled: "none",
  2208. options: [
  2209. "none",
  2210. "all",
  2211. "atmosphere",
  2212. "orbits",
  2213. "weather",
  2214. "water",
  2215. "geology",
  2216. "thicknesses",
  2217. "airspaces",
  2218. "races",
  2219. "olympic-records",
  2220. "d&d-sizes"
  2221. ],
  2222. get value() {
  2223. return config.drawAltitudes;
  2224. },
  2225. set value(param) {
  2226. config.drawAltitudes = param;
  2227. drawScales(false);
  2228. }
  2229. },
  2230. "lock-y-axis": {
  2231. name: "Lock Y-Axis",
  2232. desc: "Keep the camera at ground-level",
  2233. type: "toggle",
  2234. default: true,
  2235. get value() {
  2236. return config.lockYAxis;
  2237. },
  2238. set value(param) {
  2239. config.lockYAxis = param;
  2240. if (param) {
  2241. config.y = 0;
  2242. updateSizes();
  2243. document.querySelector("#scroll-up").disabled = true;
  2244. document.querySelector("#scroll-down").disabled = true;
  2245. } else {
  2246. document.querySelector("#scroll-up").disabled = false;
  2247. document.querySelector("#scroll-down").disabled = false;
  2248. }
  2249. }
  2250. },
  2251. "ground-snap": {
  2252. name: "Snap to Ground",
  2253. desc: "Snap things to the ground",
  2254. type: "toggle",
  2255. default: true,
  2256. get value() {
  2257. return config.groundSnap;
  2258. },
  2259. set value(param) {
  2260. config.groundSnap = param;
  2261. }
  2262. },
  2263. "axis-spacing": {
  2264. name: "Axis Spacing",
  2265. desc: "How frequent the axis lines are",
  2266. type: "select",
  2267. default: "standard",
  2268. options: [
  2269. "dense",
  2270. "standard",
  2271. "sparse"
  2272. ],
  2273. get value() {
  2274. return config.axisSpacing;
  2275. },
  2276. set value(param) {
  2277. config.axisSpacing = param;
  2278. const factor = {
  2279. "dense": 0.5,
  2280. "standard": 1,
  2281. "sparse": 2
  2282. }[param];
  2283. config.minLineSize = factor * 100;
  2284. config.maxLineSize = factor * 150;
  2285. updateSizes();
  2286. }
  2287. },
  2288. "ground-type": {
  2289. name: "Ground",
  2290. desc: "What kind of ground to show, if any",
  2291. type: "select",
  2292. default: "black",
  2293. disabled: "none",
  2294. options: [
  2295. "none",
  2296. "black",
  2297. "dark",
  2298. "medium",
  2299. "light",
  2300. ],
  2301. get value() {
  2302. return config.groundKind;
  2303. },
  2304. set value(param) {
  2305. config.groundKind = param;
  2306. document.querySelector("#ground").style.setProperty("--ground-color", backgroundColors[param])
  2307. }
  2308. },
  2309. "ground-pos": {
  2310. name: "Ground Position",
  2311. desc: "How high the ground is if the y-axis is locked",
  2312. type: "select",
  2313. default: "bottom",
  2314. options: [
  2315. "very-high",
  2316. "high",
  2317. "medium",
  2318. "low",
  2319. "very-low",
  2320. "bottom",
  2321. ],
  2322. get value() {
  2323. return config.groundPos;
  2324. },
  2325. set value(param) {
  2326. config.groundPos = param;
  2327. updateSizes();
  2328. }
  2329. },
  2330. "background-brightness": {
  2331. name: "Background Color",
  2332. desc: "How bright the background is",
  2333. type: "select",
  2334. default: "medium",
  2335. options: [
  2336. "black",
  2337. "dark",
  2338. "medium",
  2339. "light",
  2340. ],
  2341. get value() {
  2342. return config.background;
  2343. },
  2344. set value(param) {
  2345. config.background = param;
  2346. drawScales();
  2347. }
  2348. },
  2349. "auto-scale": {
  2350. name: "Auto-Size World",
  2351. desc: "Constantly zoom to fit the largest entity",
  2352. type: "toggle",
  2353. default: false,
  2354. get value() {
  2355. return config.autoFit;
  2356. },
  2357. set value(param) {
  2358. config.autoFit = param;
  2359. checkFitWorld();
  2360. }
  2361. },
  2362. "auto-units": {
  2363. name: "Auto-Select Units",
  2364. desc: "Automatically switch units when zooming in and out",
  2365. type: "toggle",
  2366. default: false,
  2367. get value() {
  2368. return config.autoUnits;
  2369. },
  2370. set value(param) {
  2371. config.autoUnits = param;
  2372. }
  2373. },
  2374. "zoom-when-adding": {
  2375. name: "Zoom On Add",
  2376. desc: "Zoom to fit when you add a new entity",
  2377. type: "toggle",
  2378. default: true,
  2379. get value() {
  2380. return config.autoFitAdd;
  2381. },
  2382. set value(param) {
  2383. config.autoFitAdd = param;
  2384. }
  2385. },
  2386. "zoom-when-sizing": {
  2387. name: "Zoom On Size",
  2388. desc: "Zoom to fit when you select an entity's size",
  2389. type: "toggle",
  2390. default: false,
  2391. get value() {
  2392. return config.autoFitSize;
  2393. },
  2394. set value(param) {
  2395. config.autoFitSize = param;
  2396. }
  2397. },
  2398. "show-ratios": {
  2399. name: "Show Ratios",
  2400. desc: "Show the proportions between the current selection and the most recent selection.",
  2401. type: "toggle",
  2402. default: false,
  2403. get value() {
  2404. return config.showRatios;
  2405. },
  2406. set value(param) {
  2407. config.showRatios = param;
  2408. updateInfo();
  2409. }
  2410. },
  2411. "show-horizon": {
  2412. name: "Show Horizon",
  2413. desc: "Show how far the horizon would be for the selected character",
  2414. type: "toggle",
  2415. default: false,
  2416. get value() {
  2417. return config.showHorizon;
  2418. },
  2419. set value(param) {
  2420. config.showHorizon = param;
  2421. updateInfo();
  2422. }
  2423. },
  2424. "attach-rulers": {
  2425. name: "Attach Rulers",
  2426. desc: "Rulers will attach to the currently-selected entity, moving around with it.",
  2427. type: "toggle",
  2428. default: true,
  2429. get value() {
  2430. return config.rulersStick;
  2431. },
  2432. set value(param) {
  2433. config.rulersStick = param;
  2434. }
  2435. },
  2436. "units": {
  2437. name: "Default Units",
  2438. desc: "Which kind of unit to use by default",
  2439. type: "select",
  2440. default: "metric",
  2441. options: [
  2442. "metric",
  2443. "customary",
  2444. "relative",
  2445. "quirky"
  2446. ],
  2447. get value() {
  2448. return config.units;
  2449. },
  2450. set value(param) {
  2451. config.units = param;
  2452. updateSizes();
  2453. }
  2454. },
  2455. "names": {
  2456. name: "Show Names",
  2457. desc: "Display names over entities",
  2458. type: "toggle",
  2459. default: true,
  2460. get value() {
  2461. return checkBodyClass("toggle-entity-name");
  2462. },
  2463. set value(param) {
  2464. toggleBodyClass("toggle-entity-name", param);
  2465. }
  2466. },
  2467. "bottom-names": {
  2468. name: "Bottom Names",
  2469. desc: "Display names at the bottom",
  2470. type: "toggle",
  2471. default: false,
  2472. get value() {
  2473. return checkBodyClass("toggle-bottom-name");
  2474. },
  2475. set value(param) {
  2476. toggleBodyClass("toggle-bottom-name", param);
  2477. }
  2478. },
  2479. "top-names": {
  2480. name: "Show Arrows",
  2481. desc: "Point to entities that are much larger than the current view",
  2482. type: "toggle",
  2483. default: false,
  2484. get value() {
  2485. return checkBodyClass("toggle-top-name");
  2486. },
  2487. set value(param) {
  2488. toggleBodyClass("toggle-top-name", param);
  2489. }
  2490. },
  2491. "height-bars": {
  2492. name: "Height Bars",
  2493. desc: "Draw dashed lines to the top of each entity",
  2494. type: "toggle",
  2495. default: false,
  2496. get value() {
  2497. return checkBodyClass("toggle-height-bars");
  2498. },
  2499. set value(param) {
  2500. toggleBodyClass("toggle-height-bars", param);
  2501. }
  2502. },
  2503. "flag-nsfw": {
  2504. name: "Flag NSFW",
  2505. desc: "Highlight NSFW things in red",
  2506. type: "toggle",
  2507. default: false,
  2508. get value() {
  2509. return checkBodyClass("flag-nsfw");
  2510. },
  2511. set value(param) {
  2512. toggleBodyClass("flag-nsfw", param);
  2513. }
  2514. },
  2515. "glowing-entities": {
  2516. name: "Glowing Edges",
  2517. desc: "Makes all entities glow",
  2518. type: "toggle",
  2519. default: false,
  2520. get value() {
  2521. return checkBodyClass("toggle-entity-glow");
  2522. },
  2523. set value(param) {
  2524. toggleBodyClass("toggle-entity-glow", param);
  2525. }
  2526. },
  2527. "smoothing": {
  2528. name: "Smoothing",
  2529. desc: "Smooth out movements and size changes. Disable for better performance.",
  2530. type: "toggle",
  2531. default: true,
  2532. get value() {
  2533. return checkBodyClass("smoothing");
  2534. },
  2535. set value(param) {
  2536. toggleBodyClass("smoothing", param);
  2537. }
  2538. },
  2539. "auto-mass": {
  2540. name: "Estimate Mass",
  2541. desc: "Guess the mass of things that don't have one specified using the selected body type",
  2542. type: "select",
  2543. default: "off",
  2544. disabled: "off",
  2545. options: [
  2546. "off",
  2547. "human",
  2548. "quadruped at shoulder",
  2549. ],
  2550. get value() {
  2551. return config.autoMass
  2552. },
  2553. set value(param) {
  2554. config.autoMass = param
  2555. }
  2556. },
  2557. "auto-food-intake": {
  2558. name: "Estimate Food Intake",
  2559. desc: "Guess how much food creatures need, based on their mass -- 2000kcal per 150lbs",
  2560. type: "toggle",
  2561. default: false,
  2562. get value() {
  2563. return config.autoFoodIntake
  2564. },
  2565. set value(param) {
  2566. config.autoFoodIntake = param
  2567. }
  2568. },
  2569. "auto-caloric-value": {
  2570. name: "Estimate Caloric Value",
  2571. desc: "Guess how much food a creature is worth -- 860kcal per pound",
  2572. type: "toggle",
  2573. default: false,
  2574. get value() {
  2575. return config.autoCaloricValue
  2576. },
  2577. set value(param) {
  2578. config.autoCaloricValue = param
  2579. }
  2580. },
  2581. "auto-prey-capacity": {
  2582. name: "Estimate Prey Capacity",
  2583. desc: "Guess how much prey creatures can hold, based on their mass",
  2584. type: "select",
  2585. default: "none",
  2586. options: [
  2587. "none",
  2588. "realistic",
  2589. "same-size"
  2590. ],
  2591. get value() {
  2592. return config.autoPreyCapacity;
  2593. },
  2594. set value(param) {
  2595. config.autoPreyCapacity = param;
  2596. }
  2597. },
  2598. }
  2599. function prepareSettings(userSettings) {
  2600. const menubar = document.querySelector("#settings-menu");
  2601. Object.entries(settingsData).forEach(([id, entry]) => {
  2602. const holder = document.createElement("label");
  2603. holder.classList.add("settings-holder");
  2604. const input = document.createElement("input");
  2605. input.id = "setting-" + id;
  2606. const vertical = document.createElement("div");
  2607. vertical.classList.add("settings-vertical");
  2608. const name = document.createElement("label");
  2609. name.innerText = entry.name;
  2610. name.classList.add("settings-name");
  2611. name.setAttribute("for", input.id);
  2612. const desc = document.createElement("label");
  2613. desc.innerText = entry.desc;
  2614. desc.classList.add("settings-desc");
  2615. desc.setAttribute("for", input.id);
  2616. if (entry.type == "toggle") {
  2617. input.type = "checkbox";
  2618. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  2619. holder.setAttribute("for", input.id);
  2620. vertical.appendChild(name);
  2621. vertical.appendChild(desc);
  2622. holder.appendChild(vertical);
  2623. holder.appendChild(input);
  2624. menubar.appendChild(holder);
  2625. const update = () => {
  2626. if (input.checked) {
  2627. holder.classList.add("enabled");
  2628. holder.classList.remove("disabled");
  2629. } else {
  2630. holder.classList.remove("enabled");
  2631. holder.classList.add("disabled");
  2632. }
  2633. entry.value = input.checked;
  2634. }
  2635. update();
  2636. input.addEventListener("change", update);
  2637. } else if (entry.type == "select") {
  2638. // we don't use the input element we made!
  2639. const select = document.createElement("select");
  2640. select.id = "setting-" + id;
  2641. entry.options.forEach(choice => {
  2642. const option = document.createElement("option");
  2643. option.innerText = choice;
  2644. select.appendChild(option);
  2645. })
  2646. select.value = userSettings[id] === undefined ? entry.default : userSettings[id];
  2647. vertical.appendChild(name);
  2648. vertical.appendChild(desc);
  2649. holder.appendChild(vertical);
  2650. holder.appendChild(select);
  2651. menubar.appendChild(holder);
  2652. const update = () => {
  2653. entry.value = select.value;
  2654. if (entry.disabled !== undefined && entry.value !== entry.disabled) {
  2655. holder.classList.add("enabled");
  2656. holder.classList.remove("disabled");
  2657. } else {
  2658. holder.classList.remove("enabled");
  2659. holder.classList.add("disabled");
  2660. }
  2661. }
  2662. update();
  2663. select.addEventListener("change", update);
  2664. }
  2665. })
  2666. }
  2667. function prepareMenu() {
  2668. prepareSidebar();
  2669. updateSaveInfo();
  2670. if (checkHelpDate()) {
  2671. document.querySelector("#open-help").classList.add("highlighted");
  2672. }
  2673. }
  2674. function updateSaveInfo() {
  2675. const saves = getSaves();
  2676. const load = document.querySelector("#menu-load ~ select");
  2677. load.innerHTML = "";
  2678. saves.forEach(save => {
  2679. const option = document.createElement("option");
  2680. option.innerText = save;
  2681. option.value = save;
  2682. load.appendChild(option);
  2683. });
  2684. const del = document.querySelector("#menu-delete ~ select");
  2685. del.innerHTML = "";
  2686. saves.forEach(save => {
  2687. const option = document.createElement("option");
  2688. option.innerText = save;
  2689. option.value = save;
  2690. del.appendChild(option);
  2691. });
  2692. }
  2693. function getSaves() {
  2694. try {
  2695. const results = [];
  2696. Object.keys(localStorage).forEach(key => {
  2697. if (key.startsWith("macrovision-save-")) {
  2698. results.push(key.replace("macrovision-save-", ""));
  2699. }
  2700. })
  2701. return results;
  2702. } catch (err) {
  2703. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2704. console.error(err);
  2705. return false;
  2706. }
  2707. }
  2708. function getUserSettings() {
  2709. try {
  2710. const settings = JSON.parse(localStorage.getItem("settings"));
  2711. return settings === null ? {} : settings;
  2712. } catch {
  2713. return {};
  2714. }
  2715. }
  2716. function exportUserSettings() {
  2717. const settings = {};
  2718. Object.entries(settingsData).forEach(([id, entry]) => {
  2719. settings[id] = entry.value;
  2720. });
  2721. return settings;
  2722. }
  2723. function setUserSettings(settings) {
  2724. try {
  2725. localStorage.setItem("settings", JSON.stringify(settings));
  2726. } catch {
  2727. // :(
  2728. }
  2729. }
  2730. const lastHelpChange = 1601955834693;
  2731. function checkHelpDate() {
  2732. // disabling this for now
  2733. return false;
  2734. try {
  2735. const old = localStorage.getItem("help-viewed");
  2736. if (old === null || old < lastHelpChange) {
  2737. return true;
  2738. }
  2739. return false;
  2740. } catch {
  2741. console.warn("Could not set the help-viewed date");
  2742. return false;
  2743. }
  2744. }
  2745. function setHelpDate() {
  2746. try {
  2747. localStorage.setItem("help-viewed", Date.now());
  2748. } catch {
  2749. console.warn("Could not set the help-viewed date");
  2750. }
  2751. }
  2752. function doYScroll() {
  2753. const worldHeight = config.height.toNumber("meters");
  2754. config.y += scrollDirection * worldHeight / 180;
  2755. updateSizes();
  2756. scrollDirection *= 1.05;
  2757. }
  2758. function doXScroll() {
  2759. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2760. config.x += scrollDirection * worldWidth / 180 ;
  2761. updateSizes();
  2762. scrollDirection *= 1.05;
  2763. }
  2764. function doZoom() {
  2765. const oldHeight = config.height;
  2766. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  2767. zoomDirection *= 1.05;
  2768. }
  2769. function doSize() {
  2770. if (selected) {
  2771. const entity = entities[selected.dataset.key];
  2772. const oldHeight = entity.views[entity.view].height;
  2773. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  2774. entity.dirty = true;
  2775. updateEntityOptions(entity, entity.view);
  2776. updateViewOptions(entity, entity.view);
  2777. updateSizes(true);
  2778. sizeDirection *= 1.01;
  2779. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  2780. let extra = entity.views[entity.view].image.extra;
  2781. extra = extra === undefined ? 1 : extra;
  2782. const worldHeight = config.height.toNumber("meters");
  2783. if (ownHeight * extra > worldHeight) {
  2784. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra));
  2785. } else if (ownHeight * extra * 10 < worldHeight) {
  2786. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, extra * 10));
  2787. }
  2788. }
  2789. }
  2790. function selectNewUnit() {
  2791. const unitSelector = document.querySelector("#options-height-unit");
  2792. checkFitWorld();
  2793. const scaleInput = document.querySelector("#options-height-value");
  2794. const newVal = math.unit(scaleInput.value, unitSelector.dataset.oldUnit).toNumber(unitSelector.value);
  2795. setNumericInput(scaleInput, newVal);
  2796. updateWorldHeight();
  2797. unitSelector.dataset.oldUnit = unitSelector.value;
  2798. }
  2799. // given a world position, return the position relative to the entity at normal scale
  2800. function entityRelativePosition(pos, entityElement) {
  2801. const entity = entities[entityElement.dataset.key]
  2802. const x = parseFloat(entityElement.dataset.x)
  2803. const y = parseFloat(entityElement.dataset.y)
  2804. pos.x -= x
  2805. pos.y -= y
  2806. pos.x /= entity.scale
  2807. pos.y /= entity.scale
  2808. return pos
  2809. }
  2810. document.addEventListener("DOMContentLoaded", () => {
  2811. prepareMenu();
  2812. prepareEntities();
  2813. document.querySelector("#open-help").addEventListener("click", e => {
  2814. setHelpDate();
  2815. document.querySelector("#open-help").classList.remove("highlighted");
  2816. window.open("https://www.notion.so/Macrovision-5c7f9377424743358ddf6db5671f439e", "_blank");
  2817. });
  2818. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  2819. copyScreenshot();
  2820. });
  2821. document.querySelector("#save-screenshot").addEventListener("click", e => {
  2822. saveScreenshot();
  2823. });
  2824. document.querySelector("#open-screenshot").addEventListener("click", e => {
  2825. openScreenshot();
  2826. });
  2827. document.querySelector("#toggle-menu").addEventListener("click", e => {
  2828. const popoutMenu = document.querySelector("#sidebar-menu");
  2829. if (popoutMenu.classList.contains("visible")) {
  2830. popoutMenu.classList.remove("visible");
  2831. } else {
  2832. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2833. const rect = e.target.getBoundingClientRect();
  2834. popoutMenu.classList.add("visible");
  2835. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2836. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2837. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2838. let screenWidth = window.innerWidth;
  2839. if (menuWidth * 1.5 > screenWidth) {
  2840. popoutMenu.style.left = 25 + "px";
  2841. }
  2842. }
  2843. e.stopPropagation();
  2844. });
  2845. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  2846. e.stopPropagation();
  2847. });
  2848. document.addEventListener("click", e => {
  2849. document.querySelector("#sidebar-menu").classList.remove("visible");
  2850. });
  2851. document.querySelector("#toggle-settings").addEventListener("click", e => {
  2852. const popoutMenu = document.querySelector("#settings-menu");
  2853. if (popoutMenu.classList.contains("visible")) {
  2854. popoutMenu.classList.remove("visible");
  2855. } else {
  2856. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  2857. const rect = e.target.getBoundingClientRect();
  2858. popoutMenu.classList.add("visible");
  2859. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  2860. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  2861. let menuWidth = popoutMenu.getBoundingClientRect().width;
  2862. let screenWidth = window.innerWidth;
  2863. if (menuWidth * 1.5 > screenWidth) {
  2864. popoutMenu.style.left = 25 + "px";
  2865. }
  2866. }
  2867. e.stopPropagation();
  2868. });
  2869. document.querySelector("#settings-menu").addEventListener("click", e => {
  2870. e.stopPropagation();
  2871. });
  2872. document.addEventListener("click", e => {
  2873. document.querySelector("#settings-menu").classList.remove("visible");
  2874. });
  2875. window.addEventListener("unload", () => {
  2876. saveScene("autosave");
  2877. setUserSettings(exportUserSettings());
  2878. });
  2879. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  2880. if (e.target.value == "None") {
  2881. deselect()
  2882. } else {
  2883. select(document.querySelector("#entity-" + e.target.value));
  2884. }
  2885. });
  2886. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  2887. const sidebar = document.querySelector("#options");
  2888. if (sidebar.classList.contains("hidden")) {
  2889. sidebar.classList.remove("hidden");
  2890. e.target.classList.remove("rotate-forward");
  2891. e.target.classList.add("rotate-backward");
  2892. } else {
  2893. sidebar.classList.add("hidden");
  2894. e.target.classList.add("rotate-forward");
  2895. e.target.classList.remove("rotate-backward");
  2896. }
  2897. handleResize();
  2898. });
  2899. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  2900. document.querySelector("#options-order-forward").addEventListener("click", e => {
  2901. if (selected) {
  2902. entities[selected.dataset.key].priority += 1;
  2903. }
  2904. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2905. updateSizes();
  2906. });
  2907. document.querySelector("#options-order-back").addEventListener("click", e => {
  2908. if (selected) {
  2909. entities[selected.dataset.key].priority -= 1;
  2910. }
  2911. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  2912. updateSizes();
  2913. });
  2914. document.querySelector("#options-brightness-up").addEventListener("click", e => {
  2915. if (selected) {
  2916. entities[selected.dataset.key].brightness += 1;
  2917. }
  2918. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2919. updateSizes();
  2920. });
  2921. document.querySelector("#options-brightness-down").addEventListener("click", e => {
  2922. if (selected) {
  2923. entities[selected.dataset.key].brightness -= 1;
  2924. }
  2925. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2926. updateSizes();
  2927. });
  2928. document.querySelector("#options-rotate-left").addEventListener("click", e => {
  2929. if (selected) {
  2930. entities[selected.dataset.key].rotation -= Math.PI/4;
  2931. }
  2932. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2933. updateSizes();
  2934. });
  2935. document.querySelector("#options-rotate-right").addEventListener("click", e => {
  2936. if (selected) {
  2937. entities[selected.dataset.key].rotation += Math.PI/4;
  2938. }
  2939. selected.querySelector("img").style.setProperty("--rotation", (entities[selected.dataset.key].rotation * 180 / Math.PI) + "deg")
  2940. updateSizes();
  2941. });
  2942. document.querySelector("#options-flip").addEventListener("click", e => {
  2943. if (selected) {
  2944. selected.querySelector(".entity-image").classList.toggle("flipped");
  2945. }
  2946. document.querySelector("#options-brightness-display").innerText = entities[selected.dataset.key].brightness;
  2947. updateSizes();
  2948. });
  2949. const sceneChoices = document.querySelector("#menu-preset ~ select");
  2950. Object.entries(scenes).forEach(([id, scene]) => {
  2951. const option = document.createElement("option");
  2952. option.innerText = id;
  2953. option.value = id;
  2954. sceneChoices.appendChild(option);
  2955. });
  2956. document.querySelector("#menu-preset").addEventListener("click", e => {
  2957. const chosen = sceneChoices.value;
  2958. removeAllEntities();
  2959. scenes[chosen]();
  2960. });
  2961. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  2962. canvasWidth = document.querySelector("#display").clientWidth - 100;
  2963. canvasHeight = document.querySelector("#display").clientHeight - 50;
  2964. document.querySelector("#options-height-value").addEventListener("change", e => {
  2965. updateWorldHeight();
  2966. })
  2967. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  2968. e.stopPropagation();
  2969. })
  2970. const unitSelector = document.querySelector("#options-height-unit");
  2971. Object.entries(unitChoices.length).forEach(([group, entries]) => {
  2972. const optGroup = document.createElement("optgroup");
  2973. optGroup.label = group;
  2974. unitSelector.appendChild(optGroup);
  2975. entries.forEach(entry => {
  2976. const option = document.createElement("option");
  2977. option.innerText = entry;
  2978. // we haven't loaded user settings yet, so we can't choose the unit just yet
  2979. unitSelector.appendChild(option);
  2980. })
  2981. });
  2982. unitSelector.addEventListener("input", selectNewUnit);
  2983. param = window.location.hash;
  2984. // we now use the fragment for links, but we should still support old stuff:
  2985. if (param.length > 0) {
  2986. param = param.substring(1);
  2987. } else {
  2988. param = new URL(window.location.href).searchParams.get("scene");
  2989. }
  2990. document.querySelector("#world").addEventListener("mousedown", e => {
  2991. // only middle mouse clicks
  2992. if (e.which == 2) {
  2993. panning = true;
  2994. panOffsetX = e.clientX;
  2995. panOffsetY = e.clientY;
  2996. Object.keys(entities).forEach(key => {
  2997. document.querySelector("#entity-" + key).classList.add("no-transition");
  2998. });
  2999. }
  3000. });
  3001. document.addEventListener("mouseup", e => {
  3002. if (e.which == 2) {
  3003. panning = false;
  3004. Object.keys(entities).forEach(key => {
  3005. document.querySelector("#entity-" + key).classList.remove("no-transition");
  3006. });
  3007. }
  3008. });
  3009. document.querySelector("#world").addEventListener("touchstart", e => {
  3010. if (!rulerMode) {
  3011. panning = true;
  3012. panOffsetX = e.touches[0].clientX;
  3013. panOffsetY = e.touches[0].clientY;
  3014. e.preventDefault();
  3015. Object.keys(entities).forEach(key => {
  3016. document.querySelector("#entity-" + key).classList.add("no-transition");
  3017. });
  3018. }
  3019. });
  3020. document.querySelector("#world").addEventListener("touchend", e => {
  3021. panning = false;
  3022. Object.keys(entities).forEach(key => {
  3023. document.querySelector("#entity-" + key).classList.remove("no-transition");
  3024. });
  3025. });
  3026. document.querySelector("#world").addEventListener("mousedown", e => {
  3027. // only left mouse clicks
  3028. if (e.which == 1 && rulerMode) {
  3029. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3030. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3031. let pos = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3032. if (config.rulersStick && selected) {
  3033. pos = entityRelativePosition(pos, selected)
  3034. }
  3035. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y, entityKey: null };
  3036. if (config.rulersStick && selected) {
  3037. currentRuler.entityKey = selected.dataset.key
  3038. }
  3039. }
  3040. });
  3041. document.querySelector("#world").addEventListener("mouseup", e => {
  3042. // only left mouse clicks
  3043. if (e.which == 1 && currentRuler) {
  3044. rulers.push(currentRuler);
  3045. currentRuler = null;
  3046. rulerMode = false;
  3047. }
  3048. });
  3049. document.querySelector("#world").addEventListener("touchstart", e => {
  3050. if (rulerMode) {
  3051. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3052. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3053. let pos = pix2pos({ x: e.touches[0].clientX - entX, y: e.touches[0].clientY - entY });
  3054. if (config.rulersStick && selected) {
  3055. pos = entityRelativePosition(pos, selected)
  3056. }
  3057. currentRuler = { x0: pos.x, y0: pos.y, x1: pos.y, y1: pos.y, entityKey: null };
  3058. if (config.rulersStick && selected) {
  3059. currentRuler.entityKey = selected.dataset.key
  3060. }
  3061. }
  3062. });
  3063. document.querySelector("#world").addEventListener("touchend", e => {
  3064. if (currentRuler) {
  3065. rulers.push(currentRuler);
  3066. currentRuler = null;
  3067. rulerMode = false;
  3068. }
  3069. });
  3070. document.querySelector("body").appendChild(testCtx.canvas);
  3071. world.addEventListener("mousedown", e => deselect(e));
  3072. world.addEventListener("touchstart", e => deselect({
  3073. which: 1,
  3074. }));
  3075. document.querySelector("#entities").addEventListener("mousedown", deselect);
  3076. document.querySelector("#display").addEventListener("mousedown", deselect);
  3077. document.addEventListener("mouseup", e => clickUp(e));
  3078. document.addEventListener("touchend", e => {
  3079. const fakeEvent = {
  3080. target: e.target,
  3081. clientX: e.changedTouches[0].clientX,
  3082. clientY: e.changedTouches[0].clientY,
  3083. which: 1
  3084. };
  3085. clickUp(fakeEvent);
  3086. });
  3087. const formList = document.querySelector("#entity-form");
  3088. formList.addEventListener("input", e => {
  3089. const entity = entities[selected.dataset.key];
  3090. entity.form = e.target.value;
  3091. entity.view = entity.formViews[entity.form];
  3092. if (Object.keys(entity.forms).length > 0)
  3093. entity.views[entity.view].height = entity.formSizes[entity.form].height;
  3094. preloadViews(entity);
  3095. configViewList(entity, entity.view);
  3096. const image = entity.views[entity.view].image;
  3097. selected.querySelector(".entity-image").src = image.source;
  3098. configViewOptions(entity, entity.view);
  3099. displayAttribution(image.source);
  3100. if (image.bottom !== undefined) {
  3101. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  3102. } else {
  3103. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  3104. }
  3105. if (config.autoFitSize) {
  3106. let targets = {};
  3107. targets[selected.dataset.key] = entities[selected.dataset.key];
  3108. fitEntities(targets);
  3109. }
  3110. configSizeList(entity);
  3111. updateSizes();
  3112. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3113. updateViewOptions(entities[selected.dataset.key], entity.view);
  3114. });
  3115. const viewList = document.querySelector("#entity-view");
  3116. document.querySelector("#entity-view").addEventListener("input", e => {
  3117. const entity = entities[selected.dataset.key];
  3118. entity.view = e.target.value;
  3119. preloadViews(entity);
  3120. const image = entities[selected.dataset.key].views[e.target.value].image;
  3121. selected.querySelector(".entity-image").src = image.source;
  3122. configViewOptions(entity, entity.view);
  3123. displayAttribution(image.source);
  3124. if (image.bottom !== undefined) {
  3125. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  3126. } else {
  3127. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  3128. }
  3129. updateSizes();
  3130. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  3131. updateViewOptions(entities[selected.dataset.key], e.target.value);
  3132. });
  3133. document.querySelector("#entity-view").addEventListener("input", e => {
  3134. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  3135. viewList.classList.add("nsfw");
  3136. } else {
  3137. viewList.classList.remove("nsfw");
  3138. }
  3139. })
  3140. clearViewList();
  3141. document.querySelector("#menu-clear").addEventListener("click", e => {
  3142. removeAllEntities();
  3143. });
  3144. document.querySelector("#delete-entity").disabled = true;
  3145. document.querySelector("#delete-entity").addEventListener("click", e => {
  3146. if (selected) {
  3147. removeEntity(selected);
  3148. selected = null;
  3149. }
  3150. });
  3151. document.querySelector("#menu-order-height").addEventListener("click", e => {
  3152. const order = Object.keys(entities).sort((a, b) => {
  3153. const entA = entities[a];
  3154. const entB = entities[b];
  3155. const viewA = entA.view;
  3156. const viewB = entB.view;
  3157. const heightA = entA.views[viewA].height.to("meter").value;
  3158. const heightB = entB.views[viewB].height.to("meter").value;
  3159. return heightA - heightB;
  3160. });
  3161. arrangeEntities(order);
  3162. });
  3163. // TODO: write some generic logic for this lol
  3164. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  3165. scrollDirection = -1;
  3166. clearInterval(scrollHandle);
  3167. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3168. e.stopPropagation();
  3169. });
  3170. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  3171. scrollDirection = 1;
  3172. clearInterval(scrollHandle);
  3173. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3174. e.stopPropagation();
  3175. });
  3176. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  3177. scrollDirection = -1;
  3178. clearInterval(scrollHandle);
  3179. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3180. e.stopPropagation();
  3181. });
  3182. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  3183. scrollDirection = 1;
  3184. clearInterval(scrollHandle);
  3185. scrollHandle = setInterval(doXScroll, 1000 / 20);
  3186. e.stopPropagation();
  3187. });
  3188. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  3189. scrollDirection = 1;
  3190. clearInterval(scrollHandle);
  3191. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3192. e.stopPropagation();
  3193. });
  3194. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  3195. scrollDirection = -1;
  3196. clearInterval(scrollHandle);
  3197. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3198. e.stopPropagation();
  3199. });
  3200. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  3201. scrollDirection = 1;
  3202. clearInterval(scrollHandle);
  3203. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3204. e.stopPropagation();
  3205. });
  3206. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  3207. scrollDirection = -1;
  3208. clearInterval(scrollHandle);
  3209. scrollHandle = setInterval(doYScroll, 1000 / 20);
  3210. e.stopPropagation();
  3211. });
  3212. document.addEventListener("mouseup", e => {
  3213. clearInterval(scrollHandle);
  3214. scrollHandle = null;
  3215. });
  3216. document.addEventListener("touchend", e => {
  3217. clearInterval(scrollHandle);
  3218. scrollHandle = null;
  3219. });
  3220. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  3221. zoomDirection = -1;
  3222. clearInterval(zoomHandle);
  3223. zoomHandle = setInterval(doZoom, 1000 / 20);
  3224. e.stopPropagation();
  3225. });
  3226. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  3227. zoomDirection = 1;
  3228. clearInterval(zoomHandle);
  3229. zoomHandle = setInterval(doZoom, 1000 / 20);
  3230. e.stopPropagation();
  3231. });
  3232. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  3233. zoomDirection = -1;
  3234. clearInterval(zoomHandle);
  3235. zoomHandle = setInterval(doZoom, 1000 / 20);
  3236. e.stopPropagation();
  3237. });
  3238. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  3239. zoomDirection = 1;
  3240. clearInterval(zoomHandle);
  3241. zoomHandle = setInterval(doZoom, 1000 / 20);
  3242. e.stopPropagation();
  3243. });
  3244. document.addEventListener("mouseup", e => {
  3245. clearInterval(zoomHandle);
  3246. zoomHandle = null;
  3247. });
  3248. document.addEventListener("touchend", e => {
  3249. clearInterval(zoomHandle);
  3250. zoomHandle = null;
  3251. });
  3252. document.querySelector("#shrink").addEventListener("mousedown", e => {
  3253. sizeDirection = -1;
  3254. clearInterval(sizeHandle);
  3255. sizeHandle = setInterval(doSize, 1000 / 20);
  3256. e.stopPropagation();
  3257. });
  3258. document.querySelector("#grow").addEventListener("mousedown", e => {
  3259. sizeDirection = 1;
  3260. clearInterval(sizeHandle);
  3261. sizeHandle = setInterval(doSize, 1000 / 20);
  3262. e.stopPropagation();
  3263. });
  3264. document.querySelector("#shrink").addEventListener("touchstart", e => {
  3265. sizeDirection = -1;
  3266. clearInterval(sizeHandle);
  3267. sizeHandle = setInterval(doSize, 1000 / 20);
  3268. e.stopPropagation();
  3269. });
  3270. document.querySelector("#grow").addEventListener("touchstart", e => {
  3271. sizeDirection = 1;
  3272. clearInterval(sizeHandle);
  3273. sizeHandle = setInterval(doSize, 1000 / 20);
  3274. e.stopPropagation();
  3275. });
  3276. document.addEventListener("mouseup", e => {
  3277. clearInterval(sizeHandle);
  3278. sizeHandle = null;
  3279. });
  3280. document.addEventListener("touchend", e => {
  3281. clearInterval(sizeHandle);
  3282. sizeHandle = null;
  3283. });
  3284. document.querySelector("#ruler").addEventListener("click", e => {
  3285. rulerMode = !rulerMode;
  3286. if (rulerMode) {
  3287. toast("Ready to draw a ruler mark");
  3288. } else {
  3289. toast("Cancelled ruler mode");
  3290. }
  3291. });
  3292. document.querySelector("#ruler").addEventListener("mousedown", e => {
  3293. e.stopPropagation();
  3294. });
  3295. document.querySelector("#ruler").addEventListener("touchstart", e => {
  3296. e.stopPropagation();
  3297. });
  3298. document.querySelector("#fit").addEventListener("click", e => {
  3299. if (selected) {
  3300. let targets = {};
  3301. targets[selected.dataset.key] = entities[selected.dataset.key];
  3302. fitEntities(targets);
  3303. }
  3304. });
  3305. document.querySelector("#fit").addEventListener("mousedown", e => {
  3306. e.stopPropagation();
  3307. });
  3308. document.querySelector("#fit").addEventListener("touchstart", e => {
  3309. e.stopPropagation();
  3310. });
  3311. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  3312. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  3313. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  3314. document.addEventListener("keydown", e => {
  3315. if (e.key == "Delete") {
  3316. if (selected) {
  3317. removeEntity(selected);
  3318. selected = null;
  3319. }
  3320. }
  3321. })
  3322. document.addEventListener("keydown", e => {
  3323. if (e.key == "Shift") {
  3324. shiftHeld = true;
  3325. e.preventDefault();
  3326. } else if (e.key == "Alt") {
  3327. altHeld = true;
  3328. movingInBounds = false; // don't snap the object back in bounds when we let go
  3329. e.preventDefault();
  3330. }
  3331. });
  3332. document.addEventListener("keyup", e => {
  3333. if (e.key == "Shift") {
  3334. shiftHeld = false;
  3335. e.preventDefault();
  3336. } else if (e.key == "Alt") {
  3337. altHeld = false;
  3338. e.preventDefault();
  3339. }
  3340. });
  3341. window.addEventListener("resize", handleResize);
  3342. // TODO: further investigate why the tool initially starts out with wrong
  3343. // values under certain circumstances (seems to be narrow aspect ratios -
  3344. // maybe the menu bar is animating when it shouldn't)
  3345. setTimeout(handleResize, 250);
  3346. setTimeout(handleResize, 500);
  3347. setTimeout(handleResize, 750);
  3348. setTimeout(handleResize, 1000);
  3349. document.querySelector("#menu-permalink").addEventListener("click", e => {
  3350. linkScene();
  3351. });
  3352. document.querySelector("#menu-export").addEventListener("click", e => {
  3353. copyScene();
  3354. });
  3355. document.querySelector("#menu-import").addEventListener("click", e => {
  3356. pasteScene();
  3357. });
  3358. document.querySelector("#menu-save").addEventListener("click", e => {
  3359. const name = document.querySelector("#menu-save ~ input").value;
  3360. if (/\S/.test(name)) {
  3361. saveScene(name);
  3362. }
  3363. updateSaveInfo();
  3364. });
  3365. document.querySelector("#menu-load").addEventListener("click", e => {
  3366. const name = document.querySelector("#menu-load ~ select").value;
  3367. if (/\S/.test(name)) {
  3368. loadScene(name);
  3369. }
  3370. });
  3371. document.querySelector("#menu-delete").addEventListener("click", e => {
  3372. const name = document.querySelector("#menu-delete ~ select").value;
  3373. if (/\S/.test(name)) {
  3374. deleteScene(name);
  3375. }
  3376. });
  3377. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  3378. loadScene("autosave");
  3379. });
  3380. document.querySelector("#menu-add-image").addEventListener("click", e => {
  3381. document.querySelector("#file-upload-picker").click();
  3382. });
  3383. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  3384. if (e.target.files.length > 0) {
  3385. for (let i=0; i<e.target.files.length; i++) {
  3386. customEntityFromFile(e.target.files[i]);
  3387. }
  3388. }
  3389. })
  3390. document.querySelector("#menu-clear-rulers").addEventListener("click", e => {
  3391. rulers = [];
  3392. drawRulers();
  3393. });
  3394. document.addEventListener("paste", e => {
  3395. let index = 0;
  3396. let item = null;
  3397. let found = false;
  3398. for (; index < e.clipboardData.items.length; index++) {
  3399. item = e.clipboardData.items[index];
  3400. if (item.type == "image/png") {
  3401. found = true;
  3402. break;
  3403. }
  3404. }
  3405. if (!found) {
  3406. return;
  3407. }
  3408. let url = null;
  3409. const file = item.getAsFile();
  3410. customEntityFromFile(file);
  3411. });
  3412. document.querySelector("#world").addEventListener("dragover", e => {
  3413. e.preventDefault();
  3414. })
  3415. document.querySelector("#world").addEventListener("drop", e => {
  3416. e.preventDefault();
  3417. if (e.dataTransfer.files.length > 0) {
  3418. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3419. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3420. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  3421. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  3422. }
  3423. })
  3424. clearEntityOptions();
  3425. clearViewOptions();
  3426. clearAttribution();
  3427. // we do this last because configuring settings can cause things
  3428. // to happen (e.g. auto-fit)
  3429. prepareSettings(getUserSettings());
  3430. // now that we have this loaded, we can set it
  3431. unitSelector.dataset.oldUnit = defaultUnits.length[config.units];
  3432. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  3433. // ...and then update the world height by setting off an input event
  3434. document.querySelector("#options-height-unit").dispatchEvent(new Event('input', {
  3435. }));
  3436. if (param === null) {
  3437. scenes["Empty"]();
  3438. }
  3439. else {
  3440. try {
  3441. const data = JSON.parse(b64DecodeUnicode(param));
  3442. if (data.entities === undefined) {
  3443. return;
  3444. }
  3445. if (data.world === undefined) {
  3446. return;
  3447. }
  3448. importScene(data);
  3449. } catch (err) {
  3450. console.error(err);
  3451. scenes["Empty"]();
  3452. // probably wasn't valid data
  3453. }
  3454. }
  3455. document.querySelector("#world").addEventListener("wheel", e => {
  3456. if (shiftHeld) {
  3457. if (selected) {
  3458. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  3459. const entity = entities[selected.dataset.key];
  3460. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  3461. entity.dirty = true;
  3462. updateEntityOptions(entity, entity.view);
  3463. updateViewOptions(entity, entity.view);
  3464. updateSizes(true);
  3465. } else {
  3466. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3467. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  3468. updateSizes();
  3469. updateSizes();
  3470. }
  3471. } else {
  3472. if (config.autoFit) {
  3473. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  3474. } else {
  3475. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  3476. const change = config.height.toNumber("meters") - math.multiply(config.height, dir).toNumber("meters");
  3477. if (!config.lockYAxis) {
  3478. config.y += change / 2;
  3479. }
  3480. setWorldHeight(config.height, math.multiply(config.height, dir));
  3481. updateWorldOptions();
  3482. }
  3483. }
  3484. checkFitWorld();
  3485. })
  3486. updateWorldHeight();
  3487. document.querySelector("#search-box").addEventListener("change", e => doSearch(e.target.value));
  3488. });
  3489. let searchText = "";
  3490. function doSearch(value) {
  3491. searchText = value;
  3492. updateFilter();
  3493. }
  3494. function customEntityFromFile(file, x=0.5, y=0.5) {
  3495. file.arrayBuffer().then(buf => {
  3496. arr = new Uint8Array(buf);
  3497. blob = new Blob([arr], {type: file.type });
  3498. url = window.URL.createObjectURL(blob)
  3499. makeCustomEntity(url, x, y);
  3500. });
  3501. }
  3502. function makeCustomEntity(url, x=0.5, y=0.5) {
  3503. const maker = createEntityMaker(
  3504. {
  3505. name: "Custom Entity"
  3506. },
  3507. {
  3508. custom: {
  3509. attributes: {
  3510. height: {
  3511. name: "Height",
  3512. power: 1,
  3513. type: "length",
  3514. base: math.unit(6, "feet")
  3515. }
  3516. },
  3517. image: {
  3518. source: url
  3519. },
  3520. name: "Image",
  3521. info: {},
  3522. rename: false
  3523. }
  3524. },
  3525. []
  3526. );
  3527. const entity = maker.constructor();
  3528. entity.scale = config.height.toNumber("feet") / 20;
  3529. entity.ephemeral = true;
  3530. displayEntity(entity, "custom", x, y, true, true);
  3531. }
  3532. const filterDefs = {
  3533. none: {
  3534. id: "none",
  3535. name: "No Filter",
  3536. extract: maker => [],
  3537. render: name => name,
  3538. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3539. },
  3540. author: {
  3541. id: "author",
  3542. name: "Authors",
  3543. extract: maker => maker.authors ? maker.authors : [],
  3544. render: author => attributionData.people[author].name,
  3545. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3546. },
  3547. owner: {
  3548. id: "owner",
  3549. name: "Owners",
  3550. extract: maker => maker.owners ? maker.owners : [],
  3551. render: owner => attributionData.people[owner].name,
  3552. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3553. },
  3554. species: {
  3555. id: "species",
  3556. name: "Species",
  3557. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  3558. render: species => speciesData[species].name,
  3559. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3560. },
  3561. tags: {
  3562. id: "tags",
  3563. name: "Tags",
  3564. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  3565. render: tag => tagDefs[tag],
  3566. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  3567. },
  3568. size: {
  3569. id: "size",
  3570. name: "Normal Size",
  3571. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  3572. if (result && !size.default) {
  3573. return result;
  3574. }
  3575. let meters = size.height.toNumber("meters");
  3576. if (meters < 1e-1) {
  3577. return ["micro"];
  3578. } else if (meters < 1e1) {
  3579. return ["moderate"];
  3580. } else {
  3581. return ["macro"];
  3582. }
  3583. }, null)) : [],
  3584. render: tag => { return {
  3585. "micro": "Micro",
  3586. "moderate": "Moderate",
  3587. "macro": "Macro"
  3588. }[tag]},
  3589. sort: (tag1, tag2) => {
  3590. const order = {
  3591. "micro": 0,
  3592. "moderate": 1,
  3593. "macro": 2
  3594. };
  3595. return order[tag1[0]] - order[tag2[0]];
  3596. }
  3597. },
  3598. allSizes: {
  3599. id: "allSizes",
  3600. name: "Possible Size",
  3601. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  3602. const height = size.height;
  3603. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  3604. if (result) {
  3605. return result;
  3606. } else {
  3607. if (math.compare(height, value) <= 0) {
  3608. return name;
  3609. }
  3610. }
  3611. }, null);
  3612. set.add(result ? result : "infinite");
  3613. return set;
  3614. }, new Set())) : [],
  3615. render: tag => tag[0].toUpperCase() + tag.slice(1),
  3616. sort: (tag1, tag2) => {
  3617. const order = [
  3618. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  3619. "galactic", "universal", "omniversal", "infinite"
  3620. ]
  3621. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  3622. }
  3623. }
  3624. }
  3625. const sizeCategories = {
  3626. "atomic": math.unit(100, "angstroms"),
  3627. "microscopic": math.unit(100, "micrometers"),
  3628. "tiny": math.unit(100, "millimeters"),
  3629. "small": math.unit(1, "meter"),
  3630. "moderate": math.unit(3, "meters"),
  3631. "large": math.unit(10, "meters"),
  3632. "macro": math.unit(300, "meters"),
  3633. "megamacro": math.unit(1000, "kilometers"),
  3634. "planetary": math.unit(10, "earths"),
  3635. "stellar": math.unit(10, "solarradii"),
  3636. "galactic": math.unit(10, "galaxies"),
  3637. "universal": math.unit(10, "universes"),
  3638. "omniversal": math.unit(10, "multiverses")
  3639. };
  3640. function prepareEntities() {
  3641. availableEntities["buildings"] = makeBuildings();
  3642. availableEntities["characters"] = makeCharacters();
  3643. availableEntities["clothing"] = makeClothing();
  3644. availableEntities["creatures"] = makeCreatures();
  3645. availableEntities["fiction"] = makeFiction();
  3646. availableEntities["food"] = makeFood();
  3647. availableEntities["furniture"] = makeFurniture();
  3648. availableEntities["landmarks"] = makeLandmarks();
  3649. availableEntities["naturals"] = makeNaturals();
  3650. availableEntities["objects"] = makeObjects();
  3651. availableEntities["pokemon"] = makePokemon();
  3652. availableEntities["real-buildings"] = makeRealBuildings();
  3653. availableEntities["real-terrain"] = makeRealTerrains();
  3654. availableEntities["species"] = makeSpecies();
  3655. availableEntities["vehicles"] = makeVehicles();
  3656. availableEntities["species"].forEach(x => {
  3657. if (x.name == "Human") {
  3658. availableEntities["food"].push(x);
  3659. }
  3660. })
  3661. availableEntities["characters"].sort((x, y) => {
  3662. return x.name.localeCompare(y.name)
  3663. });
  3664. availableEntities["species"].sort((x, y) => {
  3665. return x.name.localeCompare(y.name)
  3666. });
  3667. availableEntities["objects"].sort((x, y) => {
  3668. return x.name.localeCompare(y.name)
  3669. });
  3670. const holder = document.querySelector("#spawners");
  3671. const filterHolder = document.querySelector("#filters");
  3672. const categorySelect = document.createElement("select");
  3673. categorySelect.id = "category-picker";
  3674. const filterSelect = document.createElement("select");
  3675. filterSelect.id = "filter-picker";
  3676. holder.appendChild(categorySelect);
  3677. filterHolder.appendChild(filterSelect);
  3678. const filterSets = {};
  3679. Object.values(filterDefs).forEach(filter => {
  3680. filterSets[filter.id] = new Set();
  3681. })
  3682. Object.entries(availableEntities).forEach(([category, entityList]) => {
  3683. const select = document.createElement("select");
  3684. select.id = "create-entity-" + category;
  3685. select.classList.add("entity-select");
  3686. for (let i = 0; i < entityList.length; i++) {
  3687. const entity = entityList[i];
  3688. const option = document.createElement("option");
  3689. option.value = i;
  3690. option.innerText = entity.name;
  3691. select.appendChild(option);
  3692. if (entity.nsfw) {
  3693. option.classList.add("nsfw");
  3694. }
  3695. Object.values(filterDefs).forEach(filter => {
  3696. filter.extract(entity).forEach(result => {
  3697. filterSets[filter.id].add(result);
  3698. });
  3699. });
  3700. availableEntitiesByName[entity.name] = entity;
  3701. };
  3702. select.addEventListener("change", e => {
  3703. if (select.options[select.selectedIndex]?.classList.contains("nsfw")) {
  3704. select.classList.add("nsfw");
  3705. } else {
  3706. select.classList.remove("nsfw");
  3707. }
  3708. // preload the entity's first image
  3709. const entity = entityList[select.selectedIndex]?.constructor();
  3710. if (entity)
  3711. {
  3712. let img = new Image();
  3713. img.src = entity.currentView.image.source;
  3714. }
  3715. })
  3716. const button = document.createElement("button");
  3717. button.id = "create-entity-" + category + "-button";
  3718. button.classList.add("entity-button");
  3719. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  3720. button.addEventListener("click", e => {
  3721. if (entityList[select.value] == null)
  3722. return;
  3723. const newEntity = entityList[select.value].constructor()
  3724. let yOffset = 0;
  3725. if (config.lockYAxis) {
  3726. yOffset = getVerticalOffset();
  3727. } else {
  3728. yOffset = (config.lockYAxis ? 0 : config.height.toNumber("meters")/2);
  3729. }
  3730. displayEntity(newEntity, newEntity.defaultView, config.x, config.y + yOffset, true, true);
  3731. });
  3732. const categoryOption = document.createElement("option");
  3733. categoryOption.value = category
  3734. categoryOption.innerText = category;
  3735. if (category == "characters") {
  3736. categoryOption.selected = true;
  3737. select.classList.add("category-visible");
  3738. button.classList.add("category-visible");
  3739. }
  3740. categorySelect.appendChild(categoryOption);
  3741. holder.appendChild(select);
  3742. holder.appendChild(button);
  3743. });
  3744. Object.values(filterDefs).forEach(filter => {
  3745. const option = document.createElement("option");
  3746. option.innerText = filter.name;
  3747. option.value = filter.id;
  3748. filterSelect.appendChild(option);
  3749. const filterNameSelect = document.createElement("select");
  3750. filterNameSelect.classList.add("filter-select");
  3751. filterNameSelect.id = "filter-" + filter.id;
  3752. filterHolder.appendChild(filterNameSelect);
  3753. const button = document.createElement("button");
  3754. button.classList.add("filter-button");
  3755. button.id = "create-filtered-" + filter.id + "-button";
  3756. filterHolder.appendChild(button);
  3757. const counter = document.createElement("div");
  3758. counter.classList.add("button-counter");
  3759. counter.innerText = "10";
  3760. button.appendChild(counter);
  3761. const i = document.createElement("i");
  3762. i.classList.add("fas");
  3763. i.classList.add("fa-plus");
  3764. button.appendChild(i);
  3765. button.addEventListener("click", e => {
  3766. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  3767. const count = makers.length + 2;
  3768. let index = 1;
  3769. if (makers.length > 50) {
  3770. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  3771. return;
  3772. }
  3773. }
  3774. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3775. const spawned = makers.map(element => {
  3776. const category = document.querySelector("#category-picker").value;
  3777. const maker = availableEntities[category][element.value];
  3778. const entity = maker.constructor()
  3779. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  3780. index += 1;
  3781. return entityIndex - 1;
  3782. });
  3783. updateSizes(true);
  3784. if (config.autoFitAdd) {
  3785. let targets = {};
  3786. spawned.forEach(key => {
  3787. targets[key] = entities[key];
  3788. })
  3789. fitEntities(targets);
  3790. }
  3791. });
  3792. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  3793. const option = document.createElement("option");
  3794. option.innerText = name[1];
  3795. option.value = name[0];
  3796. filterNameSelect.appendChild(option);
  3797. });
  3798. filterNameSelect.addEventListener("change", e => {
  3799. updateFilter();
  3800. });
  3801. });
  3802. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  3803. categorySelect.addEventListener("input", e => {
  3804. const oldSelect = document.querySelector(".entity-select.category-visible");
  3805. oldSelect.classList.remove("category-visible");
  3806. const oldButton = document.querySelector(".entity-button.category-visible");
  3807. oldButton.classList.remove("category-visible");
  3808. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  3809. newSelect.classList.add("category-visible");
  3810. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  3811. newButton.classList.add("category-visible");
  3812. recomputeFilters();
  3813. updateFilter();
  3814. });
  3815. recomputeFilters();
  3816. filterSelect.addEventListener("input", e => {
  3817. const oldSelect = document.querySelector(".filter-select.category-visible");
  3818. if (oldSelect)
  3819. oldSelect.classList.remove("category-visible");
  3820. const newSelect = document.querySelector("#filter-" + e.target.value);
  3821. if (newSelect && e.target.value != "none")
  3822. newSelect.classList.add("category-visible");
  3823. updateFilter();
  3824. });
  3825. ratioInfo = document.body.querySelector(".extra-info")
  3826. }
  3827. // Only display authors and owners if they appear
  3828. // somewhere in the current entity list
  3829. function recomputeFilters() {
  3830. const category = document.querySelector("#category-picker").value;
  3831. const filterSets = {};
  3832. Object.values(filterDefs).forEach(filter => {
  3833. filterSets[filter.id] = new Set();
  3834. });
  3835. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3836. const entity = availableEntities[category][element.value];
  3837. Object.values(filterDefs).forEach(filter => {
  3838. filter.extract(entity).forEach(result => {
  3839. filterSets[filter.id].add(result);
  3840. });
  3841. });
  3842. });
  3843. Object.values(filterDefs).forEach(filter => {
  3844. // always show the "none" option
  3845. let found = filter.id == "none";
  3846. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  3847. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  3848. element.classList.remove("filtered");
  3849. element.disabled = false;
  3850. found = true;
  3851. } else {
  3852. element.classList.add("filtered");
  3853. element.disabled = true;
  3854. }
  3855. });
  3856. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  3857. if (found) {
  3858. filterOption.classList.remove("filtered");
  3859. filterOption.disabled = false;
  3860. } else {
  3861. filterOption.classList.add("filtered");
  3862. filterOption.disabled = true;
  3863. }
  3864. });
  3865. document.querySelector("#filter-picker").value = "none";
  3866. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  3867. }
  3868. function updateFilter() {
  3869. const category = document.querySelector("#category-picker").value;
  3870. const type = document.querySelector("#filter-picker").value;
  3871. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  3872. clearFilter();
  3873. const noFilter = !filterKeySelect;
  3874. let key;
  3875. let current = document.querySelector(".entity-select.category-visible").value;
  3876. if (!noFilter)
  3877. {
  3878. key = filterKeySelect.value;
  3879. current
  3880. }
  3881. let replace = current == "";
  3882. let first = null;
  3883. let count = 0;
  3884. const lowerSearchText = searchText !== "" ? searchText.toLowerCase() : null;
  3885. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3886. let keep = noFilter;
  3887. if (!noFilter && filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  3888. keep = true;
  3889. }
  3890. if (searchText != "" && !availableEntities[category][element.value].name.toLowerCase().includes(lowerSearchText))
  3891. {
  3892. keep = false;
  3893. }
  3894. if (!keep) {
  3895. element.classList.add("filtered");
  3896. element.disabled = true;
  3897. if (current == element.value) {
  3898. replace = true;
  3899. }
  3900. } else {
  3901. count += 1;
  3902. if (!first) {
  3903. first = element.value;
  3904. }
  3905. }
  3906. });
  3907. const button = document.querySelector(".filter-select.category-visible + button");
  3908. if (button) {
  3909. button.querySelector(".button-counter").innerText = count;
  3910. }
  3911. if (replace) {
  3912. document.querySelector(".entity-select.category-visible").value = first;
  3913. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  3914. }
  3915. }
  3916. function clearFilter() {
  3917. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  3918. element.classList.remove("filtered");
  3919. element.disabled = false;
  3920. });
  3921. }
  3922. document.addEventListener("mousemove", (e) => {
  3923. if (currentRuler) {
  3924. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  3925. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  3926. let position = pix2pos({ x: e.clientX - entX, y: e.clientY - entY });
  3927. if (config.rulersStick && selected) {
  3928. position = entityRelativePosition(position, selected)
  3929. }
  3930. currentRuler.x1 = position.x;
  3931. currentRuler.y1 = position.y;
  3932. }
  3933. drawRulers();
  3934. });
  3935. document.addEventListener("touchmove", (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.touches[0].clientX - entX, y: e.touches[0].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("mousemove", (e) => {
  3949. if (clicked) {
  3950. let position = pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY });
  3951. if (movingInBounds) {
  3952. position = snapPos(position);
  3953. } else {
  3954. let x = e.clientX - dragOffsetX;
  3955. let y = e.clientY - dragOffsetY;
  3956. if (x >= 0 && x <= canvasWidth && y >= 0 && y <= canvasHeight) {
  3957. movingInBounds = true;
  3958. }
  3959. }
  3960. clicked.dataset.x = position.x;
  3961. clicked.dataset.y = position.y;
  3962. updateEntityElement(entities[clicked.dataset.key], clicked);
  3963. if (hoveringInDeleteArea(e)) {
  3964. document.querySelector("#menubar").classList.add("hover-delete");
  3965. } else {
  3966. document.querySelector("#menubar").classList.remove("hover-delete");
  3967. }
  3968. }
  3969. if (panning && panReady) {
  3970. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  3971. const worldHeight = config.height.toNumber("meters");
  3972. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  3973. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  3974. panOffsetX = e.clientX;
  3975. panOffsetY = e.clientY;
  3976. updateSizes();
  3977. panReady = false;
  3978. setTimeout(() => panReady=true, 1000/120);
  3979. }
  3980. });
  3981. document.addEventListener("touchmove", (e) => {
  3982. if (clicked) {
  3983. e.preventDefault();
  3984. let x = e.touches[0].clientX;
  3985. let y = e.touches[0].clientY;
  3986. const position = snapPos(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  3987. clicked.dataset.x = position.x;
  3988. clicked.dataset.y = position.y;
  3989. updateEntityElement(entities[clicked.dataset.key], clicked);
  3990. // what a hack
  3991. // I should centralize this 'fake event' creation...
  3992. if (hoveringInDeleteArea({ clientY: y })) {
  3993. document.querySelector("#menubar").classList.add("hover-delete");
  3994. } else {
  3995. document.querySelector("#menubar").classList.remove("hover-delete");
  3996. }
  3997. }
  3998. if (panning && panReady) {
  3999. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  4000. const worldHeight = config.height.toNumber("meters");
  4001. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  4002. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  4003. panOffsetX = e.touches[0].clientX;
  4004. panOffsetY = e.touches[0].clientY;
  4005. updateSizes();
  4006. panReady = false;
  4007. setTimeout(() => panReady=true, 1000/60);
  4008. }
  4009. }, { passive: false });
  4010. function checkFitWorld() {
  4011. if (config.autoFit) {
  4012. fitWorld();
  4013. return true;
  4014. }
  4015. return false;
  4016. }
  4017. function fitWorld(manual = false, factor = 1.1) {
  4018. if (Object.keys(entities).length > 0) {
  4019. fitEntities(entities, factor);
  4020. }
  4021. }
  4022. function fitEntities(targetEntities, manual = false, factor = 1.1) {
  4023. let minX = Infinity;
  4024. let maxX = -Infinity;
  4025. let minY = Infinity;
  4026. let maxY = -Infinity;
  4027. let count = 0;
  4028. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  4029. const worldHeight = config.height.toNumber("meters");
  4030. Object.entries(targetEntities).forEach(([key, entity]) => {
  4031. const view = entity.view;
  4032. let extra = entity.views[view].image.extra;
  4033. extra = extra === undefined ? 1 : extra;
  4034. const image = document.querySelector("#entity-" + key + " > .entity-image");
  4035. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  4036. let width = image.width;
  4037. let height = image.height;
  4038. // only really relevant if the images haven't loaded in yet
  4039. if (height == 0) {
  4040. height = 100;
  4041. }
  4042. if (width == 0) {
  4043. width = height;
  4044. }
  4045. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  4046. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  4047. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  4048. const yBottom = y;
  4049. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  4050. minX = Math.min(minX, xBottom);
  4051. maxX = Math.max(maxX, xTop);
  4052. minY = Math.min(minY, yBottom);
  4053. maxY = Math.max(maxY, yTop);
  4054. count += 1;
  4055. });
  4056. if (config.lockYAxis) {
  4057. minY = 0;
  4058. }
  4059. let ySize = (maxY - minY) * factor;
  4060. let xSize = (maxX - minX) * factor;
  4061. if (xSize / ySize > worldWidth / worldHeight) {
  4062. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  4063. }
  4064. config.x = (maxX + minX) / 2;
  4065. config.y = minY;
  4066. height = math.unit(ySize, "meter")
  4067. setWorldHeight(config.height, math.multiply(height, factor));
  4068. }
  4069. function updateWorldHeight() {
  4070. const unit = document.querySelector("#options-height-unit").value;
  4071. const rawValue = document.querySelector("#options-height-value").value;
  4072. var value
  4073. try {
  4074. value = math.evaluate(rawValue)
  4075. if (typeof(value) !== "number") {
  4076. try {
  4077. value = value.toNumber(unit)
  4078. } catch {
  4079. toast("Invalid input: " + rawValue + " can't be converted to " + unit)
  4080. }
  4081. }
  4082. } catch {
  4083. toast("Invalid input: could not parse " + rawValue)
  4084. return;
  4085. }
  4086. const newHeight = Math.max(0.000000001, value);
  4087. const oldHeight = config.height;
  4088. setWorldHeight(oldHeight, math.unit(newHeight, unit), true);
  4089. }
  4090. function setWorldHeight(oldHeight, newHeight, keepUnit=false) {
  4091. worldSizeDirty = true;
  4092. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  4093. const unit = document.querySelector("#options-height-unit").value;
  4094. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  4095. Object.entries(entities).forEach(([key, entity]) => {
  4096. const element = document.querySelector("#entity-" + key);
  4097. let newPosition;
  4098. if (altHeld) {
  4099. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  4100. } else {
  4101. newPosition = { x: element.dataset.x, y: element.dataset.y };
  4102. }
  4103. element.dataset.x = newPosition.x;
  4104. element.dataset.y = newPosition.y;
  4105. });
  4106. if (!keepUnit) {
  4107. pickUnit()
  4108. }
  4109. updateSizes();
  4110. }
  4111. function loadScene(name = "default") {
  4112. if (name === "") {
  4113. name = "default"
  4114. }
  4115. try {
  4116. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  4117. if (data === null) {
  4118. console.error("Couldn't load " + name)
  4119. return false;
  4120. }
  4121. importScene(data);
  4122. toast("Loaded " + name);
  4123. return true;
  4124. } catch (err) {
  4125. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  4126. console.error(err);
  4127. return false;
  4128. }
  4129. }
  4130. function saveScene(name = "default") {
  4131. try {
  4132. const string = JSON.stringify(exportScene());
  4133. localStorage.setItem("macrovision-save-" + name, string);
  4134. toast("Saved as " + name);
  4135. } catch (err) {
  4136. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  4137. console.error(err);
  4138. }
  4139. }
  4140. function deleteScene(name = "default") {
  4141. if (confirm("Really delete the " + name + " scene?")) {
  4142. try {
  4143. localStorage.removeItem("macrovision-save-" + name)
  4144. toast("Deleted " + name);
  4145. } catch (err) {
  4146. console.error(err);
  4147. }
  4148. }
  4149. updateSaveInfo();
  4150. }
  4151. function exportScene() {
  4152. const results = {};
  4153. results.entities = [];
  4154. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  4155. const element = document.querySelector("#entity-" + key);
  4156. results.entities.push({
  4157. name: entity.identifier,
  4158. customName: entity.name,
  4159. scale: entity.scale,
  4160. rotation: entity.rotation,
  4161. view: entity.view,
  4162. form: entity.form,
  4163. x: element.dataset.x,
  4164. y: element.dataset.y,
  4165. priority: entity.priority,
  4166. brightness: entity.brightness
  4167. });
  4168. });
  4169. const unit = document.querySelector("#options-height-unit").value;
  4170. results.world = {
  4171. height: config.height.toNumber(unit),
  4172. unit: unit,
  4173. x: config.x,
  4174. y: config.y
  4175. }
  4176. results.version = migrationDefs.length;
  4177. return results;
  4178. }
  4179. // btoa doesn't like anything that isn't ASCII
  4180. // great
  4181. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  4182. // for providing an alternative
  4183. function b64EncodeUnicode(str) {
  4184. // first we use encodeURIComponent to get percent-encoded UTF-8,
  4185. // then we convert the percent encodings into raw bytes which
  4186. // can be fed into btoa.
  4187. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  4188. function toSolidBytes(match, p1) {
  4189. return String.fromCharCode('0x' + p1);
  4190. }));
  4191. }
  4192. function b64DecodeUnicode(str) {
  4193. // Going backwards: from bytestream, to percent-encoding, to original string.
  4194. return decodeURIComponent(atob(str).split('').map(function (c) {
  4195. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  4196. }).join(''));
  4197. }
  4198. function linkScene() {
  4199. loc = new URL(window.location);
  4200. const link = loc.protocol + "//" + loc.host + loc.pathname + "#" + b64EncodeUnicode(JSON.stringify(exportScene()));
  4201. window.history.replaceState(null, "Macrovision", link);
  4202. try {
  4203. navigator.clipboard.writeText(link);
  4204. toast("Copied permalink to clipboard");
  4205. } catch {
  4206. toast("Couldn't copy permalink");
  4207. }
  4208. }
  4209. function copyScene() {
  4210. const results = exportScene();
  4211. navigator.clipboard.writeText(JSON.stringify(results));
  4212. }
  4213. function pasteScene() {
  4214. try {
  4215. navigator.clipboard.readText().then(text => {
  4216. const data = JSON.parse(text);
  4217. if (data.entities === undefined) {
  4218. return;
  4219. }
  4220. if (data.world === undefined) {
  4221. return;
  4222. }
  4223. importScene(data);
  4224. }).catch(err => alert(err));
  4225. } catch (err) {
  4226. console.error(err);
  4227. // probably wasn't valid data
  4228. }
  4229. }
  4230. // TODO - don't just search through every single entity
  4231. // probably just have a way to do lookups directly
  4232. function findEntity(name) {
  4233. return availableEntitiesByName[name];
  4234. }
  4235. const migrationDefs = [
  4236. /*
  4237. Migration: 0 -> 1
  4238. Adds x and y coordinates for the camera
  4239. */
  4240. data => {
  4241. data.world.x = 0;
  4242. data.world.y = 0;
  4243. },
  4244. /*
  4245. Migration: 1 -> 2
  4246. Adds priority and brightness to each entity
  4247. */
  4248. data => {
  4249. data.entities.forEach(entity => {
  4250. entity.priority = 0;
  4251. entity.brightness = 1;
  4252. });
  4253. },
  4254. /*
  4255. Migration: 2 -> 3
  4256. Custom names are exported
  4257. */
  4258. data => {
  4259. data.entities.forEach(entity => {
  4260. entity.customName = entity.name
  4261. });
  4262. },
  4263. /*
  4264. Migration: 3 -> 4
  4265. Rotation is now stored
  4266. */
  4267. data => {
  4268. data.entities.forEach(entity => {
  4269. entity.rotation = 0
  4270. });
  4271. }
  4272. ]
  4273. function migrateScene(data) {
  4274. if (data.version === undefined) {
  4275. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  4276. console.trace()
  4277. data.version = 0;
  4278. } else if (data.version < migrationDefs.length) {
  4279. migrationDefs[data.version](data);
  4280. data.version += 1;
  4281. migrateScene(data);
  4282. }
  4283. }
  4284. function importScene(data) {
  4285. removeAllEntities();
  4286. migrateScene(data);
  4287. data.entities.forEach(entityInfo => {
  4288. const entity = findEntity(entityInfo.name).constructor();
  4289. entity.name = entityInfo.customName;
  4290. entity.scale = entityInfo.scale;
  4291. entity.rotation = entityInfo.rotation;
  4292. entity.priority = entityInfo.priority;
  4293. entity.brightness = entityInfo.brightness;
  4294. entity.form = entityInfo.form;
  4295. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  4296. });
  4297. config.height = math.unit(data.world.height, data.world.unit);
  4298. config.x = data.world.x;
  4299. config.y = data.world.y;
  4300. const height = math.unit(data.world.height, data.world.unit).toNumber(defaultUnits.length[config.units]);
  4301. document.querySelector("#options-height-value").value = height;
  4302. document.querySelector("#options-height-unit").dataset.oldUnit = defaultUnits.length[config.units];
  4303. document.querySelector("#options-height-unit").value = defaultUnits.length[config.units];
  4304. if (data.canvasWidth) {
  4305. doHorizReposition(data.canvasWidth / canvasWidth);
  4306. }
  4307. updateSizes();
  4308. }
  4309. function renderToCanvas() {
  4310. const ctx = document.querySelector("#display").getContext("2d");
  4311. Object.entries(entities).sort((ent1, ent2) => {
  4312. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  4313. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  4314. return z1 - z2;
  4315. }).forEach(([id, entity]) => {
  4316. element = document.querySelector("#entity-" + id);
  4317. img = element.querySelector("img");
  4318. let x = parseFloat(element.dataset.x);
  4319. let y = parseFloat(element.dataset.y);
  4320. let coords = pos2pix({x: x, y: y});
  4321. let offset = img.style.getPropertyValue("--offset");
  4322. offset = parseFloat(offset.substring(0, offset.length-1))
  4323. let xSize = img.width;
  4324. let ySize = img.height;
  4325. x = coords.x
  4326. y = coords.y + ySize/2 + ySize * offset / 100;
  4327. const oldFilter = ctx.filter
  4328. const brightness = getComputedStyle(element).getPropertyValue("--brightness")
  4329. ctx.filter = `brightness(${brightness})`;
  4330. ctx.save();
  4331. ctx.resetTransform();
  4332. ctx.scale(window.devicePixelRatio, window.devicePixelRatio)
  4333. ctx.translate(x, y);
  4334. ctx.rotate(entity.rotation);
  4335. ctx.drawImage(img, -xSize/2, -ySize/2, xSize, ySize);
  4336. ctx.restore();
  4337. ctx.filter = oldFilter
  4338. });
  4339. ctx.drawImage(document.querySelector("#rulers"), 0, 0);
  4340. }
  4341. function exportCanvas(callback) {
  4342. /** @type {CanvasRenderingContext2D} */
  4343. const ctx = document.querySelector("#display").getContext("2d");
  4344. const blob = ctx.canvas.toBlob(callback);
  4345. }
  4346. function generateScreenshot(callback) {
  4347. /** @type {CanvasRenderingContext2D} */
  4348. const ctx = document.querySelector("#display").getContext("2d");
  4349. if (config.groundKind !== "none") {
  4350. ctx.fillStyle = backgroundColors[config.groundKind];
  4351. ctx.fillRect(0, pos2pix({x: 0, y: 0}).y, canvasWidth + 100, canvasHeight);
  4352. }
  4353. renderToCanvas();
  4354. ctx.resetTransform();
  4355. ctx.fillStyle = "#999";
  4356. ctx.font = "normal normal lighter 16pt coda";
  4357. ctx.fillText("macrovision.crux.sexy", 10, 25);
  4358. exportCanvas(blob => {
  4359. callback(blob);
  4360. });
  4361. }
  4362. function copyScreenshot() {
  4363. if (window.ClipboardItem === undefined) {
  4364. alert("Sorry, this browser doesn't yet support writing images to the clipboard.");
  4365. return;
  4366. }
  4367. generateScreenshot(blob => {
  4368. navigator.clipboard.write([
  4369. new ClipboardItem({
  4370. "image/png": blob
  4371. })
  4372. ]).then(e =>
  4373. toast("Copied to clipboard!"))
  4374. .catch(e => {
  4375. toast("Couldn't write to the clipboard. Make sure the screenshot completes before switching tabs.")
  4376. })
  4377. });
  4378. drawScales(false);
  4379. }
  4380. function saveScreenshot() {
  4381. generateScreenshot(blob => {
  4382. const a = document.createElement("a");
  4383. a.href = URL.createObjectURL(blob);
  4384. a.setAttribute("download", "macrovision.png");
  4385. a.click();
  4386. });
  4387. drawScales(false);
  4388. }
  4389. function openScreenshot() {
  4390. generateScreenshot(blob => {
  4391. const a = document.createElement("a");
  4392. a.href = URL.createObjectURL(blob);
  4393. a.setAttribute("target", "_blank");
  4394. a.click();
  4395. });
  4396. drawScales(false);
  4397. }
  4398. const rateLimits = {};
  4399. function toast(msg) {
  4400. let div = document.createElement("div");
  4401. div.innerHTML = msg;
  4402. div.classList.add("toast");
  4403. document.body.appendChild(div);
  4404. setTimeout(() => {
  4405. document.body.removeChild(div);
  4406. }, 5000)
  4407. }
  4408. function toastRateLimit(msg, key, delay) {
  4409. if (!rateLimits[key]) {
  4410. toast(msg);
  4411. rateLimits[key] = setTimeout(() => {
  4412. delete rateLimits[key]
  4413. }, delay);
  4414. }
  4415. }
  4416. let lastTime = undefined;
  4417. function pan(fromX, fromY, fromHeight, toX, toY, toHeight, duration) {
  4418. Object.keys(entities).forEach(key => {
  4419. document.querySelector("#entity-" + key).classList.add("no-transition");
  4420. });
  4421. config.x = fromX;
  4422. config.y = fromY;
  4423. config.height = math.unit(fromHeight, "meters")
  4424. updateSizes();
  4425. lastTime = undefined;
  4426. requestAnimationFrame((timestamp) => panTo(toX, toY, toHeight, (toX - fromX) / duration, (toY - fromY) / duration, (toHeight - fromHeight) / duration, timestamp, duration));
  4427. }
  4428. function panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining) {
  4429. if (lastTime === undefined) {
  4430. lastTime = timestamp;
  4431. }
  4432. dt = timestamp - lastTime;
  4433. remaining -= dt;
  4434. if (remaining < 0) {
  4435. dt += remaining
  4436. }
  4437. let newX = config.x + xSpeed * dt;
  4438. let newY = config.y + ySpeed * dt;
  4439. let newHeight = config.height.toNumber("meters") + heightSpeed * dt;
  4440. if (remaining > 0) {
  4441. requestAnimationFrame((timestamp) => panTo(x, y, height, xSpeed, ySpeed, heightSpeed, timestamp, remaining))
  4442. } else {
  4443. Object.keys(entities).forEach(key => {
  4444. document.querySelector("#entity-" + key).classList.remove("no-transition");
  4445. });
  4446. }
  4447. config.x = newX;
  4448. config.y = newY;
  4449. config.height = math.unit(newHeight, "meters");
  4450. updateSizes();
  4451. }
  4452. function getVerticalOffset() {
  4453. if (config.groundPos === "very-high") {
  4454. return config.height.toNumber("meters") / 12 * 5;
  4455. } else if (config.groundPos === "high") {
  4456. return config.height.toNumber("meters") / 12 * 4;
  4457. } else if (config.groundPos === "medium") {
  4458. return config.height.toNumber("meters") / 12 * 3;
  4459. } else if (config.groundPos === "low") {
  4460. return config.height.toNumber("meters") / 12 * 2;
  4461. } else if (config.groundPos === "very-low") {
  4462. return config.height.toNumber("meters") / 12;
  4463. } else {
  4464. return 0;
  4465. }
  4466. }