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

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