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.
 
 
 

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