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

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