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

3278 строки
99 KiB

  1. let selected = null;
  2. let selectedEntity = null;
  3. let entityIndex = 0;
  4. let clicked = null;
  5. let dragging = false;
  6. let clickTimeout = null;
  7. let dragOffsetX = null;
  8. let dragOffsetY = null;
  9. let panning = false;
  10. let panReady = true;
  11. let panOffsetX = null;
  12. let panOffsetY = null;
  13. let shiftHeld = false;
  14. let altHeld = false;
  15. let entityX;
  16. let canvasWidth;
  17. let canvasHeight;
  18. let dragScale = 1;
  19. let dragScaleHandle = null;
  20. let dragEntityScale = 1;
  21. let dragEntityScaleHandle = null;
  22. let scrollDirection = 0;
  23. let scrollHandle = null;
  24. let zoomDirection = 0;
  25. let zoomHandle = null;
  26. let sizeDirection = 0;
  27. let sizeHandle = null;
  28. let worldSizeDirty = false;
  29. const tagDefs = {
  30. "anthro": "Anthro",
  31. "feral": "Feral",
  32. "taur": "Taur",
  33. "naga": "Naga",
  34. "goo": "Goo"
  35. }
  36. math.createUnit("humans", {
  37. definition: "5.75 feet"
  38. });
  39. math.createUnit("story", {
  40. definition: "12 feet",
  41. prefixes: "long"
  42. });
  43. math.createUnit("stories", {
  44. definition: "12 feet",
  45. prefixes: "long"
  46. });
  47. math.createUnit("earths", {
  48. definition: "12756km",
  49. prefixes: "long"
  50. });
  51. math.createUnit("parsec", {
  52. definition: "3.086e16 meters",
  53. prefixes: "long"
  54. })
  55. math.createUnit("parsecs", {
  56. definition: "3.086e16 meters",
  57. prefixes: "long"
  58. })
  59. math.createUnit("lightyears", {
  60. definition: "9.461e15 meters",
  61. prefixes: "long"
  62. })
  63. math.createUnit("AU", {
  64. definition: "149597870700 meters"
  65. })
  66. math.createUnit("AUs", {
  67. definition: "149597870700 meters"
  68. })
  69. math.createUnit("dalton", {
  70. definition: "1.66e-27 kg",
  71. prefixes: "long"
  72. });
  73. math.createUnit("daltons", {
  74. definition: "1.66e-27 kg",
  75. prefixes: "long"
  76. });
  77. math.createUnit("solarradii", {
  78. definition: "695990 km",
  79. prefixes: "long"
  80. });
  81. math.createUnit("solarmasses", {
  82. definition: "2e30 kg",
  83. prefixes: "long"
  84. });
  85. math.createUnit("galaxy", {
  86. definition: "105700 lightyears",
  87. prefixes: "long"
  88. });
  89. math.createUnit("galaxies", {
  90. definition: "105700 lightyears",
  91. prefixes: "long"
  92. });
  93. math.createUnit("universe", {
  94. definition: "93.016e9 lightyears",
  95. prefixes: "long"
  96. });
  97. math.createUnit("universes", {
  98. definition: "93.016e9 lightyears",
  99. prefixes: "long"
  100. });
  101. math.createUnit("multiverse", {
  102. definition: "1e30 lightyears",
  103. prefixes: "long"
  104. });
  105. math.createUnit("multiverses", {
  106. definition: "1e30 lightyears",
  107. prefixes: "long"
  108. });
  109. math.createUnit("people", {
  110. definition: "75 liters",
  111. prefixes: "long"
  112. });
  113. math.createUnit("olympicPools", {
  114. definition: "2500 m^3",
  115. prefixes: "long"
  116. });
  117. math.createUnit("oceans", {
  118. definition: "700000000 km^3",
  119. prefixes: "long"
  120. });
  121. math.createUnit("earthVolumes", {
  122. definition: "1.0867813e12 km^3",
  123. prefixes: "long"
  124. });
  125. math.createUnit("universeVolumes", {
  126. definition: "4.2137775e+32 lightyears^3",
  127. prefixes: "long"
  128. });
  129. math.createUnit("multiverseVolumes", {
  130. definition: "5.2359878e+89 lightyears^3",
  131. prefixes: "long"
  132. });
  133. const unitChoices = {
  134. length: [
  135. "meters",
  136. "angstroms",
  137. "millimeters",
  138. "centimeters",
  139. "kilometers",
  140. "inches",
  141. "feet",
  142. "humans",
  143. "stories",
  144. "miles",
  145. "earths",
  146. "solarradii",
  147. "AUs",
  148. "lightyears",
  149. "parsecs",
  150. "galaxies",
  151. "universes",
  152. "multiverses"
  153. ],
  154. area: [
  155. "meters^2",
  156. "cm^2",
  157. "kilometers^2",
  158. "acres",
  159. "miles^2"
  160. ],
  161. volume: [
  162. "liters",
  163. "milliliters",
  164. "m^3",
  165. "gallons",
  166. "people",
  167. "olympicPools",
  168. "oceans",
  169. "earthVolumes",
  170. "universeVolumes",
  171. "multiverseVolumes",
  172. ],
  173. mass: [
  174. "kilograms",
  175. "milligrams",
  176. "grams",
  177. "tonnes",
  178. "lbs",
  179. "ounces",
  180. "tons"
  181. ]
  182. }
  183. const config = {
  184. height: math.unit(1500, "meters"),
  185. x: 0,
  186. y: 0,
  187. minLineSize: 100,
  188. maxLineSize: 150,
  189. autoFit: false
  190. }
  191. const availableEntities = {
  192. }
  193. const availableEntitiesByName = {
  194. }
  195. const entities = {
  196. }
  197. function constrainRel(coords) {
  198. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  199. const worldHeight = config.height.toNumber("meters");
  200. if (altHeld) {
  201. return coords;
  202. }
  203. return {
  204. x: Math.min(Math.max(coords.x, -worldWidth / 2 + config.x), worldWidth / 2 + config.x),
  205. y: Math.min(Math.max(coords.y, config.y), worldHeight + config.y)
  206. }
  207. }
  208. function snapRel(coords) {
  209. return constrainRel({
  210. x: coords.x,
  211. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  212. });
  213. }
  214. function adjustAbs(coords, oldHeight, newHeight) {
  215. const ratio = math.divide(newHeight, oldHeight);
  216. const x = coords.x * ratio;
  217. const y = coords.y * ratio;
  218. return { x: x, y: y};
  219. }
  220. function pos2pix(coords) {
  221. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  222. const worldHeight = config.height.toNumber("meters");
  223. const x = ((coords.x - config.x) / worldWidth + 0.5) * canvasWidth + 50;
  224. const y = (1 - (coords.y - config.y) / worldHeight) * canvasHeight;
  225. return { x: x, y: y };
  226. }
  227. function pix2pos(coords) {
  228. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  229. const worldHeight = config.height.toNumber("meters");
  230. const x = (((coords.x - 50) / canvasWidth) - 0.5) * worldWidth + config.x;
  231. const y = (1 - (coords.y / canvasHeight)) * worldHeight + config.y;
  232. return { x: x, y: y };
  233. }
  234. function updateEntityElement(entity, element) {
  235. const position = pos2pix({ x: element.dataset.x, y: element.dataset.y });
  236. const view = entity.view;
  237. element.style.left = position.x + "px";
  238. element.style.top = position.y + "px";
  239. element.style.setProperty("--xpos", position.x + "px");
  240. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  241. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  242. const extra = entity.views[view].image.extra;
  243. const bottom = entity.views[view].image.bottom;
  244. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  245. element.style.setProperty("--height", pixels * bonus + "px");
  246. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  247. if (entity.views[view].rename)
  248. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  249. else
  250. element.querySelector(".entity-name").innerText = entity.name;
  251. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  252. bottomName.style.left = position.x + entityX + "px";
  253. bottomName.style.bottom = "0vh";
  254. bottomName.innerText = entity.name;
  255. const topName = document.querySelector("#top-name-" + element.dataset.key);
  256. topName.style.left = position.x + entityX + "px";
  257. topName.style.top = "20vh";
  258. topName.innerText = entity.name;
  259. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  260. topName.classList.add("top-name-needed");
  261. } else {
  262. topName.classList.remove("top-name-needed");
  263. }
  264. }
  265. function updateSizes(dirtyOnly = false) {
  266. if (config.lockYAxis) {
  267. config.y = 0;
  268. }
  269. drawScale(dirtyOnly);
  270. let ordered = Object.entries(entities);
  271. ordered.sort((e1, e2) => {
  272. if (e1[1].priority != e2[1].priority) {
  273. return e2[1].priority - e1[1].priority;
  274. } else {
  275. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  276. }
  277. });
  278. let zIndex = ordered.length;
  279. ordered.forEach(entity => {
  280. const element = document.querySelector("#entity-" + entity[0]);
  281. element.style.zIndex = zIndex;
  282. if (!dirtyOnly || entity[1].dirty) {
  283. updateEntityElement(entity[1], element, zIndex);
  284. entity[1].dirty = false;
  285. }
  286. zIndex -= 1;
  287. });
  288. }
  289. function drawScale(ifDirty = false) {
  290. if (ifDirty && !worldSizeDirty)
  291. return;
  292. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  293. let total = heightPer.clone();
  294. total.value = math.unit(config.y, "meters").toNumber(config.unit);
  295. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  296. drawTick(ctx, 50, y, total);
  297. total = math.add(total, heightPer);
  298. }
  299. }
  300. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  301. const oldStroke = ctx.strokeStyle;
  302. const oldFill = ctx.fillStyle;
  303. ctx.beginPath();
  304. ctx.moveTo(x, y);
  305. ctx.lineTo(x + 20, y);
  306. ctx.strokeStyle = "#000000";
  307. ctx.stroke();
  308. ctx.beginPath();
  309. ctx.moveTo(x + 20, y);
  310. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  311. ctx.strokeStyle = "#aaaaaa";
  312. ctx.stroke();
  313. ctx.beginPath();
  314. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  315. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  316. ctx.strokeStyle = "#000000";
  317. ctx.stroke();
  318. const oldFont = ctx.font;
  319. ctx.font = 'normal 24pt coda';
  320. ctx.fillStyle = "#dddddd";
  321. ctx.beginPath();
  322. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  323. ctx.font = oldFont;
  324. ctx.strokeStyle = oldStroke;
  325. ctx.fillStyle = oldFill;
  326. }
  327. const canvas = document.querySelector("#display");
  328. /** @type {CanvasRenderingContext2D} */
  329. const ctx = canvas.getContext("2d");
  330. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  331. heightPer = 1;
  332. if (pixelsPer < config.minLineSize) {
  333. const factor = math.ceil(config.minLineSize / pixelsPer);
  334. heightPer *= factor;
  335. pixelsPer *= factor;
  336. }
  337. if (pixelsPer > config.maxLineSize) {
  338. const factor = math.ceil(pixelsPer / config.maxLineSize);
  339. heightPer /= factor;
  340. pixelsPer /= factor;
  341. }
  342. if (heightPer == 0) {
  343. console.error("The world size is invalid! Refusing to draw the scale...");
  344. return;
  345. }
  346. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  347. ctx.scale(1, 1);
  348. ctx.canvas.width = canvas.clientWidth;
  349. ctx.canvas.height = canvas.clientHeight;
  350. ctx.beginPath();
  351. ctx.rect(0, 0, canvas.width, canvas.height);
  352. ctx.fillStyle = "#333";
  353. ctx.fill();
  354. ctx.beginPath();
  355. ctx.moveTo(50, 50);
  356. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  357. ctx.stroke();
  358. ctx.beginPath();
  359. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  360. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  361. ctx.stroke();
  362. drawTicks(ctx, pixelsPer, heightPer);
  363. }
  364. // Entities are generated as needed, and we make a copy
  365. // every time - the resulting objects get mutated, after all.
  366. // But we also want to be able to read some information without
  367. // calling the constructor -- e.g. making a list of authors and
  368. // owners. So, this function is used to generate that information.
  369. // It is invoked like makeEntity so that it can be dropped in easily,
  370. // but returns an object that lets you construct many copies of an entity,
  371. // rather than creating a new entity.
  372. function createEntityMaker(info, views, sizes) {
  373. const maker = {};
  374. maker.name = info.name;
  375. maker.info = info;
  376. maker.sizes = sizes;
  377. maker.constructor = () => makeEntity(info, views, sizes);
  378. maker.authors = [];
  379. maker.owners = [];
  380. maker.nsfw = false;
  381. Object.values(views).forEach(view => {
  382. const authors = authorsOf(view.image.source);
  383. if (authors) {
  384. authors.forEach(author => {
  385. if (maker.authors.indexOf(author) == -1) {
  386. maker.authors.push(author);
  387. }
  388. });
  389. }
  390. const owners = ownersOf(view.image.source);
  391. if (owners) {
  392. owners.forEach(owner => {
  393. if (maker.owners.indexOf(owner) == -1) {
  394. maker.owners.push(owner);
  395. }
  396. });
  397. }
  398. if (isNsfw(view.image.source)) {
  399. maker.nsfw = true;
  400. }
  401. });
  402. return maker;
  403. }
  404. // This function serializes and parses its arguments to avoid sharing
  405. // references to a common object. This allows for the objects to be
  406. // safely mutated.
  407. function makeEntity(info, views, sizes) {
  408. const entityTemplate = {
  409. name: info.name,
  410. identifier: info.name,
  411. scale: 1,
  412. info: JSON.parse(JSON.stringify(info)),
  413. views: JSON.parse(JSON.stringify(views), math.reviver),
  414. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  415. init: function () {
  416. const entity = this;
  417. Object.entries(this.views).forEach(([viewKey, view]) => {
  418. view.parent = this;
  419. if (this.defaultView === undefined) {
  420. this.defaultView = viewKey;
  421. this.view = viewKey;
  422. }
  423. if (view.default) {
  424. this.defaultView = viewKey;
  425. this.view = viewKey;
  426. }
  427. Object.entries(view.attributes).forEach(([key, val]) => {
  428. Object.defineProperty(
  429. view,
  430. key,
  431. {
  432. get: function () {
  433. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  434. },
  435. set: function (value) {
  436. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  437. this.parent.scale = newScale;
  438. }
  439. }
  440. )
  441. });
  442. });
  443. this.sizes.forEach(size => {
  444. if (size.default === true) {
  445. this.views[this.defaultView].height = size.height;
  446. this.size = size;
  447. }
  448. });
  449. if (this.size === undefined && this.sizes.length > 0) {
  450. this.views[this.defaultView].height = this.sizes[0].height;
  451. this.size = this.sizes[0];
  452. console.warn("No default size set for " + info.name);
  453. } else if (this.sizes.length == 0) {
  454. this.sizes = [
  455. {
  456. name: "Normal",
  457. height: this.views[this.defaultView].height
  458. }
  459. ];
  460. this.size = this.sizes[0];
  461. }
  462. this.desc = {};
  463. Object.entries(this.info).forEach(([key, value]) => {
  464. Object.defineProperty(
  465. this.desc,
  466. key,
  467. {
  468. get: function () {
  469. let text = value.text;
  470. if (entity.views[entity.view].info) {
  471. if (entity.views[entity.view].info[key]) {
  472. text = combineInfo(text, entity.views[entity.view].info[key]);
  473. }
  474. }
  475. if (entity.size.info) {
  476. if (entity.size.info[key]) {
  477. text = combineInfo(text, entity.size.info[key]);
  478. }
  479. }
  480. return { title: value.title, text: text };
  481. }
  482. }
  483. )
  484. });
  485. delete this.init;
  486. return this;
  487. }
  488. }.init();
  489. return entityTemplate;
  490. }
  491. function combineInfo(existing, next) {
  492. switch (next.mode) {
  493. case "replace":
  494. return next.text;
  495. case "prepend":
  496. return next.text + existing;
  497. case "append":
  498. return existing + next.text;
  499. }
  500. return existing;
  501. }
  502. function clickDown(target, x, y) {
  503. clicked = target;
  504. const rect = target.getBoundingClientRect();
  505. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  506. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  507. dragOffsetX = x - rect.left + entX;
  508. dragOffsetY = y - rect.top + entY;
  509. clickTimeout = setTimeout(() => { dragging = true }, 200)
  510. target.classList.add("no-transition");
  511. }
  512. // could we make this actually detect the menu area?
  513. function hoveringInDeleteArea(e) {
  514. return e.clientY < document.body.clientHeight / 10;
  515. }
  516. function clickUp(e) {
  517. if (e.which != 1) {
  518. return;
  519. }
  520. clearTimeout(clickTimeout);
  521. if (clicked) {
  522. if (dragging) {
  523. dragging = false;
  524. if (hoveringInDeleteArea(e)) {
  525. removeEntity(clicked);
  526. document.querySelector("#menubar").classList.remove("hover-delete");
  527. }
  528. } else {
  529. select(clicked);
  530. }
  531. clicked.classList.remove("no-transition");
  532. clicked = null;
  533. }
  534. }
  535. function deselect(e) {
  536. if (e !== undefined && e.which != 1) {
  537. return;
  538. }
  539. if (selected) {
  540. selected.classList.remove("selected");
  541. }
  542. document.getElementById("options-selected-entity-none").selected = "selected";
  543. clearAttribution();
  544. selected = null;
  545. clearViewList();
  546. clearEntityOptions();
  547. clearViewOptions();
  548. document.querySelector("#delete-entity").disabled = true;
  549. document.querySelector("#grow").disabled = true;
  550. document.querySelector("#shrink").disabled = true;
  551. document.querySelector("#fit").disabled = true;
  552. }
  553. function select(target) {
  554. deselect();
  555. selected = target;
  556. selectedEntity = entities[target.dataset.key];
  557. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  558. selected.classList.add("selected");
  559. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  560. configViewList(selectedEntity, selectedEntity.view);
  561. configEntityOptions(selectedEntity, selectedEntity.view);
  562. configViewOptions(selectedEntity, selectedEntity.view);
  563. document.querySelector("#delete-entity").disabled = false;
  564. document.querySelector("#grow").disabled = false;
  565. document.querySelector("#shrink").disabled = false;
  566. document.querySelector("#fit").disabled = false;
  567. }
  568. function configViewList(entity, selectedView) {
  569. const list = document.querySelector("#entity-view");
  570. list.innerHTML = "";
  571. list.style.display = "block";
  572. Object.keys(entity.views).forEach(view => {
  573. const option = document.createElement("option");
  574. option.innerText = entity.views[view].name;
  575. option.value = view;
  576. if (isNsfw(entity.views[view].image.source)) {
  577. option.classList.add("nsfw")
  578. }
  579. if (view === selectedView) {
  580. option.selected = true;
  581. if (option.classList.contains("nsfw")) {
  582. list.classList.add("nsfw");
  583. } else {
  584. list.classList.remove("nsfw");
  585. }
  586. }
  587. list.appendChild(option);
  588. });
  589. }
  590. function clearViewList() {
  591. const list = document.querySelector("#entity-view");
  592. list.innerHTML = "";
  593. list.style.display = "none";
  594. }
  595. function updateWorldOptions(entity, view) {
  596. const heightInput = document.querySelector("#options-height-value");
  597. const heightSelect = document.querySelector("#options-height-unit");
  598. const converted = config.height.toNumber(heightSelect.value);
  599. setNumericInput(heightInput, converted);
  600. }
  601. function configEntityOptions(entity, view) {
  602. const holder = document.querySelector("#options-entity");
  603. document.querySelector("#entity-category-header").style.display = "block";
  604. document.querySelector("#entity-category").style.display = "block";
  605. holder.innerHTML = "";
  606. const scaleLabel = document.createElement("div");
  607. scaleLabel.classList.add("options-label");
  608. scaleLabel.innerText = "Scale";
  609. const scaleRow = document.createElement("div");
  610. scaleRow.classList.add("options-row");
  611. const scaleInput = document.createElement("input");
  612. scaleInput.classList.add("options-field-numeric");
  613. scaleInput.id = "options-entity-scale";
  614. scaleInput.addEventListener("change", e => {
  615. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  616. entity.dirty = true;
  617. if (config.autoFit) {
  618. fitWorld();
  619. } else {
  620. updateSizes(true);
  621. }
  622. updateEntityOptions(entity, view);
  623. updateViewOptions(entity, view);
  624. });
  625. scaleInput.addEventListener("keydown", e => {
  626. e.stopPropagation();
  627. })
  628. scaleInput.setAttribute("min", 1);
  629. scaleInput.setAttribute("type", "number");
  630. setNumericInput(scaleInput, entity.scale);
  631. scaleRow.appendChild(scaleInput);
  632. holder.appendChild(scaleLabel);
  633. holder.appendChild(scaleRow);
  634. const nameLabel = document.createElement("div");
  635. nameLabel.classList.add("options-label");
  636. nameLabel.innerText = "Name";
  637. const nameRow = document.createElement("div");
  638. nameRow.classList.add("options-row");
  639. const nameInput = document.createElement("input");
  640. nameInput.classList.add("options-field-text");
  641. nameInput.value = entity.name;
  642. nameInput.addEventListener("input", e => {
  643. entity.name = e.target.value;
  644. entity.dirty = true;
  645. updateSizes(true);
  646. })
  647. nameInput.addEventListener("keydown", e => {
  648. e.stopPropagation();
  649. })
  650. nameRow.appendChild(nameInput);
  651. holder.appendChild(nameLabel);
  652. holder.appendChild(nameRow);
  653. const defaultHolder = document.querySelector("#options-entity-defaults");
  654. defaultHolder.innerHTML = "";
  655. entity.sizes.forEach(defaultInfo => {
  656. const button = document.createElement("button");
  657. button.classList.add("options-button");
  658. button.innerText = defaultInfo.name;
  659. button.addEventListener("click", e => {
  660. entity.views[entity.defaultView].height = defaultInfo.height;
  661. entity.dirty = true;
  662. updateEntityOptions(entity, entity.view);
  663. updateViewOptions(entity, entity.view);
  664. if (!checkFitWorld()) {
  665. updateSizes(true);
  666. }
  667. if (config.autoFitSize) {
  668. const x = parseFloat(selected.dataset.x);
  669. Object.keys(entities).forEach(id => {
  670. const element = document.querySelector("#entity-" + id);
  671. const newX = parseFloat(element.dataset.x) - x + 0.5;
  672. element.dataset.x = newX;
  673. });
  674. const entity = entities[selected.dataset.key];
  675. const height = math.multiply(entity.views[entity.view].height, 1.1);
  676. setWorldHeight(config.height, height);
  677. }
  678. });
  679. defaultHolder.appendChild(button);
  680. });
  681. document.querySelector("#options-order-display").innerText = entity.priority;
  682. document.querySelector("#options-ordering").style.display = "flex";
  683. }
  684. function updateEntityOptions(entity, view) {
  685. const scaleInput = document.querySelector("#options-entity-scale");
  686. setNumericInput(scaleInput, entity.scale);
  687. document.querySelector("#options-order-display").innerText = entity.priority;
  688. }
  689. function clearEntityOptions() {
  690. document.querySelector("#entity-category-header").style.display = "none";
  691. document.querySelector("#entity-category").style.display = "none";
  692. /*
  693. const holder = document.querySelector("#options-entity");
  694. holder.innerHTML = "";
  695. document.querySelector("#options-entity-defaults").innerHTML = "";
  696. document.querySelector("#options-ordering").style.display = "none";
  697. document.querySelector("#options-ordering").style.display = "none";*/
  698. }
  699. function configViewOptions(entity, view) {
  700. const holder = document.querySelector("#options-view");
  701. document.querySelector("#view-category-header").style.display = "block";
  702. document.querySelector("#view-category").style.display = "block";
  703. holder.innerHTML = "";
  704. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  705. const label = document.createElement("div");
  706. label.classList.add("options-label");
  707. label.innerText = val.name;
  708. holder.appendChild(label);
  709. const row = document.createElement("div");
  710. row.classList.add("options-row");
  711. holder.appendChild(row);
  712. const input = document.createElement("input");
  713. input.classList.add("options-field-numeric");
  714. input.id = "options-view-" + key + "-input";
  715. input.setAttribute("type", "number");
  716. input.setAttribute("min", 1);
  717. const select = document.createElement("select");
  718. select.classList.add("options-field-unit");
  719. select.id = "options-view-" + key + "-select"
  720. unitChoices[val.type].forEach(name => {
  721. const option = document.createElement("option");
  722. option.innerText = name;
  723. select.appendChild(option);
  724. });
  725. input.addEventListener("change", e => {
  726. const value = input.value == 0 ? 1 : input.value;
  727. entity.views[view][key] = math.unit(value, select.value);
  728. entity.dirty = true;
  729. if (config.autoFit) {
  730. fitWorld();
  731. } else {
  732. updateSizes(true);
  733. }
  734. updateEntityOptions(entity, view);
  735. updateViewOptions(entity, view, key);
  736. });
  737. input.addEventListener("keydown", e => {
  738. e.stopPropagation();
  739. })
  740. select.setAttribute("oldUnit", select.value);
  741. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  742. // TODO does this ever cause a change in the world?
  743. select.addEventListener("input", e => {
  744. const value = input.value == 0 ? 1 : input.value;
  745. const oldUnit = select.getAttribute("oldUnit");
  746. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  747. entity.dirty = true;
  748. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  749. select.setAttribute("oldUnit", select.value);
  750. if (config.autoFit) {
  751. fitWorld();
  752. } else {
  753. updateSizes(true);
  754. }
  755. updateEntityOptions(entity, view);
  756. updateViewOptions(entity, view, key);
  757. });
  758. row.appendChild(input);
  759. row.appendChild(select);
  760. });
  761. }
  762. function updateViewOptions(entity, view, changed) {
  763. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  764. if (key != changed) {
  765. const input = document.querySelector("#options-view-" + key + "-input");
  766. const select = document.querySelector("#options-view-" + key + "-select");
  767. const currentUnit = select.value;
  768. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  769. setNumericInput(input, convertedAmount);
  770. }
  771. });
  772. }
  773. function setNumericInput(input, value, round = 6) {
  774. if (typeof value == "string") {
  775. value = parseFloat(value)
  776. }
  777. input.value = value.toPrecision(round);
  778. }
  779. function getSortedEntities() {
  780. return Object.keys(entities).sort((a, b) => {
  781. const entA = entities[a];
  782. const entB = entities[b];
  783. const viewA = entA.view;
  784. const viewB = entB.view;
  785. const heightA = entA.views[viewA].height.to("meter").value;
  786. const heightB = entB.views[viewB].height.to("meter").value;
  787. return heightA - heightB;
  788. });
  789. }
  790. function clearViewOptions() {
  791. document.querySelector("#view-category-header").style.display = "none";
  792. document.querySelector("#view-category").style.display = "none";
  793. }
  794. // this is a crime against humanity, and also stolen from
  795. // stack overflow
  796. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  797. const testCanvas = document.createElement("canvas");
  798. testCanvas.id = "test-canvas";
  799. const testCtx = testCanvas.getContext("2d");
  800. function testClick(event) {
  801. // oh my god I can't believe I'm doing this
  802. const target = event.target;
  803. if (navigator.userAgent.indexOf("Firefox") != -1) {
  804. clickDown(target.parentElement, event.clientX, event.clientY);
  805. return;
  806. }
  807. // Get click coordinates
  808. let w = target.width;
  809. let h = target.height;
  810. let ratioW = 1, ratioH = 1;
  811. // Limit the size of the canvas so that very large images don't cause problems)
  812. if (w > 1000) {
  813. ratioW = w / 1000;
  814. w /= ratioW;
  815. h /= ratioW;
  816. }
  817. if (h > 1000) {
  818. ratioH = h / 1000;
  819. w /= ratioH;
  820. h /= ratioH;
  821. }
  822. const ratio = ratioW * ratioH;
  823. var x = event.clientX - target.getBoundingClientRect().x,
  824. y = event.clientY - target.getBoundingClientRect().y,
  825. alpha;
  826. testCtx.canvas.width = w;
  827. testCtx.canvas.height = h;
  828. // Draw image to canvas
  829. // and read Alpha channel value
  830. testCtx.drawImage(target, 0, 0, w, h);
  831. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  832. // If pixel is transparent,
  833. // retrieve the element underneath and trigger its click event
  834. if (alpha === 0) {
  835. const oldDisplay = target.style.display;
  836. target.style.display = "none";
  837. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  838. newTarget.dispatchEvent(new MouseEvent(event.type, {
  839. "clientX": event.clientX,
  840. "clientY": event.clientY
  841. }));
  842. target.style.display = oldDisplay;
  843. } else {
  844. clickDown(target.parentElement, event.clientX, event.clientY);
  845. }
  846. }
  847. function arrangeEntities(order) {
  848. fitWorld();
  849. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  850. let x = -worldWidth * 0.45 + config.x;
  851. order.forEach(key => {
  852. document.querySelector("#entity-" + key).dataset.x = x;
  853. document.querySelector("#entity-" + key).dataset.y = config.y;
  854. x += worldWidth * 0.9 / (order.length - 1);
  855. });
  856. updateSizes();
  857. }
  858. function removeAllEntities() {
  859. Object.keys(entities).forEach(key => {
  860. removeEntity(document.querySelector("#entity-" + key));
  861. });
  862. }
  863. function clearAttribution() {
  864. document.querySelector("#attribution-category-header").style.display = "none";
  865. document.querySelector("#options-attribution").style.display = "none";
  866. }
  867. function displayAttribution(file) {
  868. document.querySelector("#attribution-category-header").style.display = "block";
  869. document.querySelector("#options-attribution").style.display = "inline";
  870. const authors = authorsOfFull(file);
  871. const owners = ownersOfFull(file);
  872. const source = sourceOf(file);
  873. const authorHolder = document.querySelector("#options-attribution-authors");
  874. const ownerHolder = document.querySelector("#options-attribution-owners");
  875. const sourceHolder = document.querySelector("#options-attribution-source");
  876. if (authors === []) {
  877. const div = document.createElement("div");
  878. div.innerText = "Unknown";
  879. authorHolder.innerHTML = "";
  880. authorHolder.appendChild(div);
  881. } else if (authors === undefined) {
  882. const div = document.createElement("div");
  883. div.innerText = "Not yet entered";
  884. authorHolder.innerHTML = "";
  885. authorHolder.appendChild(div);
  886. } else {
  887. authorHolder.innerHTML = "";
  888. const list = document.createElement("ul");
  889. authorHolder.appendChild(list);
  890. authors.forEach(author => {
  891. const authorEntry = document.createElement("li");
  892. if (author.url) {
  893. const link = document.createElement("a");
  894. link.href = author.url;
  895. link.innerText = author.name;
  896. authorEntry.appendChild(link);
  897. } else {
  898. const div = document.createElement("div");
  899. div.innerText = author.name;
  900. authorEntry.appendChild(div);
  901. }
  902. list.appendChild(authorEntry);
  903. });
  904. }
  905. if (owners === []) {
  906. const div = document.createElement("div");
  907. div.innerText = "Unknown";
  908. ownerHolder.innerHTML = "";
  909. ownerHolder.appendChild(div);
  910. } else if (owners === undefined) {
  911. const div = document.createElement("div");
  912. div.innerText = "Not yet entered";
  913. ownerHolder.innerHTML = "";
  914. ownerHolder.appendChild(div);
  915. } else {
  916. ownerHolder.innerHTML = "";
  917. const list = document.createElement("ul");
  918. ownerHolder.appendChild(list);
  919. owners.forEach(owner => {
  920. const ownerEntry = document.createElement("li");
  921. if (owner.url) {
  922. const link = document.createElement("a");
  923. link.href = owner.url;
  924. link.innerText = owner.name;
  925. ownerEntry.appendChild(link);
  926. } else {
  927. const div = document.createElement("div");
  928. div.innerText = owner.name;
  929. ownerEntry.appendChild(div);
  930. }
  931. list.appendChild(ownerEntry);
  932. });
  933. }
  934. if (source === null) {
  935. const div = document.createElement("div");
  936. div.innerText = "No link";
  937. sourceHolder.innerHTML = "";
  938. sourceHolder.appendChild(div);
  939. } else if (source === undefined) {
  940. const div = document.createElement("div");
  941. div.innerText = "Not yet entered";
  942. sourceHolder.innerHTML = "";
  943. sourceHolder.appendChild(div);
  944. } else {
  945. sourceHolder.innerHTML = "";
  946. const link = document.createElement("a");
  947. link.style.display = "block";
  948. link.href = source;
  949. link.innerText = new URL(source).host;
  950. sourceHolder.appendChild(link);
  951. }
  952. }
  953. function removeEntity(element) {
  954. if (selected == element) {
  955. deselect();
  956. }
  957. if (clicked == element) {
  958. clicked = null;
  959. }
  960. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  961. option.parentElement.removeChild(option);
  962. delete entities[element.dataset.key];
  963. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  964. const topName = document.querySelector("#top-name-" + element.dataset.key);
  965. bottomName.parentElement.removeChild(bottomName);
  966. topName.parentElement.removeChild(topName);
  967. element.parentElement.removeChild(element);
  968. }
  969. function checkEntity(entity) {
  970. Object.values(entity.views).forEach(view => {
  971. if (authorsOf(view.image.source) === undefined) {
  972. console.warn("No authors: " + view.image.source);
  973. }
  974. });
  975. }
  976. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  977. checkEntity(entity);
  978. const box = document.createElement("div");
  979. box.classList.add("entity-box");
  980. const img = document.createElement("img");
  981. img.classList.add("entity-image");
  982. img.addEventListener("dragstart", e => {
  983. e.preventDefault();
  984. });
  985. const nameTag = document.createElement("div");
  986. nameTag.classList.add("entity-name");
  987. nameTag.innerText = entity.name;
  988. box.appendChild(img);
  989. box.appendChild(nameTag);
  990. const image = entity.views[view].image;
  991. img.src = image.source;
  992. if (image.bottom !== undefined) {
  993. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  994. } else {
  995. img.style.setProperty("--offset", ((-1) * 100) + "%")
  996. }
  997. box.dataset.x = x;
  998. box.dataset.y = y;
  999. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); if (clicked) { e.stopPropagation() } } });
  1000. img.addEventListener("touchstart", e => {
  1001. const fakeEvent = {
  1002. target: e.target,
  1003. clientX: e.touches[0].clientX,
  1004. clientY: e.touches[0].clientY,
  1005. which: 1
  1006. };
  1007. testClick(fakeEvent);
  1008. if (clicked) { e.stopPropagation() }
  1009. });
  1010. const heightBar = document.createElement("div");
  1011. heightBar.classList.add("height-bar");
  1012. box.appendChild(heightBar);
  1013. box.id = "entity-" + entityIndex;
  1014. box.dataset.key = entityIndex;
  1015. entity.view = view;
  1016. entity.priority = 0;
  1017. entities[entityIndex] = entity;
  1018. entity.index = entityIndex;
  1019. const world = document.querySelector("#entities");
  1020. world.appendChild(box);
  1021. const bottomName = document.createElement("div");
  1022. bottomName.classList.add("bottom-name");
  1023. bottomName.id = "bottom-name-" + entityIndex;
  1024. bottomName.innerText = entity.name;
  1025. bottomName.addEventListener("click", () => select(box));
  1026. world.appendChild(bottomName);
  1027. const topName = document.createElement("div");
  1028. topName.classList.add("top-name");
  1029. topName.id = "top-name-" + entityIndex;
  1030. topName.innerText = entity.name;
  1031. topName.addEventListener("click", () => select(box));
  1032. world.appendChild(topName);
  1033. const entityOption = document.createElement("option");
  1034. entityOption.id = "options-selected-entity-" + entityIndex;
  1035. entityOption.value = entityIndex;
  1036. entityOption.innerText = entity.name;
  1037. document.getElementById("options-selected-entity").appendChild(entityOption);
  1038. entityIndex += 1;
  1039. if (config.autoFit) {
  1040. fitWorld();
  1041. }
  1042. if (selectEntity)
  1043. select(box);
  1044. entity.dirty = true;
  1045. if (refresh && config.autoFitAdd) {
  1046. const x = parseFloat(selected.dataset.x);
  1047. const y = parseFloat(selected.dataset.y);
  1048. config.x = x;
  1049. config.y = y;
  1050. const entity = entities[selected.dataset.key];
  1051. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1052. setWorldHeight(config.height, height);
  1053. }
  1054. if (refresh)
  1055. updateSizes(true);
  1056. }
  1057. window.onblur = function () {
  1058. altHeld = false;
  1059. shiftHeld = false;
  1060. }
  1061. window.onfocus = function () {
  1062. window.dispatchEvent(new Event("keydown"));
  1063. }
  1064. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1065. function toggleFullScreen() {
  1066. var doc = window.document;
  1067. var docEl = doc.documentElement;
  1068. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1069. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1070. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1071. requestFullScreen.call(docEl);
  1072. }
  1073. else {
  1074. cancelFullScreen.call(doc);
  1075. }
  1076. }
  1077. function handleResize() {
  1078. const oldCanvasWidth = canvasWidth;
  1079. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1080. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1081. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1082. const change = oldCanvasWidth / canvasWidth;
  1083. updateSizes();
  1084. }
  1085. function prepareSidebar() {
  1086. const menubar = document.querySelector("#sidebar-menu");
  1087. [
  1088. {
  1089. name: "Show/hide sidebar",
  1090. id: "menu-toggle-sidebar",
  1091. icon: "fas fa-chevron-circle-down",
  1092. rotates: true
  1093. },
  1094. {
  1095. name: "Fullscreen",
  1096. id: "menu-fullscreen",
  1097. icon: "fas fa-compress"
  1098. },
  1099. {
  1100. name: "Clear",
  1101. id: "menu-clear",
  1102. icon: "fas fa-file"
  1103. },
  1104. {
  1105. name: "Sort by height",
  1106. id: "menu-order-height",
  1107. icon: "fas fa-sort-numeric-up"
  1108. },
  1109. {
  1110. name: "Permalink",
  1111. id: "menu-permalink",
  1112. icon: "fas fa-link"
  1113. },
  1114. {
  1115. name: "Export to clipboard",
  1116. id: "menu-export",
  1117. icon: "fas fa-share"
  1118. },
  1119. {
  1120. name: "Import from clipboard",
  1121. id: "menu-import",
  1122. icon: "fas fa-share",
  1123. classes: ["flipped"]
  1124. },
  1125. {
  1126. name: "Save",
  1127. id: "menu-save",
  1128. icon: "fas fa-download"
  1129. },
  1130. {
  1131. name: "Load",
  1132. id: "menu-load",
  1133. icon: "fas fa-upload"
  1134. },
  1135. {
  1136. name: "Load Autosave",
  1137. id: "menu-load-autosave",
  1138. icon: "fas fa-redo"
  1139. },
  1140. {
  1141. name: "Add Image",
  1142. id: "menu-add-image",
  1143. icon: "fas fa-camera"
  1144. }
  1145. ].forEach(entry => {
  1146. const buttonHolder = document.createElement("div");
  1147. buttonHolder.classList.add("menu-button-holder");
  1148. const button = document.createElement("button");
  1149. button.id = entry.id;
  1150. button.classList.add("menu-button");
  1151. const icon = document.createElement("i");
  1152. icon.classList.add(...entry.icon.split(" "));
  1153. if (entry.rotates) {
  1154. icon.classList.add("rotate-backward", "transitions");
  1155. }
  1156. if (entry.classes) {
  1157. entry.classes.forEach(cls => icon.classList.add(cls));
  1158. }
  1159. const actionText = document.createElement("span");
  1160. actionText.innerText = entry.name;
  1161. actionText.classList.add("menu-text");
  1162. const srText = document.createElement("span");
  1163. srText.classList.add("sr-only");
  1164. srText.innerText = entry.name;
  1165. button.appendChild(icon);
  1166. button.appendChild(srText);
  1167. buttonHolder.appendChild(button);
  1168. buttonHolder.appendChild(actionText);
  1169. menubar.appendChild(buttonHolder);
  1170. });
  1171. }
  1172. function checkBodyClass(cls) {
  1173. return document.body.classList.contains(cls);
  1174. }
  1175. function toggleBodyClass(cls, setting) {
  1176. if (setting) {
  1177. document.body.classList.add(cls);
  1178. } else {
  1179. document.body.classList.remove(cls);
  1180. }
  1181. }
  1182. const settingsData = {
  1183. "lock-y-axis": {
  1184. name: "Lock Y-Axis",
  1185. desc: "Keep the camera at ground-level",
  1186. type: "toggle",
  1187. default: true,
  1188. get value() {
  1189. return config.lockYAxis;
  1190. },
  1191. set value(param) {
  1192. config.lockYAxis = param;
  1193. if (param) {
  1194. config.y = 0;
  1195. updateSizes();
  1196. document.querySelector("#scroll-up").disabled = true;
  1197. document.querySelector("#scroll-down").disabled = true;
  1198. } else {
  1199. document.querySelector("#scroll-up").disabled = false;
  1200. document.querySelector("#scroll-down").disabled = false;
  1201. }
  1202. }
  1203. },
  1204. "auto-scale": {
  1205. name: "Auto-Size World",
  1206. desc: "Constantly zoom to fit the largest entity",
  1207. type: "toggle",
  1208. default: false,
  1209. get value() {
  1210. return config.autoFit;
  1211. },
  1212. set value(param) {
  1213. config.autoFit = param;
  1214. checkFitWorld();
  1215. }
  1216. },
  1217. "zoom-when-adding": {
  1218. name: "Zoom When Adding",
  1219. desc: "Zoom to fit when you add a new entity",
  1220. type: "toggle",
  1221. default: true,
  1222. get value() {
  1223. return config.autoFitAdd;
  1224. },
  1225. set value(param) {
  1226. config.autoFitAdd = param;
  1227. }
  1228. },
  1229. "zoom-when-sizing": {
  1230. name: "Zoom When Sizing",
  1231. desc: "Zoom to fit when you select an entity's size",
  1232. type: "toggle",
  1233. default: true,
  1234. get value() {
  1235. return config.autoFitSize;
  1236. },
  1237. set value(param) {
  1238. config.autoFitSize = param;
  1239. }
  1240. },
  1241. "names": {
  1242. name: "Show Names",
  1243. desc: "Display names over entities",
  1244. type: "toggle",
  1245. default: true,
  1246. get value() {
  1247. return checkBodyClass("toggle-entity-name");
  1248. },
  1249. set value(param) {
  1250. toggleBodyClass("toggle-entity-name", param);
  1251. }
  1252. },
  1253. "bottom-names": {
  1254. name: "Bottom Names",
  1255. desc: "Display names at the bottom",
  1256. type: "toggle",
  1257. default: false,
  1258. get value() {
  1259. return checkBodyClass("toggle-bottom-name");
  1260. },
  1261. set value(param) {
  1262. toggleBodyClass("toggle-bottom-name", param);
  1263. }
  1264. },
  1265. "top-names": {
  1266. name: "Show Arrows",
  1267. desc: "Point to entities that are much larger than the current view",
  1268. type: "toggle",
  1269. default: false,
  1270. get value() {
  1271. return checkBodyClass("toggle-top-name");
  1272. },
  1273. set value(param) {
  1274. toggleBodyClass("toggle-top-name", param);
  1275. }
  1276. },
  1277. "height-bars": {
  1278. name: "Height Bars",
  1279. desc: "Draw dashed lines to the top of each entity",
  1280. type: "toggle",
  1281. default: false,
  1282. get value() {
  1283. return checkBodyClass("toggle-height-bars");
  1284. },
  1285. set value(param) {
  1286. toggleBodyClass("toggle-height-bars", param);
  1287. }
  1288. },
  1289. "glowing-entities": {
  1290. name: "Glowing Edges",
  1291. desc: "Makes all entities glow",
  1292. type: "toggle",
  1293. default: false,
  1294. get value() {
  1295. return checkBodyClass("toggle-entity-glow");
  1296. },
  1297. set value(param) {
  1298. toggleBodyClass("toggle-entity-glow", param);
  1299. }
  1300. },
  1301. "solid-ground": {
  1302. name: "Solid Ground",
  1303. desc: "Draw solid ground at the y=0 line",
  1304. type: "toggle",
  1305. default: false,
  1306. get value() {
  1307. return checkBodyClass("toggle-bottom-cover");
  1308. },
  1309. set value(param) {
  1310. toggleBodyClass("toggle-bottom-cover", param);
  1311. }
  1312. },
  1313. "show-scale": {
  1314. name: "Show Scale",
  1315. desc: "Show the scale",
  1316. type: "toggle",
  1317. default: true,
  1318. get value() {
  1319. return checkBodyClass("toggle-scale");
  1320. },
  1321. set value(param) {
  1322. toggleBodyClass("toggle-scale", param);
  1323. }
  1324. },
  1325. }
  1326. function prepareSettings(userSettings) {
  1327. const menubar = document.querySelector("#settings-menu");
  1328. Object.entries(settingsData).forEach(([id, entry]) => {
  1329. const holder = document.createElement("label");
  1330. holder.classList.add("settings-holder");
  1331. const input = document.createElement("input");
  1332. input.id = "setting-" + id;
  1333. const name = document.createElement("label");
  1334. name.innerText = entry.name;
  1335. name.classList.add("settings-name");
  1336. name.setAttribute("for", input.id);
  1337. const desc = document.createElement("label");
  1338. desc.innerText = entry.desc;
  1339. desc.classList.add("settings-desc");
  1340. desc.setAttribute("for", input.id);
  1341. if (entry.type == "toggle") {
  1342. input.type = "checkbox";
  1343. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  1344. holder.setAttribute("for", input.id);
  1345. input.appendChild(name);
  1346. input.appendChild(desc);
  1347. holder.appendChild(input);
  1348. holder.appendChild(name);
  1349. holder.appendChild(desc);
  1350. menubar.appendChild(holder);
  1351. const update = () => {
  1352. if (input.checked) {
  1353. holder.classList.add("enabled");
  1354. holder.classList.remove("disabled");
  1355. } else {
  1356. holder.classList.remove("enabled");
  1357. holder.classList.add("disabled");
  1358. }
  1359. entry.value = input.checked;
  1360. }
  1361. update();
  1362. input.addEventListener("change", update);
  1363. }
  1364. })
  1365. }
  1366. function prepareMenu() {
  1367. prepareSidebar();
  1368. if (checkHelpDate()) {
  1369. document.querySelector("#open-help").classList.add("highlighted");
  1370. }
  1371. }
  1372. function getUserSettings() {
  1373. try {
  1374. const settings = JSON.parse(localStorage.getItem("settings"));
  1375. return settings === null ? {} : settings;
  1376. } catch {
  1377. return {};
  1378. }
  1379. }
  1380. function exportUserSettings() {
  1381. const settings = {};
  1382. Object.entries(settingsData).forEach(([id, entry]) => {
  1383. settings[id] = entry.value;
  1384. });
  1385. return settings;
  1386. }
  1387. function setUserSettings(settings) {
  1388. try {
  1389. localStorage.setItem("settings", JSON.stringify(settings));
  1390. } catch {
  1391. // :(
  1392. }
  1393. }
  1394. const lastHelpChange = 1587847743294;
  1395. function checkHelpDate() {
  1396. try {
  1397. const old = localStorage.getItem("help-viewed");
  1398. if (old === null || old < lastHelpChange) {
  1399. return true;
  1400. }
  1401. return false;
  1402. } catch {
  1403. console.warn("Could not set the help-viewed date");
  1404. return false;
  1405. }
  1406. }
  1407. function setHelpDate() {
  1408. try {
  1409. localStorage.setItem("help-viewed", Date.now());
  1410. } catch {
  1411. console.warn("Could not set the help-viewed date");
  1412. }
  1413. }
  1414. function doYScroll() {
  1415. const worldHeight = config.height.toNumber("meters");
  1416. config.y += scrollDirection * worldHeight / 180;
  1417. updateSizes();
  1418. scrollDirection *= 1.05;
  1419. }
  1420. function doXScroll() {
  1421. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1422. config.x += scrollDirection * worldWidth / 180 ;
  1423. updateSizes();
  1424. scrollDirection *= 1.05;
  1425. }
  1426. function doZoom() {
  1427. const oldHeight = config.height;
  1428. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1429. zoomDirection *= 1.05;
  1430. }
  1431. function doSize() {
  1432. if (selected) {
  1433. const entity = entities[selected.dataset.key];
  1434. const oldHeight = entity.views[entity.view].height;
  1435. entity.views[entity.view].height = math.multiply(oldHeight, sizeDirection < 0 ? -1/sizeDirection : sizeDirection);
  1436. entity.dirty = true;
  1437. updateEntityOptions(entity, entity.view);
  1438. updateViewOptions(entity, entity.view);
  1439. updateSizes(true);
  1440. sizeDirection *= 1.01;
  1441. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1442. const worldHeight = config.height.toNumber("meters");
  1443. if (ownHeight > worldHeight) {
  1444. setWorldHeight(config.height, entity.views[entity.view].height)
  1445. } else if (ownHeight * 10 < worldHeight) {
  1446. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1447. }
  1448. }
  1449. }
  1450. function prepareHelp() {
  1451. const toc = document.querySelector("#table-of-contents");
  1452. const holder = document.querySelector("#help-contents-holder");
  1453. document.querySelectorAll("#help-contents h2").forEach(header => {
  1454. const li = document.createElement("li");
  1455. li.innerText = header.textContent;
  1456. li.addEventListener("click", e => {
  1457. holder.scrollTop = header.offsetTop;
  1458. });
  1459. toc.appendChild(li);
  1460. });
  1461. }
  1462. document.addEventListener("DOMContentLoaded", () => {
  1463. prepareMenu();
  1464. prepareEntities();
  1465. prepareHelp();
  1466. document.querySelector("#open-help").addEventListener("click", e => {
  1467. setHelpDate();
  1468. document.querySelector("#help-menu").classList.add("visible");
  1469. document.querySelector("#open-help").classList.remove("highlighted");
  1470. });
  1471. document.querySelector("#close-help").addEventListener("click", e => {
  1472. document.querySelector("#help-menu").classList.remove("visible");
  1473. });
  1474. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1475. copyScreenshot();
  1476. toast("Copied to clipboard!");
  1477. });
  1478. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1479. saveScreenshot();
  1480. });
  1481. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1482. const popoutMenu = document.querySelector("#sidebar-menu");
  1483. if (popoutMenu.classList.contains("visible")) {
  1484. popoutMenu.classList.remove("visible");
  1485. } else {
  1486. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1487. const rect = e.target.getBoundingClientRect();
  1488. popoutMenu.classList.add("visible");
  1489. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1490. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1491. }
  1492. e.stopPropagation();
  1493. });
  1494. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  1495. e.stopPropagation();
  1496. });
  1497. document.addEventListener("click", e => {
  1498. document.querySelector("#sidebar-menu").classList.remove("visible");
  1499. });
  1500. document.querySelector("#toggle-settings").addEventListener("click", e => {
  1501. const popoutMenu = document.querySelector("#settings-menu");
  1502. if (popoutMenu.classList.contains("visible")) {
  1503. popoutMenu.classList.remove("visible");
  1504. } else {
  1505. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1506. const rect = e.target.getBoundingClientRect();
  1507. popoutMenu.classList.add("visible");
  1508. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1509. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1510. }
  1511. e.stopPropagation();
  1512. });
  1513. document.querySelector("#settings-menu").addEventListener("click", e => {
  1514. e.stopPropagation();
  1515. });
  1516. document.addEventListener("click", e => {
  1517. document.querySelector("#settings-menu").classList.remove("visible");
  1518. });
  1519. window.addEventListener("unload", () => {
  1520. saveScene("autosave");
  1521. setUserSettings(exportUserSettings());
  1522. });
  1523. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1524. if (e.target.value == "None") {
  1525. deselect()
  1526. } else {
  1527. select(document.querySelector("#entity-" + e.target.value));
  1528. }
  1529. });
  1530. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1531. const sidebar = document.querySelector("#options");
  1532. if (sidebar.classList.contains("hidden")) {
  1533. sidebar.classList.remove("hidden");
  1534. e.target.classList.remove("rotate-forward");
  1535. e.target.classList.add("rotate-backward");
  1536. } else {
  1537. sidebar.classList.add("hidden");
  1538. e.target.classList.add("rotate-forward");
  1539. e.target.classList.remove("rotate-backward");
  1540. }
  1541. handleResize();
  1542. });
  1543. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1544. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1545. if (selected) {
  1546. entities[selected.dataset.key].priority += 1;
  1547. }
  1548. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1549. updateSizes();
  1550. });
  1551. document.querySelector("#options-order-back").addEventListener("click", e => {
  1552. if (selected) {
  1553. entities[selected.dataset.key].priority -= 1;
  1554. }
  1555. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1556. updateSizes();
  1557. });
  1558. const sceneChoices = document.querySelector("#scene-choices");
  1559. Object.entries(scenes).forEach(([id, scene]) => {
  1560. const option = document.createElement("option");
  1561. option.innerText = id;
  1562. option.value = id;
  1563. sceneChoices.appendChild(option);
  1564. });
  1565. document.querySelector("#load-scene").addEventListener("click", e => {
  1566. const chosen = sceneChoices.value;
  1567. removeAllEntities();
  1568. scenes[chosen]();
  1569. });
  1570. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1571. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1572. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1573. document.querySelector("#options-height-value").addEventListener("change", e => {
  1574. updateWorldHeight();
  1575. })
  1576. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1577. e.stopPropagation();
  1578. })
  1579. const unitSelector = document.querySelector("#options-height-unit");
  1580. unitChoices.length.forEach(lengthOption => {
  1581. const option = document.createElement("option");
  1582. option.innerText = lengthOption;
  1583. option.value = lengthOption;
  1584. if (lengthOption === "meters") {
  1585. option.selected = true;
  1586. }
  1587. unitSelector.appendChild(option);
  1588. });
  1589. unitSelector.setAttribute("oldUnit", "meters");
  1590. unitSelector.addEventListener("input", e => {
  1591. checkFitWorld();
  1592. const scaleInput = document.querySelector("#options-height-value");
  1593. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1594. setNumericInput(scaleInput, newVal);
  1595. updateWorldHeight();
  1596. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1597. });
  1598. param = new URL(window.location.href).searchParams.get("scene");
  1599. if (param === null) {
  1600. scenes["Default"]();
  1601. }
  1602. else {
  1603. try {
  1604. const data = JSON.parse(b64DecodeUnicode(param));
  1605. if (data.entities === undefined) {
  1606. return;
  1607. }
  1608. if (data.world === undefined) {
  1609. return;
  1610. }
  1611. importScene(data);
  1612. } catch (err) {
  1613. console.error(err);
  1614. scenes["Default"]();
  1615. // probably wasn't valid data
  1616. }
  1617. }
  1618. document.querySelector("#world").addEventListener("wheel", e => {
  1619. if (shiftHeld) {
  1620. if (selected) {
  1621. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1622. const entity = entities[selected.dataset.key];
  1623. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1624. entity.dirty = true;
  1625. updateEntityOptions(entity, entity.view);
  1626. updateViewOptions(entity, entity.view);
  1627. updateSizes(true);
  1628. } else {
  1629. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1630. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  1631. updateSizes();
  1632. updateSizes();
  1633. }
  1634. } else {
  1635. if (config.autoFit) {
  1636. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  1637. } else {
  1638. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1639. setWorldHeight(config.height, math.multiply(config.height, dir));
  1640. updateWorldOptions();
  1641. }
  1642. }
  1643. checkFitWorld();
  1644. })
  1645. document.querySelector("#world").addEventListener("mousedown", e => {
  1646. // only middle mouse clicks
  1647. if (e.which == 2) {
  1648. panning = true;
  1649. panOffsetX = e.clientX;
  1650. panOffsetY = e.clientY;
  1651. Object.keys(entities).forEach(key => {
  1652. document.querySelector("#entity-" + key).classList.add("no-transition");
  1653. });
  1654. }
  1655. });
  1656. document.querySelector("#world").addEventListener("mouseup", e => {
  1657. if (e.which == 2) {
  1658. panning = false;
  1659. Object.keys(entities).forEach(key => {
  1660. document.querySelector("#entity-" + key).classList.remove("no-transition");
  1661. });
  1662. }
  1663. });
  1664. document.querySelector("#world").addEventListener("touchstart", e => {
  1665. panning = true;
  1666. panOffsetX = e.touches[0].clientX;
  1667. panOffsetY = e.touches[0].clientY;
  1668. e.preventDefault();
  1669. Object.keys(entities).forEach(key => {
  1670. document.querySelector("#entity-" + key).classList.add("no-transition");
  1671. });
  1672. });
  1673. document.querySelector("#world").addEventListener("touchend", e => {
  1674. panning = false;
  1675. Object.keys(entities).forEach(key => {
  1676. document.querySelector("#entity-" + key).classList.remove("no-transition");
  1677. });
  1678. });
  1679. document.querySelector("body").appendChild(testCtx.canvas);
  1680. updateSizes();
  1681. world.addEventListener("mousedown", e => deselect(e));
  1682. world.addEventListener("touchstart", e => deselect({
  1683. which: 1,
  1684. }));
  1685. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1686. document.querySelector("#display").addEventListener("mousedown", deselect);
  1687. document.addEventListener("mouseup", e => clickUp(e));
  1688. document.addEventListener("touchend", e => {
  1689. const fakeEvent = {
  1690. target: e.target,
  1691. clientX: e.changedTouches[0].clientX,
  1692. clientY: e.changedTouches[0].clientY,
  1693. which: 1
  1694. };
  1695. clickUp(fakeEvent);
  1696. });
  1697. const viewList = document.querySelector("#entity-view");
  1698. document.querySelector("#entity-view").addEventListener("input", e => {
  1699. const entity = entities[selected.dataset.key];
  1700. entity.view = e.target.value;
  1701. const image = entities[selected.dataset.key].views[e.target.value].image;
  1702. selected.querySelector(".entity-image").src = image.source;
  1703. configViewOptions(entity, entity.view);
  1704. displayAttribution(image.source);
  1705. if (image.bottom !== undefined) {
  1706. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1707. } else {
  1708. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1709. }
  1710. updateSizes();
  1711. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1712. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1713. });
  1714. document.querySelector("#entity-view").addEventListener("input", e => {
  1715. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  1716. viewList.classList.add("nsfw");
  1717. } else {
  1718. viewList.classList.remove("nsfw");
  1719. }
  1720. })
  1721. clearViewList();
  1722. document.querySelector("#menu-clear").addEventListener("click", e => {
  1723. removeAllEntities();
  1724. });
  1725. document.querySelector("#delete-entity").disabled = true;
  1726. document.querySelector("#delete-entity").addEventListener("click", e => {
  1727. if (selected) {
  1728. removeEntity(selected);
  1729. selected = null;
  1730. }
  1731. });
  1732. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1733. const order = Object.keys(entities).sort((a, b) => {
  1734. const entA = entities[a];
  1735. const entB = entities[b];
  1736. const viewA = entA.view;
  1737. const viewB = entB.view;
  1738. const heightA = entA.views[viewA].height.to("meter").value;
  1739. const heightB = entB.views[viewB].height.to("meter").value;
  1740. return heightA - heightB;
  1741. });
  1742. arrangeEntities(order);
  1743. });
  1744. // TODO: write some generic logic for this lol
  1745. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1746. scrollDirection = -1;
  1747. clearInterval(scrollHandle);
  1748. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1749. e.stopPropagation();
  1750. });
  1751. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1752. scrollDirection = 1;
  1753. clearInterval(scrollHandle);
  1754. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1755. e.stopPropagation();
  1756. });
  1757. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1758. scrollDirection = -1;
  1759. clearInterval(scrollHandle);
  1760. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1761. e.stopPropagation();
  1762. });
  1763. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1764. scrollDirection = 1;
  1765. clearInterval(scrollHandle);
  1766. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1767. e.stopPropagation();
  1768. });
  1769. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  1770. scrollDirection = 1;
  1771. clearInterval(scrollHandle);
  1772. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1773. e.stopPropagation();
  1774. });
  1775. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  1776. scrollDirection = -1;
  1777. clearInterval(scrollHandle);
  1778. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1779. e.stopPropagation();
  1780. });
  1781. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  1782. scrollDirection = 1;
  1783. clearInterval(scrollHandle);
  1784. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1785. e.stopPropagation();
  1786. });
  1787. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  1788. scrollDirection = -1;
  1789. clearInterval(scrollHandle);
  1790. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1791. e.stopPropagation();
  1792. });
  1793. document.addEventListener("mouseup", e => {
  1794. clearInterval(scrollHandle);
  1795. scrollHandle = null;
  1796. });
  1797. document.addEventListener("touchend", e => {
  1798. clearInterval(scrollHandle);
  1799. scrollHandle = null;
  1800. });
  1801. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1802. zoomDirection = -1;
  1803. clearInterval(zoomHandle);
  1804. zoomHandle = setInterval(doZoom, 1000 / 20);
  1805. e.stopPropagation();
  1806. });
  1807. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1808. zoomDirection = 1;
  1809. clearInterval(zoomHandle);
  1810. zoomHandle = setInterval(doZoom, 1000 / 20);
  1811. e.stopPropagation();
  1812. });
  1813. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1814. zoomDirection = -1;
  1815. clearInterval(zoomHandle);
  1816. zoomHandle = setInterval(doZoom, 1000 / 20);
  1817. e.stopPropagation();
  1818. });
  1819. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1820. zoomDirection = 1;
  1821. clearInterval(zoomHandle);
  1822. zoomHandle = setInterval(doZoom, 1000 / 20);
  1823. e.stopPropagation();
  1824. });
  1825. document.addEventListener("mouseup", e => {
  1826. clearInterval(zoomHandle);
  1827. zoomHandle = null;
  1828. });
  1829. document.addEventListener("touchend", e => {
  1830. clearInterval(zoomHandle);
  1831. zoomHandle = null;
  1832. });
  1833. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1834. sizeDirection = -1;
  1835. clearInterval(sizeHandle);
  1836. sizeHandle = setInterval(doSize, 1000 / 20);
  1837. e.stopPropagation();
  1838. });
  1839. document.querySelector("#grow").addEventListener("mousedown", e => {
  1840. sizeDirection = 1;
  1841. clearInterval(sizeHandle);
  1842. sizeHandle = setInterval(doSize, 1000 / 20);
  1843. e.stopPropagation();
  1844. });
  1845. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1846. sizeDirection = -1;
  1847. clearInterval(sizeHandle);
  1848. sizeHandle = setInterval(doSize, 1000 / 20);
  1849. e.stopPropagation();
  1850. });
  1851. document.querySelector("#grow").addEventListener("touchstart", e => {
  1852. sizeDirection = 1;
  1853. clearInterval(sizeHandle);
  1854. sizeHandle = setInterval(doSize, 1000 / 20);
  1855. e.stopPropagation();
  1856. });
  1857. document.addEventListener("mouseup", e => {
  1858. clearInterval(sizeHandle);
  1859. sizeHandle = null;
  1860. });
  1861. document.addEventListener("touchend", e => {
  1862. clearInterval(sizeHandle);
  1863. sizeHandle = null;
  1864. });
  1865. document.querySelector("#fit").addEventListener("click", e => {
  1866. const x = parseFloat(selected.dataset.x);
  1867. const y = parseFloat(selected.dataset.y);
  1868. config.x = x;
  1869. config.y = y;
  1870. const entity = entities[selected.dataset.key];
  1871. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1872. setWorldHeight(config.height, height);
  1873. });
  1874. document.querySelector("#fit").addEventListener("mousedown", e => {
  1875. e.stopPropagation();
  1876. });
  1877. document.querySelector("#fit").addEventListener("touchstart", e => {
  1878. e.stopPropagation();
  1879. });
  1880. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1881. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  1882. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  1883. document.addEventListener("keydown", e => {
  1884. if (e.key == "Delete") {
  1885. if (selected) {
  1886. removeEntity(selected);
  1887. selected = null;
  1888. }
  1889. }
  1890. })
  1891. document.addEventListener("keydown", e => {
  1892. if (e.key == "Shift") {
  1893. shiftHeld = true;
  1894. e.preventDefault();
  1895. } else if (e.key == "Alt") {
  1896. altHeld = true;
  1897. e.preventDefault();
  1898. }
  1899. });
  1900. document.addEventListener("keyup", e => {
  1901. if (e.key == "Shift") {
  1902. shiftHeld = false;
  1903. e.preventDefault();
  1904. } else if (e.key == "Alt") {
  1905. altHeld = false;
  1906. e.preventDefault();
  1907. }
  1908. });
  1909. window.addEventListener("resize", handleResize);
  1910. // TODO: further investigate why the tool initially starts out with wrong
  1911. // values under certain circumstances (seems to be narrow aspect ratios -
  1912. // maybe the menu bar is animating when it shouldn't)
  1913. setTimeout(handleResize, 250);
  1914. setTimeout(handleResize, 500);
  1915. setTimeout(handleResize, 750);
  1916. setTimeout(handleResize, 1000);
  1917. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1918. linkScene();
  1919. });
  1920. document.querySelector("#menu-export").addEventListener("click", e => {
  1921. copyScene();
  1922. });
  1923. document.querySelector("#menu-import").addEventListener("click", e => {
  1924. pasteScene();
  1925. });
  1926. document.querySelector("#menu-save").addEventListener("click", e => {
  1927. saveScene();
  1928. });
  1929. document.querySelector("#menu-load").addEventListener("click", e => {
  1930. loadScene();
  1931. });
  1932. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1933. loadScene("autosave");
  1934. });
  1935. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1936. document.querySelector("#file-upload-picker").click();
  1937. });
  1938. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1939. if (e.target.files.length > 0) {
  1940. for (let i=0; i<e.target.files.length; i++) {
  1941. customEntityFromFile(e.target.files[i]);
  1942. }
  1943. }
  1944. })
  1945. document.addEventListener("paste", e => {
  1946. let index = 0;
  1947. let item = null;
  1948. let found = false;
  1949. for (; index < e.clipboardData.items.length; index++) {
  1950. item = e.clipboardData.items[index];
  1951. if (item.type == "image/png") {
  1952. found = true;
  1953. break;
  1954. }
  1955. }
  1956. if (!found) {
  1957. return;
  1958. }
  1959. let url = null;
  1960. const file = item.getAsFile();
  1961. customEntityFromFile(file);
  1962. });
  1963. document.querySelector("#world").addEventListener("dragover", e => {
  1964. e.preventDefault();
  1965. })
  1966. document.querySelector("#world").addEventListener("drop", e => {
  1967. e.preventDefault();
  1968. if (e.dataTransfer.files.length > 0) {
  1969. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1970. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1971. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  1972. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1973. }
  1974. })
  1975. clearEntityOptions();
  1976. clearViewOptions();
  1977. clearAttribution();
  1978. // we do this last because configuring settings can cause things
  1979. // to happen (e.g. auto-fit)
  1980. prepareSettings(getUserSettings());
  1981. });
  1982. function customEntityFromFile(file, x=0.5, y=0.5) {
  1983. file.arrayBuffer().then(buf => {
  1984. arr = new Uint8Array(buf);
  1985. blob = new Blob([arr], {type: file.type });
  1986. url = window.URL.createObjectURL(blob)
  1987. makeCustomEntity(url, x, y);
  1988. });
  1989. }
  1990. function makeCustomEntity(url, x=0.5, y=0.5) {
  1991. const maker = createEntityMaker(
  1992. {
  1993. name: "Custom Entity"
  1994. },
  1995. {
  1996. custom: {
  1997. attributes: {
  1998. height: {
  1999. name: "Height",
  2000. power: 1,
  2001. type: "length",
  2002. base: math.unit(6, "feet")
  2003. }
  2004. },
  2005. image: {
  2006. source: url
  2007. },
  2008. name: "Image",
  2009. info: {},
  2010. rename: false
  2011. }
  2012. },
  2013. []
  2014. );
  2015. const entity = maker.constructor();
  2016. entity.scale = config.height.toNumber("feet") / 20;
  2017. entity.ephemeral = true;
  2018. displayEntity(entity, "custom", x, y, true, true);
  2019. }
  2020. const filterDefs = {
  2021. none: {
  2022. id: "none",
  2023. name: "No Filter",
  2024. extract: maker => [],
  2025. render: name => name,
  2026. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2027. },
  2028. author: {
  2029. id: "author",
  2030. name: "Authors",
  2031. extract: maker => maker.authors ? maker.authors : [],
  2032. render: author => attributionData.people[author].name,
  2033. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2034. },
  2035. owner: {
  2036. id: "owner",
  2037. name: "Owners",
  2038. extract: maker => maker.owners ? maker.owners : [],
  2039. render: owner => attributionData.people[owner].name,
  2040. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2041. },
  2042. species: {
  2043. id: "species",
  2044. name: "Species",
  2045. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  2046. render: species => speciesData[species].name,
  2047. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2048. },
  2049. tags: {
  2050. id: "tags",
  2051. name: "Tags",
  2052. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  2053. render: tag => tagDefs[tag],
  2054. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2055. },
  2056. size: {
  2057. id: "size",
  2058. name: "Normal Size",
  2059. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  2060. if (result && !size.default) {
  2061. return result;
  2062. }
  2063. let meters = size.height.toNumber("meters");
  2064. if (meters < 1e-1) {
  2065. return ["micro"];
  2066. } else if (meters < 1e1) {
  2067. return ["moderate"];
  2068. } else {
  2069. return ["macro"];
  2070. }
  2071. }, null)) : [],
  2072. render: tag => { return {
  2073. "micro": "Micro",
  2074. "moderate": "Moderate",
  2075. "macro": "Macro"
  2076. }[tag]},
  2077. sort: (tag1, tag2) => {
  2078. const order = {
  2079. "micro": 0,
  2080. "moderate": 1,
  2081. "macro": 2
  2082. };
  2083. return order[tag1[0]] - order[tag2[0]];
  2084. }
  2085. },
  2086. allSizes: {
  2087. id: "allSizes",
  2088. name: "Possible Size",
  2089. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  2090. const height = size.height;
  2091. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  2092. if (result) {
  2093. return result;
  2094. } else {
  2095. if (math.compare(height, value) <= 0) {
  2096. return name;
  2097. }
  2098. }
  2099. }, null);
  2100. set.add(result ? result : "infinite");
  2101. return set;
  2102. }, new Set())) : [],
  2103. render: tag => tag[0].toUpperCase() + tag.slice(1),
  2104. sort: (tag1, tag2) => {
  2105. const order = [
  2106. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  2107. "galactic", "universal", "omniversal", "infinite"
  2108. ]
  2109. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  2110. }
  2111. }
  2112. }
  2113. const sizeCategories = {
  2114. "atomic": math.unit(100, "angstroms"),
  2115. "microscopic": math.unit(100, "micrometers"),
  2116. "tiny": math.unit(100, "millimeters"),
  2117. "small": math.unit(1, "meter"),
  2118. "moderate": math.unit(3, "meters"),
  2119. "large": math.unit(10, "meters"),
  2120. "macro": math.unit(300, "meters"),
  2121. "megamacro": math.unit(1000, "kilometers"),
  2122. "planetary": math.unit(10, "earths"),
  2123. "stellar": math.unit(10, "solarradii"),
  2124. "galactic": math.unit(10, "galaxies"),
  2125. "universal": math.unit(10, "universes"),
  2126. "omniversal": math.unit(10, "multiverses")
  2127. };
  2128. function prepareEntities() {
  2129. availableEntities["buildings"] = makeBuildings();
  2130. availableEntities["characters"] = makeCharacters();
  2131. availableEntities["cities"] = makeCities();
  2132. availableEntities["fiction"] = makeFiction();
  2133. availableEntities["food"] = makeFood();
  2134. availableEntities["landmarks"] = makeLandmarks();
  2135. availableEntities["naturals"] = makeNaturals();
  2136. availableEntities["objects"] = makeObjects();
  2137. availableEntities["dildos"] = makeDildos();
  2138. availableEntities["pokemon"] = makePokemon();
  2139. availableEntities["species"] = makeSpecies();
  2140. availableEntities["vehicles"] = makeVehicles();
  2141. availableEntities["characters"].sort((x, y) => {
  2142. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  2143. });
  2144. const holder = document.querySelector("#spawners");
  2145. const filterHolder = document.querySelector("#filters");
  2146. const categorySelect = document.createElement("select");
  2147. categorySelect.id = "category-picker";
  2148. const filterSelect = document.createElement("select");
  2149. filterSelect.id = "filter-picker";
  2150. holder.appendChild(categorySelect);
  2151. filterHolder.appendChild(filterSelect);
  2152. const filterSets = {};
  2153. Object.values(filterDefs).forEach(filter => {
  2154. filterSets[filter.id] = new Set();
  2155. })
  2156. Object.entries(availableEntities).forEach(([category, entityList]) => {
  2157. const select = document.createElement("select");
  2158. select.id = "create-entity-" + category;
  2159. select.classList.add("entity-select");
  2160. for (let i = 0; i < entityList.length; i++) {
  2161. const entity = entityList[i];
  2162. const option = document.createElement("option");
  2163. option.value = i;
  2164. option.innerText = entity.name;
  2165. select.appendChild(option);
  2166. if (entity.nsfw) {
  2167. option.classList.add("nsfw");
  2168. }
  2169. Object.values(filterDefs).forEach(filter => {
  2170. filter.extract(entity).forEach(result => {
  2171. filterSets[filter.id].add(result);
  2172. });
  2173. });
  2174. availableEntitiesByName[entity.name] = entity;
  2175. };
  2176. select.addEventListener("change", e => {
  2177. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  2178. select.classList.add("nsfw");
  2179. } else {
  2180. select.classList.remove("nsfw");
  2181. }
  2182. })
  2183. const button = document.createElement("button");
  2184. button.id = "create-entity-" + category + "-button";
  2185. button.classList.add("entity-button");
  2186. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  2187. button.addEventListener("click", e => {
  2188. const newEntity = entityList[select.value].constructor()
  2189. displayEntity(newEntity, newEntity.defaultView, 0, 0, true, true);
  2190. });
  2191. const categoryOption = document.createElement("option");
  2192. categoryOption.value = category
  2193. categoryOption.innerText = category;
  2194. if (category == "characters") {
  2195. categoryOption.selected = true;
  2196. select.classList.add("category-visible");
  2197. button.classList.add("category-visible");
  2198. }
  2199. categorySelect.appendChild(categoryOption);
  2200. holder.appendChild(select);
  2201. holder.appendChild(button);
  2202. });
  2203. Object.values(filterDefs).forEach(filter => {
  2204. const option = document.createElement("option");
  2205. option.innerText = filter.name;
  2206. option.value = filter.id;
  2207. filterSelect.appendChild(option);
  2208. const filterNameSelect = document.createElement("select");
  2209. filterNameSelect.classList.add("filter-select");
  2210. filterNameSelect.id = "filter-" + filter.id;
  2211. filterHolder.appendChild(filterNameSelect);
  2212. const button = document.createElement("button");
  2213. button.classList.add("filter-button");
  2214. button.id = "create-filtered-" + filter.id + "-button";
  2215. filterHolder.appendChild(button);
  2216. const counter = document.createElement("div");
  2217. counter.classList.add("button-counter");
  2218. counter.innerText = "10";
  2219. button.appendChild(counter);
  2220. const i = document.createElement("i");
  2221. i.classList.add("fas");
  2222. i.classList.add("fa-plus");
  2223. button.appendChild(i);
  2224. button.addEventListener("click", e => {
  2225. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  2226. const count = makers.length + 2;
  2227. let index = 1;
  2228. if (makers.length > 50) {
  2229. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  2230. return;
  2231. }
  2232. }
  2233. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2234. makers.map(element => {
  2235. const category = document.querySelector("#category-picker").value;
  2236. const maker = availableEntities[category][element.value];
  2237. const entity = maker.constructor()
  2238. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  2239. index += 1;
  2240. });
  2241. updateSizes(true);
  2242. });
  2243. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  2244. const option = document.createElement("option");
  2245. option.innerText = name[1];
  2246. option.value = name[0];
  2247. filterNameSelect.appendChild(option);
  2248. });
  2249. filterNameSelect.addEventListener("change", e => {
  2250. updateFilter();
  2251. });
  2252. });
  2253. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  2254. categorySelect.addEventListener("input", e => {
  2255. const oldSelect = document.querySelector(".entity-select.category-visible");
  2256. oldSelect.classList.remove("category-visible");
  2257. const oldButton = document.querySelector(".entity-button.category-visible");
  2258. oldButton.classList.remove("category-visible");
  2259. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  2260. newSelect.classList.add("category-visible");
  2261. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  2262. newButton.classList.add("category-visible");
  2263. recomputeFilters();
  2264. updateFilter();
  2265. });
  2266. recomputeFilters();
  2267. filterSelect.addEventListener("input", e => {
  2268. const oldSelect = document.querySelector(".filter-select.category-visible");
  2269. if (oldSelect)
  2270. oldSelect.classList.remove("category-visible");
  2271. const newSelect = document.querySelector("#filter-" + e.target.value);
  2272. if (newSelect && e.target.value != "none")
  2273. newSelect.classList.add("category-visible");
  2274. updateFilter();
  2275. });
  2276. }
  2277. // Only display authors and owners if they appear
  2278. // somewhere in the current entity list
  2279. function recomputeFilters() {
  2280. const category = document.querySelector("#category-picker").value;
  2281. const filterSets = {};
  2282. Object.values(filterDefs).forEach(filter => {
  2283. filterSets[filter.id] = new Set();
  2284. });
  2285. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2286. const entity = availableEntities[category][element.value];
  2287. Object.values(filterDefs).forEach(filter => {
  2288. filter.extract(entity).forEach(result => {
  2289. filterSets[filter.id].add(result);
  2290. });
  2291. });
  2292. });
  2293. Object.values(filterDefs).forEach(filter => {
  2294. // always show the "none" option
  2295. let found = filter.id == "none";
  2296. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  2297. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  2298. element.classList.remove("filtered");
  2299. element.disabled = false;
  2300. found = true;
  2301. } else {
  2302. element.classList.add("filtered");
  2303. element.disabled = true;
  2304. }
  2305. });
  2306. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  2307. if (found) {
  2308. filterOption.classList.remove("filtered");
  2309. filterOption.disabled = false;
  2310. } else {
  2311. filterOption.classList.add("filtered");
  2312. filterOption.disabled = true;
  2313. }
  2314. });
  2315. document.querySelector("#filter-picker").value = "none";
  2316. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  2317. }
  2318. function updateFilter() {
  2319. const category = document.querySelector("#category-picker").value;
  2320. const type = document.querySelector("#filter-picker").value;
  2321. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  2322. clearFilter();
  2323. if (!filterKeySelect) {
  2324. return;
  2325. }
  2326. const key = filterKeySelect.value;
  2327. let current = document.querySelector(".entity-select.category-visible").value;
  2328. let replace = false;
  2329. let first = null;
  2330. let count = 0;
  2331. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2332. let keep = type == "none";
  2333. if (filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  2334. keep = true;
  2335. }
  2336. if (!keep) {
  2337. element.classList.add("filtered");
  2338. element.disabled = true;
  2339. if (current == element.value) {
  2340. replace = true;
  2341. }
  2342. } else {
  2343. count += 1;
  2344. if (!first) {
  2345. first = element.value;
  2346. }
  2347. }
  2348. });
  2349. const button = document.querySelector(".filter-select.category-visible + button");
  2350. if (button) {
  2351. button.querySelector(".button-counter").innerText = count;
  2352. }
  2353. if (replace) {
  2354. document.querySelector(".entity-select.category-visible").value = first;
  2355. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  2356. }
  2357. }
  2358. function clearFilter() {
  2359. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2360. element.classList.remove("filtered");
  2361. element.disabled = false;
  2362. });
  2363. }
  2364. document.addEventListener("mousemove", (e) => {
  2365. if (clicked) {
  2366. const position = snapRel(pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  2367. clicked.dataset.x = position.x;
  2368. clicked.dataset.y = position.y;
  2369. updateEntityElement(entities[clicked.dataset.key], clicked);
  2370. if (hoveringInDeleteArea(e)) {
  2371. document.querySelector("#menubar").classList.add("hover-delete");
  2372. } else {
  2373. document.querySelector("#menubar").classList.remove("hover-delete");
  2374. }
  2375. }
  2376. if (panning && panReady) {
  2377. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2378. const worldHeight = config.height.toNumber("meters");
  2379. config.x -= (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  2380. config.y += (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  2381. panOffsetX = e.clientX;
  2382. panOffsetY = e.clientY;
  2383. updateSizes();
  2384. panReady = false;
  2385. setTimeout(() => panReady=true, 1000/120);
  2386. }
  2387. });
  2388. document.addEventListener("touchmove", (e) => {
  2389. if (clicked) {
  2390. e.preventDefault();
  2391. let x = e.touches[0].clientX;
  2392. let y = e.touches[0].clientY;
  2393. const position = snapRel(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  2394. clicked.dataset.x = position.x;
  2395. clicked.dataset.y = position.y;
  2396. updateEntityElement(entities[clicked.dataset.key], clicked);
  2397. // what a hack
  2398. // I should centralize this 'fake event' creation...
  2399. if (hoveringInDeleteArea({ clientY: y })) {
  2400. document.querySelector("#menubar").classList.add("hover-delete");
  2401. } else {
  2402. document.querySelector("#menubar").classList.remove("hover-delete");
  2403. }
  2404. }
  2405. if (panning && panReady) {
  2406. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2407. const worldHeight = config.height.toNumber("meters");
  2408. config.x -= (e.touches[0].clientX - panOffsetX) / canvasWidth * worldWidth;
  2409. config.y += (e.touches[0].clientY - panOffsetY) / canvasHeight * worldHeight;
  2410. panOffsetX = e.touches[0].clientX;
  2411. panOffsetY = e.touches[0].clientY;
  2412. updateSizes();
  2413. panReady = false;
  2414. setTimeout(() => panReady=true, 50);
  2415. }
  2416. }, { passive: false });
  2417. function checkFitWorld() {
  2418. if (config.autoFit) {
  2419. fitWorld();
  2420. return true;
  2421. }
  2422. return false;
  2423. }
  2424. function fitWorld(manual = false, factor = 1.1) {
  2425. let minX = Infinity;
  2426. let maxX = -Infinity;
  2427. let minY = Infinity;
  2428. let maxY = -Infinity;
  2429. let count = 0;
  2430. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2431. const worldHeight = config.height.toNumber("meters");
  2432. Object.entries(entities).forEach(([key, entity]) => {
  2433. const view = entity.view;
  2434. let extra = entity.views[view].image.extra;
  2435. extra = extra === undefined ? 1 : extra;
  2436. const image = document.querySelector("#entity-" + key + " > .entity-image");
  2437. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  2438. let width = image.width;
  2439. let height = image.height;
  2440. // only really relevant if the images haven't loaded in yet
  2441. if (height == 0) {
  2442. height = 100;
  2443. }
  2444. if (width == 0) {
  2445. width = height;
  2446. }
  2447. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  2448. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  2449. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  2450. const yBottom = y;
  2451. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  2452. minX = Math.min(minX, xBottom);
  2453. maxX = Math.max(maxX, xTop);
  2454. minY = Math.min(minY, yBottom);
  2455. maxY = Math.max(maxY, yTop);
  2456. count += 1;
  2457. });
  2458. let ySize = (maxY - minY) * factor;
  2459. let xSize = (maxX - minX) * factor;
  2460. if (xSize / ySize > worldWidth / worldHeight) {
  2461. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  2462. }
  2463. config.x = (maxX + minX) / 2;
  2464. config.y = minY;
  2465. height = math.unit(ySize, "meter")
  2466. setWorldHeight(config.height, math.multiply(height, factor));
  2467. }
  2468. // TODO why am I doing this
  2469. function updateWorldHeight() {
  2470. const unit = document.querySelector("#options-height-unit").value;
  2471. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  2472. const oldHeight = config.height;
  2473. setWorldHeight(oldHeight, math.unit(value, unit));
  2474. }
  2475. function setWorldHeight(oldHeight, newHeight) {
  2476. worldSizeDirty = true;
  2477. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  2478. const unit = document.querySelector("#options-height-unit").value;
  2479. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  2480. Object.entries(entities).forEach(([key, entity]) => {
  2481. const element = document.querySelector("#entity-" + key);
  2482. let newPosition;
  2483. if (altHeld) {
  2484. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  2485. } else {
  2486. newPosition = { x: element.dataset.x, y: element.dataset.y };
  2487. }
  2488. element.dataset.x = newPosition.x;
  2489. element.dataset.y = newPosition.y;
  2490. });
  2491. updateSizes();
  2492. }
  2493. function loadScene(name = "default") {
  2494. try {
  2495. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  2496. if (data === null) {
  2497. return false;
  2498. }
  2499. importScene(data);
  2500. return true;
  2501. } catch (err) {
  2502. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2503. console.error(err);
  2504. return false;
  2505. }
  2506. }
  2507. function saveScene(name = "default") {
  2508. try {
  2509. const string = JSON.stringify(exportScene());
  2510. localStorage.setItem("macrovision-save-" + name, string);
  2511. } catch (err) {
  2512. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  2513. console.error(err);
  2514. }
  2515. }
  2516. function deleteScene(name = "default") {
  2517. try {
  2518. localStorage.removeItem("macrovision-save-" + name)
  2519. } catch (err) {
  2520. console.error(err);
  2521. }
  2522. }
  2523. function exportScene() {
  2524. const results = {};
  2525. results.entities = [];
  2526. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  2527. const element = document.querySelector("#entity-" + key);
  2528. results.entities.push({
  2529. name: entity.identifier,
  2530. scale: entity.scale,
  2531. view: entity.view,
  2532. x: element.dataset.x,
  2533. y: element.dataset.y
  2534. });
  2535. });
  2536. const unit = document.querySelector("#options-height-unit").value;
  2537. results.world = {
  2538. height: config.height.toNumber(unit),
  2539. unit: unit,
  2540. x: config.x,
  2541. y: config.y
  2542. }
  2543. results.version = migrationDefs.length;
  2544. return results;
  2545. }
  2546. // btoa doesn't like anything that isn't ASCII
  2547. // great
  2548. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  2549. // for providing an alternative
  2550. function b64EncodeUnicode(str) {
  2551. // first we use encodeURIComponent to get percent-encoded UTF-8,
  2552. // then we convert the percent encodings into raw bytes which
  2553. // can be fed into btoa.
  2554. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  2555. function toSolidBytes(match, p1) {
  2556. return String.fromCharCode('0x' + p1);
  2557. }));
  2558. }
  2559. function b64DecodeUnicode(str) {
  2560. // Going backwards: from bytestream, to percent-encoding, to original string.
  2561. return decodeURIComponent(atob(str).split('').map(function (c) {
  2562. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  2563. }).join(''));
  2564. }
  2565. function linkScene() {
  2566. loc = new URL(window.location);
  2567. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  2568. }
  2569. function copyScene() {
  2570. const results = exportScene();
  2571. navigator.clipboard.writeText(JSON.stringify(results));
  2572. }
  2573. function pasteScene() {
  2574. try {
  2575. navigator.clipboard.readText().then(text => {
  2576. const data = JSON.parse(text);
  2577. if (data.entities === undefined) {
  2578. return;
  2579. }
  2580. if (data.world === undefined) {
  2581. return;
  2582. }
  2583. importScene(data);
  2584. }).catch(err => alert(err));
  2585. } catch (err) {
  2586. console.error(err);
  2587. // probably wasn't valid data
  2588. }
  2589. }
  2590. // TODO - don't just search through every single entity
  2591. // probably just have a way to do lookups directly
  2592. function findEntity(name) {
  2593. return availableEntitiesByName[name];
  2594. }
  2595. const migrationDefs = [
  2596. /*
  2597. Migration: 0 -> 1
  2598. Adds x and y coordinates for the camera
  2599. */
  2600. data => {
  2601. data.world.x = 0;
  2602. data.world.y = 0;
  2603. }
  2604. ]
  2605. function migrateScene(data) {
  2606. if (data.version === undefined) {
  2607. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  2608. console.trace()
  2609. data.version = 0;
  2610. } else if (data.version < migrationDefs.length) {
  2611. migrationDefs[data.version](data);
  2612. data.version += 1;
  2613. migrateScene(data);
  2614. }
  2615. }
  2616. function importScene(data) {
  2617. removeAllEntities();
  2618. migrateScene(data);
  2619. data.entities.forEach(entityInfo => {
  2620. const entity = findEntity(entityInfo.name).constructor();
  2621. entity.scale = entityInfo.scale
  2622. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  2623. });
  2624. config.height = math.unit(data.world.height, data.world.unit);
  2625. config.x = data.world.x;
  2626. config.y = data.world.y;
  2627. document.querySelector("#options-height-unit").value = data.world.unit;
  2628. if (data.canvasWidth) {
  2629. doHorizReposition(data.canvasWidth / canvasWidth);
  2630. }
  2631. updateSizes();
  2632. }
  2633. function renderToCanvas() {
  2634. const ctx = document.querySelector("#display").getContext("2d");
  2635. Object.entries(entities).sort((ent1, ent2) => {
  2636. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  2637. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  2638. return z1 - z2;
  2639. }).forEach(([id, entity]) => {
  2640. element = document.querySelector("#entity-" + id);
  2641. img = element.querySelector("img");
  2642. let x = parseFloat(element.dataset.x);
  2643. let y = parseFloat(element.dataset.y);
  2644. let coords = pos2pix({x: x, y: y});
  2645. let offset = img.style.getPropertyValue("--offset");
  2646. offset = parseFloat(offset.substring(0, offset.length-1))
  2647. x = coords.x - img.getBoundingClientRect().width/2;
  2648. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  2649. let xSize = img.getBoundingClientRect().width;
  2650. let ySize = img.getBoundingClientRect().height;
  2651. ctx.drawImage(img, x, y, xSize, ySize);
  2652. });
  2653. }
  2654. function exportCanvas(callback) {
  2655. /** @type {CanvasRenderingContext2D} */
  2656. const ctx = document.querySelector("#display").getContext("2d");
  2657. const blob = ctx.canvas.toBlob(callback);
  2658. }
  2659. function generateScreenshot(callback) {
  2660. renderToCanvas();
  2661. /** @type {CanvasRenderingContext2D} */
  2662. const ctx = document.querySelector("#display").getContext("2d");
  2663. ctx.fillStyle = "#555";
  2664. ctx.font = "normal normal lighter 16pt coda";
  2665. ctx.fillText("macrovision.crux.sexy", 10, 25);
  2666. exportCanvas(blob => {
  2667. callback(blob);
  2668. });
  2669. }
  2670. function copyScreenshot() {
  2671. generateScreenshot(blob => {
  2672. navigator.clipboard.write([
  2673. new ClipboardItem({
  2674. "image/png": blob
  2675. })
  2676. ]);
  2677. });
  2678. drawScale(false);
  2679. }
  2680. function saveScreenshot() {
  2681. generateScreenshot(blob => {
  2682. const a = document.createElement("a");
  2683. a.href = URL.createObjectURL(blob);
  2684. a.setAttribute("download", "macrovision.png");
  2685. a.click();
  2686. });
  2687. drawScale(false);
  2688. }
  2689. const rateLimits = {};
  2690. function toast(msg) {
  2691. let div = document.createElement("div");
  2692. div.innerHTML = msg;
  2693. div.classList.add("toast");
  2694. document.body.appendChild(div);
  2695. setTimeout(() => {
  2696. document.body.removeChild(div);
  2697. }, 5000)
  2698. }
  2699. function toastRateLimit(msg, key, delay) {
  2700. if (!rateLimits[key]) {
  2701. toast(msg);
  2702. rateLimits[key] = setTimeout(() => {
  2703. delete rateLimits[key]
  2704. }, delay);
  2705. }
  2706. }