less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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