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.
 
 
 

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