less copy protection, more size visualization
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 

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