less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

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