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

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