less copy protection, more size visualization
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

692 行
21 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 altHeld = false;
  10. const unitChoices = {
  11. length: [
  12. "meters",
  13. "kilometers",
  14. "feet",
  15. "miles",
  16. ],
  17. area: [
  18. "cm^2",
  19. "meters^2"
  20. ],
  21. mass: [
  22. "kilograms"
  23. ]
  24. }
  25. const config = {
  26. height: math.unit(1500, "meters"),
  27. minLineSize: 50,
  28. maxLineSize: 250
  29. }
  30. const availableEntities = {
  31. }
  32. const entities = {
  33. }
  34. function constrainRel(coords) {
  35. return {
  36. x: Math.min(Math.max(coords.x, 0), 1),
  37. y: Math.min(Math.max(coords.y, 0), 1)
  38. }
  39. }
  40. function snapRel(coords) {
  41. return constrainRel({
  42. x: coords.x,
  43. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  44. });
  45. }
  46. function adjustAbs(coords, oldHeight, newHeight) {
  47. return { x: coords.x, y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  48. }
  49. function rel2abs(coords) {
  50. const canvasWidth = document.querySelector("#display").clientWidth - 50;
  51. const canvasHeight = document.querySelector("#display").clientHeight - 50;
  52. return { x: coords.x * canvasWidth, y: coords.y * canvasHeight };
  53. }
  54. function abs2rel(coords) {
  55. const canvasWidth = document.querySelector("#display").clientWidth - 50;
  56. const canvasHeight = document.querySelector("#display").clientHeight - 50;
  57. return { x: coords.x / canvasWidth, y: coords.y / canvasHeight };
  58. }
  59. function updateEntityElement(entity, element) {
  60. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  61. const view = element.dataset.view;
  62. element.style.left = position.x + "px";
  63. element.style.top = position.y + "px";
  64. const canvasHeight = document.querySelector("#display").clientHeight;
  65. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 100);
  66. element.style.setProperty("--height", pixels + "px");
  67. element.querySelector(".entity-name").innerText = entity.name;
  68. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  69. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  70. bottomName.style.left = position.x + entX + "px";
  71. bottomName.style.top = "95vh";
  72. bottomName.innerText = entity.name;
  73. }
  74. function updateSizes() {
  75. drawScale();
  76. Object.entries(entities).forEach(([key, entity]) => {
  77. const element = document.querySelector("#entity-" + key);
  78. updateEntityElement(entity, element);
  79. });
  80. }
  81. function drawScale() {
  82. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  83. let total = heightPer.clone();
  84. total.value = 0;
  85. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  86. drawTick(ctx, 50, y, total);
  87. total = math.add(total, heightPer);
  88. }
  89. }
  90. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  91. const oldStroke = ctx.strokeStyle;
  92. const oldFill = ctx.fillStyle;
  93. ctx.beginPath();
  94. ctx.moveTo(x, y);
  95. ctx.lineTo(x + 20, y);
  96. ctx.strokeStyle = "#000000";
  97. ctx.stroke();
  98. ctx.beginPath();
  99. ctx.moveTo(x + 20, y);
  100. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  101. ctx.strokeStyle = "#aaaaaa";
  102. ctx.stroke();
  103. ctx.beginPath();
  104. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  105. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  106. ctx.strokeStyle = "#000000";
  107. ctx.stroke();
  108. const oldFont = ctx.font;
  109. ctx.font = 'normal 24pt coda';
  110. ctx.fillStyle = "#dddddd";
  111. ctx.beginPath();
  112. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  113. ctx.font = oldFont;
  114. ctx.strokeStyle = oldStroke;
  115. ctx.fillStyle = oldFill;
  116. }
  117. const canvas = document.querySelector("#display");
  118. /** @type {CanvasRenderingContext2D} */
  119. const ctx = canvas.getContext("2d");
  120. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.value;
  121. let heightPer = config.height.clone();
  122. heightPer.value = 1;
  123. if (pixelsPer < config.minLineSize) {
  124. heightPer.value /= pixelsPer / config.minLineSize;
  125. pixelsPer = config.minLineSize;
  126. }
  127. if (pixelsPer > config.maxLineSize) {
  128. heightPer.value /= pixelsPer / config.maxLineSize;
  129. pixelsPer = config.maxLineSize;
  130. }
  131. ctx.clearRect(0, 0, canvas.width, canvas.height);
  132. ctx.scale(1, 1);
  133. ctx.canvas.width = canvas.clientWidth;
  134. ctx.canvas.height = canvas.clientHeight;
  135. ctx.beginPath();
  136. ctx.moveTo(50, 50);
  137. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  138. ctx.stroke();
  139. ctx.beginPath();
  140. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  141. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  142. ctx.stroke();
  143. drawTicks(ctx, pixelsPer, heightPer);
  144. }
  145. function makeEntity(name, author, views) {
  146. const entityTemplate = {
  147. name: name,
  148. author: author,
  149. scale: 1,
  150. views: views,
  151. init: function () {
  152. Object.entries(this.views).forEach(([viewKey, view]) => {
  153. view.parent = this;
  154. if (this.defaultView === undefined) {
  155. this.defaultView = viewKey;
  156. }
  157. Object.entries(view.attributes).forEach(([key, val]) => {
  158. Object.defineProperty(
  159. view,
  160. key,
  161. {
  162. get: function() {
  163. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  164. },
  165. set: function(value) {
  166. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  167. this.parent.scale = newScale;
  168. }
  169. }
  170. )
  171. });
  172. });
  173. delete this.init;
  174. return this;
  175. }
  176. }.init();
  177. return entityTemplate;
  178. }
  179. function clickDown(target, x, y) {
  180. clicked = target;
  181. const rect = target.getBoundingClientRect();
  182. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  183. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  184. dragOffsetX = x - rect.left + entX;
  185. dragOffsetY = y - rect.top + entY;
  186. clickTimeout = setTimeout(() => { dragging = true }, 200)
  187. }
  188. // could we make this actually detect the menu area?
  189. function hoveringInDeleteArea(e) {
  190. return e.clientY < document.body.clientHeight / 10;
  191. }
  192. function clickUp(e) {
  193. clearTimeout(clickTimeout);
  194. if (clicked) {
  195. if (dragging) {
  196. dragging = false;
  197. if (hoveringInDeleteArea(e)) {
  198. removeEntity(clicked);
  199. document.querySelector("#menubar").classList.remove("hover-delete");
  200. }
  201. } else {
  202. select(clicked);
  203. }
  204. clicked = null;
  205. }
  206. }
  207. function deselect() {
  208. if (selected) {
  209. selected.classList.remove("selected");
  210. }
  211. selected = null;
  212. clearViewList();
  213. clearEntityOptions();
  214. clearViewOptions();
  215. }
  216. function select(target) {
  217. deselect();
  218. selected = target;
  219. selectedEntity = entities[target.dataset.key];
  220. selected.classList.add("selected");
  221. configViewList(selectedEntity, target.dataset.view);
  222. configEntityOptions(selectedEntity, target.dataset.view);
  223. configViewOptions(selectedEntity, target.dataset.view);
  224. }
  225. function configViewList(entity, selectedView) {
  226. const list = document.querySelector("#entity-view");
  227. list.innerHTML = "";
  228. list.style.display = "block";
  229. Object.keys(entity.views).forEach(view => {
  230. const option = document.createElement("option");
  231. option.innerText = entity.views[view].name;
  232. option.value = view;
  233. if (view === selectedView) {
  234. option.selected = true;
  235. }
  236. list.appendChild(option);
  237. });
  238. }
  239. function clearViewList() {
  240. const list = document.querySelector("#entity-view");
  241. list.innerHTML = "";
  242. list.style.display = "none";
  243. }
  244. function updateWorldOptions(entity, view) {
  245. const heightInput = document.querySelector("#options-height-value");
  246. const heightSelect = document.querySelector("#options-height-unit");
  247. const converted = config.height.to(heightSelect.value);
  248. heightInput.value = math.round(converted.value, 3);
  249. }
  250. function configEntityOptions(entity, view) {
  251. const holder = document.querySelector("#options-entity");
  252. holder.innerHTML = "";
  253. const scaleLabel = document.createElement("div");
  254. scaleLabel.classList.add("options-label");
  255. scaleLabel.innerText = "Scale";
  256. const scaleRow = document.createElement("div");
  257. scaleRow.classList.add("options-row");
  258. const scaleInput = document.createElement("input");
  259. scaleInput.classList.add("options-field-numeric");
  260. scaleInput.id = "options-entity-scale";
  261. scaleInput.addEventListener("input", e => {
  262. entity.scale = e.target.value;
  263. updateSizes();
  264. updateEntityOptions(entity, view);
  265. updateViewOptions(entity, view);
  266. });
  267. scaleInput.setAttribute("min", 1);
  268. scaleInput.setAttribute("type", "number");
  269. scaleInput.value = entity.scale;
  270. scaleRow.appendChild(scaleInput);
  271. holder.appendChild(scaleLabel);
  272. holder.appendChild(scaleRow);
  273. const nameLabel = document.createElement("div");
  274. nameLabel.classList.add("options-label");
  275. nameLabel.innerText = "Name";
  276. const nameRow = document.createElement("div");
  277. nameRow.classList.add("options-row");
  278. const nameInput = document.createElement("input");
  279. nameInput.classList.add("options-field-text");
  280. nameInput.value = entity.name;
  281. nameInput.addEventListener("input", e => {
  282. entity.name = e.target.value;
  283. updateSizes();
  284. })
  285. nameRow.appendChild(nameInput);
  286. holder.appendChild(nameLabel);
  287. holder.appendChild(nameRow);
  288. }
  289. function updateEntityOptions(entity, view) {
  290. const scaleInput = document.querySelector("#options-entity-scale");
  291. scaleInput.value = entity.scale;
  292. }
  293. function clearEntityOptions() {
  294. const holder = document.querySelector("#options-entity");
  295. holder.innerHTML = "";
  296. }
  297. function configViewOptions(entity, view) {
  298. const holder = document.querySelector("#options-view");
  299. holder.innerHTML = "";
  300. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  301. const label = document.createElement("div");
  302. label.classList.add("options-label");
  303. label.innerText = val.name;
  304. holder.appendChild(label);
  305. const row = document.createElement("div");
  306. row.classList.add("options-row");
  307. holder.appendChild(row);
  308. const input = document.createElement("input");
  309. input.classList.add("options-field-numeric");
  310. input.id = "options-view-" + key + "-input";
  311. input.setAttribute("type", "number");
  312. input.setAttribute("min", 1);
  313. input.value = entity.views[view][key].value;
  314. const select = document.createElement("select");
  315. select.id = "options-view-" + key + "-select"
  316. unitChoices[val.type].forEach(name => {
  317. const option = document.createElement("option");
  318. option.innerText = name;
  319. select.appendChild(option);
  320. });
  321. input.addEventListener("input", e => {
  322. entity.views[view][key] = math.unit(input.value, select.value);
  323. updateSizes();
  324. updateEntityOptions(entity, view);
  325. updateViewOptions(entity, view, key);
  326. });
  327. select.addEventListener("input", e => {
  328. entity.views[view][key] = math.unit(input.value, select.value);
  329. updateSizes();
  330. updateEntityOptions(entity, view);
  331. updateViewOptions(entity, view, key);
  332. });
  333. row.appendChild(input);
  334. row.appendChild(select);
  335. });
  336. }
  337. function updateViewOptions(entity, view, changed) {
  338. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  339. if (key != changed) {
  340. const input = document.querySelector("#options-view-" + key + "-input");
  341. const select = document.querySelector("#options-view-" + key + "-select");
  342. const currentUnit = select.value;
  343. const convertedAmount = entity.views[view][key].to(currentUnit);
  344. input.value = math.round(convertedAmount.value, 5);
  345. }
  346. });
  347. }
  348. function clearViewOptions() {
  349. const holder = document.querySelector("#options-view");
  350. holder.innerHTML = "";
  351. }
  352. // this is a crime against humanity, and also stolen from
  353. // stack overflow
  354. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  355. const testCanvas = document.createElement("canvas");
  356. testCanvas.id = "test-canvas";
  357. const testCtx = testCanvas.getContext("2d");
  358. function testClick(event) {
  359. const target = event.target;
  360. // Get click coordinates
  361. var x = event.clientX - target.getBoundingClientRect().x,
  362. y = event.clientY - target.getBoundingClientRect().y,
  363. w = testCtx.canvas.width = target.width,
  364. h = testCtx.canvas.height = target.height,
  365. alpha;
  366. // Draw image to canvas
  367. // and read Alpha channel value
  368. testCtx.drawImage(target, 0, 0, w, h);
  369. alpha = testCtx.getImageData(x, y, 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  370. // If pixel is transparent,
  371. // retrieve the element underneath and trigger it's click event
  372. if (alpha === 0) {
  373. const oldDisplay = target.style.display;
  374. target.style.display = "none";
  375. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  376. newTarget.dispatchEvent(new MouseEvent(event.type, {
  377. "clientX": event.clientX,
  378. "clientY": event.clientY
  379. }));
  380. target.style.display = oldDisplay;
  381. } else {
  382. clickDown(target.parentElement, event.clientX, event.clientY);
  383. }
  384. }
  385. function removeAllEntities() {
  386. Object.keys(entities).forEach(key => {
  387. removeEntity(document.querySelector("#entity-" + key));
  388. });
  389. }
  390. function removeEntity(element) {
  391. delete entities[element.dataset.key];
  392. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  393. bottomName.parentElement.removeChild(bottomName);
  394. element.parentElement.removeChild(element);
  395. }
  396. function displayEntity(entity, view, x, y) {
  397. const box = document.createElement("div");
  398. box.classList.add("entity-box");
  399. const img = document.createElement("img");
  400. img.classList.add("entity-image");
  401. const nameTag = document.createElement("div");
  402. nameTag.classList.add("entity-name");
  403. nameTag.innerText = entity.name;
  404. box.appendChild(img);
  405. box.appendChild(nameTag);
  406. console.log(entity)
  407. img.src = entity.views[view].image.source;
  408. box.dataset.x = x;
  409. box.dataset.y = y;
  410. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  411. img.addEventListener("touchstart", e => {
  412. const fakeEvent = {
  413. target: e.target,
  414. clientX: e.touches[0].clientX,
  415. clientY: e.touches[0].clientY
  416. };
  417. testClick(fakeEvent);});
  418. box.id = "entity-" + entityIndex;
  419. box.dataset.key = entityIndex;
  420. box.dataset.view = view;
  421. entities[entityIndex] = entity;
  422. entity.index = entityIndex;
  423. const world = document.querySelector("#entities");
  424. world.appendChild(box);
  425. const bottomName = document.createElement("div");
  426. bottomName.classList.add("bottom-name");
  427. bottomName.id = "bottom-name-" + entityIndex;
  428. bottomName.innerText = entity.name;
  429. bottomName.addEventListener("click", () => select(box));
  430. world.appendChild(bottomName);
  431. entityIndex += 1;
  432. updateEntityElement(entity, box);
  433. }
  434. document.addEventListener("DOMContentLoaded", () => {
  435. const stuff = [makeFen].concat( makeBuildings().map(x => x.constructor))
  436. console.log(stuff)
  437. let x = 0.2;
  438. stuff.forEach(entity => {
  439. displayEntity(entity(), entity().defaultView, x, 1);
  440. x += 0.7 / stuff.length;
  441. })
  442. window.addEventListener("wheel", e => {
  443. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  444. config.height = math.multiply(config.height, dir);
  445. updateSizes();
  446. updateWorldOptions();
  447. })
  448. document.querySelector("body").appendChild(testCtx.canvas);
  449. updateSizes();
  450. document.querySelector("#options-height-value").addEventListener("input", e => {
  451. updateWorldHeight();
  452. })
  453. document.querySelector("#options-height-unit").addEventListener("input", e => {
  454. updateWorldHeight();
  455. })
  456. world.addEventListener("mousedown", e => deselect());
  457. document.addEventListener("mouseup", e => clickUp(e));
  458. document.addEventListener("touchend", e => {
  459. console.log(e)
  460. const fakeEvent = {
  461. target: e.target,
  462. clientX: e.changedTouches[0].clientX,
  463. clientY: e.changedTouches[0].clientY
  464. };
  465. clickUp(fakeEvent);});
  466. document.querySelector("#entity-view").addEventListener("input", e => {
  467. selected.dataset.view = e.target.value
  468. selected.querySelector(".entity-image").src = entities[selected.dataset.key].views[e.target.value].image.source;
  469. updateSizes();
  470. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  471. updateViewOptions(entities[selected.dataset.key], e.target.value);
  472. });
  473. clearViewList();
  474. document.querySelector("#menu-clear").addEventListener("click", e => {
  475. removeAllEntities();
  476. });
  477. prepareEntities();
  478. });
  479. function prepareEntities() {
  480. availableEntities["buildings"] = makeBuildings();
  481. availableEntities["characters"] = makeCharacters();
  482. const holder = document.querySelector("#menubar");
  483. Object.entries(availableEntities).forEach(([category, entityList]) => {
  484. const select = document.createElement("select");
  485. select.id = "create-entity-" + category;
  486. for (let i = 0; i < entityList.length; i++) {
  487. const entity = entityList[i];
  488. const option = document.createElement("option");
  489. option.value = i;
  490. option.innerText = entity.name;
  491. select.appendChild(option);
  492. };
  493. const button = document.createElement("button");
  494. button.innerText = "Create " + category;
  495. button.addEventListener("click", e => {
  496. const newEntity = entityList[select.value].constructor()
  497. displayEntity(newEntity, newEntity.defaultView, 0.5, 0.5);
  498. });
  499. holder.appendChild(select);
  500. holder.appendChild(button);
  501. });
  502. }
  503. window.addEventListener("resize", () => {
  504. updateSizes();
  505. })
  506. document.addEventListener("mousemove", (e) => {
  507. if (clicked) {
  508. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  509. clicked.dataset.x = position.x;
  510. clicked.dataset.y = position.y;
  511. updateEntityElement(entities[clicked.dataset.key], clicked);
  512. if (hoveringInDeleteArea(e)) {
  513. document.querySelector("#menubar").classList.add("hover-delete");
  514. } else {
  515. document.querySelector("#menubar").classList.remove("hover-delete");
  516. }
  517. }
  518. });
  519. document.addEventListener("touchmove", (e) => {
  520. if (clicked) {
  521. e.preventDefault();
  522. let x = e.touches[0].clientX;
  523. let y = e.touches[0].clientY;
  524. console.log(y)
  525. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  526. clicked.dataset.x = position.x;
  527. clicked.dataset.y = position.y;
  528. updateEntityElement(entities[clicked.dataset.key], clicked);
  529. // what a hack
  530. // I should centralize this 'fake event' creation...
  531. if (hoveringInDeleteArea({clientY: y})) {
  532. document.querySelector("#menubar").classList.add("hover-delete");
  533. } else {
  534. document.querySelector("#menubar").classList.remove("hover-delete");
  535. }
  536. }
  537. }, {passive: false});
  538. function updateWorldHeight() {
  539. const value = Math.max(1, document.querySelector("#options-height-value").value);
  540. const unit = document.querySelector("#options-height-unit").value;
  541. const oldHeight = config.height;
  542. config.height = math.unit(value + " " + unit)
  543. Object.entries(entities).forEach(([key, entity]) => {
  544. const element = document.querySelector("#entity-" + key);
  545. const newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  546. element.dataset.x = newPosition.x;
  547. element.dataset.y = newPosition.y;
  548. });
  549. updateSizes();
  550. }