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.
 
 
 

2362 lines
71 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. let scrollDirection = 0;
  19. let scrollHandle = null;
  20. let zoomDirection = 0;
  21. let zoomHandle = null;
  22. let sizeDirection = 0;
  23. let sizeHandle = null;
  24. let worldSizeDirty = false;
  25. math.createUnit("humans", {
  26. definition: "5.75 feet"
  27. });
  28. math.createUnit("story", {
  29. definition: "12 feet",
  30. prefixes: "long"
  31. });
  32. math.createUnit("stories", {
  33. definition: "12 feet",
  34. prefixes: "long"
  35. });
  36. math.createUnit("earths", {
  37. definition: "12756km",
  38. prefixes: "long"
  39. });
  40. math.createUnit("parsec", {
  41. definition: "3.086e16 meters",
  42. prefixes: "long"
  43. })
  44. math.createUnit("parsecs", {
  45. definition: "3.086e16 meters",
  46. prefixes: "long"
  47. })
  48. math.createUnit("lightyears", {
  49. definition: "9.461e15 meters",
  50. prefixes: "long"
  51. })
  52. math.createUnit("AU", {
  53. definition: "149597870700 meters"
  54. })
  55. math.createUnit("AUs", {
  56. definition: "149597870700 meters"
  57. })
  58. math.createUnit("dalton", {
  59. definition: "1.66e-27 kg",
  60. prefixes: "long"
  61. });
  62. math.createUnit("daltons", {
  63. definition: "1.66e-27 kg",
  64. prefixes: "long"
  65. });
  66. math.createUnit("solarradii", {
  67. definition: "695990 km",
  68. prefixes: "long"
  69. });
  70. math.createUnit("solarmasses", {
  71. definition: "2e30 kg",
  72. prefixes: "long"
  73. });
  74. math.createUnit("galaxy", {
  75. definition: "105700 lightyears",
  76. prefixes: "long"
  77. });
  78. math.createUnit("galaxies", {
  79. definition: "105700 lightyears",
  80. prefixes: "long"
  81. });
  82. math.createUnit("universe", {
  83. definition: "93.016e9 lightyears",
  84. prefixes: "long"
  85. });
  86. math.createUnit("universes", {
  87. definition: "93.016e9 lightyears",
  88. prefixes: "long"
  89. });
  90. const unitChoices = {
  91. length: [
  92. "meters",
  93. "angstroms",
  94. "millimeters",
  95. "centimeters",
  96. "kilometers",
  97. "inches",
  98. "feet",
  99. "humans",
  100. "stories",
  101. "miles",
  102. "earths",
  103. "solarradii",
  104. "AUs",
  105. "lightyears",
  106. "parsecs",
  107. "galaxies",
  108. "universes"
  109. ],
  110. area: [
  111. "meters^2",
  112. "cm^2",
  113. "kilometers^2",
  114. "acres",
  115. "miles^2"
  116. ],
  117. mass: [
  118. "kilograms",
  119. "milligrams",
  120. "grams",
  121. "tonnes",
  122. "lbs",
  123. "ounces",
  124. "tons"
  125. ]
  126. }
  127. const config = {
  128. height: math.unit(1500, "meters"),
  129. minLineSize: 100,
  130. maxLineSize: 150,
  131. autoFit: false,
  132. autoFitMode: "max"
  133. }
  134. const availableEntities = {
  135. }
  136. const availableEntitiesByName = {
  137. }
  138. const entities = {
  139. }
  140. function constrainRel(coords) {
  141. if (altHeld) {
  142. return coords;
  143. }
  144. return {
  145. x: Math.min(Math.max(coords.x, 0), 1),
  146. y: Math.min(Math.max(coords.y, 0), 1)
  147. }
  148. }
  149. function snapRel(coords) {
  150. return constrainRel({
  151. x: coords.x,
  152. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  153. });
  154. }
  155. function adjustAbs(coords, oldHeight, newHeight) {
  156. const ratio = math.divide(oldHeight, newHeight);
  157. return { x: 0.5 + (coords.x - 0.5) * math.divide(oldHeight, newHeight), y: 1 + (coords.y - 1) * math.divide(oldHeight, newHeight) };
  158. }
  159. function rel2abs(coords) {
  160. return { x: coords.x * canvasWidth + 50, y: coords.y * canvasHeight };
  161. }
  162. function abs2rel(coords) {
  163. return { x: (coords.x - 50) / canvasWidth, y: coords.y / canvasHeight };
  164. }
  165. function updateEntityElement(entity, element) {
  166. const position = rel2abs({ x: element.dataset.x, y: element.dataset.y });
  167. const view = entity.view;
  168. element.style.left = position.x + "px";
  169. element.style.top = position.y + "px";
  170. element.style.setProperty("--xpos", position.x + "px");
  171. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  172. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  173. const extra = entity.views[view].image.extra;
  174. const bottom = entity.views[view].image.bottom;
  175. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  176. element.style.setProperty("--height", pixels * bonus + "px");
  177. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  178. if (entity.views[view].rename)
  179. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  180. else
  181. element.querySelector(".entity-name").innerText = entity.name;
  182. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  183. bottomName.style.left = position.x + entityX + "px";
  184. bottomName.style.bottom = "0vh";
  185. bottomName.innerText = entity.name;
  186. const topName = document.querySelector("#top-name-" + element.dataset.key);
  187. topName.style.left = position.x + entityX + "px";
  188. topName.style.top = "20vh";
  189. topName.innerText = entity.name;
  190. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  191. topName.classList.add("top-name-needed");
  192. } else {
  193. topName.classList.remove("top-name-needed");
  194. }
  195. }
  196. function updateSizes(dirtyOnly = false) {
  197. drawScale(dirtyOnly);
  198. let ordered = Object.entries(entities);
  199. ordered.sort((e1, e2) => {
  200. if (e1[1].priority != e2[1].priority) {
  201. return e2[1].priority - e1[1].priority;
  202. } else {
  203. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  204. }
  205. });
  206. let zIndex = ordered.length;
  207. ordered.forEach(entity => {
  208. const element = document.querySelector("#entity-" + entity[0]);
  209. element.style.zIndex = zIndex;
  210. if (!dirtyOnly || entity[1].dirty) {
  211. updateEntityElement(entity[1], element, zIndex);
  212. entity[1].dirty = false;
  213. }
  214. zIndex -= 1;
  215. });
  216. }
  217. function drawScale(ifDirty = false) {
  218. if (ifDirty && !worldSizeDirty)
  219. return;
  220. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  221. let total = heightPer.clone();
  222. total.value = 0;
  223. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  224. drawTick(ctx, 50, y, total);
  225. total = math.add(total, heightPer);
  226. }
  227. }
  228. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  229. const oldStroke = ctx.strokeStyle;
  230. const oldFill = ctx.fillStyle;
  231. ctx.beginPath();
  232. ctx.moveTo(x, y);
  233. ctx.lineTo(x + 20, y);
  234. ctx.strokeStyle = "#000000";
  235. ctx.stroke();
  236. ctx.beginPath();
  237. ctx.moveTo(x + 20, y);
  238. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  239. ctx.strokeStyle = "#aaaaaa";
  240. ctx.stroke();
  241. ctx.beginPath();
  242. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  243. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  244. ctx.strokeStyle = "#000000";
  245. ctx.stroke();
  246. const oldFont = ctx.font;
  247. ctx.font = 'normal 24pt coda';
  248. ctx.fillStyle = "#dddddd";
  249. ctx.beginPath();
  250. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  251. ctx.font = oldFont;
  252. ctx.strokeStyle = oldStroke;
  253. ctx.fillStyle = oldFill;
  254. }
  255. const canvas = document.querySelector("#display");
  256. /** @type {CanvasRenderingContext2D} */
  257. const ctx = canvas.getContext("2d");
  258. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  259. heightPer = 1;
  260. if (pixelsPer < config.minLineSize) {
  261. const factor = math.ceil(config.minLineSize / pixelsPer);
  262. heightPer *= factor;
  263. pixelsPer *= factor;
  264. }
  265. if (pixelsPer > config.maxLineSize) {
  266. const factor = math.ceil(pixelsPer / config.maxLineSize);
  267. heightPer /= factor;
  268. pixelsPer /= factor;
  269. }
  270. heightPer = math.unit(heightPer, config.height.units[0].unit.name)
  271. ctx.scale(1, 1);
  272. ctx.canvas.width = canvas.clientWidth;
  273. ctx.canvas.height = canvas.clientHeight;
  274. ctx.beginPath();
  275. ctx.rect(0, 0, canvas.width, canvas.height);
  276. ctx.fillStyle = "#333";
  277. ctx.fill();
  278. ctx.beginPath();
  279. ctx.moveTo(50, 50);
  280. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  281. ctx.stroke();
  282. ctx.beginPath();
  283. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  284. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  285. ctx.stroke();
  286. drawTicks(ctx, pixelsPer, heightPer);
  287. }
  288. // Entities are generated as needed, and we make a copy
  289. // every time - the resulting objects get mutated, after all.
  290. // But we also want to be able to read some information without
  291. // calling the constructor -- e.g. making a list of authors and
  292. // owners. So, this function is used to generate that information.
  293. // It is invoked like makeEntity so that it can be dropped in easily,
  294. // but returns an object that lets you construct many copies of an entity,
  295. // rather than creating a new entity.
  296. function createEntityMaker(info, views, sizes) {
  297. const maker = {};
  298. maker.name = info.name;
  299. maker.constructor = () => makeEntity(info, views, sizes);
  300. maker.authors = [];
  301. maker.owners = [];
  302. Object.values(views).forEach(view => {
  303. const authors = authorsOf(view.image.source);
  304. if (authors) {
  305. authors.forEach(author => {
  306. if (maker.authors.indexOf(author) == -1) {
  307. maker.authors.push(author);
  308. }
  309. });
  310. }
  311. const owners = ownersOf(view.image.source);
  312. if (owners) {
  313. owners.forEach(owner => {
  314. if (maker.owners.indexOf(owner) == -1) {
  315. maker.owners.push(owner);
  316. }
  317. });
  318. }
  319. });
  320. return maker;
  321. }
  322. // This function serializes and parses its arguments to avoid sharing
  323. // references to a common object. This allows for the objects to be
  324. // safely mutated.
  325. function makeEntity(info, views, sizes) {
  326. const entityTemplate = {
  327. name: info.name,
  328. identifier: info.name,
  329. scale: 1,
  330. info: JSON.parse(JSON.stringify(info)),
  331. views: JSON.parse(JSON.stringify(views), math.reviver),
  332. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  333. init: function () {
  334. const entity = this;
  335. Object.entries(this.views).forEach(([viewKey, view]) => {
  336. view.parent = this;
  337. if (this.defaultView === undefined) {
  338. this.defaultView = viewKey;
  339. this.view = viewKey;
  340. }
  341. Object.entries(view.attributes).forEach(([key, val]) => {
  342. Object.defineProperty(
  343. view,
  344. key,
  345. {
  346. get: function () {
  347. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  348. },
  349. set: function (value) {
  350. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  351. this.parent.scale = newScale;
  352. }
  353. }
  354. )
  355. });
  356. });
  357. this.sizes.forEach(size => {
  358. if (size.default === true) {
  359. this.views[this.defaultView].height = size.height;
  360. this.size = size;
  361. }
  362. });
  363. if (this.size === undefined && this.sizes.length > 0) {
  364. this.views[this.defaultView].height = this.sizes[0].height;
  365. this.size = this.sizes[0];
  366. console.warn("No default size set for " + info.name);
  367. } else if (this.sizes.length == 0) {
  368. this.sizes = [
  369. {
  370. name: "Normal",
  371. height: this.views[this.defaultView].height
  372. }
  373. ];
  374. this.size = this.sizes[0];
  375. }
  376. this.desc = {};
  377. Object.entries(this.info).forEach(([key, value]) => {
  378. Object.defineProperty(
  379. this.desc,
  380. key,
  381. {
  382. get: function () {
  383. let text = value.text;
  384. if (entity.views[entity.view].info) {
  385. if (entity.views[entity.view].info[key]) {
  386. text = combineInfo(text, entity.views[entity.view].info[key]);
  387. }
  388. }
  389. if (entity.size.info) {
  390. if (entity.size.info[key]) {
  391. text = combineInfo(text, entity.size.info[key]);
  392. }
  393. }
  394. return { title: value.title, text: text };
  395. }
  396. }
  397. )
  398. });
  399. delete this.init;
  400. return this;
  401. }
  402. }.init();
  403. return entityTemplate;
  404. }
  405. function combineInfo(existing, next) {
  406. switch (next.mode) {
  407. case "replace":
  408. return next.text;
  409. case "prepend":
  410. return next.text + existing;
  411. case "append":
  412. return existing + next.text;
  413. }
  414. return existing;
  415. }
  416. function clickDown(target, x, y) {
  417. clicked = target;
  418. const rect = target.getBoundingClientRect();
  419. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  420. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  421. dragOffsetX = x - rect.left + entX;
  422. dragOffsetY = y - rect.top + entY;
  423. clickTimeout = setTimeout(() => { dragging = true }, 200)
  424. target.classList.add("no-transition");
  425. }
  426. // could we make this actually detect the menu area?
  427. function hoveringInDeleteArea(e) {
  428. return e.clientY < document.body.clientHeight / 10;
  429. }
  430. function clickUp(e) {
  431. clearTimeout(clickTimeout);
  432. if (clicked) {
  433. if (dragging) {
  434. dragging = false;
  435. if (hoveringInDeleteArea(e)) {
  436. removeEntity(clicked);
  437. document.querySelector("#menubar").classList.remove("hover-delete");
  438. }
  439. } else {
  440. select(clicked);
  441. }
  442. clicked.classList.remove("no-transition");
  443. clicked = null;
  444. }
  445. }
  446. function deselect() {
  447. if (selected) {
  448. selected.classList.remove("selected");
  449. }
  450. document.getElementById("options-selected-entity-none").selected = "selected";
  451. clearAttribution();
  452. selected = null;
  453. clearViewList();
  454. clearEntityOptions();
  455. clearViewOptions();
  456. document.querySelector("#delete-entity").disabled = true;
  457. document.querySelector("#grow").disabled = true;
  458. document.querySelector("#shrink").disabled = true;
  459. document.querySelector("#fit").disabled = true;
  460. }
  461. function select(target) {
  462. deselect();
  463. selected = target;
  464. selectedEntity = entities[target.dataset.key];
  465. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  466. selected.classList.add("selected");
  467. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  468. configViewList(selectedEntity, selectedEntity.view);
  469. configEntityOptions(selectedEntity, selectedEntity.view);
  470. configViewOptions(selectedEntity, selectedEntity.view);
  471. document.querySelector("#delete-entity").disabled = false;
  472. document.querySelector("#grow").disabled = false;
  473. document.querySelector("#shrink").disabled = false;
  474. document.querySelector("#fit").disabled = false;
  475. }
  476. function configViewList(entity, selectedView) {
  477. const list = document.querySelector("#entity-view");
  478. list.innerHTML = "";
  479. list.style.display = "block";
  480. Object.keys(entity.views).forEach(view => {
  481. const option = document.createElement("option");
  482. option.innerText = entity.views[view].name;
  483. option.value = view;
  484. if (view === selectedView) {
  485. option.selected = true;
  486. }
  487. list.appendChild(option);
  488. });
  489. }
  490. function clearViewList() {
  491. const list = document.querySelector("#entity-view");
  492. list.innerHTML = "";
  493. list.style.display = "none";
  494. }
  495. function updateWorldOptions(entity, view) {
  496. const heightInput = document.querySelector("#options-height-value");
  497. const heightSelect = document.querySelector("#options-height-unit");
  498. const converted = config.height.toNumber(heightSelect.value);
  499. setNumericInput(heightInput, converted);
  500. }
  501. function configEntityOptions(entity, view) {
  502. const holder = document.querySelector("#options-entity");
  503. document.querySelector("#entity-category-header").style.display = "block";
  504. document.querySelector("#entity-category").style.display = "block";
  505. holder.innerHTML = "";
  506. const scaleLabel = document.createElement("div");
  507. scaleLabel.classList.add("options-label");
  508. scaleLabel.innerText = "Scale";
  509. const scaleRow = document.createElement("div");
  510. scaleRow.classList.add("options-row");
  511. const scaleInput = document.createElement("input");
  512. scaleInput.classList.add("options-field-numeric");
  513. scaleInput.id = "options-entity-scale";
  514. scaleInput.addEventListener("change", e => {
  515. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  516. entity.dirty = true;
  517. if (config.autoFit) {
  518. fitWorld();
  519. } else {
  520. updateSizes(true);
  521. }
  522. updateEntityOptions(entity, view);
  523. updateViewOptions(entity, view);
  524. });
  525. scaleInput.addEventListener("keydown", e => {
  526. e.stopPropagation();
  527. })
  528. scaleInput.setAttribute("min", 1);
  529. scaleInput.setAttribute("type", "number");
  530. setNumericInput(scaleInput, entity.scale);
  531. scaleRow.appendChild(scaleInput);
  532. holder.appendChild(scaleLabel);
  533. holder.appendChild(scaleRow);
  534. const nameLabel = document.createElement("div");
  535. nameLabel.classList.add("options-label");
  536. nameLabel.innerText = "Name";
  537. const nameRow = document.createElement("div");
  538. nameRow.classList.add("options-row");
  539. const nameInput = document.createElement("input");
  540. nameInput.classList.add("options-field-text");
  541. nameInput.value = entity.name;
  542. nameInput.addEventListener("input", e => {
  543. entity.name = e.target.value;
  544. entity.dirty = true;
  545. updateSizes(true);
  546. })
  547. nameInput.addEventListener("keydown", e => {
  548. e.stopPropagation();
  549. })
  550. nameRow.appendChild(nameInput);
  551. holder.appendChild(nameLabel);
  552. holder.appendChild(nameRow);
  553. const defaultHolder = document.querySelector("#options-entity-defaults");
  554. defaultHolder.innerHTML = "";
  555. entity.sizes.forEach(defaultInfo => {
  556. const button = document.createElement("button");
  557. button.classList.add("options-button");
  558. button.innerText = defaultInfo.name;
  559. button.addEventListener("click", e => {
  560. entity.views[entity.defaultView].height = defaultInfo.height;
  561. entity.dirty = true;
  562. updateEntityOptions(entity, entity.view);
  563. updateViewOptions(entity, entity.view);
  564. if (!checkFitWorld()) {
  565. updateSizes(true);
  566. }
  567. });
  568. defaultHolder.appendChild(button);
  569. });
  570. document.querySelector("#options-order-display").innerText = entity.priority;
  571. document.querySelector("#options-ordering").style.display = "flex";
  572. }
  573. function updateEntityOptions(entity, view) {
  574. const scaleInput = document.querySelector("#options-entity-scale");
  575. setNumericInput(scaleInput, entity.scale);
  576. document.querySelector("#options-order-display").innerText = entity.priority;
  577. }
  578. function clearEntityOptions() {
  579. document.querySelector("#entity-category-header").style.display = "none";
  580. document.querySelector("#entity-category").style.display = "none";
  581. /*
  582. const holder = document.querySelector("#options-entity");
  583. holder.innerHTML = "";
  584. document.querySelector("#options-entity-defaults").innerHTML = "";
  585. document.querySelector("#options-ordering").style.display = "none";
  586. document.querySelector("#options-ordering").style.display = "none";*/
  587. }
  588. function configViewOptions(entity, view) {
  589. const holder = document.querySelector("#options-view");
  590. document.querySelector("#view-category-header").style.display = "block";
  591. document.querySelector("#view-category").style.display = "block";
  592. holder.innerHTML = "";
  593. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  594. const label = document.createElement("div");
  595. label.classList.add("options-label");
  596. label.innerText = val.name;
  597. holder.appendChild(label);
  598. const row = document.createElement("div");
  599. row.classList.add("options-row");
  600. holder.appendChild(row);
  601. const input = document.createElement("input");
  602. input.classList.add("options-field-numeric");
  603. input.id = "options-view-" + key + "-input";
  604. input.setAttribute("type", "number");
  605. input.setAttribute("min", 1);
  606. setNumericInput(input, entity.views[view][key].value);
  607. const select = document.createElement("select");
  608. select.classList.add("options-field-unit");
  609. select.id = "options-view-" + key + "-select"
  610. unitChoices[val.type].forEach(name => {
  611. const option = document.createElement("option");
  612. option.innerText = name;
  613. select.appendChild(option);
  614. });
  615. input.addEventListener("change", e => {
  616. const value = input.value == 0 ? 1 : input.value;
  617. entity.views[view][key] = math.unit(value, select.value);
  618. entity.dirty = true;
  619. if (config.autoFit) {
  620. fitWorld();
  621. } else {
  622. updateSizes(true);
  623. }
  624. updateEntityOptions(entity, view);
  625. updateViewOptions(entity, view, key);
  626. });
  627. input.addEventListener("keydown", e => {
  628. e.stopPropagation();
  629. })
  630. select.setAttribute("oldUnit", select.value);
  631. // TODO does this ever cause a change in the world?
  632. select.addEventListener("input", e => {
  633. const value = input.value == 0 ? 1 : input.value;
  634. const oldUnit = select.getAttribute("oldUnit");
  635. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  636. entity.dirty = true;
  637. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  638. select.setAttribute("oldUnit", select.value);
  639. if (config.autoFit) {
  640. fitWorld();
  641. } else {
  642. updateSizes(true);
  643. }
  644. updateEntityOptions(entity, view);
  645. updateViewOptions(entity, view, key);
  646. });
  647. row.appendChild(input);
  648. row.appendChild(select);
  649. });
  650. }
  651. function updateViewOptions(entity, view, changed) {
  652. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  653. if (key != changed) {
  654. const input = document.querySelector("#options-view-" + key + "-input");
  655. const select = document.querySelector("#options-view-" + key + "-select");
  656. const currentUnit = select.value;
  657. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  658. setNumericInput(input, convertedAmount);
  659. }
  660. });
  661. }
  662. function setNumericInput(input, value, round = 3) {
  663. input.value = math.round(value, round);
  664. }
  665. function getSortedEntities() {
  666. return Object.keys(entities).sort((a, b) => {
  667. const entA = entities[a];
  668. const entB = entities[b];
  669. const viewA = entA.view;
  670. const viewB = entB.view;
  671. const heightA = entA.views[viewA].height.to("meter").value;
  672. const heightB = entB.views[viewB].height.to("meter").value;
  673. return heightA - heightB;
  674. });
  675. }
  676. function clearViewOptions() {
  677. document.querySelector("#view-category-header").style.display = "none";
  678. document.querySelector("#view-category").style.display = "none";
  679. }
  680. // this is a crime against humanity, and also stolen from
  681. // stack overflow
  682. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  683. const testCanvas = document.createElement("canvas");
  684. testCanvas.id = "test-canvas";
  685. const testCtx = testCanvas.getContext("2d");
  686. function testClick(event) {
  687. // oh my god I can't believe I'm doing this
  688. const target = event.target;
  689. if (navigator.userAgent.indexOf("Firefox") != -1) {
  690. clickDown(target.parentElement, event.clientX, event.clientY);
  691. return;
  692. }
  693. // Get click coordinates
  694. let w = target.width;
  695. let h = target.height;
  696. let ratioW = 1, ratioH = 1;
  697. // Limit the size of the canvas so that very large images don't cause problems)
  698. if (w > 1000) {
  699. ratioW = w / 1000;
  700. w /= ratioW;
  701. h /= ratioW;
  702. }
  703. if (h > 1000) {
  704. ratioH = h / 1000;
  705. w /= ratioH;
  706. h /= ratioH;
  707. }
  708. const ratio = ratioW * ratioH;
  709. var x = event.clientX - target.getBoundingClientRect().x,
  710. y = event.clientY - target.getBoundingClientRect().y,
  711. alpha;
  712. testCtx.canvas.width = w;
  713. testCtx.canvas.height = h;
  714. // Draw image to canvas
  715. // and read Alpha channel value
  716. testCtx.drawImage(target, 0, 0, w, h);
  717. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  718. // If pixel is transparent,
  719. // retrieve the element underneath and trigger its click event
  720. if (alpha === 0) {
  721. const oldDisplay = target.style.display;
  722. target.style.display = "none";
  723. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  724. newTarget.dispatchEvent(new MouseEvent(event.type, {
  725. "clientX": event.clientX,
  726. "clientY": event.clientY
  727. }));
  728. target.style.display = oldDisplay;
  729. } else {
  730. clickDown(target.parentElement, event.clientX, event.clientY);
  731. }
  732. }
  733. function arrangeEntities(order) {
  734. let x = 0.1;
  735. order.forEach(key => {
  736. document.querySelector("#entity-" + key).dataset.x = x;
  737. x += 0.8 / (order.length - 1);
  738. });
  739. updateSizes();
  740. }
  741. function removeAllEntities() {
  742. Object.keys(entities).forEach(key => {
  743. removeEntity(document.querySelector("#entity-" + key));
  744. });
  745. }
  746. function clearAttribution() {
  747. document.querySelector("#attribution-category-header").style.display = "none";
  748. document.querySelector("#options-attribution").style.display = "none";
  749. }
  750. function displayAttribution(file) {
  751. document.querySelector("#attribution-category-header").style.display = "block";
  752. document.querySelector("#options-attribution").style.display = "inline";
  753. const authors = authorsOfFull(file);
  754. const owners = ownersOfFull(file);
  755. const source = sourceOf(file);
  756. const authorHolder = document.querySelector("#options-attribution-authors");
  757. const ownerHolder = document.querySelector("#options-attribution-owners");
  758. const sourceHolder = document.querySelector("#options-attribution-source");
  759. if (authors === []) {
  760. const div = document.createElement("div");
  761. div.innerText = "Unknown";
  762. authorHolder.innerHTML = "";
  763. authorHolder.appendChild(div);
  764. } else if (authors === undefined) {
  765. const div = document.createElement("div");
  766. div.innerText = "Not yet entered";
  767. authorHolder.innerHTML = "";
  768. authorHolder.appendChild(div);
  769. } else {
  770. authorHolder.innerHTML = "";
  771. const list = document.createElement("ul");
  772. authorHolder.appendChild(list);
  773. authors.forEach(author => {
  774. const authorEntry = document.createElement("li");
  775. if (author.url) {
  776. const link = document.createElement("a");
  777. link.href = author.url;
  778. link.innerText = author.name;
  779. authorEntry.appendChild(link);
  780. } else {
  781. const div = document.createElement("div");
  782. div.innerText = author.name;
  783. authorEntry.appendChild(div);
  784. }
  785. list.appendChild(authorEntry);
  786. });
  787. }
  788. if (owners === []) {
  789. const div = document.createElement("div");
  790. div.innerText = "Unknown";
  791. ownerHolder.innerHTML = "";
  792. ownerHolder.appendChild(div);
  793. } else if (owners === undefined) {
  794. const div = document.createElement("div");
  795. div.innerText = "Not yet entered";
  796. ownerHolder.innerHTML = "";
  797. ownerHolder.appendChild(div);
  798. } else {
  799. ownerHolder.innerHTML = "";
  800. const list = document.createElement("ul");
  801. ownerHolder.appendChild(list);
  802. owners.forEach(owner => {
  803. const ownerEntry = document.createElement("li");
  804. if (owner.url) {
  805. const link = document.createElement("a");
  806. link.href = owner.url;
  807. link.innerText = owner.name;
  808. ownerEntry.appendChild(link);
  809. } else {
  810. const div = document.createElement("div");
  811. div.innerText = owner.name;
  812. ownerEntry.appendChild(div);
  813. }
  814. list.appendChild(ownerEntry);
  815. });
  816. }
  817. if (source === null) {
  818. const div = document.createElement("div");
  819. div.innerText = "No link";
  820. sourceHolder.innerHTML = "";
  821. sourceHolder.appendChild(div);
  822. } else if (source === undefined) {
  823. const div = document.createElement("div");
  824. div.innerText = "Not yet entered";
  825. sourceHolder.innerHTML = "";
  826. sourceHolder.appendChild(div);
  827. } else {
  828. sourceHolder.innerHTML = "";
  829. const link = document.createElement("a");
  830. link.style.display = "block";
  831. link.href = source;
  832. link.innerText = new URL(source).host;
  833. sourceHolder.appendChild(link);
  834. }
  835. }
  836. function removeEntity(element) {
  837. if (selected == element) {
  838. deselect();
  839. }
  840. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  841. option.parentElement.removeChild(option);
  842. delete entities[element.dataset.key];
  843. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  844. const topName = document.querySelector("#top-name-" + element.dataset.key);
  845. bottomName.parentElement.removeChild(bottomName);
  846. topName.parentElement.removeChild(topName);
  847. element.parentElement.removeChild(element);
  848. }
  849. function checkEntity(entity) {
  850. Object.values(entity.views).forEach(view => {
  851. if (authorsOf(view.image.source) === undefined) {
  852. console.warn("No authors: " + view.image.source);
  853. }
  854. });
  855. }
  856. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  857. checkEntity(entity);
  858. const box = document.createElement("div");
  859. box.classList.add("entity-box");
  860. const img = document.createElement("img");
  861. img.classList.add("entity-image");
  862. img.addEventListener("dragstart", e => {
  863. e.preventDefault();
  864. });
  865. const nameTag = document.createElement("div");
  866. nameTag.classList.add("entity-name");
  867. nameTag.innerText = entity.name;
  868. box.appendChild(img);
  869. box.appendChild(nameTag);
  870. const image = entity.views[view].image;
  871. img.src = image.source;
  872. if (image.bottom !== undefined) {
  873. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  874. } else {
  875. img.style.setProperty("--offset", ((-1) * 100) + "%")
  876. }
  877. box.dataset.x = x;
  878. box.dataset.y = y;
  879. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  880. img.addEventListener("touchstart", e => {
  881. const fakeEvent = {
  882. target: e.target,
  883. clientX: e.touches[0].clientX,
  884. clientY: e.touches[0].clientY
  885. };
  886. testClick(fakeEvent);
  887. });
  888. const heightBar = document.createElement("div");
  889. heightBar.classList.add("height-bar");
  890. box.appendChild(heightBar);
  891. box.id = "entity-" + entityIndex;
  892. box.dataset.key = entityIndex;
  893. entity.view = view;
  894. entity.priority = 0;
  895. entities[entityIndex] = entity;
  896. entity.index = entityIndex;
  897. const world = document.querySelector("#entities");
  898. world.appendChild(box);
  899. const bottomName = document.createElement("div");
  900. bottomName.classList.add("bottom-name");
  901. bottomName.id = "bottom-name-" + entityIndex;
  902. bottomName.innerText = entity.name;
  903. bottomName.addEventListener("click", () => select(box));
  904. world.appendChild(bottomName);
  905. const topName = document.createElement("div");
  906. topName.classList.add("top-name");
  907. topName.id = "top-name-" + entityIndex;
  908. topName.innerText = entity.name;
  909. topName.addEventListener("click", () => select(box));
  910. world.appendChild(topName);
  911. const entityOption = document.createElement("option");
  912. entityOption.id = "options-selected-entity-" + entityIndex;
  913. entityOption.value = entityIndex;
  914. entityOption.innerText = entity.name;
  915. document.getElementById("options-selected-entity").appendChild(entityOption);
  916. entityIndex += 1;
  917. if (config.autoFit) {
  918. fitWorld();
  919. }
  920. if (selectEntity)
  921. select(box);
  922. entity.dirty = true;
  923. if (refresh)
  924. updateSizes(true);
  925. }
  926. window.onblur = function () {
  927. altHeld = false;
  928. shiftHeld = false;
  929. }
  930. window.onfocus = function () {
  931. window.dispatchEvent(new Event("keydown"));
  932. }
  933. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  934. function toggleFullScreen() {
  935. var doc = window.document;
  936. var docEl = doc.documentElement;
  937. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  938. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  939. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  940. requestFullScreen.call(docEl);
  941. }
  942. else {
  943. cancelFullScreen.call(doc);
  944. }
  945. }
  946. function handleResize() {
  947. const oldCanvasWidth = canvasWidth;
  948. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  949. canvasWidth = document.querySelector("#display").clientWidth - 100;
  950. canvasHeight = document.querySelector("#display").clientHeight - 50;
  951. const change = oldCanvasWidth / canvasWidth;
  952. doHorizReposition(change);
  953. updateSizes();
  954. }
  955. function doHorizReposition(change) {
  956. Object.keys(entities).forEach(key => {
  957. const element = document.querySelector("#entity-" + key);
  958. const x = element.dataset.x;
  959. element.dataset.x = (x - 0.5) * change + 0.5;
  960. });
  961. }
  962. function prepareMenu() {
  963. const menubar = document.querySelector("#popout-menu");
  964. [
  965. [
  966. {
  967. name: "Show/hide sidebar",
  968. id: "menu-toggle-sidebar",
  969. icon: "fas fa-chevron-circle-down",
  970. rotates: true
  971. },
  972. {
  973. name: "Fullscreen",
  974. id: "menu-fullscreen",
  975. icon: "fas fa-compress"
  976. }
  977. ],
  978. [
  979. {
  980. name: "Clear",
  981. id: "menu-clear",
  982. icon: "fas fa-file"
  983. }
  984. ],
  985. [
  986. {
  987. name: "Sort by height",
  988. id: "menu-order-height",
  989. icon: "fas fa-sort-numeric-up"
  990. }
  991. ],
  992. [
  993. {
  994. name: "Permalink",
  995. id: "menu-permalink",
  996. icon: "fas fa-link"
  997. },
  998. {
  999. name: "Export to clipboard",
  1000. id: "menu-export",
  1001. icon: "fas fa-share"
  1002. },
  1003. {
  1004. name: "Import from clipboard",
  1005. id: "menu-import",
  1006. icon: "fas fa-share"
  1007. },
  1008. {
  1009. name: "Save",
  1010. id: "menu-save",
  1011. icon: "fas fa-download"
  1012. },
  1013. {
  1014. name: "Load",
  1015. id: "menu-load",
  1016. icon: "fas fa-upload"
  1017. },
  1018. {
  1019. name: "Load Autosave",
  1020. id: "menu-load-autosave",
  1021. icon: "fas fa-redo"
  1022. }
  1023. ]
  1024. ].forEach(group => {
  1025. const span = document.createElement("span");
  1026. span.classList.add("popout-group");
  1027. group.forEach(entry => {
  1028. const buttonHolder = document.createElement("div");
  1029. buttonHolder.classList.add("menu-button-holder");
  1030. const button = document.createElement("button");
  1031. button.id = entry.id;
  1032. button.classList.add("menu-button");
  1033. const icon = document.createElement("i");
  1034. icon.classList.add(...entry.icon.split(" "));
  1035. if (entry.rotates) {
  1036. icon.classList.add("rotate-backward", "transitions");
  1037. }
  1038. const actionText = document.createElement("span");
  1039. actionText.innerText = entry.name;
  1040. actionText.classList.add("menu-text");
  1041. const srText = document.createElement("span");
  1042. srText.classList.add("sr-only");
  1043. srText.innerText = entry.name;
  1044. button.appendChild(icon);
  1045. button.appendChild(srText);
  1046. buttonHolder.appendChild(button);
  1047. buttonHolder.appendChild(actionText);
  1048. span.appendChild(buttonHolder);
  1049. });
  1050. menubar.appendChild(span);
  1051. });
  1052. if (checkHelpDate()) {
  1053. document.querySelector("#open-help").classList.add("highlighted");
  1054. }
  1055. }
  1056. const lastHelpChange = 1585487259753;
  1057. function checkHelpDate() {
  1058. try {
  1059. const old = localStorage.getItem("help-viewed");
  1060. if (old === null || old < lastHelpChange) {
  1061. return true;
  1062. }
  1063. return false;
  1064. } catch {
  1065. console.warn("Could not set the help-viewed date");
  1066. return false;
  1067. }
  1068. }
  1069. function setHelpDate() {
  1070. try {
  1071. localStorage.setItem("help-viewed", Date.now());
  1072. } catch {
  1073. console.warn("Could not set the help-viewed date");
  1074. }
  1075. }
  1076. function doScroll() {
  1077. document.querySelectorAll(".entity-box").forEach(element => {
  1078. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection / 180;
  1079. });
  1080. updateSizes();
  1081. scrollDirection *= 1.05;
  1082. }
  1083. function doZoom() {
  1084. const oldHeight = config.height;
  1085. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1086. zoomDirection *= 1.05;
  1087. }
  1088. function doSize() {
  1089. if (selected) {
  1090. const entity = entities[selected.dataset.key];
  1091. const oldHeight = entity.views[entity.view].height;
  1092. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection / 20);
  1093. entity.dirty = true;
  1094. updateEntityOptions(entity, entity.view);
  1095. updateViewOptions(entity, entity.view);
  1096. updateSizes(true);
  1097. sizeDirection *= 1.05;
  1098. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1099. const worldHeight = config.height.toNumber("meters");
  1100. console.log(ownHeight, worldHeight)
  1101. if (ownHeight > worldHeight) {
  1102. setWorldHeight(config.height, entity.views[entity.view].height)
  1103. } else if (ownHeight * 10 < worldHeight) {
  1104. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1105. }
  1106. }
  1107. }
  1108. document.addEventListener("DOMContentLoaded", () => {
  1109. prepareMenu();
  1110. prepareEntities();
  1111. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1112. copyScreenshot();
  1113. toast("Copied to clipboard!");
  1114. });
  1115. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1116. saveScreenshot();
  1117. });
  1118. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1119. const popoutMenu = document.querySelector("#popout-menu");
  1120. if (popoutMenu.classList.contains("visible")) {
  1121. popoutMenu.classList.remove("visible");
  1122. } else {
  1123. const rect = e.target.getBoundingClientRect();
  1124. popoutMenu.classList.add("visible");
  1125. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1126. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1127. }
  1128. e.stopPropagation();
  1129. });
  1130. document.querySelector("#popout-menu").addEventListener("click", e => {
  1131. e.stopPropagation();
  1132. });
  1133. document.addEventListener("click", e => {
  1134. document.querySelector("#popout-menu").classList.remove("visible");
  1135. });
  1136. window.addEventListener("unload", () => saveScene("autosave"));
  1137. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1138. if (e.target.value == "none") {
  1139. deselect()
  1140. } else {
  1141. select(document.querySelector("#entity-" + e.target.value));
  1142. }
  1143. });
  1144. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1145. const sidebar = document.querySelector("#options");
  1146. if (sidebar.classList.contains("hidden")) {
  1147. sidebar.classList.remove("hidden");
  1148. e.target.classList.remove("rotate-forward");
  1149. e.target.classList.add("rotate-backward");
  1150. } else {
  1151. sidebar.classList.add("hidden");
  1152. e.target.classList.add("rotate-forward");
  1153. e.target.classList.remove("rotate-backward");
  1154. }
  1155. handleResize();
  1156. });
  1157. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1158. document.querySelector("#options-show-extra").addEventListener("input", e => {
  1159. document.body.classList[e.target.checked ? "add" : "remove"]("show-extra-options");
  1160. });
  1161. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  1162. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  1163. });
  1164. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  1165. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  1166. });
  1167. document.querySelector("#options-world-show-top-names").addEventListener("input", e => {
  1168. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-top-name");
  1169. });
  1170. document.querySelector("#options-world-show-height-bars").addEventListener("input", e => {
  1171. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-height-bars");
  1172. });
  1173. document.querySelector("#options-world-show-entity-glow").addEventListener("input", e => {
  1174. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-glow");
  1175. });
  1176. document.querySelector("#options-world-show-bottom-cover").addEventListener("input", e => {
  1177. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  1178. });
  1179. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  1180. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  1181. });
  1182. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1183. if (selected) {
  1184. entities[selected.dataset.key].priority += 1;
  1185. }
  1186. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1187. updateSizes();
  1188. });
  1189. document.querySelector("#options-order-back").addEventListener("click", e => {
  1190. if (selected) {
  1191. entities[selected.dataset.key].priority -= 1;
  1192. }
  1193. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1194. updateSizes();
  1195. });
  1196. const sceneChoices = document.querySelector("#scene-choices");
  1197. Object.entries(scenes).forEach(([id, scene]) => {
  1198. const option = document.createElement("option");
  1199. option.innerText = id;
  1200. option.value = id;
  1201. sceneChoices.appendChild(option);
  1202. });
  1203. document.querySelector("#load-scene").addEventListener("click", e => {
  1204. const chosen = sceneChoices.value;
  1205. removeAllEntities();
  1206. scenes[chosen]();
  1207. });
  1208. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1209. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1210. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1211. document.querySelector("#open-help").addEventListener("click", e => {
  1212. setHelpDate();
  1213. document.querySelector("#open-help").classList.remove("highlighted");
  1214. document.querySelector("#help").classList.add("visible");
  1215. });
  1216. document.querySelector("#close-help").addEventListener("click", e => {
  1217. document.querySelector("#help").classList.remove("visible");
  1218. });
  1219. document.querySelector("#options-height-value").addEventListener("change", e => {
  1220. updateWorldHeight();
  1221. })
  1222. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1223. e.stopPropagation();
  1224. })
  1225. const unitSelector = document.querySelector("#options-height-unit");
  1226. unitChoices.length.forEach(lengthOption => {
  1227. const option = document.createElement("option");
  1228. option.innerText = lengthOption;
  1229. option.value = lengthOption;
  1230. if (lengthOption === "meters") {
  1231. option.selected = true;
  1232. }
  1233. unitSelector.appendChild(option);
  1234. });
  1235. unitSelector.setAttribute("oldUnit", "meters");
  1236. unitSelector.addEventListener("input", e => {
  1237. checkFitWorld();
  1238. const scaleInput = document.querySelector("#options-height-value");
  1239. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1240. setNumericInput(scaleInput, newVal);
  1241. updateWorldHeight();
  1242. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1243. });
  1244. param = new URL(window.location.href).searchParams.get("scene");
  1245. if (param === null) {
  1246. scenes["Default"]();
  1247. }
  1248. else {
  1249. try {
  1250. const data = JSON.parse(b64DecodeUnicode(param));
  1251. if (data.entities === undefined) {
  1252. return;
  1253. }
  1254. if (data.world === undefined) {
  1255. return;
  1256. }
  1257. importScene(data);
  1258. } catch (err) {
  1259. console.error(err);
  1260. scenes["Default"]();
  1261. // probably wasn't valid data
  1262. }
  1263. }
  1264. document.querySelector("#world").addEventListener("wheel", e => {
  1265. if (shiftHeld) {
  1266. if (selected) {
  1267. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1268. const entity = entities[selected.dataset.key];
  1269. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1270. entity.dirty = true;
  1271. updateEntityOptions(entity, entity.view);
  1272. updateViewOptions(entity, entity.view);
  1273. updateSizes(true);
  1274. } else {
  1275. document.querySelectorAll(".entity-box").forEach(element => {
  1276. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1277. });
  1278. updateSizes();
  1279. }
  1280. } else {
  1281. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1282. setWorldHeight(config.height, math.multiply(config.height, dir));
  1283. updateWorldOptions();
  1284. }
  1285. checkFitWorld();
  1286. })
  1287. document.querySelector("body").appendChild(testCtx.canvas);
  1288. updateSizes();
  1289. world.addEventListener("mousedown", e => deselect());
  1290. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1291. document.querySelector("#display").addEventListener("mousedown", deselect);
  1292. document.addEventListener("mouseup", e => clickUp(e));
  1293. document.addEventListener("touchend", e => {
  1294. const fakeEvent = {
  1295. target: e.target,
  1296. clientX: e.changedTouches[0].clientX,
  1297. clientY: e.changedTouches[0].clientY
  1298. };
  1299. clickUp(fakeEvent);
  1300. });
  1301. document.querySelector("#entity-view").addEventListener("input", e => {
  1302. const entity = entities[selected.dataset.key];
  1303. entity.view = e.target.value;
  1304. const image = entities[selected.dataset.key].views[e.target.value].image;
  1305. selected.querySelector(".entity-image").src = image.source;
  1306. displayAttribution(image.source);
  1307. if (image.bottom !== undefined) {
  1308. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1309. } else {
  1310. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1311. }
  1312. updateSizes();
  1313. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1314. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1315. });
  1316. clearViewList();
  1317. document.querySelector("#menu-clear").addEventListener("click", e => {
  1318. removeAllEntities();
  1319. });
  1320. document.querySelector("#delete-entity").disabled = true;
  1321. document.querySelector("#delete-entity").addEventListener("click", e => {
  1322. if (selected) {
  1323. removeEntity(selected);
  1324. selected = null;
  1325. }
  1326. });
  1327. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1328. const order = Object.keys(entities).sort((a, b) => {
  1329. const entA = entities[a];
  1330. const entB = entities[b];
  1331. const viewA = entA.view;
  1332. const viewB = entB.view;
  1333. const heightA = entA.views[viewA].height.to("meter").value;
  1334. const heightB = entB.views[viewB].height.to("meter").value;
  1335. return heightA - heightB;
  1336. });
  1337. arrangeEntities(order);
  1338. });
  1339. // TODO: write some generic logic for this lol
  1340. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1341. scrollDirection = 1;
  1342. clearInterval(scrollHandle);
  1343. scrollHandle = setInterval(doScroll, 1000 / 20);
  1344. e.stopPropagation();
  1345. });
  1346. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1347. scrollDirection = -1;
  1348. clearInterval(scrollHandle);
  1349. scrollHandle = setInterval(doScroll, 1000 / 20);
  1350. e.stopPropagation();
  1351. });
  1352. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1353. scrollDirection = 1;
  1354. clearInterval(scrollHandle);
  1355. scrollHandle = setInterval(doScroll, 1000 / 20);
  1356. e.stopPropagation();
  1357. });
  1358. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1359. scrollDirection = -1;
  1360. clearInterval(scrollHandle);
  1361. scrollHandle = setInterval(doScroll, 1000 / 20);
  1362. e.stopPropagation();
  1363. });
  1364. document.addEventListener("mouseup", e => {
  1365. clearInterval(scrollHandle);
  1366. scrollHandle = null;
  1367. });
  1368. document.addEventListener("touchend", e => {
  1369. clearInterval(scrollHandle);
  1370. scrollHandle = null;
  1371. });
  1372. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1373. zoomDirection = -1;
  1374. clearInterval(zoomHandle);
  1375. zoomHandle = setInterval(doZoom, 1000 / 20);
  1376. e.stopPropagation();
  1377. });
  1378. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1379. zoomDirection = 1;
  1380. clearInterval(zoomHandle);
  1381. zoomHandle = setInterval(doZoom, 1000 / 20);
  1382. e.stopPropagation();
  1383. });
  1384. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1385. zoomDirection = -1;
  1386. clearInterval(zoomHandle);
  1387. zoomHandle = setInterval(doZoom, 1000 / 20);
  1388. e.stopPropagation();
  1389. });
  1390. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1391. zoomDirection = 1;
  1392. clearInterval(zoomHandle);
  1393. zoomHandle = setInterval(doZoom, 1000 / 20);
  1394. e.stopPropagation();
  1395. });
  1396. document.addEventListener("mouseup", e => {
  1397. clearInterval(zoomHandle);
  1398. zoomHandle = null;
  1399. });
  1400. document.addEventListener("touchend", e => {
  1401. clearInterval(zoomHandle);
  1402. zoomHandle = null;
  1403. });
  1404. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1405. sizeDirection = -1;
  1406. clearInterval(sizeHandle);
  1407. sizeHandle = setInterval(doSize, 1000 / 20);
  1408. e.stopPropagation();
  1409. });
  1410. document.querySelector("#grow").addEventListener("mousedown", e => {
  1411. sizeDirection = 1;
  1412. clearInterval(sizeHandle);
  1413. sizeHandle = setInterval(doSize, 1000 / 20);
  1414. e.stopPropagation();
  1415. });
  1416. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1417. sizeDirection = -1;
  1418. clearInterval(sizeHandle);
  1419. sizeHandle = setInterval(doSize, 1000 / 20);
  1420. e.stopPropagation();
  1421. });
  1422. document.querySelector("#grow").addEventListener("touchstart", e => {
  1423. sizeDirection = 1;
  1424. clearInterval(sizeHandle);
  1425. sizeHandle = setInterval(doSize, 1000 / 20);
  1426. e.stopPropagation();
  1427. });
  1428. document.addEventListener("mouseup", e => {
  1429. clearInterval(sizeHandle);
  1430. sizeHandle = null;
  1431. });
  1432. document.addEventListener("touchend", e => {
  1433. clearInterval(sizeHandle);
  1434. sizeHandle = null;
  1435. });
  1436. document.querySelector("#fit").addEventListener("click", e => {
  1437. const x = parseFloat(selected.dataset.x);
  1438. Object.keys(entities).forEach(id => {
  1439. const element = document.querySelector("#entity-" + id);
  1440. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1441. element.dataset.x = newX;
  1442. });
  1443. const entity = entities[selected.dataset.key];
  1444. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1445. setWorldHeight(config.height, height);
  1446. });
  1447. document.querySelector("#fit").addEventListener("mousedown", e => {
  1448. e.stopPropagation();
  1449. });
  1450. document.querySelector("#fit").addEventListener("touchstart", e => {
  1451. e.stopPropagation();
  1452. });
  1453. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1454. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1455. config.autoFit = e.target.checked;
  1456. if (config.autoFit) {
  1457. fitWorld();
  1458. }
  1459. });
  1460. document.addEventListener("keydown", e => {
  1461. if (e.key == "Delete") {
  1462. if (selected) {
  1463. removeEntity(selected);
  1464. selected = null;
  1465. }
  1466. }
  1467. })
  1468. document.addEventListener("keydown", e => {
  1469. if (e.key == "Shift") {
  1470. shiftHeld = true;
  1471. e.preventDefault();
  1472. } else if (e.key == "Alt") {
  1473. altHeld = true;
  1474. e.preventDefault();
  1475. }
  1476. });
  1477. document.addEventListener("keyup", e => {
  1478. if (e.key == "Shift") {
  1479. shiftHeld = false;
  1480. e.preventDefault();
  1481. } else if (e.key == "Alt") {
  1482. altHeld = false;
  1483. e.preventDefault();
  1484. }
  1485. });
  1486. window.addEventListener("resize", handleResize);
  1487. // TODO: further investigate why the tool initially starts out with wrong
  1488. // values under certain circumstances (seems to be narrow aspect ratios -
  1489. // maybe the menu bar is animating when it shouldn't)
  1490. setTimeout(handleResize, 250);
  1491. setTimeout(handleResize, 500);
  1492. setTimeout(handleResize, 750);
  1493. setTimeout(handleResize, 1000);
  1494. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1495. linkScene();
  1496. });
  1497. document.querySelector("#menu-export").addEventListener("click", e => {
  1498. copyScene();
  1499. });
  1500. document.querySelector("#menu-import").addEventListener("click", e => {
  1501. pasteScene();
  1502. });
  1503. document.querySelector("#menu-save").addEventListener("click", e => {
  1504. saveScene();
  1505. });
  1506. document.querySelector("#menu-load").addEventListener("click", e => {
  1507. loadScene();
  1508. });
  1509. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1510. loadScene("autosave");
  1511. });
  1512. document.addEventListener("paste", e => {
  1513. let index = 0;
  1514. let item = null;
  1515. let found = false;
  1516. for (; index < e.clipboardData.items.length; index++) {
  1517. item = e.clipboardData.items[index];
  1518. if (item.type == "image/png") {
  1519. found = true;
  1520. break;
  1521. }
  1522. }
  1523. if (!found) {
  1524. return;
  1525. }
  1526. console.log(item)
  1527. console.log(item.type)
  1528. let url = null;
  1529. const file = item.getAsFile();
  1530. customEntityFromFile(file);
  1531. });
  1532. document.querySelector("#world").addEventListener("dragover", e => {
  1533. e.preventDefault();
  1534. })
  1535. document.querySelector("#world").addEventListener("drop", e => {
  1536. e.preventDefault();
  1537. if (e.dataTransfer.files.length > 0) {
  1538. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1539. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1540. let coords = abs2rel({x: e.clientX-entX, y: e.clientY-entY});
  1541. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1542. }
  1543. })
  1544. clearEntityOptions();
  1545. clearViewOptions();
  1546. clearAttribution();
  1547. });
  1548. function customEntityFromFile(file, x=0.5, y=0.5) {
  1549. file.arrayBuffer().then(buf => {
  1550. arr = new Uint8Array(buf);
  1551. blob = new Blob([arr], {type: file.type });
  1552. url = window.URL.createObjectURL(blob)
  1553. makeCustomEntity(url, x, y);
  1554. });
  1555. }
  1556. function makeCustomEntity(url, x=0.5, y=0.5) {
  1557. const maker = createEntityMaker(
  1558. {
  1559. name: "Custom Entity"
  1560. },
  1561. {
  1562. custom: {
  1563. attributes: {
  1564. height: {
  1565. name: "Height",
  1566. power: 1,
  1567. type: "length",
  1568. base: math.unit(6, "feet")
  1569. }
  1570. },
  1571. image: {
  1572. source: url
  1573. },
  1574. name: "Image",
  1575. info: {},
  1576. rename: false
  1577. }
  1578. },
  1579. []
  1580. );
  1581. const entity = maker.constructor();
  1582. entity.ephemeral = true;
  1583. displayEntity(entity, "custom", x, y, true, true);
  1584. }
  1585. function prepareEntities() {
  1586. availableEntities["buildings"] = makeBuildings();
  1587. availableEntities["characters"] = makeCharacters();
  1588. availableEntities["cities"] = makeCities();
  1589. availableEntities["fiction"] = makeFiction();
  1590. availableEntities["food"] = makeFood();
  1591. availableEntities["landmarks"] = makeLandmarks();
  1592. availableEntities["naturals"] = makeNaturals();
  1593. availableEntities["objects"] = makeObjects();
  1594. availableEntities["pokemon"] = makePokemon();
  1595. availableEntities["species"] = makeSpecies();
  1596. availableEntities["vehicles"] = makeVehicles();
  1597. availableEntities["characters"].sort((x, y) => {
  1598. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1599. });
  1600. const holder = document.querySelector("#spawners");
  1601. const categorySelect = document.createElement("select");
  1602. categorySelect.id = "category-picker";
  1603. holder.appendChild(categorySelect);
  1604. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1605. const select = document.createElement("select");
  1606. select.id = "create-entity-" + category;
  1607. for (let i = 0; i < entityList.length; i++) {
  1608. const entity = entityList[i];
  1609. const option = document.createElement("option");
  1610. option.value = i;
  1611. option.innerText = entity.name;
  1612. select.appendChild(option);
  1613. availableEntitiesByName[entity.name] = entity;
  1614. };
  1615. const button = document.createElement("button");
  1616. button.id = "create-entity-" + category + "-button";
  1617. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1618. button.addEventListener("click", e => {
  1619. const newEntity = entityList[select.value].constructor()
  1620. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1621. });
  1622. const categoryOption = document.createElement("option");
  1623. categoryOption.value = category
  1624. categoryOption.innerText = category;
  1625. if (category == "characters") {
  1626. categoryOption.selected = true;
  1627. select.classList.add("category-visible");
  1628. button.classList.add("category-visible");
  1629. }
  1630. categorySelect.appendChild(categoryOption);
  1631. holder.appendChild(select);
  1632. holder.appendChild(button);
  1633. });
  1634. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  1635. categorySelect.addEventListener("input", e => {
  1636. const oldSelect = document.querySelector("select.category-visible");
  1637. oldSelect.classList.remove("category-visible");
  1638. const oldButton = document.querySelector("button.category-visible");
  1639. oldButton.classList.remove("category-visible");
  1640. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1641. newSelect.classList.add("category-visible");
  1642. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1643. newButton.classList.add("category-visible");
  1644. });
  1645. }
  1646. document.addEventListener("mousemove", (e) => {
  1647. if (clicked) {
  1648. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1649. clicked.dataset.x = position.x;
  1650. clicked.dataset.y = position.y;
  1651. updateEntityElement(entities[clicked.dataset.key], clicked);
  1652. if (hoveringInDeleteArea(e)) {
  1653. document.querySelector("#menubar").classList.add("hover-delete");
  1654. } else {
  1655. document.querySelector("#menubar").classList.remove("hover-delete");
  1656. }
  1657. }
  1658. });
  1659. document.addEventListener("touchmove", (e) => {
  1660. if (clicked) {
  1661. e.preventDefault();
  1662. let x = e.touches[0].clientX;
  1663. let y = e.touches[0].clientY;
  1664. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1665. clicked.dataset.x = position.x;
  1666. clicked.dataset.y = position.y;
  1667. updateEntityElement(entities[clicked.dataset.key], clicked);
  1668. // what a hack
  1669. // I should centralize this 'fake event' creation...
  1670. if (hoveringInDeleteArea({ clientY: y })) {
  1671. document.querySelector("#menubar").classList.add("hover-delete");
  1672. } else {
  1673. document.querySelector("#menubar").classList.remove("hover-delete");
  1674. }
  1675. }
  1676. }, { passive: false });
  1677. function checkFitWorld() {
  1678. if (config.autoFit) {
  1679. fitWorld();
  1680. return true;
  1681. }
  1682. return false;
  1683. }
  1684. const fitModes = {
  1685. "max": {
  1686. start: 0,
  1687. binop: Math.max,
  1688. final: (total, count) => total
  1689. },
  1690. "arithmetic mean": {
  1691. start: 0,
  1692. binop: math.add,
  1693. final: (total, count) => total / count
  1694. },
  1695. "geometric mean": {
  1696. start: 1,
  1697. binop: math.multiply,
  1698. final: (total, count) => math.pow(total, 1 / count)
  1699. }
  1700. }
  1701. function fitWorld(manual = false, factor = 1.1) {
  1702. const fitMode = fitModes[config.autoFitMode]
  1703. let max = fitMode.start
  1704. let count = 0;
  1705. Object.entries(entities).forEach(([key, entity]) => {
  1706. const view = entity.view;
  1707. let extra = entity.views[view].image.extra;
  1708. extra = extra === undefined ? 1 : extra;
  1709. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1710. count += 1;
  1711. });
  1712. max = fitMode.final(max, count)
  1713. max = math.unit(max, "meter")
  1714. if (manual)
  1715. altHeld = true;
  1716. setWorldHeight(config.height, math.multiply(max, factor));
  1717. if (manual)
  1718. altHeld = false;
  1719. }
  1720. function updateWorldHeight() {
  1721. const unit = document.querySelector("#options-height-unit").value;
  1722. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1723. const oldHeight = config.height;
  1724. setWorldHeight(oldHeight, math.unit(value, unit));
  1725. }
  1726. function setWorldHeight(oldHeight, newHeight) {
  1727. worldSizeDirty = true;
  1728. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1729. const unit = document.querySelector("#options-height-unit").value;
  1730. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1731. Object.entries(entities).forEach(([key, entity]) => {
  1732. const element = document.querySelector("#entity-" + key);
  1733. let newPosition;
  1734. if (!altHeld) {
  1735. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1736. } else {
  1737. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1738. }
  1739. element.dataset.x = newPosition.x;
  1740. element.dataset.y = newPosition.y;
  1741. });
  1742. updateSizes();
  1743. }
  1744. function loadScene(name = "default") {
  1745. try {
  1746. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  1747. if (data === null) {
  1748. return false;
  1749. }
  1750. importScene(data);
  1751. return true;
  1752. } catch (err) {
  1753. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1754. console.error(err);
  1755. return false;
  1756. }
  1757. }
  1758. function saveScene(name = "default") {
  1759. try {
  1760. const string = JSON.stringify(exportScene());
  1761. localStorage.setItem("macrovision-save-" + name, string);
  1762. } catch (err) {
  1763. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1764. console.error(err);
  1765. }
  1766. }
  1767. function deleteScene(name = "default") {
  1768. try {
  1769. localStorage.removeItem("macrovision-save-" + name)
  1770. } catch (err) {
  1771. console.error(err);
  1772. }
  1773. }
  1774. function exportScene() {
  1775. const results = {};
  1776. results.entities = [];
  1777. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  1778. const element = document.querySelector("#entity-" + key);
  1779. results.entities.push({
  1780. name: entity.identifier,
  1781. scale: entity.scale,
  1782. view: entity.view,
  1783. x: element.dataset.x,
  1784. y: element.dataset.y
  1785. });
  1786. });
  1787. const unit = document.querySelector("#options-height-unit").value;
  1788. results.world = {
  1789. height: config.height.toNumber(unit),
  1790. unit: unit
  1791. }
  1792. results.canvasWidth = canvasWidth;
  1793. return results;
  1794. }
  1795. // btoa doesn't like anything that isn't ASCII
  1796. // great
  1797. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1798. // for providing an alternative
  1799. function b64EncodeUnicode(str) {
  1800. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1801. // then we convert the percent encodings into raw bytes which
  1802. // can be fed into btoa.
  1803. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1804. function toSolidBytes(match, p1) {
  1805. return String.fromCharCode('0x' + p1);
  1806. }));
  1807. }
  1808. function b64DecodeUnicode(str) {
  1809. // Going backwards: from bytestream, to percent-encoding, to original string.
  1810. return decodeURIComponent(atob(str).split('').map(function (c) {
  1811. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1812. }).join(''));
  1813. }
  1814. function linkScene() {
  1815. loc = new URL(window.location);
  1816. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1817. }
  1818. function copyScene() {
  1819. const results = exportScene();
  1820. navigator.clipboard.writeText(JSON.stringify(results));
  1821. }
  1822. function pasteScene() {
  1823. try {
  1824. navigator.clipboard.readText().then(text => {
  1825. const data = JSON.parse(text);
  1826. if (data.entities === undefined) {
  1827. return;
  1828. }
  1829. if (data.world === undefined) {
  1830. return;
  1831. }
  1832. importScene(data);
  1833. }).catch(err => alert(err));
  1834. } catch (err) {
  1835. console.error(err);
  1836. // probably wasn't valid data
  1837. }
  1838. }
  1839. // TODO - don't just search through every single entity
  1840. // probably just have a way to do lookups directly
  1841. function findEntity(name) {
  1842. return availableEntitiesByName[name];
  1843. }
  1844. function importScene(data) {
  1845. removeAllEntities();
  1846. data.entities.forEach(entityInfo => {
  1847. const entity = findEntity(entityInfo.name).constructor();
  1848. entity.scale = entityInfo.scale
  1849. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1850. });
  1851. config.height = math.unit(data.world.height, data.world.unit);
  1852. document.querySelector("#options-height-unit").value = data.world.unit;
  1853. if (data.canvasWidth) {
  1854. doHorizReposition(data.canvasWidth / canvasWidth);
  1855. }
  1856. updateSizes();
  1857. }
  1858. function renderToCanvas() {
  1859. const ctx = document.querySelector("#display").getContext("2d");
  1860. Object.entries(entities).sort((ent1, ent2) => {
  1861. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  1862. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  1863. return z1 - z2;
  1864. }).forEach(([id, entity]) => {
  1865. element = document.querySelector("#entity-" + id);
  1866. img = element.querySelector("img");
  1867. let x = parseFloat(element.dataset.x);
  1868. let y = parseFloat(element.dataset.y);
  1869. let coords = rel2abs({x: x, y: y});
  1870. let offset = img.style.getPropertyValue("--offset");
  1871. offset = parseFloat(offset.substring(0, offset.length-1))
  1872. x = coords.x - img.getBoundingClientRect().width/2;
  1873. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  1874. let xSize = img.getBoundingClientRect().width;
  1875. let ySize = img.getBoundingClientRect().height;
  1876. ctx.drawImage(img, x, y, xSize, ySize);
  1877. });
  1878. }
  1879. function exportCanvas(callback) {
  1880. /** @type {CanvasRenderingContext2D} */
  1881. const ctx = document.querySelector("#display").getContext("2d");
  1882. const blob = ctx.canvas.toBlob(callback);
  1883. }
  1884. function generateScreenshot(callback) {
  1885. renderToCanvas();
  1886. /** @type {CanvasRenderingContext2D} */
  1887. const ctx = document.querySelector("#display").getContext("2d");
  1888. ctx.fillStyle = "#555";
  1889. ctx.font = "normal normal lighter 16pt coda";
  1890. ctx.fillText("macrovision.crux.sexy", 10, 25);
  1891. exportCanvas(blob => {
  1892. callback(blob);
  1893. });
  1894. }
  1895. function copyScreenshot() {
  1896. generateScreenshot(blob => {
  1897. navigator.clipboard.write([
  1898. new ClipboardItem({
  1899. "image/png": blob
  1900. })
  1901. ]);
  1902. });
  1903. drawScale(false);
  1904. }
  1905. function saveScreenshot() {
  1906. generateScreenshot(blob => {
  1907. const a = document.createElement("a");
  1908. a.href = URL.createObjectURL(blob);
  1909. a.setAttribute("download", "macrovision.png");
  1910. a.click();
  1911. });
  1912. drawScale(false);
  1913. }
  1914. function toast(msg) {
  1915. div = document.createElement("div");
  1916. div.innerHTML = msg;
  1917. div.classList.add("toast");
  1918. document.body.appendChild(div);
  1919. setTimeout(() => {
  1920. document.body.removeChild(div);
  1921. }, 5000)
  1922. }