less copy protection, more size visualization
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

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