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

2638 строки
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: "Automatically 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. "names": {
  1102. name: "Show Names",
  1103. desc: "Display names over entities",
  1104. type: "toggle",
  1105. default: true,
  1106. get value() {
  1107. return checkBodyClass("toggle-entity-name");
  1108. },
  1109. set value(param) {
  1110. toggleBodyClass("toggle-entity-name", param);
  1111. }
  1112. },
  1113. "bottom-names": {
  1114. name: "Bottom Names",
  1115. desc: "Display names at the bottom",
  1116. type: "toggle",
  1117. default: false,
  1118. get value() {
  1119. return checkBodyClass("toggle-bottom-name");
  1120. },
  1121. set value(param) {
  1122. toggleBodyClass("toggle-bottom-name", param);
  1123. }
  1124. },
  1125. "top-names": {
  1126. name: "Show Arrows",
  1127. desc: "Point to entities that are much larger than the current view",
  1128. type: "toggle",
  1129. default: false,
  1130. get value() {
  1131. return checkBodyClass("toggle-top-name");
  1132. },
  1133. set value(param) {
  1134. toggleBodyClass("toggle-top-name", param);
  1135. }
  1136. },
  1137. "height-bars": {
  1138. name: "Height Bars",
  1139. desc: "Draw dashed lines to the top of each entity",
  1140. type: "toggle",
  1141. default: true,
  1142. get value() {
  1143. return checkBodyClass("toggle-height-bars");
  1144. },
  1145. set value(param) {
  1146. toggleBodyClass("toggle-height-bars", param);
  1147. }
  1148. },
  1149. "glowing-entities": {
  1150. name: "Glowing Edges",
  1151. desc: "Makes all entities glow",
  1152. type: "toggle",
  1153. default: false,
  1154. get value() {
  1155. return checkBodyClass("toggle-entity-glow");
  1156. },
  1157. set value(param) {
  1158. toggleBodyClass("toggle-entity-glow", param);
  1159. }
  1160. },
  1161. "solid-ground": {
  1162. name: "Solid Ground",
  1163. desc: "Draw solid ground at the y=0 line",
  1164. type: "toggle",
  1165. default: false,
  1166. get value() {
  1167. return checkBodyClass("toggle-bottom-cover");
  1168. },
  1169. set value(param) {
  1170. toggleBodyClass("toggle-bottom-cover", param);
  1171. }
  1172. },
  1173. "show-scale": {
  1174. name: "Show Scale",
  1175. desc: "Show the scale",
  1176. type: "toggle",
  1177. default: true,
  1178. get value() {
  1179. return checkBodyClass("toggle-scale");
  1180. },
  1181. set value(param) {
  1182. toggleBodyClass("toggle-scale", param);
  1183. }
  1184. },
  1185. }
  1186. function prepareSettings(userSettings) {
  1187. const menubar = document.querySelector("#settings-menu");
  1188. Object.entries(settingsData).forEach(([id, entry]) => {
  1189. const holder = document.createElement("label");
  1190. holder.classList.add("settings-holder");
  1191. const input = document.createElement("input");
  1192. input.id = "setting-" + id;
  1193. const name = document.createElement("label");
  1194. name.innerText = entry.name;
  1195. name.classList.add("settings-name");
  1196. name.setAttribute("for", input.id);
  1197. const desc = document.createElement("label");
  1198. desc.innerText = entry.desc;
  1199. desc.classList.add("settings-desc");
  1200. desc.setAttribute("for", input.id);
  1201. if (entry.type == "toggle") {
  1202. input.type = "checkbox";
  1203. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  1204. holder.setAttribute("for", input.id);
  1205. input.appendChild(name);
  1206. input.appendChild(desc);
  1207. holder.appendChild(input);
  1208. holder.appendChild(name);
  1209. holder.appendChild(desc);
  1210. menubar.appendChild(holder);
  1211. const update = () => {
  1212. if (input.checked) {
  1213. holder.classList.add("enabled");
  1214. holder.classList.remove("disabled");
  1215. } else {
  1216. holder.classList.remove("enabled");
  1217. holder.classList.add("disabled");
  1218. }
  1219. entry.value = input.checked;
  1220. }
  1221. update();
  1222. input.addEventListener("change", update);
  1223. }
  1224. })
  1225. }
  1226. function prepareMenu() {
  1227. prepareSidebar();
  1228. if (checkHelpDate()) {
  1229. document.querySelector("#open-help").classList.add("highlighted");
  1230. }
  1231. }
  1232. function getUserSettings() {
  1233. try {
  1234. const settings = JSON.parse(localStorage.getItem("settings"));
  1235. return settings === null ? {} : settings;
  1236. } catch {
  1237. return {};
  1238. }
  1239. }
  1240. function exportUserSettings() {
  1241. const settings = {};
  1242. Object.entries(settingsData).forEach(([id, entry]) => {
  1243. settings[id] = entry.value;
  1244. });
  1245. return settings;
  1246. }
  1247. function setUserSettings(settings) {
  1248. try {
  1249. localStorage.setItem("settings", JSON.stringify(settings));
  1250. } catch {
  1251. // :(
  1252. }
  1253. }
  1254. const lastHelpChange = 1587847743294;
  1255. function checkHelpDate() {
  1256. try {
  1257. const old = localStorage.getItem("help-viewed");
  1258. if (old === null || old < lastHelpChange) {
  1259. return true;
  1260. }
  1261. return false;
  1262. } catch {
  1263. console.warn("Could not set the help-viewed date");
  1264. return false;
  1265. }
  1266. }
  1267. function setHelpDate() {
  1268. try {
  1269. localStorage.setItem("help-viewed", Date.now());
  1270. } catch {
  1271. console.warn("Could not set the help-viewed date");
  1272. }
  1273. }
  1274. function doScroll() {
  1275. document.querySelectorAll(".entity-box").forEach(element => {
  1276. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection / 180;
  1277. });
  1278. updateSizes();
  1279. scrollDirection *= 1.05;
  1280. }
  1281. function doZoom() {
  1282. const oldHeight = config.height;
  1283. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1284. zoomDirection *= 1.05;
  1285. }
  1286. function doSize() {
  1287. if (selected) {
  1288. const entity = entities[selected.dataset.key];
  1289. const oldHeight = entity.views[entity.view].height;
  1290. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection / 20);
  1291. entity.dirty = true;
  1292. updateEntityOptions(entity, entity.view);
  1293. updateViewOptions(entity, entity.view);
  1294. updateSizes(true);
  1295. sizeDirection *= 1.05;
  1296. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1297. const worldHeight = config.height.toNumber("meters");
  1298. console.log(ownHeight, worldHeight)
  1299. if (ownHeight > worldHeight) {
  1300. setWorldHeight(config.height, entity.views[entity.view].height)
  1301. } else if (ownHeight * 10 < worldHeight) {
  1302. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1303. }
  1304. }
  1305. }
  1306. function prepareHelp() {
  1307. const toc = document.querySelector("#table-of-contents");
  1308. const holder = document.querySelector("#help-contents-holder");
  1309. document.querySelectorAll("#help-contents h2").forEach(header => {
  1310. const li = document.createElement("li");
  1311. li.innerText = header.textContent;
  1312. li.addEventListener("click", e => {
  1313. holder.scrollTop = header.offsetTop;
  1314. });
  1315. toc.appendChild(li);
  1316. });
  1317. }
  1318. document.addEventListener("DOMContentLoaded", () => {
  1319. prepareMenu();
  1320. prepareEntities();
  1321. prepareHelp();
  1322. document.querySelector("#open-help").addEventListener("click", e => {
  1323. setHelpDate();
  1324. document.querySelector("#help-menu").classList.add("visible");
  1325. document.querySelector("#open-help").classList.remove("highlighted");
  1326. });
  1327. document.querySelector("#close-help").addEventListener("click", e => {
  1328. document.querySelector("#help-menu").classList.remove("visible");
  1329. });
  1330. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1331. copyScreenshot();
  1332. toast("Copied to clipboard!");
  1333. });
  1334. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1335. saveScreenshot();
  1336. });
  1337. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1338. const popoutMenu = document.querySelector("#sidebar-menu");
  1339. if (popoutMenu.classList.contains("visible")) {
  1340. popoutMenu.classList.remove("visible");
  1341. } else {
  1342. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1343. const rect = e.target.getBoundingClientRect();
  1344. popoutMenu.classList.add("visible");
  1345. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1346. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1347. }
  1348. e.stopPropagation();
  1349. });
  1350. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  1351. e.stopPropagation();
  1352. });
  1353. document.addEventListener("click", e => {
  1354. document.querySelector("#sidebar-menu").classList.remove("visible");
  1355. });
  1356. document.querySelector("#toggle-settings").addEventListener("click", e => {
  1357. const popoutMenu = document.querySelector("#settings-menu");
  1358. if (popoutMenu.classList.contains("visible")) {
  1359. popoutMenu.classList.remove("visible");
  1360. } else {
  1361. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1362. const rect = e.target.getBoundingClientRect();
  1363. popoutMenu.classList.add("visible");
  1364. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1365. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1366. }
  1367. e.stopPropagation();
  1368. });
  1369. document.querySelector("#settings-menu").addEventListener("click", e => {
  1370. e.stopPropagation();
  1371. });
  1372. document.addEventListener("click", e => {
  1373. document.querySelector("#settings-menu").classList.remove("visible");
  1374. });
  1375. window.addEventListener("unload", () => {
  1376. saveScene("autosave");
  1377. setUserSettings(exportUserSettings());
  1378. });
  1379. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1380. if (e.target.value == "None") {
  1381. deselect()
  1382. } else {
  1383. select(document.querySelector("#entity-" + e.target.value));
  1384. }
  1385. });
  1386. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1387. const sidebar = document.querySelector("#options");
  1388. if (sidebar.classList.contains("hidden")) {
  1389. sidebar.classList.remove("hidden");
  1390. e.target.classList.remove("rotate-forward");
  1391. e.target.classList.add("rotate-backward");
  1392. } else {
  1393. sidebar.classList.add("hidden");
  1394. e.target.classList.add("rotate-forward");
  1395. e.target.classList.remove("rotate-backward");
  1396. }
  1397. handleResize();
  1398. });
  1399. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1400. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1401. if (selected) {
  1402. entities[selected.dataset.key].priority += 1;
  1403. }
  1404. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1405. updateSizes();
  1406. });
  1407. document.querySelector("#options-order-back").addEventListener("click", e => {
  1408. if (selected) {
  1409. entities[selected.dataset.key].priority -= 1;
  1410. }
  1411. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1412. updateSizes();
  1413. });
  1414. const sceneChoices = document.querySelector("#scene-choices");
  1415. Object.entries(scenes).forEach(([id, scene]) => {
  1416. const option = document.createElement("option");
  1417. option.innerText = id;
  1418. option.value = id;
  1419. sceneChoices.appendChild(option);
  1420. });
  1421. document.querySelector("#load-scene").addEventListener("click", e => {
  1422. const chosen = sceneChoices.value;
  1423. removeAllEntities();
  1424. scenes[chosen]();
  1425. });
  1426. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1427. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1428. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1429. document.querySelector("#options-height-value").addEventListener("change", e => {
  1430. updateWorldHeight();
  1431. })
  1432. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1433. e.stopPropagation();
  1434. })
  1435. const unitSelector = document.querySelector("#options-height-unit");
  1436. unitChoices.length.forEach(lengthOption => {
  1437. const option = document.createElement("option");
  1438. option.innerText = lengthOption;
  1439. option.value = lengthOption;
  1440. if (lengthOption === "meters") {
  1441. option.selected = true;
  1442. }
  1443. unitSelector.appendChild(option);
  1444. });
  1445. unitSelector.setAttribute("oldUnit", "meters");
  1446. unitSelector.addEventListener("input", e => {
  1447. checkFitWorld();
  1448. const scaleInput = document.querySelector("#options-height-value");
  1449. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1450. setNumericInput(scaleInput, newVal);
  1451. updateWorldHeight();
  1452. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1453. });
  1454. param = new URL(window.location.href).searchParams.get("scene");
  1455. if (param === null) {
  1456. scenes["Default"]();
  1457. }
  1458. else {
  1459. try {
  1460. const data = JSON.parse(b64DecodeUnicode(param));
  1461. if (data.entities === undefined) {
  1462. return;
  1463. }
  1464. if (data.world === undefined) {
  1465. return;
  1466. }
  1467. importScene(data);
  1468. } catch (err) {
  1469. console.error(err);
  1470. scenes["Default"]();
  1471. // probably wasn't valid data
  1472. }
  1473. }
  1474. document.querySelector("#world").addEventListener("wheel", e => {
  1475. if (shiftHeld) {
  1476. if (selected) {
  1477. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1478. const entity = entities[selected.dataset.key];
  1479. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1480. entity.dirty = true;
  1481. updateEntityOptions(entity, entity.view);
  1482. updateViewOptions(entity, entity.view);
  1483. updateSizes(true);
  1484. } else {
  1485. document.querySelectorAll(".entity-box").forEach(element => {
  1486. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1487. });
  1488. updateSizes();
  1489. }
  1490. } else {
  1491. if (config.autoFit) {
  1492. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  1493. } else {
  1494. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1495. setWorldHeight(config.height, math.multiply(config.height, dir));
  1496. updateWorldOptions();
  1497. }
  1498. }
  1499. checkFitWorld();
  1500. })
  1501. document.querySelector("body").appendChild(testCtx.canvas);
  1502. updateSizes();
  1503. world.addEventListener("mousedown", e => deselect());
  1504. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1505. document.querySelector("#display").addEventListener("mousedown", deselect);
  1506. document.addEventListener("mouseup", e => clickUp(e));
  1507. document.addEventListener("touchend", e => {
  1508. const fakeEvent = {
  1509. target: e.target,
  1510. clientX: e.changedTouches[0].clientX,
  1511. clientY: e.changedTouches[0].clientY
  1512. };
  1513. clickUp(fakeEvent);
  1514. });
  1515. document.querySelector("#entity-view").addEventListener("input", e => {
  1516. const entity = entities[selected.dataset.key];
  1517. entity.view = e.target.value;
  1518. const image = entities[selected.dataset.key].views[e.target.value].image;
  1519. selected.querySelector(".entity-image").src = image.source;
  1520. displayAttribution(image.source);
  1521. if (image.bottom !== undefined) {
  1522. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1523. } else {
  1524. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1525. }
  1526. updateSizes();
  1527. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1528. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1529. });
  1530. clearViewList();
  1531. document.querySelector("#menu-clear").addEventListener("click", e => {
  1532. removeAllEntities();
  1533. });
  1534. document.querySelector("#delete-entity").disabled = true;
  1535. document.querySelector("#delete-entity").addEventListener("click", e => {
  1536. if (selected) {
  1537. removeEntity(selected);
  1538. selected = null;
  1539. }
  1540. });
  1541. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1542. const order = Object.keys(entities).sort((a, b) => {
  1543. const entA = entities[a];
  1544. const entB = entities[b];
  1545. const viewA = entA.view;
  1546. const viewB = entB.view;
  1547. const heightA = entA.views[viewA].height.to("meter").value;
  1548. const heightB = entB.views[viewB].height.to("meter").value;
  1549. return heightA - heightB;
  1550. });
  1551. arrangeEntities(order);
  1552. });
  1553. // TODO: write some generic logic for this lol
  1554. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1555. scrollDirection = 1;
  1556. clearInterval(scrollHandle);
  1557. scrollHandle = setInterval(doScroll, 1000 / 20);
  1558. e.stopPropagation();
  1559. });
  1560. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1561. scrollDirection = -1;
  1562. clearInterval(scrollHandle);
  1563. scrollHandle = setInterval(doScroll, 1000 / 20);
  1564. e.stopPropagation();
  1565. });
  1566. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1567. scrollDirection = 1;
  1568. clearInterval(scrollHandle);
  1569. scrollHandle = setInterval(doScroll, 1000 / 20);
  1570. e.stopPropagation();
  1571. });
  1572. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1573. scrollDirection = -1;
  1574. clearInterval(scrollHandle);
  1575. scrollHandle = setInterval(doScroll, 1000 / 20);
  1576. e.stopPropagation();
  1577. });
  1578. document.addEventListener("mouseup", e => {
  1579. clearInterval(scrollHandle);
  1580. scrollHandle = null;
  1581. });
  1582. document.addEventListener("touchend", e => {
  1583. clearInterval(scrollHandle);
  1584. scrollHandle = null;
  1585. });
  1586. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1587. zoomDirection = -1;
  1588. clearInterval(zoomHandle);
  1589. zoomHandle = setInterval(doZoom, 1000 / 20);
  1590. e.stopPropagation();
  1591. });
  1592. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1593. zoomDirection = 1;
  1594. clearInterval(zoomHandle);
  1595. zoomHandle = setInterval(doZoom, 1000 / 20);
  1596. e.stopPropagation();
  1597. });
  1598. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1599. zoomDirection = -1;
  1600. clearInterval(zoomHandle);
  1601. zoomHandle = setInterval(doZoom, 1000 / 20);
  1602. e.stopPropagation();
  1603. });
  1604. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1605. zoomDirection = 1;
  1606. clearInterval(zoomHandle);
  1607. zoomHandle = setInterval(doZoom, 1000 / 20);
  1608. e.stopPropagation();
  1609. });
  1610. document.addEventListener("mouseup", e => {
  1611. clearInterval(zoomHandle);
  1612. zoomHandle = null;
  1613. });
  1614. document.addEventListener("touchend", e => {
  1615. clearInterval(zoomHandle);
  1616. zoomHandle = null;
  1617. });
  1618. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1619. sizeDirection = -1;
  1620. clearInterval(sizeHandle);
  1621. sizeHandle = setInterval(doSize, 1000 / 20);
  1622. e.stopPropagation();
  1623. });
  1624. document.querySelector("#grow").addEventListener("mousedown", e => {
  1625. sizeDirection = 1;
  1626. clearInterval(sizeHandle);
  1627. sizeHandle = setInterval(doSize, 1000 / 20);
  1628. e.stopPropagation();
  1629. });
  1630. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1631. sizeDirection = -1;
  1632. clearInterval(sizeHandle);
  1633. sizeHandle = setInterval(doSize, 1000 / 20);
  1634. e.stopPropagation();
  1635. });
  1636. document.querySelector("#grow").addEventListener("touchstart", e => {
  1637. sizeDirection = 1;
  1638. clearInterval(sizeHandle);
  1639. sizeHandle = setInterval(doSize, 1000 / 20);
  1640. e.stopPropagation();
  1641. });
  1642. document.addEventListener("mouseup", e => {
  1643. clearInterval(sizeHandle);
  1644. sizeHandle = null;
  1645. });
  1646. document.addEventListener("touchend", e => {
  1647. clearInterval(sizeHandle);
  1648. sizeHandle = null;
  1649. });
  1650. document.querySelector("#fit").addEventListener("click", e => {
  1651. const x = parseFloat(selected.dataset.x);
  1652. Object.keys(entities).forEach(id => {
  1653. const element = document.querySelector("#entity-" + id);
  1654. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1655. element.dataset.x = newX;
  1656. });
  1657. const entity = entities[selected.dataset.key];
  1658. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1659. setWorldHeight(config.height, height);
  1660. });
  1661. document.querySelector("#fit").addEventListener("mousedown", e => {
  1662. e.stopPropagation();
  1663. });
  1664. document.querySelector("#fit").addEventListener("touchstart", e => {
  1665. e.stopPropagation();
  1666. });
  1667. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1668. document.addEventListener("keydown", e => {
  1669. if (e.key == "Delete") {
  1670. if (selected) {
  1671. removeEntity(selected);
  1672. selected = null;
  1673. }
  1674. }
  1675. })
  1676. document.addEventListener("keydown", e => {
  1677. if (e.key == "Shift") {
  1678. shiftHeld = true;
  1679. e.preventDefault();
  1680. } else if (e.key == "Alt") {
  1681. altHeld = true;
  1682. e.preventDefault();
  1683. }
  1684. });
  1685. document.addEventListener("keyup", e => {
  1686. if (e.key == "Shift") {
  1687. shiftHeld = false;
  1688. e.preventDefault();
  1689. } else if (e.key == "Alt") {
  1690. altHeld = false;
  1691. e.preventDefault();
  1692. }
  1693. });
  1694. window.addEventListener("resize", handleResize);
  1695. // TODO: further investigate why the tool initially starts out with wrong
  1696. // values under certain circumstances (seems to be narrow aspect ratios -
  1697. // maybe the menu bar is animating when it shouldn't)
  1698. setTimeout(handleResize, 250);
  1699. setTimeout(handleResize, 500);
  1700. setTimeout(handleResize, 750);
  1701. setTimeout(handleResize, 1000);
  1702. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1703. linkScene();
  1704. });
  1705. document.querySelector("#menu-export").addEventListener("click", e => {
  1706. copyScene();
  1707. });
  1708. document.querySelector("#menu-import").addEventListener("click", e => {
  1709. pasteScene();
  1710. });
  1711. document.querySelector("#menu-save").addEventListener("click", e => {
  1712. saveScene();
  1713. });
  1714. document.querySelector("#menu-load").addEventListener("click", e => {
  1715. loadScene();
  1716. });
  1717. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1718. loadScene("autosave");
  1719. });
  1720. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1721. document.querySelector("#file-upload-picker").click();
  1722. });
  1723. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1724. if (e.target.files.length > 0) {
  1725. for (let i=0; i<e.target.files.length; i++) {
  1726. customEntityFromFile(e.target.files[i]);
  1727. }
  1728. }
  1729. })
  1730. document.addEventListener("paste", e => {
  1731. let index = 0;
  1732. let item = null;
  1733. let found = false;
  1734. for (; index < e.clipboardData.items.length; index++) {
  1735. item = e.clipboardData.items[index];
  1736. if (item.type == "image/png") {
  1737. found = true;
  1738. break;
  1739. }
  1740. }
  1741. if (!found) {
  1742. return;
  1743. }
  1744. console.log(item)
  1745. console.log(item.type)
  1746. let url = null;
  1747. const file = item.getAsFile();
  1748. customEntityFromFile(file);
  1749. });
  1750. document.querySelector("#world").addEventListener("dragover", e => {
  1751. e.preventDefault();
  1752. })
  1753. document.querySelector("#world").addEventListener("drop", e => {
  1754. e.preventDefault();
  1755. if (e.dataTransfer.files.length > 0) {
  1756. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1757. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1758. let coords = abs2rel({x: e.clientX-entX, y: e.clientY-entY});
  1759. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1760. }
  1761. })
  1762. clearEntityOptions();
  1763. clearViewOptions();
  1764. clearAttribution();
  1765. // we do this last because configuring settings can cause things
  1766. // to happen (e.g. auto-fit)
  1767. prepareSettings(getUserSettings());
  1768. });
  1769. function customEntityFromFile(file, x=0.5, y=0.5) {
  1770. file.arrayBuffer().then(buf => {
  1771. arr = new Uint8Array(buf);
  1772. blob = new Blob([arr], {type: file.type });
  1773. url = window.URL.createObjectURL(blob)
  1774. makeCustomEntity(url, x, y);
  1775. });
  1776. }
  1777. function makeCustomEntity(url, x=0.5, y=0.5) {
  1778. const maker = createEntityMaker(
  1779. {
  1780. name: "Custom Entity"
  1781. },
  1782. {
  1783. custom: {
  1784. attributes: {
  1785. height: {
  1786. name: "Height",
  1787. power: 1,
  1788. type: "length",
  1789. base: math.unit(6, "feet")
  1790. }
  1791. },
  1792. image: {
  1793. source: url
  1794. },
  1795. name: "Image",
  1796. info: {},
  1797. rename: false
  1798. }
  1799. },
  1800. []
  1801. );
  1802. const entity = maker.constructor();
  1803. entity.scale = config.height.toNumber("feet") / 20;
  1804. entity.ephemeral = true;
  1805. displayEntity(entity, "custom", x, y, true, true);
  1806. }
  1807. function prepareEntities() {
  1808. availableEntities["buildings"] = makeBuildings();
  1809. availableEntities["characters"] = makeCharacters();
  1810. availableEntities["cities"] = makeCities();
  1811. availableEntities["fiction"] = makeFiction();
  1812. availableEntities["food"] = makeFood();
  1813. availableEntities["landmarks"] = makeLandmarks();
  1814. availableEntities["naturals"] = makeNaturals();
  1815. availableEntities["objects"] = makeObjects();
  1816. availableEntities["pokemon"] = makePokemon();
  1817. availableEntities["species"] = makeSpecies();
  1818. availableEntities["vehicles"] = makeVehicles();
  1819. availableEntities["characters"].sort((x, y) => {
  1820. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1821. });
  1822. const holder = document.querySelector("#spawners");
  1823. const categorySelect = document.createElement("select");
  1824. categorySelect.id = "category-picker";
  1825. holder.appendChild(categorySelect);
  1826. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1827. const select = document.createElement("select");
  1828. select.id = "create-entity-" + category;
  1829. for (let i = 0; i < entityList.length; i++) {
  1830. const entity = entityList[i];
  1831. const option = document.createElement("option");
  1832. option.value = i;
  1833. option.innerText = entity.name;
  1834. select.appendChild(option);
  1835. if (entity.nsfw) {
  1836. option.classList.add("nsfw");
  1837. }
  1838. availableEntitiesByName[entity.name] = entity;
  1839. };
  1840. select.addEventListener("change", e => {
  1841. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  1842. select.classList.add("nsfw");
  1843. } else {
  1844. select.classList.remove("nsfw");
  1845. }
  1846. })
  1847. const button = document.createElement("button");
  1848. button.id = "create-entity-" + category + "-button";
  1849. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1850. button.addEventListener("click", e => {
  1851. const newEntity = entityList[select.value].constructor()
  1852. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1853. });
  1854. const categoryOption = document.createElement("option");
  1855. categoryOption.value = category
  1856. categoryOption.innerText = category;
  1857. if (category == "characters") {
  1858. categoryOption.selected = true;
  1859. select.classList.add("category-visible");
  1860. button.classList.add("category-visible");
  1861. }
  1862. categorySelect.appendChild(categoryOption);
  1863. holder.appendChild(select);
  1864. holder.appendChild(button);
  1865. });
  1866. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  1867. categorySelect.addEventListener("input", e => {
  1868. const oldSelect = document.querySelector("select.category-visible");
  1869. oldSelect.classList.remove("category-visible");
  1870. const oldButton = document.querySelector("button.category-visible");
  1871. oldButton.classList.remove("category-visible");
  1872. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1873. newSelect.classList.add("category-visible");
  1874. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1875. newButton.classList.add("category-visible");
  1876. });
  1877. }
  1878. document.addEventListener("mousemove", (e) => {
  1879. if (clicked) {
  1880. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1881. clicked.dataset.x = position.x;
  1882. clicked.dataset.y = position.y;
  1883. updateEntityElement(entities[clicked.dataset.key], clicked);
  1884. if (hoveringInDeleteArea(e)) {
  1885. document.querySelector("#menubar").classList.add("hover-delete");
  1886. } else {
  1887. document.querySelector("#menubar").classList.remove("hover-delete");
  1888. }
  1889. }
  1890. });
  1891. document.addEventListener("touchmove", (e) => {
  1892. if (clicked) {
  1893. e.preventDefault();
  1894. let x = e.touches[0].clientX;
  1895. let y = e.touches[0].clientY;
  1896. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1897. clicked.dataset.x = position.x;
  1898. clicked.dataset.y = position.y;
  1899. updateEntityElement(entities[clicked.dataset.key], clicked);
  1900. // what a hack
  1901. // I should centralize this 'fake event' creation...
  1902. if (hoveringInDeleteArea({ clientY: y })) {
  1903. document.querySelector("#menubar").classList.add("hover-delete");
  1904. } else {
  1905. document.querySelector("#menubar").classList.remove("hover-delete");
  1906. }
  1907. }
  1908. }, { passive: false });
  1909. function checkFitWorld() {
  1910. if (config.autoFit) {
  1911. fitWorld();
  1912. return true;
  1913. }
  1914. return false;
  1915. }
  1916. const fitModes = {
  1917. "max": {
  1918. start: 0,
  1919. binop: Math.max,
  1920. final: (total, count) => total
  1921. },
  1922. "arithmetic mean": {
  1923. start: 0,
  1924. binop: math.add,
  1925. final: (total, count) => total / count
  1926. },
  1927. "geometric mean": {
  1928. start: 1,
  1929. binop: math.multiply,
  1930. final: (total, count) => math.pow(total, 1 / count)
  1931. }
  1932. }
  1933. function fitWorld(manual = false, factor = 1.1) {
  1934. const fitMode = fitModes[config.autoFitMode]
  1935. let max = fitMode.start
  1936. let count = 0;
  1937. Object.entries(entities).forEach(([key, entity]) => {
  1938. const view = entity.view;
  1939. let extra = entity.views[view].image.extra;
  1940. extra = extra === undefined ? 1 : extra;
  1941. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1942. count += 1;
  1943. });
  1944. max = fitMode.final(max, count)
  1945. max = math.unit(max, "meter")
  1946. if (manual)
  1947. altHeld = true;
  1948. setWorldHeight(config.height, math.multiply(max, factor));
  1949. if (manual)
  1950. altHeld = false;
  1951. }
  1952. // TODO why am I doing this
  1953. function updateWorldHeight() {
  1954. const unit = document.querySelector("#options-height-unit").value;
  1955. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1956. const oldHeight = config.height;
  1957. setWorldHeight(oldHeight, math.unit(value, unit));
  1958. }
  1959. function setWorldHeight(oldHeight, newHeight) {
  1960. worldSizeDirty = true;
  1961. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1962. const unit = document.querySelector("#options-height-unit").value;
  1963. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1964. Object.entries(entities).forEach(([key, entity]) => {
  1965. const element = document.querySelector("#entity-" + key);
  1966. let newPosition;
  1967. if (!altHeld) {
  1968. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1969. } else {
  1970. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1971. }
  1972. element.dataset.x = newPosition.x;
  1973. element.dataset.y = newPosition.y;
  1974. });
  1975. updateSizes();
  1976. }
  1977. function loadScene(name = "default") {
  1978. try {
  1979. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  1980. if (data === null) {
  1981. return false;
  1982. }
  1983. importScene(data);
  1984. return true;
  1985. } catch (err) {
  1986. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1987. console.error(err);
  1988. return false;
  1989. }
  1990. }
  1991. function saveScene(name = "default") {
  1992. try {
  1993. const string = JSON.stringify(exportScene());
  1994. localStorage.setItem("macrovision-save-" + name, string);
  1995. } catch (err) {
  1996. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1997. console.error(err);
  1998. }
  1999. }
  2000. function deleteScene(name = "default") {
  2001. try {
  2002. localStorage.removeItem("macrovision-save-" + name)
  2003. } catch (err) {
  2004. console.error(err);
  2005. }
  2006. }
  2007. function exportScene() {
  2008. const results = {};
  2009. results.entities = [];
  2010. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  2011. const element = document.querySelector("#entity-" + key);
  2012. results.entities.push({
  2013. name: entity.identifier,
  2014. scale: entity.scale,
  2015. view: entity.view,
  2016. x: element.dataset.x,
  2017. y: element.dataset.y
  2018. });
  2019. });
  2020. const unit = document.querySelector("#options-height-unit").value;
  2021. results.world = {
  2022. height: config.height.toNumber(unit),
  2023. unit: unit
  2024. }
  2025. results.canvasWidth = canvasWidth;
  2026. return results;
  2027. }
  2028. // btoa doesn't like anything that isn't ASCII
  2029. // great
  2030. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  2031. // for providing an alternative
  2032. function b64EncodeUnicode(str) {
  2033. // first we use encodeURIComponent to get percent-encoded UTF-8,
  2034. // then we convert the percent encodings into raw bytes which
  2035. // can be fed into btoa.
  2036. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  2037. function toSolidBytes(match, p1) {
  2038. return String.fromCharCode('0x' + p1);
  2039. }));
  2040. }
  2041. function b64DecodeUnicode(str) {
  2042. // Going backwards: from bytestream, to percent-encoding, to original string.
  2043. return decodeURIComponent(atob(str).split('').map(function (c) {
  2044. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  2045. }).join(''));
  2046. }
  2047. function linkScene() {
  2048. loc = new URL(window.location);
  2049. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  2050. }
  2051. function copyScene() {
  2052. const results = exportScene();
  2053. navigator.clipboard.writeText(JSON.stringify(results));
  2054. }
  2055. function pasteScene() {
  2056. try {
  2057. navigator.clipboard.readText().then(text => {
  2058. const data = JSON.parse(text);
  2059. if (data.entities === undefined) {
  2060. return;
  2061. }
  2062. if (data.world === undefined) {
  2063. return;
  2064. }
  2065. importScene(data);
  2066. }).catch(err => alert(err));
  2067. } catch (err) {
  2068. console.error(err);
  2069. // probably wasn't valid data
  2070. }
  2071. }
  2072. // TODO - don't just search through every single entity
  2073. // probably just have a way to do lookups directly
  2074. function findEntity(name) {
  2075. return availableEntitiesByName[name];
  2076. }
  2077. function importScene(data) {
  2078. removeAllEntities();
  2079. data.entities.forEach(entityInfo => {
  2080. const entity = findEntity(entityInfo.name).constructor();
  2081. entity.scale = entityInfo.scale
  2082. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  2083. });
  2084. config.height = math.unit(data.world.height, data.world.unit);
  2085. document.querySelector("#options-height-unit").value = data.world.unit;
  2086. if (data.canvasWidth) {
  2087. doHorizReposition(data.canvasWidth / canvasWidth);
  2088. }
  2089. updateSizes();
  2090. }
  2091. function renderToCanvas() {
  2092. const ctx = document.querySelector("#display").getContext("2d");
  2093. Object.entries(entities).sort((ent1, ent2) => {
  2094. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  2095. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  2096. return z1 - z2;
  2097. }).forEach(([id, entity]) => {
  2098. element = document.querySelector("#entity-" + id);
  2099. img = element.querySelector("img");
  2100. let x = parseFloat(element.dataset.x);
  2101. let y = parseFloat(element.dataset.y);
  2102. let coords = rel2abs({x: x, y: y});
  2103. let offset = img.style.getPropertyValue("--offset");
  2104. offset = parseFloat(offset.substring(0, offset.length-1))
  2105. x = coords.x - img.getBoundingClientRect().width/2;
  2106. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  2107. let xSize = img.getBoundingClientRect().width;
  2108. let ySize = img.getBoundingClientRect().height;
  2109. ctx.drawImage(img, x, y, xSize, ySize);
  2110. });
  2111. }
  2112. function exportCanvas(callback) {
  2113. /** @type {CanvasRenderingContext2D} */
  2114. const ctx = document.querySelector("#display").getContext("2d");
  2115. const blob = ctx.canvas.toBlob(callback);
  2116. }
  2117. function generateScreenshot(callback) {
  2118. renderToCanvas();
  2119. /** @type {CanvasRenderingContext2D} */
  2120. const ctx = document.querySelector("#display").getContext("2d");
  2121. ctx.fillStyle = "#555";
  2122. ctx.font = "normal normal lighter 16pt coda";
  2123. ctx.fillText("macrovision.crux.sexy", 10, 25);
  2124. exportCanvas(blob => {
  2125. callback(blob);
  2126. });
  2127. }
  2128. function copyScreenshot() {
  2129. generateScreenshot(blob => {
  2130. navigator.clipboard.write([
  2131. new ClipboardItem({
  2132. "image/png": blob
  2133. })
  2134. ]);
  2135. });
  2136. drawScale(false);
  2137. }
  2138. function saveScreenshot() {
  2139. generateScreenshot(blob => {
  2140. const a = document.createElement("a");
  2141. a.href = URL.createObjectURL(blob);
  2142. a.setAttribute("download", "macrovision.png");
  2143. a.click();
  2144. });
  2145. drawScale(false);
  2146. }
  2147. const rateLimits = {};
  2148. function toast(msg) {
  2149. let div = document.createElement("div");
  2150. div.innerHTML = msg;
  2151. div.classList.add("toast");
  2152. document.body.appendChild(div);
  2153. setTimeout(() => {
  2154. document.body.removeChild(div);
  2155. }, 5000)
  2156. }
  2157. function toastRateLimit(msg, key, delay) {
  2158. if (!rateLimits[key]) {
  2159. toast(msg);
  2160. rateLimits[key] = setTimeout(() => {
  2161. delete rateLimits[key]
  2162. }, delay);
  2163. }
  2164. }