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

1922 строки
59 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 worldSizeDirty = false;
  19. math.createUnit("humans", {
  20. definition: "5.75 feet"
  21. })
  22. const unitChoices = {
  23. length: [
  24. "meters",
  25. "angstroms",
  26. "millimeters",
  27. "centimeters",
  28. "kilometers",
  29. "inches",
  30. "feet",
  31. "humans",
  32. "stories",
  33. "miles",
  34. "solarradii",
  35. "AUs",
  36. "lightyears",
  37. "parsecs",
  38. "galaxies",
  39. "universes"
  40. ],
  41. area: [
  42. "meters^2",
  43. "cm^2",
  44. "kilometers^2",
  45. "acres",
  46. "miles^2"
  47. ],
  48. mass: [
  49. "kilograms",
  50. "milligrams",
  51. "grams",
  52. "tonnes",
  53. "lbs",
  54. "ounces",
  55. "tons"
  56. ]
  57. }
  58. const config = {
  59. height: math.unit(1500, "meters"),
  60. minLineSize: 100,
  61. maxLineSize: 150,
  62. autoFit: false,
  63. autoFitMode: "max"
  64. }
  65. const availableEntities = {
  66. }
  67. const availableEntitiesByName = {
  68. }
  69. const entities = {
  70. }
  71. function constrainRel(coords) {
  72. if (altHeld) {
  73. return coords;
  74. }
  75. return {
  76. x: Math.min(Math.max(coords.x, 0), 1),
  77. y: Math.min(Math.max(coords.y, 0), 1)
  78. }
  79. }
  80. function snapRel(coords) {
  81. return constrainRel({
  82. x: coords.x,
  83. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  84. });
  85. }
  86. function adjustAbs(coords, oldHeight, newHeight) {
  87. const ratio = math.divide(oldHeight, newHeight);
  88. return { x: 0.5 + (coords.x - 0.5) * math.divide(oldHeight, newHeight), y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  89. }
  90. function rel2abs(coords) {
  91. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  92. }
  93. function abs2rel(coords) {
  94. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  95. }
  96. function updateEntityElement(entity, element) {
  97. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  98. const view = entity.view;
  99. element.style.left = position.x + "px";
  100. element.style.top = position.y + "px";
  101. element.style.setProperty("--xpos", position.x + "px");
  102. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({precision: 2}) + "'");
  103. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  104. const extra = entity.views[view].image.extra;
  105. const bottom = entity.views[view].image.bottom;
  106. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  107. element.style.setProperty("--height", pixels * bonus + "px");
  108. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  109. if (entity.views[view].rename)
  110. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  111. else
  112. element.querySelector(".entity-name").innerText = entity.name;
  113. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  114. bottomName.style.left = position.x + entityX + "px";
  115. bottomName.style.bottom = "0vh";
  116. bottomName.innerText = entity.name;
  117. const topName = document.querySelector("#top-name-" + element.dataset.key);
  118. topName.style.left = position.x + entityX + "px";
  119. topName.style.top = "20vh";
  120. topName.innerText = entity.name;
  121. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  122. topName.classList.add("top-name-needed");
  123. } else {
  124. topName.classList.remove("top-name-needed");
  125. }
  126. }
  127. function updateSizes(dirtyOnly = false) {
  128. drawScale(dirtyOnly);
  129. let ordered = Object.entries(entities);
  130. ordered.sort((e1, e2) => {
  131. if (e1[1].priority != e2[1].priority) {
  132. return e2[1].priority - e1[1].priority;
  133. } else {
  134. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  135. }
  136. });
  137. let zIndex = ordered.length;
  138. ordered.forEach(entity => {
  139. const element = document.querySelector("#entity-" + entity[0]);
  140. element.style.zIndex = zIndex;
  141. if (!dirtyOnly || entity[1].dirty) {
  142. updateEntityElement(entity[1], element, zIndex);
  143. entity[1].dirty = false;
  144. }
  145. zIndex -= 1;
  146. });
  147. }
  148. function drawScale(ifDirty=false) {
  149. if (ifDirty && !worldSizeDirty)
  150. return;
  151. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  152. let total = heightPer.clone();
  153. total.value = 0;
  154. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  155. drawTick(ctx, 50, y, total);
  156. total = math.add(total, heightPer);
  157. }
  158. }
  159. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  160. const oldStroke = ctx.strokeStyle;
  161. const oldFill = ctx.fillStyle;
  162. ctx.beginPath();
  163. ctx.moveTo(x, y);
  164. ctx.lineTo(x + 20, y);
  165. ctx.strokeStyle = "#000000";
  166. ctx.stroke();
  167. ctx.beginPath();
  168. ctx.moveTo(x + 20, y);
  169. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  170. ctx.strokeStyle = "#aaaaaa";
  171. ctx.stroke();
  172. ctx.beginPath();
  173. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  174. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  175. ctx.strokeStyle = "#000000";
  176. ctx.stroke();
  177. const oldFont = ctx.font;
  178. ctx.font = 'normal 24pt coda';
  179. ctx.fillStyle = "#dddddd";
  180. ctx.beginPath();
  181. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  182. ctx.font = oldFont;
  183. ctx.strokeStyle = oldStroke;
  184. ctx.fillStyle = oldFill;
  185. }
  186. const canvas = document.querySelector("#display");
  187. /** @type {CanvasRenderingContext2D} */
  188. const ctx = canvas.getContext("2d");
  189. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  190. heightPer = 1;
  191. if (pixelsPer < config.minLineSize) {
  192. const factor = math.ceil(config.minLineSize / pixelsPer);
  193. heightPer *= factor;
  194. pixelsPer *= factor;
  195. }
  196. if (pixelsPer > config.maxLineSize) {
  197. const factor = math.ceil(pixelsPer / config.maxLineSize);
  198. heightPer /= factor;
  199. pixelsPer /= factor;
  200. }
  201. heightPer = math.unit(heightPer, config.height.units[0].unit.name)
  202. ctx.clearRect(0, 0, canvas.width, canvas.height);
  203. ctx.scale(1, 1);
  204. ctx.canvas.width = canvas.clientWidth;
  205. ctx.canvas.height = canvas.clientHeight;
  206. ctx.beginPath();
  207. ctx.moveTo(50, 50);
  208. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  209. ctx.stroke();
  210. ctx.beginPath();
  211. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  212. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  213. ctx.stroke();
  214. drawTicks(ctx, pixelsPer, heightPer);
  215. }
  216. function makeEntity(info, views, sizes) {
  217. const entityTemplate = {
  218. name: info.name,
  219. identifier: info.name,
  220. scale: 1,
  221. info: info,
  222. views: views,
  223. sizes: sizes === undefined ? [] : sizes,
  224. init: function () {
  225. const entity = this;
  226. Object.entries(this.views).forEach(([viewKey, view]) => {
  227. view.parent = this;
  228. if (this.defaultView === undefined) {
  229. this.defaultView = viewKey;
  230. this.view = viewKey;
  231. }
  232. Object.entries(view.attributes).forEach(([key, val]) => {
  233. Object.defineProperty(
  234. view,
  235. key,
  236. {
  237. get: function () {
  238. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  239. },
  240. set: function (value) {
  241. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  242. this.parent.scale = newScale;
  243. }
  244. }
  245. )
  246. });
  247. });
  248. this.sizes.forEach(size => {
  249. if (size.default === true) {
  250. this.views[this.defaultView].height = size.height;
  251. this.size = size;
  252. }
  253. });
  254. if (this.size === undefined && this.sizes.length > 0) {
  255. this.views[this.defaultView].height = this.sizes[0].height;
  256. this.size = this.sizes[0];
  257. console.warn("No default size set for " + info.name);
  258. } else if (this.sizes.length == 0) {
  259. this.sizes = [
  260. {
  261. name: "Normal",
  262. height: this.views[this.defaultView].height
  263. }
  264. ];
  265. this.size = this.sizes[0];
  266. }
  267. this.desc = {};
  268. Object.entries(this.info).forEach(([key, value]) => {
  269. Object.defineProperty(
  270. this.desc,
  271. key,
  272. {
  273. get: function () {
  274. let text = value.text;
  275. if (entity.views[entity.view].info) {
  276. if (entity.views[entity.view].info[key]) {
  277. text = combineInfo(text, entity.views[entity.view].info[key]);
  278. }
  279. }
  280. if (entity.size.info) {
  281. if (entity.size.info[key]) {
  282. text = combineInfo(text, entity.size.info[key]);
  283. }
  284. }
  285. return { title: value.title, text: text };
  286. }
  287. }
  288. )
  289. });
  290. delete this.init;
  291. return this;
  292. }
  293. }.init();
  294. return entityTemplate;
  295. }
  296. function combineInfo(existing, next) {
  297. switch (next.mode) {
  298. case "replace":
  299. return next.text;
  300. case "prepend":
  301. return next.text + existing;
  302. case "append":
  303. return existing + next.text;
  304. }
  305. return existing;
  306. }
  307. function clickDown(target, x, y) {
  308. clicked = target;
  309. const rect = target.getBoundingClientRect();
  310. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  311. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  312. dragOffsetX = x - rect.left + entX;
  313. dragOffsetY = y - rect.top + entY;
  314. clickTimeout = setTimeout(() => { dragging = true }, 200)
  315. target.classList.add("no-transition");
  316. }
  317. // could we make this actually detect the menu area?
  318. function hoveringInDeleteArea(e) {
  319. return e.clientY < document.body.clientHeight / 10;
  320. }
  321. function clickUp(e) {
  322. clearTimeout(clickTimeout);
  323. if (clicked) {
  324. if (dragging) {
  325. dragging = false;
  326. if (hoveringInDeleteArea(e)) {
  327. removeEntity(clicked);
  328. document.querySelector("#menubar").classList.remove("hover-delete");
  329. }
  330. } else {
  331. select(clicked);
  332. }
  333. clicked.classList.remove("no-transition");
  334. clicked = null;
  335. }
  336. }
  337. function deselect() {
  338. if (selected) {
  339. selected.classList.remove("selected");
  340. }
  341. document.getElementById("options-selected-entity-none").selected = "selected";
  342. clearAttribution();
  343. selected = null;
  344. clearViewList();
  345. clearEntityOptions();
  346. clearViewOptions();
  347. document.querySelector("#delete-entity").disabled = true;
  348. }
  349. function select(target) {
  350. deselect();
  351. selected = target;
  352. selectedEntity = entities[target.dataset.key];
  353. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  354. selected.classList.add("selected");
  355. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  356. configViewList(selectedEntity, selectedEntity.view);
  357. configEntityOptions(selectedEntity, selectedEntity.view);
  358. configViewOptions(selectedEntity, selectedEntity.view);
  359. document.querySelector("#delete-entity").disabled = false;
  360. }
  361. function configViewList(entity, selectedView) {
  362. const list = document.querySelector("#entity-view");
  363. list.innerHTML = "";
  364. list.style.display = "block";
  365. Object.keys(entity.views).forEach(view => {
  366. const option = document.createElement("option");
  367. option.innerText = entity.views[view].name;
  368. option.value = view;
  369. if (view === selectedView) {
  370. option.selected = true;
  371. }
  372. list.appendChild(option);
  373. });
  374. }
  375. function clearViewList() {
  376. const list = document.querySelector("#entity-view");
  377. list.innerHTML = "";
  378. list.style.display = "none";
  379. }
  380. function updateWorldOptions(entity, view) {
  381. const heightInput = document.querySelector("#options-height-value");
  382. const heightSelect = document.querySelector("#options-height-unit");
  383. const converted = config.height.toNumber(heightSelect.value);
  384. setNumericInput(heightInput, converted);
  385. }
  386. function configEntityOptions(entity, view) {
  387. const holder = document.querySelector("#options-entity");
  388. document.querySelector("#entity-category-header").style.display = "block";
  389. document.querySelector("#entity-category").style.display = "block";
  390. holder.innerHTML = "";
  391. const scaleLabel = document.createElement("div");
  392. scaleLabel.classList.add("options-label");
  393. scaleLabel.innerText = "Scale";
  394. const scaleRow = document.createElement("div");
  395. scaleRow.classList.add("options-row");
  396. const scaleInput = document.createElement("input");
  397. scaleInput.classList.add("options-field-numeric");
  398. scaleInput.id = "options-entity-scale";
  399. scaleInput.addEventListener("change", e => {
  400. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  401. entity.dirty = true;
  402. if (config.autoFit) {
  403. fitWorld();
  404. } else {
  405. updateSizes(true);
  406. }
  407. updateEntityOptions(entity, view);
  408. updateViewOptions(entity, view);
  409. });
  410. scaleInput.addEventListener("keydown", e => {
  411. e.stopPropagation();
  412. })
  413. scaleInput.setAttribute("min", 1);
  414. scaleInput.setAttribute("type", "number");
  415. setNumericInput(scaleInput, entity.scale);
  416. scaleRow.appendChild(scaleInput);
  417. holder.appendChild(scaleLabel);
  418. holder.appendChild(scaleRow);
  419. const nameLabel = document.createElement("div");
  420. nameLabel.classList.add("options-label");
  421. nameLabel.innerText = "Name";
  422. const nameRow = document.createElement("div");
  423. nameRow.classList.add("options-row");
  424. const nameInput = document.createElement("input");
  425. nameInput.classList.add("options-field-text");
  426. nameInput.value = entity.name;
  427. nameInput.addEventListener("input", e => {
  428. entity.name = e.target.value;
  429. entity.dirty = true;
  430. updateSizes(true);
  431. })
  432. nameInput.addEventListener("keydown", e => {
  433. e.stopPropagation();
  434. })
  435. nameRow.appendChild(nameInput);
  436. holder.appendChild(nameLabel);
  437. holder.appendChild(nameRow);
  438. const defaultHolder = document.querySelector("#options-entity-defaults");
  439. defaultHolder.innerHTML = "";
  440. entity.sizes.forEach(defaultInfo => {
  441. const button = document.createElement("button");
  442. button.classList.add("options-button");
  443. button.innerText = defaultInfo.name;
  444. button.addEventListener("click", e => {
  445. entity.views[entity.defaultView].height = defaultInfo.height;
  446. entity.dirty = true;
  447. updateEntityOptions(entity, entity.view);
  448. updateViewOptions(entity, entity.view);
  449. if (!checkFitWorld()){
  450. updateSizes(true);
  451. }
  452. });
  453. defaultHolder.appendChild(button);
  454. });
  455. document.querySelector("#options-order-display").innerText = entity.priority;
  456. document.querySelector("#options-ordering").style.display = "flex";
  457. }
  458. function updateEntityOptions(entity, view) {
  459. const scaleInput = document.querySelector("#options-entity-scale");
  460. setNumericInput(scaleInput, entity.scale);
  461. document.querySelector("#options-order-display").innerText = entity.priority;
  462. }
  463. function clearEntityOptions() {
  464. document.querySelector("#entity-category-header").style.display = "none";
  465. document.querySelector("#entity-category").style.display = "none";
  466. /*
  467. const holder = document.querySelector("#options-entity");
  468. holder.innerHTML = "";
  469. document.querySelector("#options-entity-defaults").innerHTML = "";
  470. document.querySelector("#options-ordering").style.display = "none";
  471. document.querySelector("#options-ordering").style.display = "none";*/
  472. }
  473. function configViewOptions(entity, view) {
  474. const holder = document.querySelector("#options-view");
  475. document.querySelector("#view-category-header").style.display = "block";
  476. document.querySelector("#view-category").style.display = "block";
  477. holder.innerHTML = "";
  478. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  479. const label = document.createElement("div");
  480. label.classList.add("options-label");
  481. label.innerText = val.name;
  482. holder.appendChild(label);
  483. const row = document.createElement("div");
  484. row.classList.add("options-row");
  485. holder.appendChild(row);
  486. const input = document.createElement("input");
  487. input.classList.add("options-field-numeric");
  488. input.id = "options-view-" + key + "-input";
  489. input.setAttribute("type", "number");
  490. input.setAttribute("min", 1);
  491. setNumericInput(input, entity.views[view][key].value);
  492. const select = document.createElement("select");
  493. select.classList.add("options-field-unit");
  494. select.id = "options-view-" + key + "-select"
  495. unitChoices[val.type].forEach(name => {
  496. const option = document.createElement("option");
  497. option.innerText = name;
  498. select.appendChild(option);
  499. });
  500. input.addEventListener("change", e => {
  501. const value = input.value == 0 ? 1 : input.value;
  502. entity.views[view][key] = math.unit(value, select.value);
  503. entity.dirty = true;
  504. if (config.autoFit) {
  505. fitWorld();
  506. } else {
  507. updateSizes(true);
  508. }
  509. updateEntityOptions(entity, view);
  510. updateViewOptions(entity, view, key);
  511. });
  512. input.addEventListener("keydown", e => {
  513. e.stopPropagation();
  514. })
  515. select.setAttribute("oldUnit", select.value);
  516. // TODO does this ever cause a change in the world?
  517. select.addEventListener("input", e => {
  518. const value = input.value == 0 ? 1 : input.value;
  519. const oldUnit = select.getAttribute("oldUnit");
  520. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  521. entity.dirty = true;
  522. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  523. select.setAttribute("oldUnit", select.value);
  524. if (config.autoFit) {
  525. fitWorld();
  526. } else {
  527. updateSizes(true);
  528. }
  529. updateEntityOptions(entity, view);
  530. updateViewOptions(entity, view, key);
  531. });
  532. row.appendChild(input);
  533. row.appendChild(select);
  534. });
  535. }
  536. function updateViewOptions(entity, view, changed) {
  537. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  538. if (key != changed) {
  539. const input = document.querySelector("#options-view-" + key + "-input");
  540. const select = document.querySelector("#options-view-" + key + "-select");
  541. const currentUnit = select.value;
  542. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  543. setNumericInput(input, convertedAmount);
  544. }
  545. });
  546. }
  547. function setNumericInput(input, value, round=3) {
  548. input.value = math.round(value, round);
  549. }
  550. function getSortedEntities() {
  551. return Object.keys(entities).sort((a, b) => {
  552. const entA = entities[a];
  553. const entB = entities[b];
  554. const viewA = entA.view;
  555. const viewB = entB.view;
  556. const heightA = entA.views[viewA].height.to("meter").value;
  557. const heightB = entB.views[viewB].height.to("meter").value;
  558. return heightA - heightB;
  559. });
  560. }
  561. function clearViewOptions() {
  562. document.querySelector("#view-category-header").style.display = "none";
  563. document.querySelector("#view-category").style.display = "none";
  564. }
  565. // this is a crime against humanity, and also stolen from
  566. // stack overflow
  567. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  568. const testCanvas = document.createElement("canvas");
  569. testCanvas.id = "test-canvas";
  570. const testCtx = testCanvas.getContext("2d");
  571. function testClick(event) {
  572. // oh my god I can't believe I'm doing this
  573. const target = event.target;
  574. if (navigator.userAgent.indexOf("Firefox") != -1) {
  575. clickDown(target.parentElement, event.clientX, event.clientY);
  576. return;
  577. }
  578. // Get click coordinates
  579. let w = target.width;
  580. let h = target.height;
  581. let ratioW = 1, ratioH = 1;
  582. // Limit the size of the canvas so that very large images don't cause problems)
  583. if (w > 1000) {
  584. ratioW = w / 1000;
  585. w /= ratioW;
  586. h /= ratioW;
  587. }
  588. if (h > 1000) {
  589. ratioH = h / 1000;
  590. w /= ratioH;
  591. h /= ratioH;
  592. }
  593. const ratio = ratioW * ratioH;
  594. var x = event.clientX - target.getBoundingClientRect().x,
  595. y = event.clientY - target.getBoundingClientRect().y,
  596. alpha;
  597. testCtx.canvas.width = w;
  598. testCtx.canvas.height = h;
  599. // Draw image to canvas
  600. // and read Alpha channel value
  601. testCtx.drawImage(target, 0, 0, w, h);
  602. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  603. // If pixel is transparent,
  604. // retrieve the element underneath and trigger its click event
  605. if (alpha === 0) {
  606. const oldDisplay = target.style.display;
  607. target.style.display = "none";
  608. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  609. newTarget.dispatchEvent(new MouseEvent(event.type, {
  610. "clientX": event.clientX,
  611. "clientY": event.clientY
  612. }));
  613. target.style.display = oldDisplay;
  614. } else {
  615. clickDown(target.parentElement, event.clientX, event.clientY);
  616. }
  617. }
  618. function arrangeEntities(order) {
  619. let x = 0.1;
  620. order.forEach(key => {
  621. document.querySelector("#entity-" + key).dataset.x = x;
  622. x += 0.8 / (order.length - 1);
  623. });
  624. updateSizes();
  625. }
  626. function removeAllEntities() {
  627. Object.keys(entities).forEach(key => {
  628. removeEntity(document.querySelector("#entity-" + key));
  629. });
  630. }
  631. function clearAttribution() {
  632. document.querySelector("#attribution-category-header").style.display = "none";
  633. document.querySelector("#options-attribution").style.display = "none";
  634. }
  635. function displayAttribution(file) {
  636. document.querySelector("#attribution-category-header").style.display = "block";
  637. document.querySelector("#options-attribution").style.display = "inline";
  638. const authors = authorsOfFull(file);
  639. const owners = ownersOfFull(file);
  640. const source = sourceOf(file);
  641. const authorHolder = document.querySelector("#options-attribution-authors");
  642. const ownerHolder = document.querySelector("#options-attribution-owners");
  643. const sourceHolder = document.querySelector("#options-attribution-source");
  644. if (authors === []) {
  645. const div = document.createElement("div");
  646. div.innerText = "Unknown";
  647. authorHolder.innerHTML = "";
  648. authorHolder.appendChild(div);
  649. } else if (authors === undefined) {
  650. const div = document.createElement("div");
  651. div.innerText = "Not yet entered";
  652. authorHolder.innerHTML = "";
  653. authorHolder.appendChild(div);
  654. } else {
  655. authorHolder.innerHTML = "";
  656. const list = document.createElement("ul");
  657. authorHolder.appendChild(list);
  658. authors.forEach(author => {
  659. const authorEntry = document.createElement("li");
  660. if (author.url) {
  661. const link = document.createElement("a");
  662. link.href = author.url;
  663. link.innerText = author.name;
  664. authorEntry.appendChild(link);
  665. } else {
  666. const div = document.createElement("div");
  667. div.innerText = author.name;
  668. authorEntry.appendChild(div);
  669. }
  670. list.appendChild(authorEntry);
  671. });
  672. }
  673. if (owners === []) {
  674. const div = document.createElement("div");
  675. div.innerText = "Unknown";
  676. ownerHolder.innerHTML = "";
  677. ownerHolder.appendChild(div);
  678. } else if (owners === undefined) {
  679. const div = document.createElement("div");
  680. div.innerText = "Not yet entered";
  681. ownerHolder.innerHTML = "";
  682. ownerHolder.appendChild(div);
  683. } else {
  684. ownerHolder.innerHTML = "";
  685. const list = document.createElement("ul");
  686. ownerHolder.appendChild(list);
  687. owners.forEach(owner => {
  688. const ownerEntry = document.createElement("li");
  689. if (owner.url) {
  690. const link = document.createElement("a");
  691. link.href = owner.url;
  692. link.innerText = owner.name;
  693. ownerEntry.appendChild(link);
  694. } else {
  695. const div = document.createElement("div");
  696. div.innerText = owner.name;
  697. ownerEntry.appendChild(div);
  698. }
  699. list.appendChild(ownerEntry);
  700. });
  701. }
  702. if (source === null) {
  703. const div = document.createElement("div");
  704. div.innerText = "No link";
  705. sourceHolder.innerHTML = "";
  706. sourceHolder.appendChild(div);
  707. } else if (source === undefined) {
  708. const div = document.createElement("div");
  709. div.innerText = "Not yet entered";
  710. sourceHolder.innerHTML = "";
  711. sourceHolder.appendChild(div);
  712. } else {
  713. sourceHolder.innerHTML = "";
  714. const link = document.createElement("a");
  715. link.style.display = "block";
  716. link.href = source;
  717. link.innerText = new URL(source).host;
  718. sourceHolder.appendChild(link);
  719. }
  720. }
  721. function removeEntity(element) {
  722. if (selected == element) {
  723. deselect();
  724. }
  725. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  726. option.parentElement.removeChild(option);
  727. delete entities[element.dataset.key];
  728. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  729. bottomName.parentElement.removeChild(bottomName);
  730. element.parentElement.removeChild(element);
  731. }
  732. function checkEntity(entity) {
  733. Object.values(entity.views).forEach(view => {
  734. if (authorsOf(view.image.source) === undefined) {
  735. console.warn("No authors: " + view.image.source);
  736. }
  737. });
  738. }
  739. function displayEntity(entity, view, x, y, selectEntity=false, refresh=false) {
  740. checkEntity(entity);
  741. const box = document.createElement("div");
  742. box.classList.add("entity-box");
  743. const img = document.createElement("img");
  744. img.classList.add("entity-image");
  745. img.addEventListener("dragstart", e => {
  746. e.preventDefault();
  747. });
  748. const nameTag = document.createElement("div");
  749. nameTag.classList.add("entity-name");
  750. nameTag.innerText = entity.name;
  751. box.appendChild(img);
  752. box.appendChild(nameTag);
  753. const image = entity.views[view].image;
  754. img.src = image.source;
  755. displayAttribution(image.source);
  756. if (image.bottom !== undefined) {
  757. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  758. } else {
  759. img.style.setProperty("--offset", ((-1) * 100) + "%")
  760. }
  761. box.dataset.x = x;
  762. box.dataset.y = y;
  763. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  764. img.addEventListener("touchstart", e => {
  765. const fakeEvent = {
  766. target: e.target,
  767. clientX: e.touches[0].clientX,
  768. clientY: e.touches[0].clientY
  769. };
  770. testClick(fakeEvent);
  771. });
  772. const heightBar = document.createElement("div");
  773. heightBar.classList.add("height-bar");
  774. box.appendChild(heightBar);
  775. box.id = "entity-" + entityIndex;
  776. box.dataset.key = entityIndex;
  777. entity.view = view;
  778. entity.priority = 0;
  779. entities[entityIndex] = entity;
  780. entity.index = entityIndex;
  781. const world = document.querySelector("#entities");
  782. world.appendChild(box);
  783. const bottomName = document.createElement("div");
  784. bottomName.classList.add("bottom-name");
  785. bottomName.id = "bottom-name-" + entityIndex;
  786. bottomName.innerText = entity.name;
  787. bottomName.addEventListener("click", () => select(box));
  788. world.appendChild(bottomName);
  789. const topName = document.createElement("div");
  790. topName.classList.add("top-name");
  791. topName.id = "top-name-" + entityIndex;
  792. topName.innerText = entity.name;
  793. topName.addEventListener("click", () => select(box));
  794. world.appendChild(topName);
  795. const entityOption = document.createElement("option");
  796. entityOption.id = "options-selected-entity-" + entityIndex;
  797. entityOption.value = entityIndex;
  798. entityOption.innerText = entity.name;
  799. document.getElementById("options-selected-entity").appendChild(entityOption);
  800. entityIndex += 1;
  801. if (config.autoFit) {
  802. fitWorld();
  803. }
  804. if (selectEntity)
  805. select(box);
  806. entity.dirty = true;
  807. if (refresh)
  808. updateSizes(true);
  809. }
  810. window.onblur = function () {
  811. altHeld = false;
  812. shiftHeld = false;
  813. }
  814. window.onfocus = function () {
  815. window.dispatchEvent(new Event("keydown"));
  816. }
  817. function doSliderScale() {
  818. if (sliderScale == 1) {
  819. clearInterval(dragScaleHandle);
  820. }
  821. setWorldHeight(config.height, math.multiply(config.height, (9 + sliderScale) / 10));
  822. }
  823. function doSliderEntityScale() {
  824. if (sliderEntityScale == 1) {
  825. clearInterval(dragEntityScaleHandle);
  826. }
  827. if (selected) {
  828. const entity = entities[selected.dataset.key];
  829. entity.scale *= (9 + sliderEntityScale) / 10;
  830. entity.dirty = true;
  831. updateSizes(true);
  832. updateEntityOptions(entity, entity.view);
  833. updateViewOptions(entity, entity.view);
  834. }
  835. }
  836. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  837. function toggleFullScreen() {
  838. var doc = window.document;
  839. var docEl = doc.documentElement;
  840. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  841. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  842. if(!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  843. requestFullScreen.call(docEl);
  844. }
  845. else {
  846. cancelFullScreen.call(doc);
  847. }
  848. }
  849. function handleResize() {
  850. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  851. canvasWidth = document.querySelector("#display").clientWidth - 100;
  852. canvasHeight = document.querySelector("#display").clientHeight - 50;
  853. updateSizes();
  854. }
  855. function prepareMenu() {
  856. const menubar = document.querySelector("#menubar");
  857. const help = document.querySelector("#help-icons");
  858. const spawners = document.querySelector("#spawners");
  859. [
  860. [
  861. {
  862. name: "Show/hide sidebar",
  863. id: "menu-toggle-sidebar",
  864. icon: "fas fa-chevron-circle-down",
  865. rotates: true
  866. },
  867. {
  868. name: "Fullscreen",
  869. id: "menu-fullscreen",
  870. icon: "fas fa-compress"
  871. }
  872. ],
  873. [
  874. {
  875. name: "Clear",
  876. id: "menu-clear",
  877. icon: "fas fa-file"
  878. }
  879. ],
  880. [
  881. {
  882. name: "Sort by height",
  883. id: "menu-order-height",
  884. icon: "fas fa-sort-numeric-up"
  885. }
  886. ],
  887. [
  888. {
  889. name: "Permalink",
  890. id: "menu-permalink",
  891. icon: "fas fa-link"
  892. },
  893. {
  894. name: "Export",
  895. id: "menu-export",
  896. icon: "fas fa-share"
  897. },
  898. {
  899. name: "Save",
  900. id: "menu-save",
  901. icon: "fas fa-download"
  902. },
  903. {
  904. name: "Load",
  905. id: "menu-load",
  906. icon: "fas fa-upload"
  907. },
  908. {
  909. name: "Load Autosave",
  910. id: "menu-load-autosave",
  911. icon: "fas fa-redo"
  912. }
  913. ]
  914. ].forEach(group => {
  915. const span = document.createElement("span");
  916. span.classList.add("menubar-group");
  917. group.forEach(entry => {
  918. const button = document.createElement("button");
  919. button.id = entry.id;
  920. const icon = document.createElement("i");
  921. icon.classList.add(...entry.icon.split(" "));
  922. if (entry.rotates) {
  923. icon.classList.add("rotate-backward", "transitions");
  924. }
  925. const srText = document.createElement("span");
  926. srText.classList.add("sr-only");
  927. srText.innerText = entry.name;
  928. button.appendChild(icon);
  929. button.appendChild(srText);
  930. span.appendChild(button);
  931. const helperEntry = document.createElement("div");
  932. const helperIcon = document.createElement("icon");
  933. const helperText = document.createElement("span");
  934. helperIcon.classList.add(...entry.icon.split(" "));
  935. helperText.innerText = entry.name;
  936. helperEntry.appendChild(helperIcon);
  937. helperEntry.appendChild(helperText);
  938. help.appendChild(helperEntry);
  939. });
  940. menubar.insertBefore(span, spawners);
  941. });
  942. if (checkHelpDate()) {
  943. document.querySelector("#open-help").classList.add("highlighted");
  944. }
  945. }
  946. const lastHelpChange = 1585487259753;
  947. function checkHelpDate() {
  948. try {
  949. const old = localStorage.getItem("help-viewed");
  950. if (old === null || old < lastHelpChange) {
  951. return true;
  952. }
  953. return false;
  954. } catch {
  955. console.warn("Could not set the help-viewed date");
  956. return false;
  957. }
  958. }
  959. function setHelpDate() {
  960. try {
  961. localStorage.setItem("help-viewed", Date.now());
  962. } catch {
  963. console.warn("Could not set the help-viewed date");
  964. }
  965. }
  966. document.addEventListener("DOMContentLoaded", () => {
  967. prepareMenu();
  968. prepareEntities();
  969. window.addEventListener("unload", () => saveScene("autosave"));
  970. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  971. if (e.target.value == "none") {
  972. deselect()
  973. } else {
  974. select(document.querySelector("#entity-" + e.target.value));
  975. }
  976. });
  977. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  978. const sidebar = document.querySelector("#options");
  979. if (sidebar.classList.contains("hidden")) {
  980. sidebar.classList.remove("hidden");
  981. e.target.classList.remove("rotate-forward");
  982. e.target.classList.add("rotate-backward");
  983. } else {
  984. sidebar.classList.add("hidden");
  985. e.target.classList.add("rotate-forward");
  986. e.target.classList.remove("rotate-backward");
  987. }
  988. handleResize();
  989. });
  990. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  991. document.querySelector("#options-show-extra").addEventListener("input", e => {
  992. document.body.classList[e.target.checked ? "add" : "remove"]("show-extra-options");
  993. });
  994. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  995. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  996. });
  997. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  998. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  999. });
  1000. document.querySelector("#options-world-show-top-names").addEventListener("input", e => {
  1001. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-top-name");
  1002. });
  1003. document.querySelector("#options-world-show-height-bars").addEventListener("input", e => {
  1004. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-height-bars");
  1005. });
  1006. document.querySelector("#options-world-show-entity-glow").addEventListener("input", e => {
  1007. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-glow");
  1008. });
  1009. document.querySelector("#options-world-show-scale-sliders").addEventListener("input", e => {
  1010. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale-sliders");
  1011. });
  1012. document.querySelector("#options-world-show-bottom-cover").addEventListener("input", e => {
  1013. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  1014. });
  1015. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  1016. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  1017. });
  1018. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1019. if (selected) {
  1020. entities[selected.dataset.key].priority += 1;
  1021. }
  1022. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1023. updateSizes();
  1024. });
  1025. document.querySelector("#options-order-back").addEventListener("click", e => {
  1026. if (selected) {
  1027. entities[selected.dataset.key].priority -= 1;
  1028. }
  1029. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1030. updateSizes();
  1031. });
  1032. document.querySelector("#slider-scale").addEventListener("mousedown", e => {
  1033. clearInterval(dragScaleHandle);
  1034. dragScaleHandle = setInterval(doSliderScale, 50);
  1035. e.stopPropagation();
  1036. });
  1037. document.querySelector("#slider-scale").addEventListener("touchstart", e => {
  1038. clearInterval(dragScaleHandle);
  1039. dragScaleHandle = setInterval(doSliderScale, 50);
  1040. e.stopPropagation();
  1041. });
  1042. document.querySelector("#slider-scale").addEventListener("input", e => {
  1043. const val = Number(e.target.value);
  1044. if (val < 1) {
  1045. sliderScale = (val + 1) / 2;
  1046. } else {
  1047. sliderScale = val;
  1048. }
  1049. });
  1050. document.querySelector("#slider-scale").addEventListener("change", e => {
  1051. clearInterval(dragScaleHandle);
  1052. dragScaleHandle = null;
  1053. e.target.value = 1;
  1054. });
  1055. document.querySelector("#slider-entity-scale").addEventListener("mousedown", e => {
  1056. clearInterval(dragEntityScaleHandle);
  1057. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  1058. e.stopPropagation();
  1059. });
  1060. document.querySelector("#slider-entity-scale").addEventListener("touchstart", e => {
  1061. clearInterval(dragEntityScaleHandle);
  1062. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  1063. e.stopPropagation();
  1064. });
  1065. document.querySelector("#slider-entity-scale").addEventListener("input", e => {
  1066. const val = Number(e.target.value);
  1067. if (val < 1) {
  1068. sliderEntityScale = (val + 1) / 2;
  1069. } else {
  1070. sliderEntityScale = val;
  1071. }
  1072. });
  1073. document.querySelector("#slider-entity-scale").addEventListener("change", e => {
  1074. clearInterval(dragEntityScaleHandle);
  1075. dragEntityScaleHandle = null;
  1076. e.target.value = 1;
  1077. });
  1078. const sceneChoices = document.querySelector("#scene-choices");
  1079. Object.entries(scenes).forEach(([id, scene]) => {
  1080. const option = document.createElement("option");
  1081. option.innerText = id;
  1082. option.value = id;
  1083. sceneChoices.appendChild(option);
  1084. });
  1085. document.querySelector("#load-scene").addEventListener("click", e => {
  1086. const chosen = sceneChoices.value;
  1087. removeAllEntities();
  1088. scenes[chosen]();
  1089. });
  1090. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1091. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1092. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1093. document.querySelector("#open-help").addEventListener("click", e => {
  1094. setHelpDate();
  1095. document.querySelector("#open-help").classList.remove("highlighted");
  1096. document.querySelector("#help").classList.add("visible");
  1097. });
  1098. document.querySelector("#close-help").addEventListener("click", e => {
  1099. document.querySelector("#help").classList.remove("visible");
  1100. });
  1101. const unitSelector = document.querySelector("#options-height-unit");
  1102. unitChoices.length.forEach(lengthOption => {
  1103. const option = document.createElement("option");
  1104. option.innerText = lengthOption;
  1105. option.value = lengthOption;
  1106. if (lengthOption === "meters") {
  1107. option.selected = true;
  1108. }
  1109. unitSelector.appendChild(option);
  1110. });
  1111. param = new URL(window.location.href).searchParams.get("scene");
  1112. if (param === null) {
  1113. scenes["Default"]();
  1114. }
  1115. else {
  1116. try {
  1117. const data = JSON.parse(b64DecodeUnicode(param));
  1118. if (data.entities === undefined) {
  1119. return;
  1120. }
  1121. if (data.world === undefined) {
  1122. return;
  1123. }
  1124. importScene(data);
  1125. } catch (err) {
  1126. console.error(err);
  1127. scenes["Default"]();
  1128. // probably wasn't valid data
  1129. }
  1130. }
  1131. document.querySelector("#world").addEventListener("wheel", e => {
  1132. if (shiftHeld) {
  1133. if (selected) {
  1134. const dir = e.deltaY > 0 ? 10/11 : 11/10;
  1135. const entity = entities[selected.dataset.key];
  1136. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1137. entity.dirty = true;
  1138. updateEntityOptions(entity, entity.view);
  1139. updateViewOptions(entity, entity.view);
  1140. updateSizes(true);
  1141. } else {
  1142. document.querySelectorAll(".entity-box").forEach(element => {
  1143. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1144. });
  1145. updateSizes();
  1146. }
  1147. } else {
  1148. const dir = e.deltaY < 0 ? 10/11 : 11/10;
  1149. setWorldHeight(config.height, math.multiply(config.height, dir));
  1150. updateWorldOptions();
  1151. }
  1152. checkFitWorld();
  1153. })
  1154. document.querySelector("body").appendChild(testCtx.canvas);
  1155. updateSizes();
  1156. document.querySelector("#options-height-value").addEventListener("change", e => {
  1157. updateWorldHeight();
  1158. })
  1159. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1160. e.stopPropagation();
  1161. })
  1162. unitSelector.addEventListener("input", e => {
  1163. checkFitWorld();
  1164. updateWorldHeight();
  1165. })
  1166. world.addEventListener("mousedown", e => deselect());
  1167. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1168. document.querySelector("#display").addEventListener("mousedown", deselect);
  1169. document.addEventListener("mouseup", e => clickUp(e));
  1170. document.addEventListener("touchend", e => {
  1171. const fakeEvent = {
  1172. target: e.target,
  1173. clientX: e.changedTouches[0].clientX,
  1174. clientY: e.changedTouches[0].clientY
  1175. };
  1176. clickUp(fakeEvent);
  1177. });
  1178. document.querySelector("#entity-view").addEventListener("input", e => {
  1179. const entity = entities[selected.dataset.key];
  1180. entity.view = e.target.value;
  1181. const image = entities[selected.dataset.key].views[e.target.value].image;
  1182. selected.querySelector(".entity-image").src = image.source;
  1183. displayAttribution(image.source);
  1184. if (image.bottom !== undefined) {
  1185. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1186. } else {
  1187. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1188. }
  1189. updateSizes();
  1190. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1191. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1192. });
  1193. clearViewList();
  1194. document.querySelector("#menu-clear").addEventListener("click", e => {
  1195. removeAllEntities();
  1196. });
  1197. document.querySelector("#delete-entity").disabled = true;
  1198. document.querySelector("#delete-entity").addEventListener("click", e => {
  1199. if (selected) {
  1200. removeEntity(selected);
  1201. selected = null;
  1202. }
  1203. });
  1204. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1205. const order = Object.keys(entities).sort((a, b) => {
  1206. const entA = entities[a];
  1207. const entB = entities[b];
  1208. const viewA = entA.view;
  1209. const viewB = entB.view;
  1210. const heightA = entA.views[viewA].height.to("meter").value;
  1211. const heightB = entB.views[viewB].height.to("meter").value;
  1212. return heightA - heightB;
  1213. });
  1214. arrangeEntities(order);
  1215. });
  1216. document.querySelector("#options-world-scroll-left").addEventListener("click", () => {
  1217. document.querySelectorAll(".entity-box").forEach(element => {
  1218. element.dataset.x = parseFloat(element.dataset.x) + 0.1;
  1219. });
  1220. updateSizes();
  1221. });
  1222. document.querySelector("#options-world-scroll-right").addEventListener("click", () => {
  1223. document.querySelectorAll(".entity-box").forEach(element => {
  1224. element.dataset.x = parseFloat(element.dataset.x) - 0.1;
  1225. });
  1226. updateSizes();
  1227. });
  1228. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1229. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1230. config.autoFit = e.target.checked;
  1231. if (config.autoFit) {
  1232. fitWorld();
  1233. }
  1234. });
  1235. document.addEventListener("keydown", e => {
  1236. if (e.key == "Delete") {
  1237. if (selected) {
  1238. removeEntity(selected);
  1239. selected = null;
  1240. }
  1241. }
  1242. })
  1243. document.addEventListener("keydown", e => {
  1244. if (e.key == "Shift") {
  1245. shiftHeld = true;
  1246. e.preventDefault();
  1247. } else if (e.key == "Alt") {
  1248. altHeld = true;
  1249. e.preventDefault();
  1250. }
  1251. });
  1252. document.addEventListener("keyup", e => {
  1253. if (e.key == "Shift") {
  1254. shiftHeld = false;
  1255. e.preventDefault();
  1256. } else if (e.key == "Alt") {
  1257. altHeld = false;
  1258. e.preventDefault();
  1259. }
  1260. });
  1261. document.addEventListener("paste", e => {
  1262. try {
  1263. const data = JSON.parse(e.clipboardData.getData("text"));
  1264. if (data.entities === undefined) {
  1265. return;
  1266. }
  1267. if (data.world === undefined) {
  1268. return;
  1269. }
  1270. importScene(data);
  1271. } catch (err) {
  1272. console.error(err);
  1273. // probably wasn't valid data
  1274. }
  1275. });
  1276. window.addEventListener("resize", handleResize);
  1277. // TODO: further investigate why the tool initially starts out with wrong
  1278. // values under certain circumstances (seems to be narrow aspect ratios -
  1279. // maybe the menu bar is animating when it shouldn't)
  1280. setTimeout(handleResize, 250);
  1281. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1282. linkScene();
  1283. });
  1284. document.querySelector("#menu-export").addEventListener("click", e => {
  1285. copyScene();
  1286. });
  1287. document.querySelector("#menu-save").addEventListener("click", e => {
  1288. saveScene();
  1289. });
  1290. document.querySelector("#menu-load").addEventListener("click", e => {
  1291. loadScene();
  1292. });
  1293. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1294. loadScene("autosave");
  1295. });
  1296. clearEntityOptions();
  1297. clearViewOptions();
  1298. clearAttribution();
  1299. });
  1300. function prepareEntities() {
  1301. availableEntities["buildings"] = makeBuildings();
  1302. availableEntities["landmarks"] = makeLandmarks();
  1303. availableEntities["characters"] = makeCharacters();
  1304. availableEntities["species"] = makeSpecies();
  1305. availableEntities["objects"] = makeObjects();
  1306. availableEntities["fiction"] = makeFiction();
  1307. availableEntities["food"] = makeFood();
  1308. availableEntities["naturals"] = makeNaturals();
  1309. availableEntities["vehicles"] = makeVehicles();
  1310. availableEntities["cities"] = makeCities();
  1311. availableEntities["pokemon"] = makePokemon();
  1312. availableEntities["characters"].sort((x, y) => {
  1313. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1314. });
  1315. const holder = document.querySelector("#spawners");
  1316. const categorySelect = document.createElement("select");
  1317. categorySelect.id = "category-picker";
  1318. holder.appendChild(categorySelect);
  1319. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1320. const select = document.createElement("select");
  1321. select.id = "create-entity-" + category;
  1322. for (let i = 0; i < entityList.length; i++) {
  1323. const entity = entityList[i];
  1324. const option = document.createElement("option");
  1325. option.value = i;
  1326. option.innerText = entity.name;
  1327. select.appendChild(option);
  1328. availableEntitiesByName[entity.name] = entity;
  1329. };
  1330. const button = document.createElement("button");
  1331. button.id = "create-entity-" + category + "-button";
  1332. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1333. button.addEventListener("click", e => {
  1334. const newEntity = entityList[select.value].constructor()
  1335. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1336. });
  1337. const categoryOption = document.createElement("option");
  1338. categoryOption.value = category
  1339. categoryOption.innerText = category;
  1340. if (category == "characters") {
  1341. categoryOption.selected = true;
  1342. select.classList.add("category-visible");
  1343. button.classList.add("category-visible");
  1344. }
  1345. categorySelect.appendChild(categoryOption);
  1346. holder.appendChild(select);
  1347. holder.appendChild(button);
  1348. });
  1349. categorySelect.addEventListener("input", e => {
  1350. const oldSelect = document.querySelector("select.category-visible");
  1351. oldSelect.classList.remove("category-visible");
  1352. const oldButton = document.querySelector("button.category-visible");
  1353. oldButton.classList.remove("category-visible");
  1354. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1355. newSelect.classList.add("category-visible");
  1356. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1357. newButton.classList.add("category-visible");
  1358. });
  1359. }
  1360. document.addEventListener("mousemove", (e) => {
  1361. if (clicked) {
  1362. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1363. clicked.dataset.x = position.x;
  1364. clicked.dataset.y = position.y;
  1365. updateEntityElement(entities[clicked.dataset.key], clicked);
  1366. if (hoveringInDeleteArea(e)) {
  1367. document.querySelector("#menubar").classList.add("hover-delete");
  1368. } else {
  1369. document.querySelector("#menubar").classList.remove("hover-delete");
  1370. }
  1371. }
  1372. });
  1373. document.addEventListener("touchmove", (e) => {
  1374. if (clicked) {
  1375. e.preventDefault();
  1376. let x = e.touches[0].clientX;
  1377. let y = e.touches[0].clientY;
  1378. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1379. clicked.dataset.x = position.x;
  1380. clicked.dataset.y = position.y;
  1381. updateEntityElement(entities[clicked.dataset.key], clicked);
  1382. // what a hack
  1383. // I should centralize this 'fake event' creation...
  1384. if (hoveringInDeleteArea({ clientY: y })) {
  1385. document.querySelector("#menubar").classList.add("hover-delete");
  1386. } else {
  1387. document.querySelector("#menubar").classList.remove("hover-delete");
  1388. }
  1389. }
  1390. }, { passive: false });
  1391. function checkFitWorld() {
  1392. if (config.autoFit) {
  1393. fitWorld();
  1394. return true;
  1395. }
  1396. return false;
  1397. }
  1398. const fitModes = {
  1399. "max": {
  1400. start: 0,
  1401. binop: Math.max,
  1402. final: (total, count) => total
  1403. },
  1404. "arithmetic mean": {
  1405. start: 0,
  1406. binop: math.add,
  1407. final: (total, count) => total / count
  1408. },
  1409. "geometric mean": {
  1410. start: 1,
  1411. binop: math.multiply,
  1412. final: (total, count) => math.pow(total, 1 / count)
  1413. }
  1414. }
  1415. function fitWorld(manual=false, factor=1.1) {
  1416. const fitMode = fitModes[config.autoFitMode]
  1417. let max = fitMode.start
  1418. let count = 0;
  1419. Object.entries(entities).forEach(([key, entity]) => {
  1420. const view = entity.view;
  1421. let extra = entity.views[view].image.extra;
  1422. extra = extra === undefined ? 1 : extra;
  1423. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1424. count += 1;
  1425. });
  1426. max = fitMode.final(max, count)
  1427. max = math.unit(max, "meter")
  1428. if (manual)
  1429. altHeld = true;
  1430. setWorldHeight(config.height, math.multiply(max, factor));
  1431. if (manual)
  1432. altHeld = false;
  1433. }
  1434. function updateWorldHeight() {
  1435. const unit = document.querySelector("#options-height-unit").value;
  1436. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1437. const oldHeight = config.height;
  1438. setWorldHeight(oldHeight, math.unit(value, unit));
  1439. }
  1440. function setWorldHeight(oldHeight, newHeight) {
  1441. worldSizeDirty = true;
  1442. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1443. const unit = document.querySelector("#options-height-unit").value;
  1444. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1445. Object.entries(entities).forEach(([key, entity]) => {
  1446. const element = document.querySelector("#entity-" + key);
  1447. let newPosition;
  1448. if (!altHeld) {
  1449. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1450. } else {
  1451. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1452. }
  1453. element.dataset.x = newPosition.x;
  1454. element.dataset.y = newPosition.y;
  1455. });
  1456. updateSizes();
  1457. }
  1458. function loadScene(name="default") {
  1459. try {
  1460. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  1461. if (data === null) {
  1462. return false;
  1463. }
  1464. importScene(data);
  1465. return true;
  1466. } catch (err) {
  1467. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1468. console.error(err);
  1469. return false;
  1470. }
  1471. }
  1472. function saveScene(name="default") {
  1473. try {
  1474. const string = JSON.stringify(exportScene());
  1475. localStorage.setItem("macrovision-save-" + name, string);
  1476. } catch (err) {
  1477. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1478. console.error(err);
  1479. }
  1480. }
  1481. function deleteScene(name="default") {
  1482. try {
  1483. localStorage.removeItem("macrovision-save-" + name)
  1484. } catch(err) {
  1485. console.error(err);
  1486. }
  1487. }
  1488. function exportScene() {
  1489. const results = {};
  1490. results.entities = [];
  1491. Object.entries(entities).forEach(([key, entity]) => {
  1492. const element = document.querySelector("#entity-" + key);
  1493. results.entities.push({
  1494. name: entity.identifier,
  1495. scale: entity.scale,
  1496. view: entity.view,
  1497. x: element.dataset.x,
  1498. y: element.dataset.y
  1499. });
  1500. });
  1501. const unit = document.querySelector("#options-height-unit").value;
  1502. results.world = {
  1503. height: config.height.toNumber(unit),
  1504. unit: unit
  1505. }
  1506. return results;
  1507. }
  1508. // btoa doesn't like anything that isn't ASCII
  1509. // great
  1510. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1511. // for providing an alternative
  1512. function b64EncodeUnicode(str) {
  1513. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1514. // then we convert the percent encodings into raw bytes which
  1515. // can be fed into btoa.
  1516. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1517. function toSolidBytes(match, p1) {
  1518. return String.fromCharCode('0x' + p1);
  1519. }));
  1520. }
  1521. function b64DecodeUnicode(str) {
  1522. // Going backwards: from bytestream, to percent-encoding, to original string.
  1523. return decodeURIComponent(atob(str).split('').map(function(c) {
  1524. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1525. }).join(''));
  1526. }
  1527. function linkScene() {
  1528. loc = new URL(window.location);
  1529. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1530. }
  1531. function copyScene() {
  1532. const results = exportScene();
  1533. navigator.clipboard.writeText(JSON.stringify(results))
  1534. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1535. }
  1536. // TODO - don't just search through every single entity
  1537. // probably just have a way to do lookups directly
  1538. function findEntity(name) {
  1539. return availableEntitiesByName[name];
  1540. }
  1541. function importScene(data) {
  1542. removeAllEntities();
  1543. data.entities.forEach(entityInfo => {
  1544. const entity = findEntity(entityInfo.name).constructor();
  1545. entity.scale = entityInfo.scale
  1546. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1547. });
  1548. config.height = math.unit(data.world.height, data.world.unit);
  1549. document.querySelector("#options-height-unit").value = data.world.unit;
  1550. updateSizes();
  1551. }