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.
 
 
 

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