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

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