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

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