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

1488 строки
44 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. let entityX;
  12. let canvasWidth;
  13. let canvasHeight;
  14. let dragScale = 1;
  15. let dragScaleHandle = null;
  16. let dragEntityScale = 1;
  17. let dragEntityScaleHandle = null;
  18. const unitChoices = {
  19. length: [
  20. "meters",
  21. "angstroms",
  22. "millimeters",
  23. "centimeters",
  24. "kilometers",
  25. "inches",
  26. "feet",
  27. "stories",
  28. "miles",
  29. "parsecs",
  30. ],
  31. area: [
  32. "meters^2",
  33. "cm^2",
  34. "kilometers^2",
  35. "acres",
  36. "miles^2"
  37. ],
  38. mass: [
  39. "kilograms",
  40. "milligrams",
  41. "grams",
  42. "tonnes",
  43. "lbs",
  44. "ounces",
  45. "tons"
  46. ]
  47. }
  48. const config = {
  49. height: math.unit(1500, "meters"),
  50. minLineSize: 50,
  51. maxLineSize: 250,
  52. autoFit: false,
  53. autoFitMode: "max"
  54. }
  55. const availableEntities = {
  56. }
  57. const availableEntitiesByName = {
  58. }
  59. const entities = {
  60. }
  61. function constrainRel(coords) {
  62. if (altHeld) {
  63. return coords;
  64. }
  65. return {
  66. x: Math.min(Math.max(coords.x, 0), 1),
  67. y: Math.min(Math.max(coords.y, 0), 1)
  68. }
  69. }
  70. function snapRel(coords) {
  71. return constrainRel({
  72. x: coords.x,
  73. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  74. });
  75. }
  76. function adjustAbs(coords, oldHeight, newHeight) {
  77. return { x: coords.x, y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  78. }
  79. function rel2abs(coords) {
  80. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  81. }
  82. function abs2rel(coords) {
  83. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  84. }
  85. function updateEntityElement(entity, element, zIndex) {
  86. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  87. const view = entity.view;
  88. element.style.left = position.x + "px";
  89. element.style.top = position.y + "px";
  90. const canvasHeight = document.querySelector("#display").clientHeight;
  91. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 100);
  92. const bonus = (entity.views[view].image.extra ? entity.views[view].image.extra : 1);
  93. element.style.setProperty("--height", pixels * bonus + "px");
  94. if (entity.views[view].rename)
  95. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  96. else
  97. element.querySelector(".entity-name").innerText = entity.name;
  98. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  99. bottomName.style.left = position.x + entityX + "px";
  100. bottomName.style.top = "95vh";
  101. bottomName.innerText = entity.name;
  102. if (zIndex) {
  103. element.style.zIndex = zIndex;
  104. }
  105. }
  106. function updateSizes() {
  107. drawScale();
  108. let ordered = Object.entries(entities);
  109. ordered.sort((e1, e2) => {
  110. if (e1[1].priority != e2[1].priority) {
  111. return e2[1].priority - e1[1].priority;
  112. } else {
  113. return e1[1].views[e1[1].view].height.toNumber("meters") - e2[1].views[e2[1].view].height.toNumber("meters")
  114. }
  115. });
  116. let zIndex = ordered.length;
  117. ordered.forEach(entity => {
  118. const element = document.querySelector("#entity-" + entity[0]);
  119. updateEntityElement(entity[1], element, zIndex);
  120. zIndex -= 1;
  121. });
  122. }
  123. function drawScale() {
  124. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  125. let total = heightPer.clone();
  126. total.value = 0;
  127. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  128. drawTick(ctx, 50, y, total);
  129. total = math.add(total, heightPer);
  130. }
  131. }
  132. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  133. const oldStroke = ctx.strokeStyle;
  134. const oldFill = ctx.fillStyle;
  135. ctx.beginPath();
  136. ctx.moveTo(x, y);
  137. ctx.lineTo(x + 20, y);
  138. ctx.strokeStyle = "#000000";
  139. ctx.stroke();
  140. ctx.beginPath();
  141. ctx.moveTo(x + 20, y);
  142. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  143. ctx.strokeStyle = "#aaaaaa";
  144. ctx.stroke();
  145. ctx.beginPath();
  146. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  147. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  148. ctx.strokeStyle = "#000000";
  149. ctx.stroke();
  150. const oldFont = ctx.font;
  151. ctx.font = 'normal 24pt coda';
  152. ctx.fillStyle = "#dddddd";
  153. ctx.beginPath();
  154. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  155. ctx.font = oldFont;
  156. ctx.strokeStyle = oldStroke;
  157. ctx.fillStyle = oldFill;
  158. }
  159. const canvas = document.querySelector("#display");
  160. /** @type {CanvasRenderingContext2D} */
  161. const ctx = canvas.getContext("2d");
  162. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.value;
  163. let heightPer = config.height.clone();
  164. heightPer.value = 1;
  165. if (pixelsPer < config.minLineSize) {
  166. heightPer.value /= pixelsPer / config.minLineSize;
  167. pixelsPer = config.minLineSize;
  168. }
  169. if (pixelsPer > config.maxLineSize) {
  170. heightPer.value /= pixelsPer / config.maxLineSize;
  171. pixelsPer = config.maxLineSize;
  172. }
  173. ctx.clearRect(0, 0, canvas.width, canvas.height);
  174. ctx.scale(1, 1);
  175. ctx.canvas.width = canvas.clientWidth;
  176. ctx.canvas.height = canvas.clientHeight;
  177. ctx.beginPath();
  178. ctx.moveTo(50, 50);
  179. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  180. ctx.stroke();
  181. ctx.beginPath();
  182. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  183. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  184. ctx.stroke();
  185. drawTicks(ctx, pixelsPer, heightPer);
  186. }
  187. function makeEntity(info, views, sizes) {
  188. const entityTemplate = {
  189. name: info.name,
  190. identifier: info.name,
  191. scale: 1,
  192. info: info,
  193. views: views,
  194. sizes: sizes === undefined ? [] : sizes,
  195. init: function () {
  196. const entity = this;
  197. Object.entries(this.views).forEach(([viewKey, view]) => {
  198. view.parent = this;
  199. if (this.defaultView === undefined) {
  200. this.defaultView = viewKey;
  201. this.view = viewKey;
  202. }
  203. Object.entries(view.attributes).forEach(([key, val]) => {
  204. Object.defineProperty(
  205. view,
  206. key,
  207. {
  208. get: function () {
  209. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  210. },
  211. set: function (value) {
  212. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  213. this.parent.scale = newScale;
  214. }
  215. }
  216. )
  217. });
  218. });
  219. this.sizes.forEach(size => {
  220. if (size.default === true) {
  221. this.views[this.defaultView].height = size.height;
  222. this.size = size;
  223. }
  224. });
  225. if (this.size === undefined && this.sizes.length > 0) {
  226. this.views[this.defaultView].height = this.sizes[0].height;
  227. this.size = this.sizes[0];
  228. }
  229. this.desc = {};
  230. Object.entries(this.info).forEach(([key, value]) => {
  231. Object.defineProperty(
  232. this.desc,
  233. key,
  234. {
  235. get: function () {
  236. let text = value.text;
  237. if (entity.views[entity.view].info) {
  238. if (entity.views[entity.view].info[key]) {
  239. text = combineInfo(text, entity.views[entity.view].info[key]);
  240. }
  241. }
  242. if (entity.size.info) {
  243. if (entity.size.info[key]) {
  244. text = combineInfo(text, entity.size.info[key]);
  245. }
  246. }
  247. return { title: value.title, text: text };
  248. }
  249. }
  250. )
  251. });
  252. delete this.init;
  253. return this;
  254. }
  255. }.init();
  256. return entityTemplate;
  257. }
  258. function combineInfo(existing, next) {
  259. switch (next.mode) {
  260. case "replace":
  261. return next.text;
  262. case "prepend":
  263. return next.text + existing;
  264. case "append":
  265. return existing + next.text;
  266. }
  267. return existing;
  268. }
  269. function clickDown(target, x, y) {
  270. clicked = target;
  271. const rect = target.getBoundingClientRect();
  272. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  273. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  274. dragOffsetX = x - rect.left + entX;
  275. dragOffsetY = y - rect.top + entY;
  276. clickTimeout = setTimeout(() => { dragging = true }, 200)
  277. }
  278. // could we make this actually detect the menu area?
  279. function hoveringInDeleteArea(e) {
  280. return e.clientY < document.body.clientHeight / 10;
  281. }
  282. function clickUp(e) {
  283. clearTimeout(clickTimeout);
  284. if (clicked) {
  285. if (dragging) {
  286. dragging = false;
  287. if (hoveringInDeleteArea(e)) {
  288. removeEntity(clicked);
  289. document.querySelector("#menubar").classList.remove("hover-delete");
  290. }
  291. } else {
  292. select(clicked);
  293. }
  294. clicked = null;
  295. }
  296. }
  297. function deselect() {
  298. if (selected) {
  299. selected.classList.remove("selected");
  300. }
  301. clearAttribution();
  302. selected = null;
  303. clearViewList();
  304. clearEntityOptions();
  305. clearViewOptions();
  306. }
  307. function select(target) {
  308. deselect();
  309. selected = target;
  310. selectedEntity = entities[target.dataset.key];
  311. selected.classList.add("selected");
  312. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  313. configViewList(selectedEntity, selectedEntity.view);
  314. configEntityOptions(selectedEntity, selectedEntity.view);
  315. configViewOptions(selectedEntity, selectedEntity.view);
  316. }
  317. function configViewList(entity, selectedView) {
  318. const list = document.querySelector("#entity-view");
  319. list.innerHTML = "";
  320. list.style.display = "block";
  321. Object.keys(entity.views).forEach(view => {
  322. const option = document.createElement("option");
  323. option.innerText = entity.views[view].name;
  324. option.value = view;
  325. if (view === selectedView) {
  326. option.selected = true;
  327. }
  328. list.appendChild(option);
  329. });
  330. }
  331. function clearViewList() {
  332. const list = document.querySelector("#entity-view");
  333. list.innerHTML = "";
  334. list.style.display = "none";
  335. }
  336. function updateWorldOptions(entity, view) {
  337. const heightInput = document.querySelector("#options-height-value");
  338. const heightSelect = document.querySelector("#options-height-unit");
  339. const converted = config.height.toNumber(heightSelect.value);
  340. heightInput.value = math.round(converted, 3);
  341. }
  342. function configEntityOptions(entity, view) {
  343. const holder = document.querySelector("#options-entity");
  344. holder.innerHTML = "";
  345. const scaleLabel = document.createElement("div");
  346. scaleLabel.classList.add("options-label");
  347. scaleLabel.innerText = "Scale";
  348. const scaleRow = document.createElement("div");
  349. scaleRow.classList.add("options-row");
  350. const scaleInput = document.createElement("input");
  351. scaleInput.classList.add("options-field-numeric");
  352. scaleInput.id = "options-entity-scale";
  353. scaleInput.addEventListener("input", e => {
  354. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  355. if (config.autoFit) {
  356. fitWorld();
  357. }
  358. updateSizes();
  359. updateEntityOptions(entity, view);
  360. updateViewOptions(entity, view);
  361. });
  362. scaleInput.setAttribute("min", 1);
  363. scaleInput.setAttribute("type", "number");
  364. scaleInput.value = entity.scale;
  365. scaleRow.appendChild(scaleInput);
  366. holder.appendChild(scaleLabel);
  367. holder.appendChild(scaleRow);
  368. const nameLabel = document.createElement("div");
  369. nameLabel.classList.add("options-label");
  370. nameLabel.innerText = "Name";
  371. const nameRow = document.createElement("div");
  372. nameRow.classList.add("options-row");
  373. const nameInput = document.createElement("input");
  374. nameInput.classList.add("options-field-text");
  375. nameInput.value = entity.name;
  376. nameInput.addEventListener("input", e => {
  377. entity.name = e.target.value;
  378. updateSizes();
  379. })
  380. nameRow.appendChild(nameInput);
  381. holder.appendChild(nameLabel);
  382. holder.appendChild(nameRow);
  383. const defaultHolder = document.querySelector("#options-entity-defaults");
  384. defaultHolder.innerHTML = "";
  385. entity.sizes.forEach(defaultInfo => {
  386. const button = document.createElement("button");
  387. button.classList.add("options-button");
  388. button.innerText = defaultInfo.name;
  389. button.addEventListener("click", e => {
  390. entity.views[entity.defaultView].height = defaultInfo.height;
  391. updateEntityOptions(entity, view);
  392. updateViewOptions(entity, view);
  393. updateSizes();
  394. });
  395. defaultHolder.appendChild(button);
  396. });
  397. document.querySelector("#options-order-display").innerText = entity.priority;
  398. document.querySelector("#options-ordering").style.display = "flex";
  399. }
  400. function updateEntityOptions(entity, view) {
  401. const scaleInput = document.querySelector("#options-entity-scale");
  402. scaleInput.value = entity.scale;
  403. document.querySelector("#options-order-display").innerText = entity.priority;
  404. }
  405. function clearEntityOptions() {
  406. const holder = document.querySelector("#options-entity");
  407. holder.innerHTML = "";
  408. document.querySelector("#options-entity-defaults").innerHTML = "";
  409. document.querySelector("#options-ordering").style.display = "none";
  410. }
  411. function configViewOptions(entity, view) {
  412. const holder = document.querySelector("#options-view");
  413. holder.innerHTML = "";
  414. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  415. const label = document.createElement("div");
  416. label.classList.add("options-label");
  417. label.innerText = val.name;
  418. holder.appendChild(label);
  419. const row = document.createElement("div");
  420. row.classList.add("options-row");
  421. holder.appendChild(row);
  422. const input = document.createElement("input");
  423. input.classList.add("options-field-numeric");
  424. input.id = "options-view-" + key + "-input";
  425. input.setAttribute("type", "number");
  426. input.setAttribute("min", 1);
  427. input.value = entity.views[view][key].value;
  428. const select = document.createElement("select");
  429. select.id = "options-view-" + key + "-select"
  430. unitChoices[val.type].forEach(name => {
  431. const option = document.createElement("option");
  432. option.innerText = name;
  433. select.appendChild(option);
  434. });
  435. input.addEventListener("input", e => {
  436. const value = input.value == 0 ? 1 : input.value;
  437. entity.views[view][key] = math.unit(value, select.value);
  438. if (config.autoFit) {
  439. fitWorld();
  440. }
  441. updateSizes();
  442. updateEntityOptions(entity, view);
  443. updateViewOptions(entity, view, key);
  444. });
  445. select.setAttribute("oldUnit", select.value);
  446. select.addEventListener("input", e => {
  447. const value = input.value == 0 ? 1 : input.value;
  448. const oldUnit = select.getAttribute("oldUnit");
  449. entity.views[view][key] = math.unit(value, oldUnit).to(select.value);
  450. input.value = entity.views[view][key].toNumber(select.value);
  451. select.setAttribute("oldUnit", select.value);
  452. if (config.autoFit) {
  453. fitWorld();
  454. }
  455. updateSizes();
  456. updateEntityOptions(entity, view);
  457. updateViewOptions(entity, view, key);
  458. });
  459. row.appendChild(input);
  460. row.appendChild(select);
  461. });
  462. }
  463. function updateViewOptions(entity, view, changed) {
  464. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  465. if (key != changed) {
  466. const input = document.querySelector("#options-view-" + key + "-input");
  467. const select = document.querySelector("#options-view-" + key + "-select");
  468. const currentUnit = select.value;
  469. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  470. input.value = math.round(convertedAmount, 5);
  471. }
  472. });
  473. }
  474. function getSortedEntities() {
  475. return Object.keys(entities).sort((a, b) => {
  476. const entA = entities[a];
  477. const entB = entities[b];
  478. const viewA = entA.view;
  479. const viewB = entB.view;
  480. const heightA = entA.views[viewA].height.to("meter").value;
  481. const heightB = entB.views[viewB].height.to("meter").value;
  482. return heightA - heightB;
  483. });
  484. }
  485. function clearViewOptions() {
  486. const holder = document.querySelector("#options-view");
  487. holder.innerHTML = "";
  488. }
  489. // this is a crime against humanity, and also stolen from
  490. // stack overflow
  491. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  492. const testCanvas = document.createElement("canvas");
  493. testCanvas.id = "test-canvas";
  494. const testCtx = testCanvas.getContext("2d");
  495. function testClick(event) {
  496. // oh my god I can't believe I'm doing this
  497. const target = event.target;
  498. if (navigator.userAgent.indexOf("Firefox") != -1) {
  499. clickDown(target.parentElement, event.clientX, event.clientY);
  500. return;
  501. }
  502. // Get click coordinates
  503. let w = target.width;
  504. let h = target.height;
  505. let ratioW = 1, ratioH = 1;
  506. // Limit the size of the canvas so that very large images don't cause problems)
  507. if (w > 1000) {
  508. ratioW = w / 1000;
  509. w /= ratioW;
  510. h /= ratioW;
  511. }
  512. if (h > 1000) {
  513. ratioH = h / 1000;
  514. w /= ratioH;
  515. h /= ratioH;
  516. }
  517. const ratio = ratioW * ratioH;
  518. var x = event.clientX - target.getBoundingClientRect().x,
  519. y = event.clientY - target.getBoundingClientRect().y,
  520. alpha;
  521. testCtx.canvas.width = w;
  522. testCtx.canvas.height = h;
  523. // Draw image to canvas
  524. // and read Alpha channel value
  525. testCtx.drawImage(target, 0, 0, w, h);
  526. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  527. // If pixel is transparent,
  528. // retrieve the element underneath and trigger it's click event
  529. if (alpha === 0) {
  530. const oldDisplay = target.style.display;
  531. target.style.display = "none";
  532. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  533. newTarget.dispatchEvent(new MouseEvent(event.type, {
  534. "clientX": event.clientX,
  535. "clientY": event.clientY
  536. }));
  537. target.style.display = oldDisplay;
  538. } else {
  539. clickDown(target.parentElement, event.clientX, event.clientY);
  540. }
  541. }
  542. function arrangeEntities(order) {
  543. let x = 0.1;
  544. order.forEach(key => {
  545. document.querySelector("#entity-" + key).dataset.x = x;
  546. x += 0.8 / (order.length - 1);
  547. });
  548. updateSizes();
  549. }
  550. function removeAllEntities() {
  551. Object.keys(entities).forEach(key => {
  552. removeEntity(document.querySelector("#entity-" + key));
  553. });
  554. }
  555. function clearAttribution() {
  556. document.querySelector("#options-attribution").style.display = "none";
  557. }
  558. function displayAttribution(file) {
  559. document.querySelector("#options-attribution").style.display = "inline";
  560. const authors = authorsOfFull(file);
  561. const owners = ownersOfFull(file);
  562. const source = sourceOf(file);
  563. const authorHolder = document.querySelector("#options-attribution-authors");
  564. const ownerHolder = document.querySelector("#options-attribution-owners");
  565. const sourceHolder = document.querySelector("#options-attribution-source");
  566. if (authors === []) {
  567. const div = document.createElement("div");
  568. div.innerText = "Unknown";
  569. authorHolder.innerHTML = "";
  570. authorHolder.appendChild(div);
  571. } else if (authors === undefined) {
  572. const div = document.createElement("div");
  573. div.innerText = "Not yet entered";
  574. authorHolder.innerHTML = "";
  575. authorHolder.appendChild(div);
  576. } else {
  577. authorHolder.innerHTML = "";
  578. const list = document.createElement("ul");
  579. authorHolder.appendChild(list);
  580. authors.forEach(author => {
  581. const authorEntry = document.createElement("li");
  582. const link = document.createElement("a");
  583. link.href = author.url;
  584. link.innerText = author.name;
  585. authorEntry.appendChild(link);
  586. list.appendChild(authorEntry);
  587. });
  588. }
  589. if (owners === []) {
  590. const div = document.createElement("div");
  591. div.innerText = "Unknown";
  592. ownerHolder.innerHTML = "";
  593. ownerHolder.appendChild(div);
  594. } else if (owners === undefined) {
  595. const div = document.createElement("div");
  596. div.innerText = "Not yet entered";
  597. ownerHolder.innerHTML = "";
  598. ownerHolder.appendChild(div);
  599. } else {
  600. ownerHolder.innerHTML = "";
  601. const list = document.createElement("ul");
  602. ownerHolder.appendChild(list);
  603. owners.forEach(owner => {
  604. const ownerEntry = document.createElement("li");
  605. const link = document.createElement("a");
  606. link.href = owner.url;
  607. link.innerText = owner.name;
  608. ownerEntry.appendChild(link);
  609. list.appendChild(ownerEntry);
  610. });
  611. }
  612. if (source === null) {
  613. const div = document.createElement("div");
  614. div.innerText = "No link";
  615. sourceHolder.innerHTML = "";
  616. sourceHolder.appendChild(div);
  617. } else if (source === undefined) {
  618. const div = document.createElement("div");
  619. div.innerText = "Not yet entered";
  620. sourceHolder.innerHTML = "";
  621. sourceHolder.appendChild(div);
  622. } else {
  623. sourceHolder.innerHTML = "";
  624. const link = document.createElement("a");
  625. link.style.display = "block";
  626. link.href = source;
  627. link.innerText = new URL(source).host;
  628. sourceHolder.appendChild(link);
  629. }
  630. }
  631. function removeEntity(element) {
  632. if (selected == element) {
  633. deselect();
  634. }
  635. delete entities[element.dataset.key];
  636. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  637. bottomName.parentElement.removeChild(bottomName);
  638. element.parentElement.removeChild(element);
  639. }
  640. function displayEntity(entity, view, x, y) {
  641. const box = document.createElement("div");
  642. box.classList.add("entity-box");
  643. const img = document.createElement("img");
  644. img.classList.add("entity-image");
  645. img.addEventListener("dragstart", e => {
  646. e.preventDefault();
  647. });
  648. const nameTag = document.createElement("div");
  649. nameTag.classList.add("entity-name");
  650. nameTag.innerText = entity.name;
  651. box.appendChild(img);
  652. box.appendChild(nameTag);
  653. const image = entity.views[view].image;
  654. img.src = image.source;
  655. displayAttribution(image.source);
  656. if (image.bottom !== undefined) {
  657. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  658. } else {
  659. img.style.setProperty("--offset", ((-1) * 100) + "%")
  660. }
  661. box.dataset.x = x;
  662. box.dataset.y = y;
  663. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  664. img.addEventListener("touchstart", e => {
  665. const fakeEvent = {
  666. target: e.target,
  667. clientX: e.touches[0].clientX,
  668. clientY: e.touches[0].clientY
  669. };
  670. testClick(fakeEvent);
  671. });
  672. box.id = "entity-" + entityIndex;
  673. box.dataset.key = entityIndex;
  674. entity.view = view;
  675. entity.priority = 0;
  676. entities[entityIndex] = entity;
  677. entity.index = entityIndex;
  678. const world = document.querySelector("#entities");
  679. world.appendChild(box);
  680. const bottomName = document.createElement("div");
  681. bottomName.classList.add("bottom-name");
  682. bottomName.id = "bottom-name-" + entityIndex;
  683. bottomName.innerText = entity.name;
  684. bottomName.addEventListener("click", () => select(box));
  685. world.appendChild(bottomName);
  686. entityIndex += 1;
  687. updateEntityElement(entity, box);
  688. if (config.autoFit) {
  689. fitWorld();
  690. }
  691. select(box);
  692. }
  693. window.onblur = function () {
  694. altHeld = false;
  695. shiftHeld = false;
  696. }
  697. window.onfocus = function () {
  698. window.dispatchEvent(new Event("keydown"));
  699. }
  700. function doSliderScale() {
  701. setWorldHeight(config.height, math.multiply(config.height, (9 + sliderScale) / 10));
  702. }
  703. function doSliderEntityScale() {
  704. if (selected) {
  705. const entity = entities[selected.dataset.key];
  706. entity.scale *= (9 + sliderEntityScale) / 10;
  707. updateSizes();
  708. updateEntityOptions(entity, entity.view);
  709. updateViewOptions(entity, entity.view);
  710. }
  711. }
  712. document.addEventListener("DOMContentLoaded", () => {
  713. prepareEntities();
  714. document.querySelector("#options-order-forward").addEventListener("click", e => {
  715. if (selected) {
  716. entities[selected.dataset.key].priority += 1;
  717. }
  718. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  719. updateSizes();
  720. });
  721. document.querySelector("#options-order-back").addEventListener("click", e => {
  722. if (selected) {
  723. entities[selected.dataset.key].priority -= 1;
  724. }
  725. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  726. updateSizes();
  727. });
  728. document.querySelector("#slider-scale").addEventListener("mousedown", e => {
  729. dragScaleHandle = setInterval(doSliderScale, 50);
  730. e.stopPropagation();
  731. });
  732. document.querySelector("#slider-scale").addEventListener("touchstart", e => {
  733. dragScaleHandle = setInterval(doSliderScale, 50);
  734. e.stopPropagation();
  735. });
  736. document.querySelector("#slider-scale").addEventListener("input", e => {
  737. const val = Number(e.target.value);
  738. if (val < 1) {
  739. sliderScale = (val + 1) / 2;
  740. } else {
  741. sliderScale = val;
  742. }
  743. });
  744. document.querySelector("#slider-scale").addEventListener("change", e => {
  745. clearInterval(dragScaleHandle);
  746. dragScaleHandle = null;
  747. e.target.value = 1;
  748. });
  749. document.querySelector("#slider-entity-scale").addEventListener("mousedown", e => {
  750. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  751. e.stopPropagation();
  752. });
  753. document.querySelector("#slider-entity-scale").addEventListener("touchstart", e => {
  754. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  755. e.stopPropagation();
  756. });
  757. document.querySelector("#slider-entity-scale").addEventListener("input", e => {
  758. const val = Number(e.target.value);
  759. if (val < 1) {
  760. sliderEntityScale = (val + 1) / 2;
  761. } else {
  762. sliderEntityScale = val;
  763. }
  764. });
  765. document.querySelector("#slider-entity-scale").addEventListener("change", e => {
  766. clearInterval(dragEntityScaleHandle);
  767. dragEntityScaleHandle = null;
  768. e.target.value = 1;
  769. });
  770. const sceneChoices = document.querySelector("#scene-choices");
  771. Object.entries(scenes).forEach(([id, scene]) => {
  772. const option = document.createElement("option");
  773. option.innerText = id;
  774. option.value = id;
  775. sceneChoices.appendChild(option);
  776. });
  777. document.querySelector("#load-scene").addEventListener("click", e => {
  778. const chosen = sceneChoices.value;
  779. removeAllEntities();
  780. scenes[chosen]();
  781. });
  782. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  783. canvasWidth = document.querySelector("#display").clientWidth - 100;
  784. canvasHeight = document.querySelector("#display").clientHeight - 50;
  785. document.querySelector("#open-help").addEventListener("click", e => {
  786. document.querySelector("#help").classList.add("visible");
  787. });
  788. document.querySelector("#close-help").addEventListener("click", e => {
  789. document.querySelector("#help").classList.remove("visible");
  790. });
  791. const unitSelector = document.querySelector("#options-height-unit");
  792. unitChoices.length.forEach(lengthOption => {
  793. const option = document.createElement("option");
  794. option.innerText = lengthOption;
  795. option.value = lengthOption;
  796. if (lengthOption === "meters") {
  797. option.selected = true;
  798. }
  799. unitSelector.appendChild(option);
  800. });
  801. param = new URL(window.location.href).searchParams.get("scene");
  802. if (param === null)
  803. scenes["Demo"]();
  804. else {
  805. try {
  806. const data = JSON.parse(b64DecodeUnicode(param));
  807. if (data.entities === undefined) {
  808. return;
  809. }
  810. if (data.world === undefined) {
  811. return;
  812. }
  813. importScene(data);
  814. } catch (err) {
  815. console.error(err);
  816. scenes["Demo"]();
  817. // probably wasn't valid data
  818. }
  819. }
  820. fitWorld();
  821. document.querySelector("#world").addEventListener("wheel", e => {
  822. if (shiftHeld) {
  823. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  824. if (selected) {
  825. const entity = entities[selected.dataset.key];
  826. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  827. updateEntityOptions(entity, entity.view);
  828. updateViewOptions(entity, entity.view);
  829. updateSizes();
  830. }
  831. } else {
  832. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  833. setWorldHeight(config.height, math.multiply(config.height, dir));
  834. updateWorldOptions();
  835. }
  836. checkFitWorld();
  837. })
  838. document.querySelector("body").appendChild(testCtx.canvas);
  839. updateSizes();
  840. document.querySelector("#options-height-value").addEventListener("input", e => {
  841. updateWorldHeight();
  842. })
  843. unitSelector.addEventListener("input", e => {
  844. checkFitWorld();
  845. updateWorldHeight();
  846. })
  847. world.addEventListener("mousedown", e => deselect());
  848. document.querySelector("#display").addEventListener("mousedown", deselect);
  849. document.addEventListener("mouseup", e => clickUp(e));
  850. document.addEventListener("touchend", e => {
  851. const fakeEvent = {
  852. target: e.target,
  853. clientX: e.changedTouches[0].clientX,
  854. clientY: e.changedTouches[0].clientY
  855. };
  856. clickUp(fakeEvent);
  857. });
  858. document.querySelector("#entity-view").addEventListener("input", e => {
  859. const entity = entities[selected.dataset.key];
  860. entity.view = e.target.value;
  861. const image = entities[selected.dataset.key].views[e.target.value].image;
  862. selected.querySelector(".entity-image").src = image.source;
  863. displayAttribution(image.source);
  864. if (image.bottom !== undefined) {
  865. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  866. } else {
  867. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  868. }
  869. updateSizes();
  870. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  871. updateViewOptions(entities[selected.dataset.key], e.target.value);
  872. });
  873. clearViewList();
  874. document.querySelector("#menu-clear").addEventListener("click", e => {
  875. removeAllEntities();
  876. });
  877. document.querySelector("#menu-order-height").addEventListener("click", e => {
  878. const order = Object.keys(entities).sort((a, b) => {
  879. const entA = entities[a];
  880. const entB = entities[b];
  881. const viewA = entA.view;
  882. const viewB = entB.view;
  883. const heightA = entA.views[viewA].height.to("meter").value;
  884. const heightB = entB.views[viewB].height.to("meter").value;
  885. return heightA - heightB;
  886. });
  887. arrangeEntities(order);
  888. });
  889. document.querySelector("#options-world-fit").addEventListener("click", fitWorld);
  890. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  891. config.autoFit = e.target.checked;
  892. if (config.autoFit) {
  893. fitWorld();
  894. }
  895. });
  896. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  897. config.autoFitMode = e.target.value;
  898. if (config.autoFit) {
  899. fitWorld();
  900. }
  901. })
  902. document.addEventListener("keydown", e => {
  903. if (e.key == "Delete") {
  904. if (selected) {
  905. removeEntity(selected);
  906. selected = null;
  907. }
  908. }
  909. })
  910. document.addEventListener("keydown", e => {
  911. if (e.key == "Shift") {
  912. shiftHeld = true;
  913. e.preventDefault();
  914. } else if (e.key == "Alt") {
  915. altHeld = true;
  916. e.preventDefault();
  917. }
  918. });
  919. document.addEventListener("keyup", e => {
  920. if (e.key == "Shift") {
  921. shiftHeld = false;
  922. e.preventDefault();
  923. } else if (e.key == "Alt") {
  924. altHeld = false;
  925. e.preventDefault();
  926. }
  927. });
  928. document.addEventListener("paste", e => {
  929. try {
  930. const data = JSON.parse(e.clipboardData.getData("text"));
  931. if (data.entities === undefined) {
  932. return;
  933. }
  934. if (data.world === undefined) {
  935. return;
  936. }
  937. importScene(data);
  938. } catch (err) {
  939. console.error(err);
  940. // probably wasn't valid data
  941. }
  942. });
  943. document.querySelector("#menu-permalink").addEventListener("click", e => {
  944. linkScene();
  945. });
  946. document.querySelector("#menu-export").addEventListener("click", e => {
  947. copyScene();
  948. });
  949. document.querySelector("#menu-save").addEventListener("click", e => {
  950. saveScene();
  951. });
  952. document.querySelector("#menu-load").addEventListener("click", e => {
  953. loadScene();
  954. });
  955. });
  956. function prepareEntities() {
  957. availableEntities["buildings"] = makeBuildings();
  958. availableEntities["landmarks"] = makeLandmarks();
  959. availableEntities["characters"] = makeCharacters();
  960. availableEntities["objects"] = makeObjects();
  961. availableEntities["naturals"] = makeNaturals();
  962. availableEntities["vehicles"] = makeVehicles();
  963. availableEntities["cities"] = makeCities();
  964. availableEntities["pokemon"] = makePokemon();
  965. availableEntities["characters"].sort((x, y) => {
  966. return x.name < y.name ? -1 : 1
  967. });
  968. const holder = document.querySelector("#spawners");
  969. const categorySelect = document.createElement("select");
  970. categorySelect.id = "category-picker";
  971. holder.appendChild(categorySelect);
  972. Object.entries(availableEntities).forEach(([category, entityList]) => {
  973. const select = document.createElement("select");
  974. select.id = "create-entity-" + category;
  975. for (let i = 0; i < entityList.length; i++) {
  976. const entity = entityList[i];
  977. const option = document.createElement("option");
  978. option.value = i;
  979. option.innerText = entity.name;
  980. select.appendChild(option);
  981. availableEntitiesByName[entity.name] = entity;
  982. };
  983. const button = document.createElement("button");
  984. button.id = "create-entity-" + category + "-button";
  985. button.innerText = "Create";
  986. button.addEventListener("click", e => {
  987. const newEntity = entityList[select.value].constructor()
  988. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  989. });
  990. const categoryOption = document.createElement("option");
  991. categoryOption.value = category
  992. categoryOption.innerText = category;
  993. if (category == "characters") {
  994. categoryOption.selected = true;
  995. select.classList.add("category-visible");
  996. button.classList.add("category-visible");
  997. }
  998. categorySelect.appendChild(categoryOption);
  999. holder.appendChild(select);
  1000. holder.appendChild(button);
  1001. });
  1002. categorySelect.addEventListener("input", e => {
  1003. const oldSelect = document.querySelector("select.category-visible");
  1004. oldSelect.classList.remove("category-visible");
  1005. const oldButton = document.querySelector("button.category-visible");
  1006. oldButton.classList.remove("category-visible");
  1007. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1008. newSelect.classList.add("category-visible");
  1009. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1010. newButton.classList.add("category-visible");
  1011. });
  1012. }
  1013. window.addEventListener("resize", () => {
  1014. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1015. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1016. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1017. updateSizes();
  1018. })
  1019. document.addEventListener("mousemove", (e) => {
  1020. if (clicked) {
  1021. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1022. clicked.dataset.x = position.x;
  1023. clicked.dataset.y = position.y;
  1024. updateEntityElement(entities[clicked.dataset.key], clicked);
  1025. if (hoveringInDeleteArea(e)) {
  1026. document.querySelector("#menubar").classList.add("hover-delete");
  1027. } else {
  1028. document.querySelector("#menubar").classList.remove("hover-delete");
  1029. }
  1030. }
  1031. });
  1032. document.addEventListener("touchmove", (e) => {
  1033. if (clicked) {
  1034. e.preventDefault();
  1035. let x = e.touches[0].clientX;
  1036. let y = e.touches[0].clientY;
  1037. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1038. clicked.dataset.x = position.x;
  1039. clicked.dataset.y = position.y;
  1040. updateEntityElement(entities[clicked.dataset.key], clicked);
  1041. // what a hack
  1042. // I should centralize this 'fake event' creation...
  1043. if (hoveringInDeleteArea({ clientY: y })) {
  1044. document.querySelector("#menubar").classList.add("hover-delete");
  1045. } else {
  1046. document.querySelector("#menubar").classList.remove("hover-delete");
  1047. }
  1048. }
  1049. }, { passive: false });
  1050. function checkFitWorld() {
  1051. if (config.autoFit) {
  1052. fitWorld();
  1053. }
  1054. }
  1055. const fitModes = {
  1056. "max": {
  1057. start: 0,
  1058. binop: math.max,
  1059. final: (total, count) => total
  1060. },
  1061. "arithmetic mean": {
  1062. start: 0,
  1063. binop: math.add,
  1064. final: (total, count) => total / count
  1065. },
  1066. "geometric mean": {
  1067. start: 1,
  1068. binop: math.multiply,
  1069. final: (total, count) => math.pow(total, 1 / count)
  1070. }
  1071. }
  1072. function fitWorld() {
  1073. const fitMode = fitModes[config.autoFitMode]
  1074. let max = fitMode.start
  1075. let count = 0;
  1076. Object.entries(entities).forEach(([key, entity]) => {
  1077. const view = entity.view;
  1078. max = fitMode.binop(max, entity.views[view].height.toNumber("meter"));
  1079. count += 1;
  1080. });
  1081. max = fitMode.final(max, count)
  1082. max = math.unit(max, "meter")
  1083. setWorldHeight(config.height, math.multiply(max, 1.1));
  1084. }
  1085. function updateWorldHeight() {
  1086. const unit = document.querySelector("#options-height-unit").value;
  1087. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1088. const oldHeight = config.height;
  1089. setWorldHeight(oldHeight, math.unit(value, unit));
  1090. }
  1091. function setWorldHeight(oldHeight, newHeight) {
  1092. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1093. const unit = document.querySelector("#options-height-unit").value;
  1094. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  1095. Object.entries(entities).forEach(([key, entity]) => {
  1096. const element = document.querySelector("#entity-" + key);
  1097. let newPosition;
  1098. if (!altHeld) {
  1099. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1100. } else {
  1101. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1102. }
  1103. element.dataset.x = newPosition.x;
  1104. element.dataset.y = newPosition.y;
  1105. });
  1106. updateSizes();
  1107. }
  1108. function loadScene() {
  1109. try {
  1110. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  1111. importScene(data);
  1112. } catch (err) {
  1113. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1114. console.error(err);
  1115. }
  1116. }
  1117. function saveScene() {
  1118. try {
  1119. const string = JSON.stringify(exportScene());
  1120. localStorage.setItem("macrovision-save", string);
  1121. } catch (err) {
  1122. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1123. console.error(err);
  1124. }
  1125. }
  1126. function exportScene() {
  1127. const results = {};
  1128. results.entities = [];
  1129. Object.entries(entities).forEach(([key, entity]) => {
  1130. const element = document.querySelector("#entity-" + key);
  1131. results.entities.push({
  1132. name: entity.identifier,
  1133. scale: entity.scale,
  1134. view: entity.view,
  1135. x: element.dataset.x,
  1136. y: element.dataset.y
  1137. });
  1138. });
  1139. const unit = document.querySelector("#options-height-unit").value;
  1140. results.world = {
  1141. height: config.height.toNumber(unit),
  1142. unit: unit
  1143. }
  1144. return results;
  1145. }
  1146. // btoa doesn't like anything that isn't ASCII
  1147. // great
  1148. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1149. // for providing an alternative
  1150. function b64EncodeUnicode(str) {
  1151. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1152. // then we convert the percent encodings into raw bytes which
  1153. // can be fed into btoa.
  1154. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1155. function toSolidBytes(match, p1) {
  1156. return String.fromCharCode('0x' + p1);
  1157. }));
  1158. }
  1159. function b64DecodeUnicode(str) {
  1160. // Going backwards: from bytestream, to percent-encoding, to original string.
  1161. return decodeURIComponent(atob(str).split('').map(function(c) {
  1162. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1163. }).join(''));
  1164. }
  1165. function linkScene() {
  1166. loc = new URL(window.location);
  1167. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1168. }
  1169. function copyScene() {
  1170. const results = exportScene();
  1171. navigator.clipboard.writeText(JSON.stringify(results))
  1172. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1173. }
  1174. // TODO - don't just search through every single entity
  1175. // probably just have a way to do lookups directly
  1176. function findEntity(name) {
  1177. return availableEntitiesByName[name];
  1178. }
  1179. function importScene(data) {
  1180. removeAllEntities();
  1181. data.entities.forEach(entityInfo => {
  1182. const entity = findEntity(entityInfo.name).constructor();
  1183. entity.scale = entityInfo.scale
  1184. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1185. });
  1186. config.height = math.unit(data.world.height, data.world.unit);
  1187. document.querySelector("#options-height-unit").value = data.world.unit;
  1188. updateSizes();
  1189. }