less copy protection, more size visualization
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

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