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

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