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.
 
 
 

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