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

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