less copy protection, more size visualization
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

2389 lignes
72 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. name: "Show/hide sidebar",
  967. id: "menu-toggle-sidebar",
  968. icon: "fas fa-chevron-circle-down",
  969. rotates: true
  970. },
  971. {
  972. name: "Fullscreen",
  973. id: "menu-fullscreen",
  974. icon: "fas fa-compress"
  975. },
  976. {
  977. name: "Clear",
  978. id: "menu-clear",
  979. icon: "fas fa-file"
  980. },
  981. {
  982. name: "Sort by height",
  983. id: "menu-order-height",
  984. icon: "fas fa-sort-numeric-up"
  985. },
  986. {
  987. name: "Permalink",
  988. id: "menu-permalink",
  989. icon: "fas fa-link"
  990. },
  991. {
  992. name: "Export to clipboard",
  993. id: "menu-export",
  994. icon: "fas fa-share"
  995. },
  996. {
  997. name: "Import from clipboard",
  998. id: "menu-import",
  999. icon: "fas fa-share",
  1000. classes: ["flipped"]
  1001. },
  1002. {
  1003. name: "Save",
  1004. id: "menu-save",
  1005. icon: "fas fa-download"
  1006. },
  1007. {
  1008. name: "Load",
  1009. id: "menu-load",
  1010. icon: "fas fa-upload"
  1011. },
  1012. {
  1013. name: "Load Autosave",
  1014. id: "menu-load-autosave",
  1015. icon: "fas fa-redo"
  1016. },
  1017. {
  1018. name: "Add Image",
  1019. id: "menu-add-image",
  1020. icon: "fas fa-camera"
  1021. }
  1022. ].forEach(entry => {
  1023. const buttonHolder = document.createElement("div");
  1024. buttonHolder.classList.add("menu-button-holder");
  1025. const button = document.createElement("button");
  1026. button.id = entry.id;
  1027. button.classList.add("menu-button");
  1028. const icon = document.createElement("i");
  1029. icon.classList.add(...entry.icon.split(" "));
  1030. if (entry.rotates) {
  1031. icon.classList.add("rotate-backward", "transitions");
  1032. }
  1033. if (entry.classes) {
  1034. entry.classes.forEach(cls => icon.classList.add(cls));
  1035. }
  1036. const actionText = document.createElement("span");
  1037. actionText.innerText = entry.name;
  1038. actionText.classList.add("menu-text");
  1039. const srText = document.createElement("span");
  1040. srText.classList.add("sr-only");
  1041. srText.innerText = entry.name;
  1042. button.appendChild(icon);
  1043. button.appendChild(srText);
  1044. buttonHolder.appendChild(button);
  1045. buttonHolder.appendChild(actionText);
  1046. menubar.appendChild(buttonHolder);
  1047. });
  1048. if (checkHelpDate()) {
  1049. document.querySelector("#open-help").classList.add("highlighted");
  1050. }
  1051. }
  1052. const lastHelpChange = 1587847743294;
  1053. function checkHelpDate() {
  1054. try {
  1055. const old = localStorage.getItem("help-viewed");
  1056. if (old === null || old < lastHelpChange) {
  1057. return true;
  1058. }
  1059. return false;
  1060. } catch {
  1061. console.warn("Could not set the help-viewed date");
  1062. return false;
  1063. }
  1064. }
  1065. function setHelpDate() {
  1066. try {
  1067. localStorage.setItem("help-viewed", Date.now());
  1068. } catch {
  1069. console.warn("Could not set the help-viewed date");
  1070. }
  1071. }
  1072. function doScroll() {
  1073. document.querySelectorAll(".entity-box").forEach(element => {
  1074. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection / 180;
  1075. });
  1076. updateSizes();
  1077. scrollDirection *= 1.05;
  1078. }
  1079. function doZoom() {
  1080. const oldHeight = config.height;
  1081. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1082. zoomDirection *= 1.05;
  1083. }
  1084. function doSize() {
  1085. if (selected) {
  1086. const entity = entities[selected.dataset.key];
  1087. const oldHeight = entity.views[entity.view].height;
  1088. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection / 20);
  1089. entity.dirty = true;
  1090. updateEntityOptions(entity, entity.view);
  1091. updateViewOptions(entity, entity.view);
  1092. updateSizes(true);
  1093. sizeDirection *= 1.05;
  1094. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1095. const worldHeight = config.height.toNumber("meters");
  1096. console.log(ownHeight, worldHeight)
  1097. if (ownHeight > worldHeight) {
  1098. setWorldHeight(config.height, entity.views[entity.view].height)
  1099. } else if (ownHeight * 10 < worldHeight) {
  1100. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1101. }
  1102. }
  1103. }
  1104. function prepareHelp() {
  1105. const toc = document.querySelector("#table-of-contents");
  1106. const holder = document.querySelector("#help-contents-holder");
  1107. document.querySelectorAll("#help-contents h2").forEach(header => {
  1108. const li = document.createElement("li");
  1109. li.innerText = header.textContent;
  1110. li.addEventListener("click", e => {
  1111. holder.scrollTop = header.offsetTop;
  1112. });
  1113. toc.appendChild(li);
  1114. });
  1115. }
  1116. document.addEventListener("DOMContentLoaded", () => {
  1117. prepareMenu();
  1118. prepareEntities();
  1119. prepareHelp();
  1120. document.querySelector("#open-help").addEventListener("click", e => {
  1121. setHelpDate();
  1122. document.querySelector("#help-menu").classList.add("visible");
  1123. document.querySelector("#open-help").classList.remove("highlighted");
  1124. });
  1125. document.querySelector("#close-help").addEventListener("click", e => {
  1126. document.querySelector("#help-menu").classList.remove("visible");
  1127. });
  1128. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1129. copyScreenshot();
  1130. toast("Copied to clipboard!");
  1131. });
  1132. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1133. saveScreenshot();
  1134. });
  1135. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1136. const popoutMenu = document.querySelector("#popout-menu");
  1137. if (popoutMenu.classList.contains("visible")) {
  1138. popoutMenu.classList.remove("visible");
  1139. } else {
  1140. const rect = e.target.getBoundingClientRect();
  1141. popoutMenu.classList.add("visible");
  1142. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1143. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1144. }
  1145. e.stopPropagation();
  1146. });
  1147. document.querySelector("#popout-menu").addEventListener("click", e => {
  1148. e.stopPropagation();
  1149. });
  1150. document.addEventListener("click", e => {
  1151. document.querySelector("#popout-menu").classList.remove("visible");
  1152. });
  1153. window.addEventListener("unload", () => saveScene("autosave"));
  1154. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1155. if (e.target.value == "none") {
  1156. deselect()
  1157. } else {
  1158. select(document.querySelector("#entity-" + e.target.value));
  1159. }
  1160. });
  1161. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1162. const sidebar = document.querySelector("#options");
  1163. if (sidebar.classList.contains("hidden")) {
  1164. sidebar.classList.remove("hidden");
  1165. e.target.classList.remove("rotate-forward");
  1166. e.target.classList.add("rotate-backward");
  1167. } else {
  1168. sidebar.classList.add("hidden");
  1169. e.target.classList.add("rotate-forward");
  1170. e.target.classList.remove("rotate-backward");
  1171. }
  1172. handleResize();
  1173. });
  1174. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1175. document.querySelector("#options-show-extra").addEventListener("input", e => {
  1176. document.body.classList[e.target.checked ? "add" : "remove"]("show-extra-options");
  1177. });
  1178. document.querySelector("#options-world-show-names").addEventListener("input", e => {
  1179. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-name");
  1180. });
  1181. document.querySelector("#options-world-show-bottom-names").addEventListener("input", e => {
  1182. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-name");
  1183. });
  1184. document.querySelector("#options-world-show-top-names").addEventListener("input", e => {
  1185. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-top-name");
  1186. });
  1187. document.querySelector("#options-world-show-height-bars").addEventListener("input", e => {
  1188. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-height-bars");
  1189. });
  1190. document.querySelector("#options-world-show-entity-glow").addEventListener("input", e => {
  1191. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-entity-glow");
  1192. });
  1193. document.querySelector("#options-world-show-bottom-cover").addEventListener("input", e => {
  1194. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-bottom-cover");
  1195. });
  1196. document.querySelector("#options-world-show-scale").addEventListener("input", e => {
  1197. document.body.classList[e.target.checked ? "add" : "remove"]("toggle-scale");
  1198. });
  1199. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1200. if (selected) {
  1201. entities[selected.dataset.key].priority += 1;
  1202. }
  1203. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1204. updateSizes();
  1205. });
  1206. document.querySelector("#options-order-back").addEventListener("click", e => {
  1207. if (selected) {
  1208. entities[selected.dataset.key].priority -= 1;
  1209. }
  1210. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1211. updateSizes();
  1212. });
  1213. const sceneChoices = document.querySelector("#scene-choices");
  1214. Object.entries(scenes).forEach(([id, scene]) => {
  1215. const option = document.createElement("option");
  1216. option.innerText = id;
  1217. option.value = id;
  1218. sceneChoices.appendChild(option);
  1219. });
  1220. document.querySelector("#load-scene").addEventListener("click", e => {
  1221. const chosen = sceneChoices.value;
  1222. removeAllEntities();
  1223. scenes[chosen]();
  1224. });
  1225. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1226. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1227. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1228. document.querySelector("#options-height-value").addEventListener("change", e => {
  1229. updateWorldHeight();
  1230. })
  1231. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1232. e.stopPropagation();
  1233. })
  1234. const unitSelector = document.querySelector("#options-height-unit");
  1235. unitChoices.length.forEach(lengthOption => {
  1236. const option = document.createElement("option");
  1237. option.innerText = lengthOption;
  1238. option.value = lengthOption;
  1239. if (lengthOption === "meters") {
  1240. option.selected = true;
  1241. }
  1242. unitSelector.appendChild(option);
  1243. });
  1244. unitSelector.setAttribute("oldUnit", "meters");
  1245. unitSelector.addEventListener("input", e => {
  1246. checkFitWorld();
  1247. const scaleInput = document.querySelector("#options-height-value");
  1248. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1249. setNumericInput(scaleInput, newVal);
  1250. updateWorldHeight();
  1251. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1252. });
  1253. param = new URL(window.location.href).searchParams.get("scene");
  1254. if (param === null) {
  1255. scenes["Default"]();
  1256. }
  1257. else {
  1258. try {
  1259. const data = JSON.parse(b64DecodeUnicode(param));
  1260. if (data.entities === undefined) {
  1261. return;
  1262. }
  1263. if (data.world === undefined) {
  1264. return;
  1265. }
  1266. importScene(data);
  1267. } catch (err) {
  1268. console.error(err);
  1269. scenes["Default"]();
  1270. // probably wasn't valid data
  1271. }
  1272. }
  1273. document.querySelector("#world").addEventListener("wheel", e => {
  1274. if (shiftHeld) {
  1275. if (selected) {
  1276. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1277. const entity = entities[selected.dataset.key];
  1278. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1279. entity.dirty = true;
  1280. updateEntityOptions(entity, entity.view);
  1281. updateViewOptions(entity, entity.view);
  1282. updateSizes(true);
  1283. } else {
  1284. document.querySelectorAll(".entity-box").forEach(element => {
  1285. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1286. });
  1287. updateSizes();
  1288. }
  1289. } else {
  1290. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1291. setWorldHeight(config.height, math.multiply(config.height, dir));
  1292. updateWorldOptions();
  1293. }
  1294. checkFitWorld();
  1295. })
  1296. document.querySelector("body").appendChild(testCtx.canvas);
  1297. updateSizes();
  1298. world.addEventListener("mousedown", e => deselect());
  1299. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1300. document.querySelector("#display").addEventListener("mousedown", deselect);
  1301. document.addEventListener("mouseup", e => clickUp(e));
  1302. document.addEventListener("touchend", e => {
  1303. const fakeEvent = {
  1304. target: e.target,
  1305. clientX: e.changedTouches[0].clientX,
  1306. clientY: e.changedTouches[0].clientY
  1307. };
  1308. clickUp(fakeEvent);
  1309. });
  1310. document.querySelector("#entity-view").addEventListener("input", e => {
  1311. const entity = entities[selected.dataset.key];
  1312. entity.view = e.target.value;
  1313. const image = entities[selected.dataset.key].views[e.target.value].image;
  1314. selected.querySelector(".entity-image").src = image.source;
  1315. displayAttribution(image.source);
  1316. if (image.bottom !== undefined) {
  1317. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1318. } else {
  1319. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1320. }
  1321. updateSizes();
  1322. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1323. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1324. });
  1325. clearViewList();
  1326. document.querySelector("#menu-clear").addEventListener("click", e => {
  1327. removeAllEntities();
  1328. });
  1329. document.querySelector("#delete-entity").disabled = true;
  1330. document.querySelector("#delete-entity").addEventListener("click", e => {
  1331. if (selected) {
  1332. removeEntity(selected);
  1333. selected = null;
  1334. }
  1335. });
  1336. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1337. const order = Object.keys(entities).sort((a, b) => {
  1338. const entA = entities[a];
  1339. const entB = entities[b];
  1340. const viewA = entA.view;
  1341. const viewB = entB.view;
  1342. const heightA = entA.views[viewA].height.to("meter").value;
  1343. const heightB = entB.views[viewB].height.to("meter").value;
  1344. return heightA - heightB;
  1345. });
  1346. arrangeEntities(order);
  1347. });
  1348. // TODO: write some generic logic for this lol
  1349. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1350. scrollDirection = 1;
  1351. clearInterval(scrollHandle);
  1352. scrollHandle = setInterval(doScroll, 1000 / 20);
  1353. e.stopPropagation();
  1354. });
  1355. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1356. scrollDirection = -1;
  1357. clearInterval(scrollHandle);
  1358. scrollHandle = setInterval(doScroll, 1000 / 20);
  1359. e.stopPropagation();
  1360. });
  1361. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1362. scrollDirection = 1;
  1363. clearInterval(scrollHandle);
  1364. scrollHandle = setInterval(doScroll, 1000 / 20);
  1365. e.stopPropagation();
  1366. });
  1367. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1368. scrollDirection = -1;
  1369. clearInterval(scrollHandle);
  1370. scrollHandle = setInterval(doScroll, 1000 / 20);
  1371. e.stopPropagation();
  1372. });
  1373. document.addEventListener("mouseup", e => {
  1374. clearInterval(scrollHandle);
  1375. scrollHandle = null;
  1376. });
  1377. document.addEventListener("touchend", e => {
  1378. clearInterval(scrollHandle);
  1379. scrollHandle = null;
  1380. });
  1381. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1382. zoomDirection = -1;
  1383. clearInterval(zoomHandle);
  1384. zoomHandle = setInterval(doZoom, 1000 / 20);
  1385. e.stopPropagation();
  1386. });
  1387. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1388. zoomDirection = 1;
  1389. clearInterval(zoomHandle);
  1390. zoomHandle = setInterval(doZoom, 1000 / 20);
  1391. e.stopPropagation();
  1392. });
  1393. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1394. zoomDirection = -1;
  1395. clearInterval(zoomHandle);
  1396. zoomHandle = setInterval(doZoom, 1000 / 20);
  1397. e.stopPropagation();
  1398. });
  1399. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1400. zoomDirection = 1;
  1401. clearInterval(zoomHandle);
  1402. zoomHandle = setInterval(doZoom, 1000 / 20);
  1403. e.stopPropagation();
  1404. });
  1405. document.addEventListener("mouseup", e => {
  1406. clearInterval(zoomHandle);
  1407. zoomHandle = null;
  1408. });
  1409. document.addEventListener("touchend", e => {
  1410. clearInterval(zoomHandle);
  1411. zoomHandle = null;
  1412. });
  1413. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1414. sizeDirection = -1;
  1415. clearInterval(sizeHandle);
  1416. sizeHandle = setInterval(doSize, 1000 / 20);
  1417. e.stopPropagation();
  1418. });
  1419. document.querySelector("#grow").addEventListener("mousedown", e => {
  1420. sizeDirection = 1;
  1421. clearInterval(sizeHandle);
  1422. sizeHandle = setInterval(doSize, 1000 / 20);
  1423. e.stopPropagation();
  1424. });
  1425. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1426. sizeDirection = -1;
  1427. clearInterval(sizeHandle);
  1428. sizeHandle = setInterval(doSize, 1000 / 20);
  1429. e.stopPropagation();
  1430. });
  1431. document.querySelector("#grow").addEventListener("touchstart", e => {
  1432. sizeDirection = 1;
  1433. clearInterval(sizeHandle);
  1434. sizeHandle = setInterval(doSize, 1000 / 20);
  1435. e.stopPropagation();
  1436. });
  1437. document.addEventListener("mouseup", e => {
  1438. clearInterval(sizeHandle);
  1439. sizeHandle = null;
  1440. });
  1441. document.addEventListener("touchend", e => {
  1442. clearInterval(sizeHandle);
  1443. sizeHandle = null;
  1444. });
  1445. document.querySelector("#fit").addEventListener("click", e => {
  1446. const x = parseFloat(selected.dataset.x);
  1447. Object.keys(entities).forEach(id => {
  1448. const element = document.querySelector("#entity-" + id);
  1449. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1450. element.dataset.x = newX;
  1451. });
  1452. const entity = entities[selected.dataset.key];
  1453. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1454. setWorldHeight(config.height, height);
  1455. });
  1456. document.querySelector("#fit").addEventListener("mousedown", e => {
  1457. e.stopPropagation();
  1458. });
  1459. document.querySelector("#fit").addEventListener("touchstart", e => {
  1460. e.stopPropagation();
  1461. });
  1462. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1463. document.querySelector("#options-world-autofit").addEventListener("input", e => {
  1464. config.autoFit = e.target.checked;
  1465. if (config.autoFit) {
  1466. fitWorld();
  1467. }
  1468. });
  1469. document.addEventListener("keydown", e => {
  1470. if (e.key == "Delete") {
  1471. if (selected) {
  1472. removeEntity(selected);
  1473. selected = null;
  1474. }
  1475. }
  1476. })
  1477. document.addEventListener("keydown", e => {
  1478. if (e.key == "Shift") {
  1479. shiftHeld = true;
  1480. e.preventDefault();
  1481. } else if (e.key == "Alt") {
  1482. altHeld = true;
  1483. e.preventDefault();
  1484. }
  1485. });
  1486. document.addEventListener("keyup", e => {
  1487. if (e.key == "Shift") {
  1488. shiftHeld = false;
  1489. e.preventDefault();
  1490. } else if (e.key == "Alt") {
  1491. altHeld = false;
  1492. e.preventDefault();
  1493. }
  1494. });
  1495. window.addEventListener("resize", handleResize);
  1496. // TODO: further investigate why the tool initially starts out with wrong
  1497. // values under certain circumstances (seems to be narrow aspect ratios -
  1498. // maybe the menu bar is animating when it shouldn't)
  1499. setTimeout(handleResize, 250);
  1500. setTimeout(handleResize, 500);
  1501. setTimeout(handleResize, 750);
  1502. setTimeout(handleResize, 1000);
  1503. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1504. linkScene();
  1505. });
  1506. document.querySelector("#menu-export").addEventListener("click", e => {
  1507. copyScene();
  1508. });
  1509. document.querySelector("#menu-import").addEventListener("click", e => {
  1510. pasteScene();
  1511. });
  1512. document.querySelector("#menu-save").addEventListener("click", e => {
  1513. saveScene();
  1514. });
  1515. document.querySelector("#menu-load").addEventListener("click", e => {
  1516. loadScene();
  1517. });
  1518. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1519. loadScene("autosave");
  1520. });
  1521. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1522. document.querySelector("#file-upload-picker").click();
  1523. });
  1524. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1525. if (e.target.files.length > 0) {
  1526. for (let i=0; i<e.target.files.length; i++) {
  1527. customEntityFromFile(e.target.files[i]);
  1528. }
  1529. }
  1530. })
  1531. document.addEventListener("paste", e => {
  1532. let index = 0;
  1533. let item = null;
  1534. let found = false;
  1535. for (; index < e.clipboardData.items.length; index++) {
  1536. item = e.clipboardData.items[index];
  1537. if (item.type == "image/png") {
  1538. found = true;
  1539. break;
  1540. }
  1541. }
  1542. if (!found) {
  1543. return;
  1544. }
  1545. console.log(item)
  1546. console.log(item.type)
  1547. let url = null;
  1548. const file = item.getAsFile();
  1549. customEntityFromFile(file);
  1550. });
  1551. document.querySelector("#world").addEventListener("dragover", e => {
  1552. e.preventDefault();
  1553. })
  1554. document.querySelector("#world").addEventListener("drop", e => {
  1555. e.preventDefault();
  1556. if (e.dataTransfer.files.length > 0) {
  1557. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1558. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1559. let coords = abs2rel({x: e.clientX-entX, y: e.clientY-entY});
  1560. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1561. }
  1562. })
  1563. clearEntityOptions();
  1564. clearViewOptions();
  1565. clearAttribution();
  1566. });
  1567. function customEntityFromFile(file, x=0.5, y=0.5) {
  1568. file.arrayBuffer().then(buf => {
  1569. arr = new Uint8Array(buf);
  1570. blob = new Blob([arr], {type: file.type });
  1571. url = window.URL.createObjectURL(blob)
  1572. makeCustomEntity(url, x, y);
  1573. });
  1574. }
  1575. function makeCustomEntity(url, x=0.5, y=0.5) {
  1576. const maker = createEntityMaker(
  1577. {
  1578. name: "Custom Entity"
  1579. },
  1580. {
  1581. custom: {
  1582. attributes: {
  1583. height: {
  1584. name: "Height",
  1585. power: 1,
  1586. type: "length",
  1587. base: math.unit(6, "feet")
  1588. }
  1589. },
  1590. image: {
  1591. source: url
  1592. },
  1593. name: "Image",
  1594. info: {},
  1595. rename: false
  1596. }
  1597. },
  1598. []
  1599. );
  1600. const entity = maker.constructor();
  1601. entity.scale = config.height.toNumber("feet") / 20;
  1602. entity.ephemeral = true;
  1603. displayEntity(entity, "custom", x, y, true, true);
  1604. }
  1605. function prepareEntities() {
  1606. availableEntities["buildings"] = makeBuildings();
  1607. availableEntities["characters"] = makeCharacters();
  1608. availableEntities["cities"] = makeCities();
  1609. availableEntities["fiction"] = makeFiction();
  1610. availableEntities["food"] = makeFood();
  1611. availableEntities["landmarks"] = makeLandmarks();
  1612. availableEntities["naturals"] = makeNaturals();
  1613. availableEntities["objects"] = makeObjects();
  1614. availableEntities["pokemon"] = makePokemon();
  1615. availableEntities["species"] = makeSpecies();
  1616. availableEntities["vehicles"] = makeVehicles();
  1617. availableEntities["characters"].sort((x, y) => {
  1618. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1619. });
  1620. const holder = document.querySelector("#spawners");
  1621. const categorySelect = document.createElement("select");
  1622. categorySelect.id = "category-picker";
  1623. holder.appendChild(categorySelect);
  1624. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1625. const select = document.createElement("select");
  1626. select.id = "create-entity-" + category;
  1627. for (let i = 0; i < entityList.length; i++) {
  1628. const entity = entityList[i];
  1629. const option = document.createElement("option");
  1630. option.value = i;
  1631. option.innerText = entity.name;
  1632. select.appendChild(option);
  1633. availableEntitiesByName[entity.name] = entity;
  1634. };
  1635. const button = document.createElement("button");
  1636. button.id = "create-entity-" + category + "-button";
  1637. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1638. button.addEventListener("click", e => {
  1639. const newEntity = entityList[select.value].constructor()
  1640. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1641. });
  1642. const categoryOption = document.createElement("option");
  1643. categoryOption.value = category
  1644. categoryOption.innerText = category;
  1645. if (category == "characters") {
  1646. categoryOption.selected = true;
  1647. select.classList.add("category-visible");
  1648. button.classList.add("category-visible");
  1649. }
  1650. categorySelect.appendChild(categoryOption);
  1651. holder.appendChild(select);
  1652. holder.appendChild(button);
  1653. });
  1654. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  1655. categorySelect.addEventListener("input", e => {
  1656. const oldSelect = document.querySelector("select.category-visible");
  1657. oldSelect.classList.remove("category-visible");
  1658. const oldButton = document.querySelector("button.category-visible");
  1659. oldButton.classList.remove("category-visible");
  1660. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1661. newSelect.classList.add("category-visible");
  1662. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  1663. newButton.classList.add("category-visible");
  1664. });
  1665. }
  1666. document.addEventListener("mousemove", (e) => {
  1667. if (clicked) {
  1668. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  1669. clicked.dataset.x = position.x;
  1670. clicked.dataset.y = position.y;
  1671. updateEntityElement(entities[clicked.dataset.key], clicked);
  1672. if (hoveringInDeleteArea(e)) {
  1673. document.querySelector("#menubar").classList.add("hover-delete");
  1674. } else {
  1675. document.querySelector("#menubar").classList.remove("hover-delete");
  1676. }
  1677. }
  1678. });
  1679. document.addEventListener("touchmove", (e) => {
  1680. if (clicked) {
  1681. e.preventDefault();
  1682. let x = e.touches[0].clientX;
  1683. let y = e.touches[0].clientY;
  1684. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  1685. clicked.dataset.x = position.x;
  1686. clicked.dataset.y = position.y;
  1687. updateEntityElement(entities[clicked.dataset.key], clicked);
  1688. // what a hack
  1689. // I should centralize this 'fake event' creation...
  1690. if (hoveringInDeleteArea({ clientY: y })) {
  1691. document.querySelector("#menubar").classList.add("hover-delete");
  1692. } else {
  1693. document.querySelector("#menubar").classList.remove("hover-delete");
  1694. }
  1695. }
  1696. }, { passive: false });
  1697. function checkFitWorld() {
  1698. if (config.autoFit) {
  1699. fitWorld();
  1700. return true;
  1701. }
  1702. return false;
  1703. }
  1704. const fitModes = {
  1705. "max": {
  1706. start: 0,
  1707. binop: Math.max,
  1708. final: (total, count) => total
  1709. },
  1710. "arithmetic mean": {
  1711. start: 0,
  1712. binop: math.add,
  1713. final: (total, count) => total / count
  1714. },
  1715. "geometric mean": {
  1716. start: 1,
  1717. binop: math.multiply,
  1718. final: (total, count) => math.pow(total, 1 / count)
  1719. }
  1720. }
  1721. function fitWorld(manual = false, factor = 1.1) {
  1722. const fitMode = fitModes[config.autoFitMode]
  1723. let max = fitMode.start
  1724. let count = 0;
  1725. Object.entries(entities).forEach(([key, entity]) => {
  1726. const view = entity.view;
  1727. let extra = entity.views[view].image.extra;
  1728. extra = extra === undefined ? 1 : extra;
  1729. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  1730. count += 1;
  1731. });
  1732. max = fitMode.final(max, count)
  1733. max = math.unit(max, "meter")
  1734. if (manual)
  1735. altHeld = true;
  1736. setWorldHeight(config.height, math.multiply(max, factor));
  1737. if (manual)
  1738. altHeld = false;
  1739. }
  1740. function updateWorldHeight() {
  1741. const unit = document.querySelector("#options-height-unit").value;
  1742. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  1743. const oldHeight = config.height;
  1744. setWorldHeight(oldHeight, math.unit(value, unit));
  1745. }
  1746. function setWorldHeight(oldHeight, newHeight) {
  1747. worldSizeDirty = true;
  1748. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  1749. const unit = document.querySelector("#options-height-unit").value;
  1750. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  1751. Object.entries(entities).forEach(([key, entity]) => {
  1752. const element = document.querySelector("#entity-" + key);
  1753. let newPosition;
  1754. if (!altHeld) {
  1755. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  1756. } else {
  1757. newPosition = { x: element.dataset.x, y: element.dataset.y };
  1758. }
  1759. element.dataset.x = newPosition.x;
  1760. element.dataset.y = newPosition.y;
  1761. });
  1762. updateSizes();
  1763. }
  1764. function loadScene(name = "default") {
  1765. try {
  1766. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  1767. if (data === null) {
  1768. return false;
  1769. }
  1770. importScene(data);
  1771. return true;
  1772. } catch (err) {
  1773. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  1774. console.error(err);
  1775. return false;
  1776. }
  1777. }
  1778. function saveScene(name = "default") {
  1779. try {
  1780. const string = JSON.stringify(exportScene());
  1781. localStorage.setItem("macrovision-save-" + name, string);
  1782. } catch (err) {
  1783. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  1784. console.error(err);
  1785. }
  1786. }
  1787. function deleteScene(name = "default") {
  1788. try {
  1789. localStorage.removeItem("macrovision-save-" + name)
  1790. } catch (err) {
  1791. console.error(err);
  1792. }
  1793. }
  1794. function exportScene() {
  1795. const results = {};
  1796. results.entities = [];
  1797. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  1798. const element = document.querySelector("#entity-" + key);
  1799. results.entities.push({
  1800. name: entity.identifier,
  1801. scale: entity.scale,
  1802. view: entity.view,
  1803. x: element.dataset.x,
  1804. y: element.dataset.y
  1805. });
  1806. });
  1807. const unit = document.querySelector("#options-height-unit").value;
  1808. results.world = {
  1809. height: config.height.toNumber(unit),
  1810. unit: unit
  1811. }
  1812. results.canvasWidth = canvasWidth;
  1813. return results;
  1814. }
  1815. // btoa doesn't like anything that isn't ASCII
  1816. // great
  1817. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  1818. // for providing an alternative
  1819. function b64EncodeUnicode(str) {
  1820. // first we use encodeURIComponent to get percent-encoded UTF-8,
  1821. // then we convert the percent encodings into raw bytes which
  1822. // can be fed into btoa.
  1823. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  1824. function toSolidBytes(match, p1) {
  1825. return String.fromCharCode('0x' + p1);
  1826. }));
  1827. }
  1828. function b64DecodeUnicode(str) {
  1829. // Going backwards: from bytestream, to percent-encoding, to original string.
  1830. return decodeURIComponent(atob(str).split('').map(function (c) {
  1831. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  1832. }).join(''));
  1833. }
  1834. function linkScene() {
  1835. loc = new URL(window.location);
  1836. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  1837. }
  1838. function copyScene() {
  1839. const results = exportScene();
  1840. navigator.clipboard.writeText(JSON.stringify(results));
  1841. }
  1842. function pasteScene() {
  1843. try {
  1844. navigator.clipboard.readText().then(text => {
  1845. const data = JSON.parse(text);
  1846. if (data.entities === undefined) {
  1847. return;
  1848. }
  1849. if (data.world === undefined) {
  1850. return;
  1851. }
  1852. importScene(data);
  1853. }).catch(err => alert(err));
  1854. } catch (err) {
  1855. console.error(err);
  1856. // probably wasn't valid data
  1857. }
  1858. }
  1859. // TODO - don't just search through every single entity
  1860. // probably just have a way to do lookups directly
  1861. function findEntity(name) {
  1862. return availableEntitiesByName[name];
  1863. }
  1864. function importScene(data) {
  1865. removeAllEntities();
  1866. data.entities.forEach(entityInfo => {
  1867. const entity = findEntity(entityInfo.name).constructor();
  1868. entity.scale = entityInfo.scale
  1869. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  1870. });
  1871. config.height = math.unit(data.world.height, data.world.unit);
  1872. document.querySelector("#options-height-unit").value = data.world.unit;
  1873. if (data.canvasWidth) {
  1874. doHorizReposition(data.canvasWidth / canvasWidth);
  1875. }
  1876. updateSizes();
  1877. }
  1878. function renderToCanvas() {
  1879. const ctx = document.querySelector("#display").getContext("2d");
  1880. Object.entries(entities).sort((ent1, ent2) => {
  1881. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  1882. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  1883. return z1 - z2;
  1884. }).forEach(([id, entity]) => {
  1885. element = document.querySelector("#entity-" + id);
  1886. img = element.querySelector("img");
  1887. let x = parseFloat(element.dataset.x);
  1888. let y = parseFloat(element.dataset.y);
  1889. let coords = rel2abs({x: x, y: y});
  1890. let offset = img.style.getPropertyValue("--offset");
  1891. offset = parseFloat(offset.substring(0, offset.length-1))
  1892. x = coords.x - img.getBoundingClientRect().width/2;
  1893. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  1894. let xSize = img.getBoundingClientRect().width;
  1895. let ySize = img.getBoundingClientRect().height;
  1896. ctx.drawImage(img, x, y, xSize, ySize);
  1897. });
  1898. }
  1899. function exportCanvas(callback) {
  1900. /** @type {CanvasRenderingContext2D} */
  1901. const ctx = document.querySelector("#display").getContext("2d");
  1902. const blob = ctx.canvas.toBlob(callback);
  1903. }
  1904. function generateScreenshot(callback) {
  1905. renderToCanvas();
  1906. /** @type {CanvasRenderingContext2D} */
  1907. const ctx = document.querySelector("#display").getContext("2d");
  1908. ctx.fillStyle = "#555";
  1909. ctx.font = "normal normal lighter 16pt coda";
  1910. ctx.fillText("macrovision.crux.sexy", 10, 25);
  1911. exportCanvas(blob => {
  1912. callback(blob);
  1913. });
  1914. }
  1915. function copyScreenshot() {
  1916. generateScreenshot(blob => {
  1917. navigator.clipboard.write([
  1918. new ClipboardItem({
  1919. "image/png": blob
  1920. })
  1921. ]);
  1922. });
  1923. drawScale(false);
  1924. }
  1925. function saveScreenshot() {
  1926. generateScreenshot(blob => {
  1927. const a = document.createElement("a");
  1928. a.href = URL.createObjectURL(blob);
  1929. a.setAttribute("download", "macrovision.png");
  1930. a.click();
  1931. });
  1932. drawScale(false);
  1933. }
  1934. function toast(msg) {
  1935. let div = document.createElement("div");
  1936. div.innerHTML = msg;
  1937. div.classList.add("toast");
  1938. document.body.appendChild(div);
  1939. setTimeout(() => {
  1940. document.body.removeChild(div);
  1941. }, 5000)
  1942. }