less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

1535 lignes
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. box.id = "entity-" + entityIndex;
  705. box.dataset.key = entityIndex;
  706. entity.view = view;
  707. entity.priority = 0;
  708. entities[entityIndex] = entity;
  709. entity.index = entityIndex;
  710. const world = document.querySelector("#entities");
  711. world.appendChild(box);
  712. const bottomName = document.createElement("div");
  713. bottomName.classList.add("bottom-name");
  714. bottomName.id = "bottom-name-" + entityIndex;
  715. bottomName.innerText = entity.name;
  716. bottomName.addEventListener("click", () => select(box));
  717. world.appendChild(bottomName);
  718. entityIndex += 1;
  719. updateEntityElement(entity, box);
  720. if (config.autoFit) {
  721. fitWorld();
  722. }
  723. select(box);
  724. }
  725. window.onblur = function () {
  726. altHeld = false;
  727. shiftHeld = false;
  728. }
  729. window.onfocus = function () {
  730. window.dispatchEvent(new Event("keydown"));
  731. }
  732. function doSliderScale() {
  733. setWorldHeight(config.height, math.multiply(config.height, (9 + sliderScale) / 10));
  734. }
  735. function doSliderEntityScale() {
  736. if (selected) {
  737. const entity = entities[selected.dataset.key];
  738. entity.scale *= (9 + sliderEntityScale) / 10;
  739. updateSizes();
  740. updateEntityOptions(entity, entity.view);
  741. updateViewOptions(entity, entity.view);
  742. }
  743. }
  744. document.addEventListener("DOMContentLoaded", () => {
  745. prepareEntities();
  746. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  747. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  748. });
  749. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  750. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  751. });
  752. document.querySelector("#options-order-forward").addEventListener("click", e => {
  753. if (selected) {
  754. entities[selected.dataset.key].priority += 1;
  755. }
  756. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  757. updateSizes();
  758. });
  759. document.querySelector("#options-order-back").addEventListener("click", e => {
  760. if (selected) {
  761. entities[selected.dataset.key].priority -= 1;
  762. }
  763. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  764. updateSizes();
  765. });
  766. document.querySelector("#slider-scale").addEventListener("mousedown", e => {
  767. dragScaleHandle = setInterval(doSliderScale, 50);
  768. e.stopPropagation();
  769. });
  770. document.querySelector("#slider-scale").addEventListener("touchstart", e => {
  771. dragScaleHandle = setInterval(doSliderScale, 50);
  772. e.stopPropagation();
  773. });
  774. document.querySelector("#slider-scale").addEventListener("input", e => {
  775. const val = Number(e.target.value);
  776. if (val < 1) {
  777. sliderScale = (val + 1) / 2;
  778. } else {
  779. sliderScale = val;
  780. }
  781. });
  782. document.querySelector("#slider-scale").addEventListener("change", e => {
  783. clearInterval(dragScaleHandle);
  784. dragScaleHandle = null;
  785. e.target.value = 1;
  786. });
  787. document.querySelector("#slider-entity-scale").addEventListener("mousedown", e => {
  788. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  789. e.stopPropagation();
  790. });
  791. document.querySelector("#slider-entity-scale").addEventListener("touchstart", e => {
  792. dragEntityScaleHandle = setInterval(doSliderEntityScale, 50);
  793. e.stopPropagation();
  794. });
  795. document.querySelector("#slider-entity-scale").addEventListener("input", e => {
  796. const val = Number(e.target.value);
  797. if (val < 1) {
  798. sliderEntityScale = (val + 1) / 2;
  799. } else {
  800. sliderEntityScale = val;
  801. }
  802. });
  803. document.querySelector("#slider-entity-scale").addEventListener("change", e => {
  804. clearInterval(dragEntityScaleHandle);
  805. dragEntityScaleHandle = null;
  806. e.target.value = 1;
  807. });
  808. const sceneChoices = document.querySelector("#scene-choices");
  809. Object.entries(scenes).forEach(([id, scene]) => {
  810. const option = document.createElement("option");
  811. option.innerText = id;
  812. option.value = id;
  813. sceneChoices.appendChild(option);
  814. });
  815. document.querySelector("#load-scene").addEventListener("click", e => {
  816. const chosen = sceneChoices.value;
  817. removeAllEntities();
  818. scenes[chosen]();
  819. });
  820. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  821. canvasWidth = document.querySelector("#display").clientWidth - 100;
  822. canvasHeight = document.querySelector("#display").clientHeight - 50;
  823. document.querySelector("#open-help").addEventListener("click", e => {
  824. document.querySelector("#help").classList.add("visible");
  825. });
  826. document.querySelector("#close-help").addEventListener("click", e => {
  827. document.querySelector("#help").classList.remove("visible");
  828. });
  829. const unitSelector = document.querySelector("#options-height-unit");
  830. unitChoices.length.forEach(lengthOption => {
  831. const option = document.createElement("option");
  832. option.innerText = lengthOption;
  833. option.value = lengthOption;
  834. if (lengthOption === "meters") {
  835. option.selected = true;
  836. }
  837. unitSelector.appendChild(option);
  838. });
  839. param = new URL(window.location.href).searchParams.get("scene");
  840. if (param === null)
  841. scenes["Demo"]();
  842. else {
  843. try {
  844. const data = JSON.parse(b64DecodeUnicode(param));
  845. if (data.entities === undefined) {
  846. return;
  847. }
  848. if (data.world === undefined) {
  849. return;
  850. }
  851. importScene(data);
  852. } catch (err) {
  853. console.error(err);
  854. scenes["Demo"]();
  855. // probably wasn't valid data
  856. }
  857. }
  858. fitWorld();
  859. document.querySelector("#world").addEventListener("wheel", e => {
  860. if (shiftHeld) {
  861. const dir = e.deltaY > 0 ? 0.9 : 1.1;
  862. if (selected) {
  863. const entity = entities[selected.dataset.key];
  864. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  865. updateEntityOptions(entity, entity.view);
  866. updateViewOptions(entity, entity.view);
  867. updateSizes();
  868. }
  869. } else {
  870. const dir = e.deltaY < 0 ? 0.9 : 1.1;
  871. setWorldHeight(config.height, math.multiply(config.height, dir));
  872. updateWorldOptions();
  873. }
  874. checkFitWorld();
  875. })
  876. document.querySelector("body").appendChild(testCtx.canvas);
  877. updateSizes();
  878. document.querySelector("#options-height-value").addEventListener("input", e => {
  879. updateWorldHeight();
  880. })
  881. unitSelector.addEventListener("input", e => {
  882. checkFitWorld();
  883. updateWorldHeight();
  884. })
  885. world.addEventListener("mousedown", e => deselect());
  886. document.querySelector("#display").addEventListener("mousedown", deselect);
  887. document.addEventListener("mouseup", e => clickUp(e));
  888. document.addEventListener("touchend", e => {
  889. const fakeEvent = {
  890. target: e.target,
  891. clientX: e.changedTouches[0].clientX,
  892. clientY: e.changedTouches[0].clientY
  893. };
  894. clickUp(fakeEvent);
  895. });
  896. document.querySelector("#entity-view").addEventListener("input", e => {
  897. const entity = entities[selected.dataset.key];
  898. entity.view = e.target.value;
  899. const image = entities[selected.dataset.key].views[e.target.value].image;
  900. selected.querySelector(".entity-image").src = image.source;
  901. displayAttribution(image.source);
  902. if (image.bottom !== undefined) {
  903. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  904. } else {
  905. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  906. }
  907. updateSizes();
  908. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  909. updateViewOptions(entities[selected.dataset.key], e.target.value);
  910. });
  911. clearViewList();
  912. document.querySelector("#menu-clear").addEventListener("click", e => {
  913. removeAllEntities();
  914. });
  915. document.querySelector("#menu-order-height").addEventListener("click", e => {
  916. const order = Object.keys(entities).sort((a, b) => {
  917. const entA = entities[a];
  918. const entB = entities[b];
  919. const viewA = entA.view;
  920. const viewB = entB.view;
  921. const heightA = entA.views[viewA].height.to("meter").value;
  922. const heightB = entB.views[viewB].height.to("meter").value;
  923. return heightA - heightB;
  924. });
  925. arrangeEntities(order);
  926. });
  927. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  928. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  929. config.autoFit = e.target.checked;
  930. if (config.autoFit) {
  931. fitWorld();
  932. }
  933. });
  934. document.querySelector("#options-world-autofit-mode").addEventListener("input", e => {
  935. config.autoFitMode = e.target.value;
  936. if (config.autoFit) {
  937. fitWorld();
  938. }
  939. })
  940. document.addEventListener("keydown", e => {
  941. if (e.key == "Delete") {
  942. if (selected) {
  943. removeEntity(selected);
  944. selected = null;
  945. }
  946. }
  947. })
  948. document.addEventListener("keydown", e => {
  949. if (e.key == "Shift") {
  950. shiftHeld = true;
  951. e.preventDefault();
  952. } else if (e.key == "Alt") {
  953. altHeld = true;
  954. e.preventDefault();
  955. }
  956. });
  957. document.addEventListener("keyup", e => {
  958. if (e.key == "Shift") {
  959. shiftHeld = false;
  960. e.preventDefault();
  961. } else if (e.key == "Alt") {
  962. altHeld = false;
  963. e.preventDefault();
  964. }
  965. });
  966. document.addEventListener("paste", e => {
  967. try {
  968. const data = JSON.parse(e.clipboardData.getData("text"));
  969. if (data.entities === undefined) {
  970. return;
  971. }
  972. if (data.world === undefined) {
  973. return;
  974. }
  975. importScene(data);
  976. } catch (err) {
  977. console.error(err);
  978. // probably wasn't valid data
  979. }
  980. });
  981. document.querySelector("#menu-permalink").addEventListener("click", e => {
  982. linkScene();
  983. });
  984. document.querySelector("#menu-export").addEventListener("click", e => {
  985. copyScene();
  986. });
  987. document.querySelector("#menu-save").addEventListener("click", e => {
  988. saveScene();
  989. });
  990. document.querySelector("#menu-load").addEventListener("click", e => {
  991. loadScene();
  992. });
  993. });
  994. function prepareEntities() {
  995. availableEntities["buildings"] = makeBuildings();
  996. availableEntities["landmarks"] = makeLandmarks();
  997. availableEntities["characters"] = makeCharacters();
  998. availableEntities["objects"] = makeObjects();
  999. availableEntities["naturals"] = makeNaturals();
  1000. availableEntities["vehicles"] = makeVehicles();
  1001. availableEntities["cities"] = makeCities();
  1002. availableEntities["pokemon"] = makePokemon();
  1003. availableEntities["characters"].sort((x, y) => {
  1004. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1005. });
  1006. const holder = document.querySelector("#spawners");
  1007. const categorySelect = document.createElement("select");
  1008. categorySelect.id = "category-picker";
  1009. holder.appendChild(categorySelect);
  1010. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1011. const select = document.createElement("select");
  1012. select.id = "create-entity-" + category;
  1013. for (let i = 0; i < entityList.length; i++) {
  1014. const entity = entityList[i];
  1015. const option = document.createElement("option");
  1016. option.value = i;
  1017. option.innerText = entity.name;
  1018. select.appendChild(option);
  1019. availableEntitiesByName[entity.name] = entity;
  1020. };
  1021. const button = document.createElement("button");
  1022. button.id = "create-entity-" + category + "-button";
  1023. button.innerText = "Create";
  1024. button.addEventListener("click", e => {
  1025. const newEntity = entityList[select.value].constructor()
  1026. displayEntity(newEntity, newEntity.defaultView, 0.5, 1);
  1027. });
  1028. const categoryOption = document.createElement("option");
  1029. categoryOption.value = category
  1030. categoryOption.innerText = category;
  1031. if (category == "characters") {
  1032. categoryOption.selected = true;
  1033. select.classList.add("category-visible");
  1034. button.classList.add("category-visible");
  1035. }
  1036. categorySelect.appendChild(categoryOption);
  1037. holder.appendChild(select);
  1038. holder.appendChild(button);
  1039. });
  1040. categorySelect.addEventListener("input", e => {
  1041. const oldSelect = document.querySelector("select.category-visible");
  1042. oldSelect.classList.remove("category-visible");
  1043. const oldButton = document.querySelector("button.category-visible");
  1044. oldButton.classList.remove("category-visible");
  1045. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1046. newSelect.classList.add("category-visible");
  1047. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1048. newButton.classList.add("category-visible");
  1049. });
  1050. }
  1051. window.addEventListener("resize", () => {
  1052. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1053. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1054. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1055. updateSizes();
  1056. })
  1057. document.addEventListener("mousemove", (e) => {
  1058. if (clicked) {
  1059. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1060. clicked.dataset.x = position.x;
  1061. clicked.dataset.y = position.y;
  1062. updateEntityElement(entities[clicked.dataset.key], clicked);
  1063. if (hoveringInDeleteArea(e)) {
  1064. document.querySelector("#menubar").classList.add("hover-delete");
  1065. } else {
  1066. document.querySelector("#menubar").classList.remove("hover-delete");
  1067. }
  1068. }
  1069. });
  1070. document.addEventListener("touchmove", (e) => {
  1071. if (clicked) {
  1072. e.preventDefault();
  1073. let x = e.touches[0].clientX;
  1074. let y = e.touches[0].clientY;
  1075. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1076. clicked.dataset.x = position.x;
  1077. clicked.dataset.y = position.y;
  1078. updateEntityElement(entities[clicked.dataset.key], clicked);
  1079. // what a hack
  1080. // I should centralize this 'fake event' creation...
  1081. if (hoveringInDeleteArea({ clientY: y })) {
  1082. document.querySelector("#menubar").classList.add("hover-delete");
  1083. } else {
  1084. document.querySelector("#menubar").classList.remove("hover-delete");
  1085. }
  1086. }
  1087. }, { passive: false });
  1088. function checkFitWorld() {
  1089. if (config.autoFit) {
  1090. fitWorld();
  1091. }
  1092. }
  1093. const fitModes = {
  1094. "max": {
  1095. start: 0,
  1096. binop: math.max,
  1097. final: (total, count) => total
  1098. },
  1099. "arithmetic mean": {
  1100. start: 0,
  1101. binop: math.add,
  1102. final: (total, count) => total / count
  1103. },
  1104. "geometric mean": {
  1105. start: 1,
  1106. binop: math.multiply,
  1107. final: (total, count) => math.pow(total, 1 / count)
  1108. }
  1109. }
  1110. function fitWorld(manual=false, factor=1.1) {
  1111. const fitMode = fitModes[config.autoFitMode]
  1112. let max = fitMode.start
  1113. let count = 0;
  1114. Object.entries(entities).forEach(([key, entity]) => {
  1115. const view = entity.view;
  1116. let extra = entity.views[view].image.extra;
  1117. extra = extra === undefined ? 1 : extra;
  1118. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1119. count += 1;
  1120. });
  1121. max = fitMode.final(max, count)
  1122. max = math.unit(max, "meter")
  1123. if (manual)
  1124. altHeld = true;
  1125. setWorldHeight(config.height, math.multiply(max, factor));
  1126. if (manual)
  1127. altHeld = false;
  1128. }
  1129. function updateWorldHeight() {
  1130. const unit = document.querySelector("#options-height-unit").value;
  1131. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1132. const oldHeight = config.height;
  1133. setWorldHeight(oldHeight, math.unit(value, unit));
  1134. }
  1135. function setWorldHeight(oldHeight, newHeight) {
  1136. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1137. const unit = document.querySelector("#options-height-unit").value;
  1138. document.querySelector("#options-height-value").value = config.height.toNumber(unit);
  1139. Object.entries(entities).forEach(([key, entity]) => {
  1140. const element = document.querySelector("#entity-" + key);
  1141. let newPosition;
  1142. if (!altHeld) {
  1143. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1144. } else {
  1145. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1146. }
  1147. element.dataset.x = newPosition.x;
  1148. element.dataset.y = newPosition.y;
  1149. });
  1150. updateSizes();
  1151. }
  1152. function loadScene() {
  1153. try {
  1154. const data = JSON.parse(localStorage.getItem("macrovision-save"));
  1155. importScene(data);
  1156. } catch (err) {
  1157. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1158. console.error(err);
  1159. }
  1160. }
  1161. function saveScene() {
  1162. try {
  1163. const string = JSON.stringify(exportScene());
  1164. localStorage.setItem("macrovision-save", string);
  1165. } catch (err) {
  1166. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1167. console.error(err);
  1168. }
  1169. }
  1170. function exportScene() {
  1171. const results = {};
  1172. results.entities = [];
  1173. Object.entries(entities).forEach(([key, entity]) => {
  1174. const element = document.querySelector("#entity-" + key);
  1175. results.entities.push({
  1176. name: entity.identifier,
  1177. scale: entity.scale,
  1178. view: entity.view,
  1179. x: element.dataset.x,
  1180. y: element.dataset.y
  1181. });
  1182. });
  1183. const unit = document.querySelector("#options-height-unit").value;
  1184. results.world = {
  1185. height: config.height.toNumber(unit),
  1186. unit: unit
  1187. }
  1188. return results;
  1189. }
  1190. // btoa doesn't like anything that isn't ASCII
  1191. // great
  1192. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1193. // for providing an alternative
  1194. function b64EncodeUnicode(str) {
  1195. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1196. // then we convert the percent encodings into raw bytes which
  1197. // can be fed into btoa.
  1198. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1199. function toSolidBytes(match, p1) {
  1200. return String.fromCharCode('0x' + p1);
  1201. }));
  1202. }
  1203. function b64DecodeUnicode(str) {
  1204. // Going backwards: from bytestream, to percent-encoding, to original string.
  1205. return decodeURIComponent(atob(str).split('').map(function(c) {
  1206. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1207. }).join(''));
  1208. }
  1209. function linkScene() {
  1210. loc = new URL(window.location);
  1211. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1212. }
  1213. function copyScene() {
  1214. const results = exportScene();
  1215. navigator.clipboard.writeText(JSON.stringify(results))
  1216. alert("Scene copied to clipboard. Paste text into the page to load the scene.");
  1217. }
  1218. // TODO - don't just search through every single entity
  1219. // probably just have a way to do lookups directly
  1220. function findEntity(name) {
  1221. return availableEntitiesByName[name];
  1222. }
  1223. function importScene(data) {
  1224. removeAllEntities();
  1225. data.entities.forEach(entityInfo => {
  1226. const entity = findEntity(entityInfo.name).constructor();
  1227. entity.scale = entityInfo.scale
  1228. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1229. });
  1230. config.height = math.unit(data.world.height, data.world.unit);
  1231. document.querySelector("#options-height-unit").value = data.world.unit;
  1232. updateSizes();
  1233. }