less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

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