less copy protection, more size visualization
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 

1281 wiersze
37 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. const unitChoices = {
  15. length: [
  16. "meters",
  17. "angstroms",
  18. "millimeters",
  19. "centimeters",
  20. "kilometers",
  21. "inches",
  22. "feet",
  23. "stories",
  24. "miles",
  25. "parsecs",
  26. ],
  27. area: [
  28. "meters^2",
  29. "cm^2",
  30. "kilometers^2",
  31. "acres",
  32. "miles^2"
  33. ],
  34. mass: [
  35. "kilograms",
  36. "lbs",
  37. "tons"
  38. ]
  39. }
  40. const config = {
  41. height: math.unit(1500, "meters"),
  42. minLineSize: 50,
  43. maxLineSize: 250,
  44. autoFit: false,
  45. autoFitMode: "max"
  46. }
  47. const availableEntities = {
  48. }
  49. const availableEntitiesByName = {
  50. }
  51. const entities = {
  52. }
  53. function constrainRel(coords) {
  54. return {
  55. x: Math.min(Math.max(coords.x, 0), 1),
  56. y: Math.min(Math.max(coords.y, 0), 1)
  57. }
  58. }
  59. function snapRel(coords) {
  60. return constrainRel({
  61. x: coords.x,
  62. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  63. });
  64. }
  65. function adjustAbs(coords, oldHeight, newHeight) {
  66. return { x: coords.x, y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  67. }
  68. function rel2abs(coords) {
  69. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  70. }
  71. function abs2rel(coords) {
  72. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  73. }
  74. function updateEntityElement(entity, element, zIndex) {
  75. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  76. const view = entity.view;
  77. element.style.left = position.x + "px";
  78. element.style.top = position.y + "px";
  79. const canvasHeight = document.querySelector("#display").clientHeight;
  80. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 100);
  81. const bonus = (entity.views[view].image.extra ? entity.views[view].image.extra : 1);
  82. element.style.setProperty("--height", pixels * bonus + "px");
  83. element.querySelector(".entity-name").innerText = entity.name;
  84. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  85. bottomName.style.left = position.x + entityX + "px";
  86. bottomName.style.top = "95vh";
  87. bottomName.innerText = entity.name;
  88. if (zIndex) {
  89. element.style.zIndex = zIndex;
  90. }
  91. }
  92. function updateSizes() {
  93. drawScale();
  94. let ordered = Object.entries(entities);
  95. ordered.sort((e1, e2) => {
  96. return e1[1].views[e1[1].view].height.toNumber("meters") - e2[1].views[e2[1].view].height.toNumber("meters")
  97. });
  98. let zIndex = ordered.length;
  99. ordered.forEach(entity => {
  100. const element = document.querySelector("#entity-" + entity[0]);
  101. updateEntityElement(entity[1], element, zIndex);
  102. zIndex -= 1;
  103. });
  104. }
  105. function drawScale() {
  106. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  107. let total = heightPer.clone();
  108. total.value = 0;
  109. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  110. drawTick(ctx, 50, y, total);
  111. total = math.add(total, heightPer);
  112. }
  113. }
  114. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  115. const oldStroke = ctx.strokeStyle;
  116. const oldFill = ctx.fillStyle;
  117. ctx.beginPath();
  118. ctx.moveTo(x, y);
  119. ctx.lineTo(x + 20, y);
  120. ctx.strokeStyle = "#000000";
  121. ctx.stroke();
  122. ctx.beginPath();
  123. ctx.moveTo(x + 20, y);
  124. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  125. ctx.strokeStyle = "#aaaaaa";
  126. ctx.stroke();
  127. ctx.beginPath();
  128. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  129. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  130. ctx.strokeStyle = "#000000";
  131. ctx.stroke();
  132. const oldFont = ctx.font;
  133. ctx.font = 'normal 24pt coda';
  134. ctx.fillStyle = "#dddddd";
  135. ctx.beginPath();
  136. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  137. ctx.font = oldFont;
  138. ctx.strokeStyle = oldStroke;
  139. ctx.fillStyle = oldFill;
  140. }
  141. const canvas = document.querySelector("#display");
  142. /** @type {CanvasRenderingContext2D} */
  143. const ctx = canvas.getContext("2d");
  144. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.value;
  145. let heightPer = config.height.clone();
  146. heightPer.value = 1;
  147. if (pixelsPer < config.minLineSize) {
  148. heightPer.value /= pixelsPer / config.minLineSize;
  149. pixelsPer = config.minLineSize;
  150. }
  151. if (pixelsPer > config.maxLineSize) {
  152. heightPer.value /= pixelsPer / config.maxLineSize;
  153. pixelsPer = config.maxLineSize;
  154. }
  155. ctx.clearRect(0, 0, canvas.width, canvas.height);
  156. ctx.scale(1, 1);
  157. ctx.canvas.width = canvas.clientWidth;
  158. ctx.canvas.height = canvas.clientHeight;
  159. ctx.beginPath();
  160. ctx.moveTo(50, 50);
  161. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  162. ctx.stroke();
  163. ctx.beginPath();
  164. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  165. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  166. ctx.stroke();
  167. drawTicks(ctx, pixelsPer, heightPer);
  168. }
  169. function makeEntity(info, views, sizes) {
  170. const entityTemplate = {
  171. name: info.name,
  172. identifier: info.name,
  173. scale: 1,
  174. info: info,
  175. views: views,
  176. sizes: sizes === undefined ? [] : sizes,
  177. init: function () {
  178. const entity = this;
  179. Object.entries(this.views).forEach(([viewKey, view]) => {
  180. view.parent = this;
  181. if (this.defaultView === undefined) {
  182. this.defaultView = viewKey;
  183. this.view = viewKey;
  184. }
  185. Object.entries(view.attributes).forEach(([key, val]) => {
  186. Object.defineProperty(
  187. view,
  188. key,
  189. {
  190. get: function () {
  191. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  192. },
  193. set: function (value) {
  194. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  195. this.parent.scale = newScale;
  196. }
  197. }
  198. )
  199. });
  200. });
  201. this.sizes.forEach(size => {
  202. if (size.default === true) {
  203. this.views[this.defaultView].height = size.height;
  204. this.size = size;
  205. }
  206. });
  207. if (this.size === undefined && this.sizes.length > 0) {
  208. this.views[this.defaultView].height = this.sizes[0].height;
  209. this.size = this.sizes[0];
  210. }
  211. this.desc = {};
  212. Object.entries(this.info).forEach(([key, value]) => {
  213. Object.defineProperty(
  214. this.desc,
  215. key,
  216. {
  217. get: function () {
  218. let text = value.text;
  219. if (entity.views[entity.view].info) {
  220. if (entity.views[entity.view].info[key]) {
  221. text = combineInfo(text, entity.views[entity.view].info[key]);
  222. }
  223. }
  224. if (entity.size.info) {
  225. if (entity.size.info[key]) {
  226. text = combineInfo(text, entity.size.info[key]);
  227. }
  228. }
  229. return { title: value.title, text: text };
  230. }
  231. }
  232. )
  233. });
  234. delete this.init;
  235. return this;
  236. }
  237. }.init();
  238. return entityTemplate;
  239. }
  240. function combineInfo(existing, next) {
  241. switch (next.mode) {
  242. case "replace":
  243. return next.text;
  244. case "prepend":
  245. return next.text + existing;
  246. case "append":
  247. return existing + next.text;
  248. }
  249. return existing;
  250. }
  251. function clickDown(target, x, y) {
  252. clicked = target;
  253. const rect = target.getBoundingClientRect();
  254. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  255. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  256. dragOffsetX = x - rect.left + entX;
  257. dragOffsetY = y - rect.top + entY;
  258. clickTimeout = setTimeout(() => { dragging = true }, 200)
  259. }
  260. // could we make this actually detect the menu area?
  261. function hoveringInDeleteArea(e) {
  262. return e.clientY < document.body.clientHeight / 10;
  263. }
  264. function clickUp(e) {
  265. clearTimeout(clickTimeout);
  266. if (clicked) {
  267. if (dragging) {
  268. dragging = false;
  269. if (hoveringInDeleteArea(e)) {
  270. removeEntity(clicked);
  271. document.querySelector("#menubar").classList.remove("hover-delete");
  272. }
  273. } else {
  274. select(clicked);
  275. }
  276. clicked = null;
  277. }
  278. }
  279. function deselect() {
  280. if (selected) {
  281. selected.classList.remove("selected");
  282. }
  283. clearAttribution();
  284. selected = null;
  285. clearViewList();
  286. clearEntityOptions();
  287. clearViewOptions();
  288. }
  289. function select(target) {
  290. deselect();
  291. selected = target;
  292. selectedEntity = entities[target.dataset.key];
  293. selected.classList.add("selected");
  294. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  295. configViewList(selectedEntity, selectedEntity.view);
  296. configEntityOptions(selectedEntity, selectedEntity.view);
  297. configViewOptions(selectedEntity, selectedEntity.view);
  298. }
  299. function configViewList(entity, selectedView) {
  300. const list = document.querySelector("#entity-view");
  301. list.innerHTML = "";
  302. list.style.display = "block";
  303. Object.keys(entity.views).forEach(view => {
  304. const option = document.createElement("option");
  305. option.innerText = entity.views[view].name;
  306. option.value = view;
  307. if (view === selectedView) {
  308. option.selected = true;
  309. }
  310. list.appendChild(option);
  311. });
  312. }
  313. function clearViewList() {
  314. const list = document.querySelector("#entity-view");
  315. list.innerHTML = "";
  316. list.style.display = "none";
  317. }
  318. function updateWorldOptions(entity, view) {
  319. const heightInput = document.querySelector("#options-height-value");
  320. const heightSelect = document.querySelector("#options-height-unit");
  321. const converted = config.height.toNumber(heightSelect.value);
  322. heightInput.value = math.round(converted, 3);
  323. }
  324. function configEntityOptions(entity, view) {
  325. const holder = document.querySelector("#options-entity");
  326. holder.innerHTML = "";
  327. const scaleLabel = document.createElement("div");
  328. scaleLabel.classList.add("options-label");
  329. scaleLabel.innerText = "Scale";
  330. const scaleRow = document.createElement("div");
  331. scaleRow.classList.add("options-row");
  332. const scaleInput = document.createElement("input");
  333. scaleInput.classList.add("options-field-numeric");
  334. scaleInput.id = "options-entity-scale";
  335. scaleInput.addEventListener("input", e => {
  336. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  337. if (config.autoFit) {
  338. fitWorld();
  339. }
  340. updateSizes();
  341. updateEntityOptions(entity, view);
  342. updateViewOptions(entity, view);
  343. });
  344. scaleInput.setAttribute("min", 1);
  345. scaleInput.setAttribute("type", "number");
  346. scaleInput.value = entity.scale;
  347. scaleRow.appendChild(scaleInput);
  348. holder.appendChild(scaleLabel);
  349. holder.appendChild(scaleRow);
  350. const nameLabel = document.createElement("div");
  351. nameLabel.classList.add("options-label");
  352. nameLabel.innerText = "Name";
  353. const nameRow = document.createElement("div");
  354. nameRow.classList.add("options-row");
  355. const nameInput = document.createElement("input");
  356. nameInput.classList.add("options-field-text");
  357. nameInput.value = entity.name;
  358. nameInput.addEventListener("input", e => {
  359. entity.name = e.target.value;
  360. updateSizes();
  361. })
  362. nameRow.appendChild(nameInput);
  363. holder.appendChild(nameLabel);
  364. holder.appendChild(nameRow);
  365. const defaultHolder = document.querySelector("#options-entity-defaults");
  366. defaultHolder.innerHTML = "";
  367. entity.sizes.forEach(defaultInfo => {
  368. const button = document.createElement("button");
  369. button.classList.add("options-button");
  370. button.innerText = defaultInfo.name;
  371. button.addEventListener("click", e => {
  372. entity.views[entity.defaultView].height = defaultInfo.height;
  373. updateEntityOptions(entity, view);
  374. updateViewOptions(entity, view);
  375. updateSizes();
  376. });
  377. defaultHolder.appendChild(button);
  378. });
  379. }
  380. function updateEntityOptions(entity, view) {
  381. const scaleInput = document.querySelector("#options-entity-scale");
  382. scaleInput.value = entity.scale;
  383. }
  384. function clearEntityOptions() {
  385. const holder = document.querySelector("#options-entity");
  386. holder.innerHTML = "";
  387. document.querySelector("#options-entity-defaults").innerHTML = "";
  388. }
  389. function configViewOptions(entity, view) {
  390. const holder = document.querySelector("#options-view");
  391. holder.innerHTML = "";
  392. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  393. const label = document.createElement("div");
  394. label.classList.add("options-label");
  395. label.innerText = val.name;
  396. holder.appendChild(label);
  397. const row = document.createElement("div");
  398. row.classList.add("options-row");
  399. holder.appendChild(row);
  400. const input = document.createElement("input");
  401. input.classList.add("options-field-numeric");
  402. input.id = "options-view-" + key + "-input";
  403. input.setAttribute("type", "number");
  404. input.setAttribute("min", 1);
  405. input.value = entity.views[view][key].value;
  406. const select = document.createElement("select");
  407. select.id = "options-view-" + key + "-select"
  408. unitChoices[val.type].forEach(name => {
  409. const option = document.createElement("option");
  410. option.innerText = name;
  411. select.appendChild(option);
  412. });
  413. input.addEventListener("input", e => {
  414. const value = input.value == 0 ? 1 : input.value;
  415. entity.views[view][key] = math.unit(value, select.value);
  416. if (config.autoFit) {
  417. fitWorld();
  418. }
  419. updateSizes();
  420. updateEntityOptions(entity, view);
  421. updateViewOptions(entity, view, key);
  422. });
  423. select.setAttribute("oldUnit", select.value);
  424. select.addEventListener("input", e => {
  425. const value = input.value == 0 ? 1 : input.value;
  426. const oldUnit = select.getAttribute("oldUnit");
  427. entity.views[view][key] = math.unit(value, oldUnit).to(select.value);
  428. input.value = entity.views[view][key].toNumber(select.value);
  429. select.setAttribute("oldUnit", select.value);
  430. if (config.autoFit) {
  431. fitWorld();
  432. }
  433. updateSizes();
  434. updateEntityOptions(entity, view);
  435. updateViewOptions(entity, view, key);
  436. });
  437. row.appendChild(input);
  438. row.appendChild(select);
  439. });
  440. }
  441. function updateViewOptions(entity, view, changed) {
  442. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  443. if (key != changed) {
  444. const input = document.querySelector("#options-view-" + key + "-input");
  445. const select = document.querySelector("#options-view-" + key + "-select");
  446. const currentUnit = select.value;
  447. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  448. input.value = math.round(convertedAmount, 5);
  449. }
  450. });
  451. }
  452. function getSortedEntities() {
  453. return Object.keys(entities).sort((a, b) => {
  454. const entA = entities[a];
  455. const entB = entities[b];
  456. const viewA = entA.view;
  457. const viewB = entB.view;
  458. const heightA = entA.views[viewA].height.to("meter").value;
  459. const heightB = entB.views[viewB].height.to("meter").value;
  460. return heightA - heightB;
  461. });
  462. }
  463. function clearViewOptions() {
  464. const holder = document.querySelector("#options-view");
  465. holder.innerHTML = "";
  466. }
  467. // this is a crime against humanity, and also stolen from
  468. // stack overflow
  469. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  470. const testCanvas = document.createElement("canvas");
  471. testCanvas.id = "test-canvas";
  472. const testCtx = testCanvas.getContext("2d");
  473. function testClick(event) {
  474. // oh my god I can't believe I'm doing this
  475. const target = event.target;
  476. if (navigator.userAgent.indexOf("Firefox") != -1) {
  477. clickDown(target.parentElement, event.clientX, event.clientY);
  478. return;
  479. }
  480. // Get click coordinates
  481. let w = target.width;
  482. let h = target.height;
  483. let ratioW = 1, ratioH = 1;
  484. // Limit the size of the canvas so that very large images don't cause problems)
  485. if (w > 1000) {
  486. ratioW = w / 1000;
  487. w /= ratioW;
  488. h /= ratioW;
  489. }
  490. if (h > 1000) {
  491. ratioH = h / 1000;
  492. w /= ratioH;
  493. h /= ratioH;
  494. }
  495. const ratio = ratioW * ratioH;
  496. var x = event.clientX - target.getBoundingClientRect().x,
  497. y = event.clientY - target.getBoundingClientRect().y,
  498. alpha;
  499. testCtx.canvas.width = w;
  500. testCtx.canvas.height = h;
  501. // Draw image to canvas
  502. // and read Alpha channel value
  503. testCtx.drawImage(target, 0, 0, w, h);
  504. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  505. // If pixel is transparent,
  506. // retrieve the element underneath and trigger it's click event
  507. if (alpha === 0) {
  508. const oldDisplay = target.style.display;
  509. target.style.display = "none";
  510. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  511. newTarget.dispatchEvent(new MouseEvent(event.type, {
  512. "clientX": event.clientX,
  513. "clientY": event.clientY
  514. }));
  515. target.style.display = oldDisplay;
  516. } else {
  517. clickDown(target.parentElement, event.clientX, event.clientY);
  518. }
  519. }
  520. function arrangeEntities(order) {
  521. let x = 0.1;
  522. order.forEach(key => {
  523. document.querySelector("#entity-" + key).dataset.x = x;
  524. x += 0.8 / (order.length - 1);
  525. });
  526. updateSizes();
  527. }
  528. function removeAllEntities() {
  529. Object.keys(entities).forEach(key => {
  530. removeEntity(document.querySelector("#entity-" + key));
  531. });
  532. }
  533. function clearAttribution() {
  534. document.querySelector("#options-attribution").style.display = "none";
  535. }
  536. function displayAttribution(file) {
  537. document.querySelector("#options-attribution").style.display = "inline";
  538. const authors = authorsOfFull(file);
  539. const source = sourceOf(file);
  540. const authorHolder = document.querySelector("#options-attribution-authors");
  541. const sourceHolder = document.querySelector("#options-attribution-source");
  542. if (authors === []) {
  543. authorHolder.innerText = "Unknown";
  544. } else if (authors === undefined) {
  545. authorHolder.innerText = "Not yet entered";
  546. } else {
  547. authorHolder.innerHTML = "";
  548. const list = document.createElement("ul");
  549. authorHolder.appendChild(list);
  550. authors.forEach(author => {
  551. const authorEntry = document.createElement("li");
  552. const link = document.createElement("a");
  553. link.href = author.url;
  554. link.innerText = author.name;
  555. authorEntry.appendChild(link);
  556. list.appendChild(authorEntry);
  557. });
  558. }
  559. if (source === null) {
  560. sourceHolder.innerText = "No Link"
  561. } else if (source === undefined) {
  562. sourceHolder.innerText = "Not yet entered";
  563. } else {
  564. sourceHolder.innerHTML = "";
  565. const link = document.createElement("a");
  566. link.href = source;
  567. link.innerText = new URL(source).host;
  568. sourceHolder.appendChild(link);
  569. }
  570. }
  571. function removeEntity(element) {
  572. if (selected == element) {
  573. deselect();
  574. }
  575. delete entities[element.dataset.key];
  576. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  577. bottomName.parentElement.removeChild(bottomName);
  578. element.parentElement.removeChild(element);
  579. }
  580. function displayEntity(entity, view, x, y) {
  581. const box = document.createElement("div");
  582. box.classList.add("entity-box");
  583. const img = document.createElement("img");
  584. img.classList.add("entity-image");
  585. img.addEventListener("dragstart", e => {
  586. e.preventDefault();
  587. });
  588. const nameTag = document.createElement("div");
  589. nameTag.classList.add("entity-name");
  590. nameTag.innerText = entity.name;
  591. box.appendChild(img);
  592. box.appendChild(nameTag);
  593. const image = entity.views[view].image;
  594. img.src = image.source;
  595. displayAttribution(image.source);
  596. if (image.bottom !== undefined) {
  597. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  598. } else {
  599. img.style.setProperty("--offset", ((-1) * 100) + "%")
  600. }
  601. box.dataset.x = x;
  602. box.dataset.y = y;
  603. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  604. img.addEventListener("touchstart", e => {
  605. const fakeEvent = {
  606. target: e.target,
  607. clientX: e.touches[0].clientX,
  608. clientY: e.touches[0].clientY
  609. };
  610. testClick(fakeEvent);
  611. });
  612. box.id = "entity-" + entityIndex;
  613. box.dataset.key = entityIndex;
  614. entity.view = view;
  615. entities[entityIndex] = entity;
  616. entity.index = entityIndex;
  617. const world = document.querySelector("#entities");
  618. world.appendChild(box);
  619. const bottomName = document.createElement("div");
  620. bottomName.classList.add("bottom-name");
  621. bottomName.id = "bottom-name-" + entityIndex;
  622. bottomName.innerText = entity.name;
  623. bottomName.addEventListener("click", () => select(box));
  624. world.appendChild(bottomName);
  625. entityIndex += 1;
  626. updateEntityElement(entity, box);
  627. if (config.autoFit) {
  628. fitWorld();
  629. }
  630. select(box);
  631. }
  632. window.onblur = function () {
  633. altHeld = false;
  634. shiftHeld = false;
  635. }
  636. window.onfocus = function () {
  637. window.dispatchEvent(new Event("keydown"));
  638. }
  639. document.addEventListener("DOMContentLoaded", () => {
  640. prepareEntities();
  641. const sceneChoices = document.querySelector("#scene-choices");
  642. Object.entries(scenes).forEach(([id, scene]) => {
  643. const option = document.createElement("option");
  644. option.innerText = id;
  645. option.value = id;
  646. sceneChoices.appendChild(option);
  647. });
  648. document.querySelector("#load-scene").addEventListener("click", e => {
  649. const chosen = sceneChoices.value;
  650. removeAllEntities();
  651. scenes[chosen]();
  652. });
  653. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  654. canvasWidth = document.querySelector("#display").clientWidth - 100;
  655. canvasHeight = document.querySelector("#display").clientHeight - 50;
  656. document.querySelector("#open-help").addEventListener("click", e => {
  657. document.querySelector("#help").classList.add("visible");
  658. });
  659. document.querySelector("#close-help").addEventListener("click", e => {
  660. document.querySelector("#help").classList.remove("visible");
  661. });
  662. const unitSelector = document.querySelector("#options-height-unit");
  663. unitChoices.length.forEach(lengthOption => {
  664. const option = document.createElement("option");
  665. option.innerText = lengthOption;
  666. option.value = lengthOption;
  667. if (lengthOption === "meters") {
  668. option.selected = true;
  669. }
  670. unitSelector.appendChild(option);
  671. });
  672. scenes["Demo"]();
  673. fitWorld();
  674. document.querySelector("#world").addEventListener("wheel", e => {
  675. if (shiftHeld) {
  676. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  677. if (selected) {
  678. const entity = entities[selected.dataset.key];
  679. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  680. updateEntityOptions(entity, entity.view);
  681. updateViewOptions(entity, entity.view);
  682. updateSizes();
  683. }
  684. } else {
  685. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  686. setWorldHeight(config.height, math.multiply(config.height, dir));
  687. updateWorldOptions();
  688. }
  689. checkFitWorld();
  690. })
  691. document.querySelector("body").appendChild(testCtx.canvas);
  692. updateSizes();
  693. document.querySelector("#options-height-value").addEventListener("input", e => {
  694. updateWorldHeight();
  695. })
  696. unitSelector.addEventListener("input", e => {
  697. checkFitWorld();
  698. updateWorldHeight();
  699. })
  700. world.addEventListener("mousedown", e => deselect());
  701. document.querySelector("#display").addEventListener("mousedown", deselect);
  702. document.addEventListener("mouseup", e => clickUp(e));
  703. document.addEventListener("touchend", e => {
  704. const fakeEvent = {
  705. target: e.target,
  706. clientX: e.changedTouches[0].clientX,
  707. clientY: e.changedTouches[0].clientY
  708. };
  709. clickUp(fakeEvent);
  710. });
  711. document.querySelector("#entity-view").addEventListener("input", e => {
  712. entities[selected.dataset.key].view = e.target.value;
  713. const image = entities[selected.dataset.key].views[e.target.value].image;
  714. selected.querySelector(".entity-image").src = image.source;
  715. displayAttribution(image.source);
  716. if (image.bottom !== undefined) {
  717. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  718. } else {
  719. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  720. }
  721. updateSizes();
  722. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  723. updateViewOptions(entities[selected.dataset.key], e.target.value);
  724. });
  725. clearViewList();
  726. document.querySelector("#menu-clear").addEventListener("click", e => {
  727. removeAllEntities();
  728. });
  729. document.querySelector("#menu-order-height").addEventListener("click", e => {
  730. const order = Object.keys(entities).sort((a, b) => {
  731. const entA = entities[a];
  732. const entB = entities[b];
  733. const viewA = entA.view;
  734. const viewB = entB.view;
  735. const heightA = entA.views[viewA].height.to("meter").value;
  736. const heightB = entB.views[viewB].height.to("meter").value;
  737. return heightA - heightB;
  738. });
  739. arrangeEntities(order);
  740. });
  741. document.querySelector("#options-world-fit").addEventListener("click", fitWorld);
  742. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  743. config.autoFit = e.target.checked;
  744. if (config.autoFit) {
  745. fitWorld();
  746. }
  747. });
  748. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  749. config.autoFitMode = e.target.value;
  750. if (config.autoFit) {
  751. fitWorld();
  752. }
  753. })
  754. document.addEventListener("keydown", e => {
  755. if (e.key == "Delete") {
  756. if (selected) {
  757. removeEntity(selected);
  758. selected = null;
  759. }
  760. }
  761. })
  762. document.addEventListener("keydown", e => {
  763. if (e.key == "Shift") {
  764. shiftHeld = true;
  765. e.preventDefault();
  766. } else if (e.key == "Alt") {
  767. altHeld = true;
  768. e.preventDefault();
  769. }
  770. });
  771. document.addEventListener("keyup", e => {
  772. if (e.key == "Shift") {
  773. shiftHeld = false;
  774. e.preventDefault();
  775. } else if (e.key == "Alt") {
  776. altHeld = false;
  777. e.preventDefault();
  778. }
  779. });
  780. document.addEventListener("paste", e => {
  781. try {
  782. const data = JSON.parse(e.clipboardData.getData("text"));
  783. if (data.entities === undefined) {
  784. return;
  785. }
  786. if (data.world === undefined) {
  787. return;
  788. }
  789. importScene(data);
  790. } catch (err) {
  791. console.error(err);
  792. // probably wasn't valid data
  793. }
  794. });
  795. document.querySelector("#menu-export").addEventListener("click", e => {
  796. copyScene();
  797. });
  798. document.querySelector("#menu-save").addEventListener("click", e => {
  799. saveScene();
  800. });
  801. document.querySelector("#menu-load").addEventListener("click", e => {
  802. loadScene();
  803. });
  804. });
  805. function prepareEntities() {
  806. availableEntities["buildings"] = makeBuildings();
  807. availableEntities["landmarks"] = makeLandmarks();
  808. availableEntities["characters"] = makeCharacters();
  809. availableEntities["objects"] = makeObjects();
  810. availableEntities["naturals"] = makeNaturals();
  811. availableEntities["vehicles"] = makeVehicles();
  812. availableEntities["cities"] = makeCities();
  813. availableEntities["characters"].sort((x, y) => {
  814. return x.name < y.name ? -1 : 1
  815. });
  816. const holder = document.querySelector("#spawners");
  817. const categorySelect = document.createElement("select");
  818. categorySelect.id = "category-picker";
  819. holder.appendChild(categorySelect);
  820. Object.entries(availableEntities).forEach(([category, entityList]) => {
  821. const select = document.createElement("select");
  822. select.id = "create-entity-" + category;
  823. for (let i = 0; i < entityList.length; i++) {
  824. const entity = entityList[i];
  825. const option = document.createElement("option");
  826. option.value = i;
  827. option.innerText = entity.name;
  828. select.appendChild(option);
  829. availableEntitiesByName[entity.name] = entity;
  830. };
  831. const button = document.createElement("button");
  832. button.id = "create-entity-" + category + "-button";
  833. button.innerText = "Create";
  834. button.addEventListener("click", e => {
  835. const newEntity = entityList[select.value].constructor()
  836. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  837. });
  838. const categoryOption = document.createElement("option");
  839. categoryOption.value = category
  840. categoryOption.innerText = category;
  841. if (category == "characters") {
  842. categoryOption.selected = true;
  843. select.classList.add("category-visible");
  844. button.classList.add("category-visible");
  845. }
  846. categorySelect.appendChild(categoryOption);
  847. holder.appendChild(select);
  848. holder.appendChild(button);
  849. });
  850. categorySelect.addEventListener("input", e => {
  851. const oldSelect = document.querySelector("select.category-visible");
  852. oldSelect.classList.remove("category-visible");
  853. const oldButton = document.querySelector("button.category-visible");
  854. oldButton.classList.remove("category-visible");
  855. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  856. newSelect.classList.add("category-visible");
  857. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  858. newButton.classList.add("category-visible");
  859. });
  860. }
  861. window.addEventListener("resize", () => {
  862. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  863. canvasWidth = document.querySelector("#display").clientWidth - 100;
  864. canvasHeight = document.querySelector("#display").clientHeight - 50;
  865. updateSizes();
  866. })
  867. document.addEventListener("mousemove", (e) => {
  868. if (clicked) {
  869. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  870. clicked.dataset.x = position.x;
  871. clicked.dataset.y = position.y;
  872. updateEntityElement(entities[clicked.dataset.key], clicked);
  873. if (hoveringInDeleteArea(e)) {
  874. document.querySelector("#menubar").classList.add("hover-delete");
  875. } else {
  876. document.querySelector("#menubar").classList.remove("hover-delete");
  877. }
  878. }
  879. });
  880. document.addEventListener("touchmove", (e) => {
  881. if (clicked) {
  882. e.preventDefault();
  883. let x = e.touches[0].clientX;
  884. let y = e.touches[0].clientY;
  885. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  886. clicked.dataset.x = position.x;
  887. clicked.dataset.y = position.y;
  888. updateEntityElement(entities[clicked.dataset.key], clicked);
  889. // what a hack
  890. // I should centralize this 'fake event' creation...
  891. if (hoveringInDeleteArea({ clientY: y })) {
  892. document.querySelector("#menubar").classList.add("hover-delete");
  893. } else {
  894. document.querySelector("#menubar").classList.remove("hover-delete");
  895. }
  896. }
  897. }, { passive: false });
  898. function checkFitWorld() {
  899. if (config.autoFit) {
  900. fitWorld();
  901. }
  902. }
  903. const fitModes = {
  904. "max": {
  905. start: 0,
  906. binop: math.max,
  907. final: (total, count) => total
  908. },
  909. "arithmetic mean": {
  910. start: 0,
  911. binop: math.add,
  912. final: (total, count) => total / count
  913. },
  914. "geometric mean": {
  915. start: 1,
  916. binop: math.multiply,
  917. final: (total, count) => math.pow(total, 1 / count)
  918. }
  919. }
  920. function fitWorld() {
  921. const fitMode = fitModes[config.autoFitMode]
  922. let max = fitMode.start
  923. let count = 0;
  924. Object.entries(entities).forEach(([key, entity]) => {
  925. const view = entity.view;
  926. max = fitMode.binop(max, entity.views[view].height.toNumber("meter"));
  927. count += 1;
  928. });
  929. max = fitMode.final(max, count)
  930. max = math.unit(max, "meter")
  931. setWorldHeight(config.height, math.multiply(max, 1.1));
  932. }
  933. function updateWorldHeight() {
  934. const unit = document.querySelector("#options-height-unit").value;
  935. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  936. const oldHeight = config.height;
  937. setWorldHeight(oldHeight, math.unit(value, unit));
  938. }
  939. function setWorldHeight(oldHeight, newHeight) {
  940. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  941. const unit = document.querySelector("#options-height-unit").value;
  942. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  943. Object.entries(entities).forEach(([key, entity]) => {
  944. const element = document.querySelector("#entity-" + key);
  945. let newPosition;
  946. if (!altHeld) {
  947. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  948. } else {
  949. newPosition = { x: element.dataset.x, y: element.dataset.y };
  950. }
  951. element.dataset.x = newPosition.x;
  952. element.dataset.y = newPosition.y;
  953. });
  954. updateSizes();
  955. }
  956. function loadScene() {
  957. try {
  958. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  959. importScene(data);
  960. } catch (err) {
  961. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  962. console.error(err);
  963. }
  964. }
  965. function saveScene() {
  966. try {
  967. const string = JSON.stringify(exportScene());
  968. localStorage.setItem("macrovision-save", string);
  969. } catch (err) {
  970. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  971. console.error(err);
  972. }
  973. }
  974. function exportScene() {
  975. const results = {};
  976. results.entities = [];
  977. Object.entries(entities).forEach(([key, entity]) => {
  978. const element = document.querySelector("#entity-" + key);
  979. results.entities.push({
  980. name: entity.identifier,
  981. scale: entity.scale,
  982. view: entity.view,
  983. x: element.dataset.x,
  984. y: element.dataset.y
  985. });
  986. });
  987. const unit = document.querySelector("#options-height-unit").value;
  988. results.world = {
  989. height: config.height.toNumber(unit),
  990. unit: unit
  991. }
  992. return results;
  993. }
  994. function copyScene() {
  995. const results = exportScene();
  996. navigator.clipboard.writeText(JSON.stringify(results))
  997. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  998. }
  999. // TODO - don't just search through every single entity
  1000. // probably just have a way to do lookups directly
  1001. function findEntity(name) {
  1002. return availableEntitiesByName[name];
  1003. }
  1004. function importScene(data) {
  1005. removeAllEntities();
  1006. data.entities.forEach(entityInfo => {
  1007. const entity = findEntity(entityInfo.name).constructor();
  1008. entity.scale = entityInfo.scale
  1009. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1010. });
  1011. config.height = math.unit(data.world.height, data.world.unit);
  1012. document.querySelector("#options-height-unit").value = data.world.unit;
  1013. updateSizes();
  1014. }