less copy protection, more size visualization
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

3215 строки
97 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 panning = false;
  10. let panReady = true;
  11. let panOffsetX = null;
  12. let panOffsetY = null;
  13. let shiftHeld = false;
  14. let altHeld = false;
  15. let entityX;
  16. let canvasWidth;
  17. let canvasHeight;
  18. let dragScale = 1;
  19. let dragScaleHandle = null;
  20. let dragEntityScale = 1;
  21. let dragEntityScaleHandle = null;
  22. let scrollDirection = 0;
  23. let scrollHandle = null;
  24. let zoomDirection = 0;
  25. let zoomHandle = null;
  26. let sizeDirection = 0;
  27. let sizeHandle = null;
  28. let worldSizeDirty = false;
  29. const tagDefs = {
  30. "anthro": "Anthro",
  31. "feral": "Feral",
  32. "taur": "Taur",
  33. "naga": "Naga",
  34. "goo": "Goo"
  35. }
  36. math.createUnit("humans", {
  37. definition: "5.75 feet"
  38. });
  39. math.createUnit("story", {
  40. definition: "12 feet",
  41. prefixes: "long"
  42. });
  43. math.createUnit("stories", {
  44. definition: "12 feet",
  45. prefixes: "long"
  46. });
  47. math.createUnit("earths", {
  48. definition: "12756km",
  49. prefixes: "long"
  50. });
  51. math.createUnit("parsec", {
  52. definition: "3.086e16 meters",
  53. prefixes: "long"
  54. })
  55. math.createUnit("parsecs", {
  56. definition: "3.086e16 meters",
  57. prefixes: "long"
  58. })
  59. math.createUnit("lightyears", {
  60. definition: "9.461e15 meters",
  61. prefixes: "long"
  62. })
  63. math.createUnit("AU", {
  64. definition: "149597870700 meters"
  65. })
  66. math.createUnit("AUs", {
  67. definition: "149597870700 meters"
  68. })
  69. math.createUnit("dalton", {
  70. definition: "1.66e-27 kg",
  71. prefixes: "long"
  72. });
  73. math.createUnit("daltons", {
  74. definition: "1.66e-27 kg",
  75. prefixes: "long"
  76. });
  77. math.createUnit("solarradii", {
  78. definition: "695990 km",
  79. prefixes: "long"
  80. });
  81. math.createUnit("solarmasses", {
  82. definition: "2e30 kg",
  83. prefixes: "long"
  84. });
  85. math.createUnit("galaxy", {
  86. definition: "105700 lightyears",
  87. prefixes: "long"
  88. });
  89. math.createUnit("galaxies", {
  90. definition: "105700 lightyears",
  91. prefixes: "long"
  92. });
  93. math.createUnit("universe", {
  94. definition: "93.016e9 lightyears",
  95. prefixes: "long"
  96. });
  97. math.createUnit("universes", {
  98. definition: "93.016e9 lightyears",
  99. prefixes: "long"
  100. });
  101. math.createUnit("multiverse", {
  102. definition: "1e30 lightyears",
  103. prefixes: "long"
  104. });
  105. math.createUnit("multiverses", {
  106. definition: "1e30 lightyears",
  107. prefixes: "long"
  108. });
  109. math.createUnit("people", {
  110. definition: "75 liters",
  111. prefixes: "long"
  112. });
  113. math.createUnit("olympicPools", {
  114. definition: "2500 m^3",
  115. prefixes: "long"
  116. });
  117. math.createUnit("oceans", {
  118. definition: "700000000 km^3",
  119. prefixes: "long"
  120. });
  121. math.createUnit("earthVolumes", {
  122. definition: "1.0867813e12 km^3",
  123. prefixes: "long"
  124. });
  125. math.createUnit("universeVolumes", {
  126. definition: "4.2137775e+32 lightyears^3",
  127. prefixes: "long"
  128. });
  129. math.createUnit("multiverseVolumes", {
  130. definition: "5.2359878e+89 lightyears^3",
  131. prefixes: "long"
  132. });
  133. const unitChoices = {
  134. length: [
  135. "meters",
  136. "angstroms",
  137. "millimeters",
  138. "centimeters",
  139. "kilometers",
  140. "inches",
  141. "feet",
  142. "humans",
  143. "stories",
  144. "miles",
  145. "earths",
  146. "solarradii",
  147. "AUs",
  148. "lightyears",
  149. "parsecs",
  150. "galaxies",
  151. "universes",
  152. "multiverses"
  153. ],
  154. area: [
  155. "meters^2",
  156. "cm^2",
  157. "kilometers^2",
  158. "acres",
  159. "miles^2"
  160. ],
  161. volume: [
  162. "liters",
  163. "milliliters",
  164. "m^3",
  165. "gallons",
  166. "people",
  167. "olympicPools",
  168. "oceans",
  169. "earthVolumes",
  170. "universeVolumes",
  171. "multiverseVolumes",
  172. ],
  173. mass: [
  174. "kilograms",
  175. "milligrams",
  176. "grams",
  177. "tonnes",
  178. "lbs",
  179. "ounces",
  180. "tons"
  181. ]
  182. }
  183. const config = {
  184. height: math.unit(1500, "meters"),
  185. x: 0,
  186. y: 0,
  187. minLineSize: 100,
  188. maxLineSize: 150,
  189. autoFit: false
  190. }
  191. const availableEntities = {
  192. }
  193. const availableEntitiesByName = {
  194. }
  195. const entities = {
  196. }
  197. function constrainRel(coords) {
  198. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  199. const worldHeight = config.height.toNumber("meters");
  200. if (altHeld) {
  201. return coords;
  202. }
  203. return {
  204. x: Math.min(Math.max(coords.x, -worldWidth / 2 + config.x), worldWidth / 2 + config.x),
  205. y: Math.min(Math.max(coords.y, config.y), worldHeight + config.y)
  206. }
  207. }
  208. function snapRel(coords) {
  209. return constrainRel({
  210. x: coords.x,
  211. y: altHeld ? coords.y : (Math.abs(coords.y - 1) < 0.05 ? 1 : coords.y)
  212. });
  213. }
  214. function adjustAbs(coords, oldHeight, newHeight) {
  215. const ratio = math.divide(newHeight, oldHeight);
  216. const x = coords.x * ratio;
  217. const y = coords.y * ratio;
  218. return { x: x, y: y};
  219. }
  220. function pos2pix(coords) {
  221. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  222. const worldHeight = config.height.toNumber("meters");
  223. const x = ((coords.x - config.x) / worldWidth + 0.5) * canvasWidth + 50;
  224. const y = (1 - (coords.y - config.y) / worldHeight) * canvasHeight;
  225. return { x: x, y: y };
  226. }
  227. function pix2pos(coords) {
  228. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  229. const worldHeight = config.height.toNumber("meters");
  230. const x = (((coords.x - 50) / canvasWidth) - 0.5) * worldWidth + config.x;
  231. const y = (1 - (coords.y / canvasHeight)) * worldHeight + config.y;
  232. return { x: x, y: y };
  233. }
  234. function updateEntityElement(entity, element) {
  235. const position = pos2pix({ x: element.dataset.x, y: element.dataset.y });
  236. const view = entity.view;
  237. element.style.left = position.x + "px";
  238. element.style.top = position.y + "px";
  239. element.style.setProperty("--xpos", position.x + "px");
  240. element.style.setProperty("--entity-height", "'" + entity.views[view].height.to(config.height.units[0].unit.name).format({ precision: 2 }) + "'");
  241. const pixels = math.divide(entity.views[view].height, config.height) * (canvasHeight - 50);
  242. const extra = entity.views[view].image.extra;
  243. const bottom = entity.views[view].image.bottom;
  244. const bonus = (extra ? extra : 1) * (1 / (1 - (bottom ? bottom : 0)));
  245. element.style.setProperty("--height", pixels * bonus + "px");
  246. element.style.setProperty("--extra", pixels * bonus - pixels + "px");
  247. if (entity.views[view].rename)
  248. element.querySelector(".entity-name").innerText = entity.name == "" ? "" : entity.views[view].name;
  249. else
  250. element.querySelector(".entity-name").innerText = entity.name;
  251. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  252. bottomName.style.left = position.x + entityX + "px";
  253. bottomName.style.bottom = "0vh";
  254. bottomName.innerText = entity.name;
  255. const topName = document.querySelector("#top-name-" + element.dataset.key);
  256. topName.style.left = position.x + entityX + "px";
  257. topName.style.top = "20vh";
  258. topName.innerText = entity.name;
  259. if (entity.views[view].height.toNumber("meters") / 10 > config.height.toNumber("meters")) {
  260. topName.classList.add("top-name-needed");
  261. } else {
  262. topName.classList.remove("top-name-needed");
  263. }
  264. }
  265. function updateSizes(dirtyOnly = false) {
  266. drawScale(dirtyOnly);
  267. let ordered = Object.entries(entities);
  268. ordered.sort((e1, e2) => {
  269. if (e1[1].priority != e2[1].priority) {
  270. return e2[1].priority - e1[1].priority;
  271. } else {
  272. return e1[1].views[e1[1].view].height.value - e2[1].views[e2[1].view].height.value
  273. }
  274. });
  275. let zIndex = ordered.length;
  276. ordered.forEach(entity => {
  277. const element = document.querySelector("#entity-" + entity[0]);
  278. element.style.zIndex = zIndex;
  279. if (!dirtyOnly || entity[1].dirty) {
  280. updateEntityElement(entity[1], element, zIndex);
  281. entity[1].dirty = false;
  282. }
  283. zIndex -= 1;
  284. });
  285. }
  286. function drawScale(ifDirty = false) {
  287. if (ifDirty && !worldSizeDirty)
  288. return;
  289. function drawTicks(/** @type {CanvasRenderingContext2D} */ ctx, pixelsPer, heightPer) {
  290. let total = heightPer.clone();
  291. total.value = math.unit(config.y, "meters").toNumber(config.unit);
  292. for (let y = ctx.canvas.clientHeight - 50; y >= 50; y -= pixelsPer) {
  293. drawTick(ctx, 50, y, total);
  294. total = math.add(total, heightPer);
  295. }
  296. }
  297. function drawTick(/** @type {CanvasRenderingContext2D} */ ctx, x, y, value) {
  298. const oldStroke = ctx.strokeStyle;
  299. const oldFill = ctx.fillStyle;
  300. ctx.beginPath();
  301. ctx.moveTo(x, y);
  302. ctx.lineTo(x + 20, y);
  303. ctx.strokeStyle = "#000000";
  304. ctx.stroke();
  305. ctx.beginPath();
  306. ctx.moveTo(x + 20, y);
  307. ctx.lineTo(ctx.canvas.clientWidth - 70, y);
  308. ctx.strokeStyle = "#aaaaaa";
  309. ctx.stroke();
  310. ctx.beginPath();
  311. ctx.moveTo(ctx.canvas.clientWidth - 70, y);
  312. ctx.lineTo(ctx.canvas.clientWidth - 50, y);
  313. ctx.strokeStyle = "#000000";
  314. ctx.stroke();
  315. const oldFont = ctx.font;
  316. ctx.font = 'normal 24pt coda';
  317. ctx.fillStyle = "#dddddd";
  318. ctx.beginPath();
  319. ctx.fillText(value.format({ precision: 3 }), x + 20, y + 35);
  320. ctx.font = oldFont;
  321. ctx.strokeStyle = oldStroke;
  322. ctx.fillStyle = oldFill;
  323. }
  324. const canvas = document.querySelector("#display");
  325. /** @type {CanvasRenderingContext2D} */
  326. const ctx = canvas.getContext("2d");
  327. let pixelsPer = (ctx.canvas.clientHeight - 100) / config.height.toNumber();
  328. heightPer = 1;
  329. if (pixelsPer < config.minLineSize) {
  330. const factor = math.ceil(config.minLineSize / pixelsPer);
  331. heightPer *= factor;
  332. pixelsPer *= factor;
  333. }
  334. if (pixelsPer > config.maxLineSize) {
  335. const factor = math.ceil(pixelsPer / config.maxLineSize);
  336. heightPer /= factor;
  337. pixelsPer /= factor;
  338. }
  339. heightPer = math.unit(heightPer, document.querySelector("#options-height-unit").value);
  340. ctx.scale(1, 1);
  341. ctx.canvas.width = canvas.clientWidth;
  342. ctx.canvas.height = canvas.clientHeight;
  343. ctx.beginPath();
  344. ctx.rect(0, 0, canvas.width, canvas.height);
  345. ctx.fillStyle = "#333";
  346. ctx.fill();
  347. ctx.beginPath();
  348. ctx.moveTo(50, 50);
  349. ctx.lineTo(50, ctx.canvas.clientHeight - 50);
  350. ctx.stroke();
  351. ctx.beginPath();
  352. ctx.moveTo(ctx.canvas.clientWidth - 50, 50);
  353. ctx.lineTo(ctx.canvas.clientWidth - 50, ctx.canvas.clientHeight - 50);
  354. ctx.stroke();
  355. drawTicks(ctx, pixelsPer, heightPer);
  356. }
  357. // Entities are generated as needed, and we make a copy
  358. // every time - the resulting objects get mutated, after all.
  359. // But we also want to be able to read some information without
  360. // calling the constructor -- e.g. making a list of authors and
  361. // owners. So, this function is used to generate that information.
  362. // It is invoked like makeEntity so that it can be dropped in easily,
  363. // but returns an object that lets you construct many copies of an entity,
  364. // rather than creating a new entity.
  365. function createEntityMaker(info, views, sizes) {
  366. const maker = {};
  367. maker.name = info.name;
  368. maker.info = info;
  369. maker.sizes = sizes;
  370. maker.constructor = () => makeEntity(info, views, sizes);
  371. maker.authors = [];
  372. maker.owners = [];
  373. maker.nsfw = false;
  374. Object.values(views).forEach(view => {
  375. const authors = authorsOf(view.image.source);
  376. if (authors) {
  377. authors.forEach(author => {
  378. if (maker.authors.indexOf(author) == -1) {
  379. maker.authors.push(author);
  380. }
  381. });
  382. }
  383. const owners = ownersOf(view.image.source);
  384. if (owners) {
  385. owners.forEach(owner => {
  386. if (maker.owners.indexOf(owner) == -1) {
  387. maker.owners.push(owner);
  388. }
  389. });
  390. }
  391. if (isNsfw(view.image.source)) {
  392. maker.nsfw = true;
  393. }
  394. });
  395. return maker;
  396. }
  397. // This function serializes and parses its arguments to avoid sharing
  398. // references to a common object. This allows for the objects to be
  399. // safely mutated.
  400. function makeEntity(info, views, sizes) {
  401. const entityTemplate = {
  402. name: info.name,
  403. identifier: info.name,
  404. scale: 1,
  405. info: JSON.parse(JSON.stringify(info)),
  406. views: JSON.parse(JSON.stringify(views), math.reviver),
  407. sizes: sizes === undefined ? [] : JSON.parse(JSON.stringify(sizes), math.reviver),
  408. init: function () {
  409. const entity = this;
  410. Object.entries(this.views).forEach(([viewKey, view]) => {
  411. view.parent = this;
  412. if (this.defaultView === undefined) {
  413. this.defaultView = viewKey;
  414. this.view = viewKey;
  415. }
  416. if (view.default) {
  417. this.defaultView = viewKey;
  418. this.view = viewKey;
  419. }
  420. Object.entries(view.attributes).forEach(([key, val]) => {
  421. Object.defineProperty(
  422. view,
  423. key,
  424. {
  425. get: function () {
  426. return math.multiply(Math.pow(this.parent.scale, this.attributes[key].power), this.attributes[key].base);
  427. },
  428. set: function (value) {
  429. const newScale = Math.pow(math.divide(value, this.attributes[key].base), 1 / this.attributes[key].power);
  430. this.parent.scale = newScale;
  431. }
  432. }
  433. )
  434. });
  435. });
  436. this.sizes.forEach(size => {
  437. if (size.default === true) {
  438. this.views[this.defaultView].height = size.height;
  439. this.size = size;
  440. }
  441. });
  442. if (this.size === undefined && this.sizes.length > 0) {
  443. this.views[this.defaultView].height = this.sizes[0].height;
  444. this.size = this.sizes[0];
  445. console.warn("No default size set for " + info.name);
  446. } else if (this.sizes.length == 0) {
  447. this.sizes = [
  448. {
  449. name: "Normal",
  450. height: this.views[this.defaultView].height
  451. }
  452. ];
  453. this.size = this.sizes[0];
  454. }
  455. this.desc = {};
  456. Object.entries(this.info).forEach(([key, value]) => {
  457. Object.defineProperty(
  458. this.desc,
  459. key,
  460. {
  461. get: function () {
  462. let text = value.text;
  463. if (entity.views[entity.view].info) {
  464. if (entity.views[entity.view].info[key]) {
  465. text = combineInfo(text, entity.views[entity.view].info[key]);
  466. }
  467. }
  468. if (entity.size.info) {
  469. if (entity.size.info[key]) {
  470. text = combineInfo(text, entity.size.info[key]);
  471. }
  472. }
  473. return { title: value.title, text: text };
  474. }
  475. }
  476. )
  477. });
  478. delete this.init;
  479. return this;
  480. }
  481. }.init();
  482. return entityTemplate;
  483. }
  484. function combineInfo(existing, next) {
  485. switch (next.mode) {
  486. case "replace":
  487. return next.text;
  488. case "prepend":
  489. return next.text + existing;
  490. case "append":
  491. return existing + next.text;
  492. }
  493. return existing;
  494. }
  495. function clickDown(target, x, y) {
  496. clicked = target;
  497. const rect = target.getBoundingClientRect();
  498. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  499. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  500. dragOffsetX = x - rect.left + entX;
  501. dragOffsetY = y - rect.top + entY;
  502. clickTimeout = setTimeout(() => { dragging = true }, 200)
  503. target.classList.add("no-transition");
  504. }
  505. // could we make this actually detect the menu area?
  506. function hoveringInDeleteArea(e) {
  507. return e.clientY < document.body.clientHeight / 10;
  508. }
  509. function clickUp(e) {
  510. clearTimeout(clickTimeout);
  511. if (clicked) {
  512. if (dragging) {
  513. dragging = false;
  514. if (hoveringInDeleteArea(e)) {
  515. removeEntity(clicked);
  516. document.querySelector("#menubar").classList.remove("hover-delete");
  517. }
  518. } else {
  519. select(clicked);
  520. }
  521. clicked.classList.remove("no-transition");
  522. clicked = null;
  523. }
  524. }
  525. function deselect(e) {
  526. if (e !== undefined && e.which != 1) {
  527. return;
  528. }
  529. if (selected) {
  530. selected.classList.remove("selected");
  531. }
  532. document.getElementById("options-selected-entity-none").selected = "selected";
  533. clearAttribution();
  534. selected = null;
  535. clearViewList();
  536. clearEntityOptions();
  537. clearViewOptions();
  538. document.querySelector("#delete-entity").disabled = true;
  539. document.querySelector("#grow").disabled = true;
  540. document.querySelector("#shrink").disabled = true;
  541. document.querySelector("#fit").disabled = true;
  542. }
  543. function select(target) {
  544. deselect();
  545. selected = target;
  546. selectedEntity = entities[target.dataset.key];
  547. document.getElementById("options-selected-entity-" + target.dataset.key).selected = "selected";
  548. selected.classList.add("selected");
  549. displayAttribution(selectedEntity.views[selectedEntity.view].image.source);
  550. configViewList(selectedEntity, selectedEntity.view);
  551. configEntityOptions(selectedEntity, selectedEntity.view);
  552. configViewOptions(selectedEntity, selectedEntity.view);
  553. document.querySelector("#delete-entity").disabled = false;
  554. document.querySelector("#grow").disabled = false;
  555. document.querySelector("#shrink").disabled = false;
  556. document.querySelector("#fit").disabled = false;
  557. }
  558. function configViewList(entity, selectedView) {
  559. const list = document.querySelector("#entity-view");
  560. list.innerHTML = "";
  561. list.style.display = "block";
  562. Object.keys(entity.views).forEach(view => {
  563. const option = document.createElement("option");
  564. option.innerText = entity.views[view].name;
  565. option.value = view;
  566. if (isNsfw(entity.views[view].image.source)) {
  567. option.classList.add("nsfw")
  568. }
  569. if (view === selectedView) {
  570. option.selected = true;
  571. if (option.classList.contains("nsfw")) {
  572. list.classList.add("nsfw");
  573. } else {
  574. list.classList.remove("nsfw");
  575. }
  576. }
  577. list.appendChild(option);
  578. });
  579. }
  580. function clearViewList() {
  581. const list = document.querySelector("#entity-view");
  582. list.innerHTML = "";
  583. list.style.display = "none";
  584. }
  585. function updateWorldOptions(entity, view) {
  586. const heightInput = document.querySelector("#options-height-value");
  587. const heightSelect = document.querySelector("#options-height-unit");
  588. const converted = config.height.toNumber(heightSelect.value);
  589. setNumericInput(heightInput, converted);
  590. }
  591. function configEntityOptions(entity, view) {
  592. const holder = document.querySelector("#options-entity");
  593. document.querySelector("#entity-category-header").style.display = "block";
  594. document.querySelector("#entity-category").style.display = "block";
  595. holder.innerHTML = "";
  596. const scaleLabel = document.createElement("div");
  597. scaleLabel.classList.add("options-label");
  598. scaleLabel.innerText = "Scale";
  599. const scaleRow = document.createElement("div");
  600. scaleRow.classList.add("options-row");
  601. const scaleInput = document.createElement("input");
  602. scaleInput.classList.add("options-field-numeric");
  603. scaleInput.id = "options-entity-scale";
  604. scaleInput.addEventListener("change", e => {
  605. entity.scale = e.target.value == 0 ? 1 : e.target.value;
  606. entity.dirty = true;
  607. if (config.autoFit) {
  608. fitWorld();
  609. } else {
  610. updateSizes(true);
  611. }
  612. updateEntityOptions(entity, view);
  613. updateViewOptions(entity, view);
  614. });
  615. scaleInput.addEventListener("keydown", e => {
  616. e.stopPropagation();
  617. })
  618. scaleInput.setAttribute("min", 1);
  619. scaleInput.setAttribute("type", "number");
  620. setNumericInput(scaleInput, entity.scale);
  621. scaleRow.appendChild(scaleInput);
  622. holder.appendChild(scaleLabel);
  623. holder.appendChild(scaleRow);
  624. const nameLabel = document.createElement("div");
  625. nameLabel.classList.add("options-label");
  626. nameLabel.innerText = "Name";
  627. const nameRow = document.createElement("div");
  628. nameRow.classList.add("options-row");
  629. const nameInput = document.createElement("input");
  630. nameInput.classList.add("options-field-text");
  631. nameInput.value = entity.name;
  632. nameInput.addEventListener("input", e => {
  633. entity.name = e.target.value;
  634. entity.dirty = true;
  635. updateSizes(true);
  636. })
  637. nameInput.addEventListener("keydown", e => {
  638. e.stopPropagation();
  639. })
  640. nameRow.appendChild(nameInput);
  641. holder.appendChild(nameLabel);
  642. holder.appendChild(nameRow);
  643. const defaultHolder = document.querySelector("#options-entity-defaults");
  644. defaultHolder.innerHTML = "";
  645. entity.sizes.forEach(defaultInfo => {
  646. const button = document.createElement("button");
  647. button.classList.add("options-button");
  648. button.innerText = defaultInfo.name;
  649. button.addEventListener("click", e => {
  650. entity.views[entity.defaultView].height = defaultInfo.height;
  651. entity.dirty = true;
  652. updateEntityOptions(entity, entity.view);
  653. updateViewOptions(entity, entity.view);
  654. if (!checkFitWorld()) {
  655. updateSizes(true);
  656. }
  657. if (config.autoFitSize) {
  658. const x = parseFloat(selected.dataset.x);
  659. Object.keys(entities).forEach(id => {
  660. const element = document.querySelector("#entity-" + id);
  661. const newX = parseFloat(element.dataset.x) - x + 0.5;
  662. element.dataset.x = newX;
  663. });
  664. const entity = entities[selected.dataset.key];
  665. const height = math.multiply(entity.views[entity.view].height, 1.1);
  666. setWorldHeight(config.height, height);
  667. }
  668. });
  669. defaultHolder.appendChild(button);
  670. });
  671. document.querySelector("#options-order-display").innerText = entity.priority;
  672. document.querySelector("#options-ordering").style.display = "flex";
  673. }
  674. function updateEntityOptions(entity, view) {
  675. const scaleInput = document.querySelector("#options-entity-scale");
  676. setNumericInput(scaleInput, entity.scale);
  677. document.querySelector("#options-order-display").innerText = entity.priority;
  678. }
  679. function clearEntityOptions() {
  680. document.querySelector("#entity-category-header").style.display = "none";
  681. document.querySelector("#entity-category").style.display = "none";
  682. /*
  683. const holder = document.querySelector("#options-entity");
  684. holder.innerHTML = "";
  685. document.querySelector("#options-entity-defaults").innerHTML = "";
  686. document.querySelector("#options-ordering").style.display = "none";
  687. document.querySelector("#options-ordering").style.display = "none";*/
  688. }
  689. function configViewOptions(entity, view) {
  690. const holder = document.querySelector("#options-view");
  691. document.querySelector("#view-category-header").style.display = "block";
  692. document.querySelector("#view-category").style.display = "block";
  693. holder.innerHTML = "";
  694. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  695. const label = document.createElement("div");
  696. label.classList.add("options-label");
  697. label.innerText = val.name;
  698. holder.appendChild(label);
  699. const row = document.createElement("div");
  700. row.classList.add("options-row");
  701. holder.appendChild(row);
  702. const input = document.createElement("input");
  703. input.classList.add("options-field-numeric");
  704. input.id = "options-view-" + key + "-input";
  705. input.setAttribute("type", "number");
  706. input.setAttribute("min", 1);
  707. const select = document.createElement("select");
  708. select.classList.add("options-field-unit");
  709. select.id = "options-view-" + key + "-select"
  710. unitChoices[val.type].forEach(name => {
  711. const option = document.createElement("option");
  712. option.innerText = name;
  713. select.appendChild(option);
  714. });
  715. input.addEventListener("change", e => {
  716. const value = input.value == 0 ? 1 : input.value;
  717. entity.views[view][key] = math.unit(value, select.value);
  718. entity.dirty = true;
  719. if (config.autoFit) {
  720. fitWorld();
  721. } else {
  722. updateSizes(true);
  723. }
  724. updateEntityOptions(entity, view);
  725. updateViewOptions(entity, view, key);
  726. });
  727. input.addEventListener("keydown", e => {
  728. e.stopPropagation();
  729. })
  730. select.setAttribute("oldUnit", select.value);
  731. setNumericInput(input, entity.views[view][key].toNumber(select.value));
  732. // TODO does this ever cause a change in the world?
  733. select.addEventListener("input", e => {
  734. const value = input.value == 0 ? 1 : input.value;
  735. const oldUnit = select.getAttribute("oldUnit");
  736. entity.views[entity.view][key] = math.unit(value, oldUnit).to(select.value);
  737. entity.dirty = true;
  738. setNumericInput(input, entity.views[entity.view][key].toNumber(select.value));
  739. select.setAttribute("oldUnit", select.value);
  740. if (config.autoFit) {
  741. fitWorld();
  742. } else {
  743. updateSizes(true);
  744. }
  745. updateEntityOptions(entity, view);
  746. updateViewOptions(entity, view, key);
  747. });
  748. row.appendChild(input);
  749. row.appendChild(select);
  750. });
  751. }
  752. function updateViewOptions(entity, view, changed) {
  753. Object.entries(entity.views[view].attributes).forEach(([key, val]) => {
  754. if (key != changed) {
  755. const input = document.querySelector("#options-view-" + key + "-input");
  756. const select = document.querySelector("#options-view-" + key + "-select");
  757. const currentUnit = select.value;
  758. const convertedAmount = entity.views[view][key].toNumber(currentUnit);
  759. setNumericInput(input, convertedAmount);
  760. }
  761. });
  762. }
  763. function setNumericInput(input, value, round = 6) {
  764. if (typeof value == "string") {
  765. value = parseFloat(value)
  766. }
  767. input.value = value.toPrecision(round);
  768. }
  769. function getSortedEntities() {
  770. return Object.keys(entities).sort((a, b) => {
  771. const entA = entities[a];
  772. const entB = entities[b];
  773. const viewA = entA.view;
  774. const viewB = entB.view;
  775. const heightA = entA.views[viewA].height.to("meter").value;
  776. const heightB = entB.views[viewB].height.to("meter").value;
  777. return heightA - heightB;
  778. });
  779. }
  780. function clearViewOptions() {
  781. document.querySelector("#view-category-header").style.display = "none";
  782. document.querySelector("#view-category").style.display = "none";
  783. }
  784. // this is a crime against humanity, and also stolen from
  785. // stack overflow
  786. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  787. const testCanvas = document.createElement("canvas");
  788. testCanvas.id = "test-canvas";
  789. const testCtx = testCanvas.getContext("2d");
  790. function testClick(event) {
  791. // oh my god I can't believe I'm doing this
  792. const target = event.target;
  793. if (navigator.userAgent.indexOf("Firefox") != -1) {
  794. clickDown(target.parentElement, event.clientX, event.clientY);
  795. return;
  796. }
  797. // Get click coordinates
  798. let w = target.width;
  799. let h = target.height;
  800. let ratioW = 1, ratioH = 1;
  801. // Limit the size of the canvas so that very large images don't cause problems)
  802. if (w > 1000) {
  803. ratioW = w / 1000;
  804. w /= ratioW;
  805. h /= ratioW;
  806. }
  807. if (h > 1000) {
  808. ratioH = h / 1000;
  809. w /= ratioH;
  810. h /= ratioH;
  811. }
  812. const ratio = ratioW * ratioH;
  813. var x = event.clientX - target.getBoundingClientRect().x,
  814. y = event.clientY - target.getBoundingClientRect().y,
  815. alpha;
  816. testCtx.canvas.width = w;
  817. testCtx.canvas.height = h;
  818. // Draw image to canvas
  819. // and read Alpha channel value
  820. testCtx.drawImage(target, 0, 0, w, h);
  821. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  822. // If pixel is transparent,
  823. // retrieve the element underneath and trigger its click event
  824. if (alpha === 0) {
  825. const oldDisplay = target.style.display;
  826. target.style.display = "none";
  827. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  828. newTarget.dispatchEvent(new MouseEvent(event.type, {
  829. "clientX": event.clientX,
  830. "clientY": event.clientY
  831. }));
  832. target.style.display = oldDisplay;
  833. } else {
  834. clickDown(target.parentElement, event.clientX, event.clientY);
  835. }
  836. }
  837. function arrangeEntities(order) {
  838. fitWorld();
  839. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  840. let x = -worldWidth * 0.45 + config.x;
  841. console.log(x);
  842. order.forEach(key => {
  843. document.querySelector("#entity-" + key).dataset.x = x;
  844. document.querySelector("#entity-" + key).dataset.y = config.y;
  845. x += worldWidth * 0.9 / (order.length - 1);
  846. });
  847. updateSizes();
  848. }
  849. function removeAllEntities() {
  850. Object.keys(entities).forEach(key => {
  851. removeEntity(document.querySelector("#entity-" + key));
  852. });
  853. }
  854. function clearAttribution() {
  855. document.querySelector("#attribution-category-header").style.display = "none";
  856. document.querySelector("#options-attribution").style.display = "none";
  857. }
  858. function displayAttribution(file) {
  859. document.querySelector("#attribution-category-header").style.display = "block";
  860. document.querySelector("#options-attribution").style.display = "inline";
  861. const authors = authorsOfFull(file);
  862. const owners = ownersOfFull(file);
  863. const source = sourceOf(file);
  864. const authorHolder = document.querySelector("#options-attribution-authors");
  865. const ownerHolder = document.querySelector("#options-attribution-owners");
  866. const sourceHolder = document.querySelector("#options-attribution-source");
  867. if (authors === []) {
  868. const div = document.createElement("div");
  869. div.innerText = "Unknown";
  870. authorHolder.innerHTML = "";
  871. authorHolder.appendChild(div);
  872. } else if (authors === undefined) {
  873. const div = document.createElement("div");
  874. div.innerText = "Not yet entered";
  875. authorHolder.innerHTML = "";
  876. authorHolder.appendChild(div);
  877. } else {
  878. authorHolder.innerHTML = "";
  879. const list = document.createElement("ul");
  880. authorHolder.appendChild(list);
  881. authors.forEach(author => {
  882. const authorEntry = document.createElement("li");
  883. if (author.url) {
  884. const link = document.createElement("a");
  885. link.href = author.url;
  886. link.innerText = author.name;
  887. authorEntry.appendChild(link);
  888. } else {
  889. const div = document.createElement("div");
  890. div.innerText = author.name;
  891. authorEntry.appendChild(div);
  892. }
  893. list.appendChild(authorEntry);
  894. });
  895. }
  896. if (owners === []) {
  897. const div = document.createElement("div");
  898. div.innerText = "Unknown";
  899. ownerHolder.innerHTML = "";
  900. ownerHolder.appendChild(div);
  901. } else if (owners === undefined) {
  902. const div = document.createElement("div");
  903. div.innerText = "Not yet entered";
  904. ownerHolder.innerHTML = "";
  905. ownerHolder.appendChild(div);
  906. } else {
  907. ownerHolder.innerHTML = "";
  908. const list = document.createElement("ul");
  909. ownerHolder.appendChild(list);
  910. owners.forEach(owner => {
  911. const ownerEntry = document.createElement("li");
  912. if (owner.url) {
  913. const link = document.createElement("a");
  914. link.href = owner.url;
  915. link.innerText = owner.name;
  916. ownerEntry.appendChild(link);
  917. } else {
  918. const div = document.createElement("div");
  919. div.innerText = owner.name;
  920. ownerEntry.appendChild(div);
  921. }
  922. list.appendChild(ownerEntry);
  923. });
  924. }
  925. if (source === null) {
  926. const div = document.createElement("div");
  927. div.innerText = "No link";
  928. sourceHolder.innerHTML = "";
  929. sourceHolder.appendChild(div);
  930. } else if (source === undefined) {
  931. const div = document.createElement("div");
  932. div.innerText = "Not yet entered";
  933. sourceHolder.innerHTML = "";
  934. sourceHolder.appendChild(div);
  935. } else {
  936. sourceHolder.innerHTML = "";
  937. const link = document.createElement("a");
  938. link.style.display = "block";
  939. link.href = source;
  940. link.innerText = new URL(source).host;
  941. sourceHolder.appendChild(link);
  942. }
  943. }
  944. function removeEntity(element) {
  945. if (selected == element) {
  946. deselect();
  947. }
  948. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  949. option.parentElement.removeChild(option);
  950. delete entities[element.dataset.key];
  951. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  952. const topName = document.querySelector("#top-name-" + element.dataset.key);
  953. bottomName.parentElement.removeChild(bottomName);
  954. topName.parentElement.removeChild(topName);
  955. element.parentElement.removeChild(element);
  956. }
  957. function checkEntity(entity) {
  958. Object.values(entity.views).forEach(view => {
  959. if (authorsOf(view.image.source) === undefined) {
  960. console.warn("No authors: " + view.image.source);
  961. }
  962. });
  963. }
  964. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  965. checkEntity(entity);
  966. const box = document.createElement("div");
  967. box.classList.add("entity-box");
  968. const img = document.createElement("img");
  969. img.classList.add("entity-image");
  970. img.addEventListener("dragstart", e => {
  971. e.preventDefault();
  972. });
  973. const nameTag = document.createElement("div");
  974. nameTag.classList.add("entity-name");
  975. nameTag.innerText = entity.name;
  976. box.appendChild(img);
  977. box.appendChild(nameTag);
  978. const image = entity.views[view].image;
  979. img.src = image.source;
  980. if (image.bottom !== undefined) {
  981. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  982. } else {
  983. img.style.setProperty("--offset", ((-1) * 100) + "%")
  984. }
  985. box.dataset.x = x;
  986. box.dataset.y = y;
  987. img.addEventListener("mousedown", e => { if (e.which == 1) { testClick(e); e.stopPropagation() } });
  988. img.addEventListener("touchstart", e => {
  989. const fakeEvent = {
  990. target: e.target,
  991. clientX: e.touches[0].clientX,
  992. clientY: e.touches[0].clientY
  993. };
  994. testClick(fakeEvent);
  995. });
  996. const heightBar = document.createElement("div");
  997. heightBar.classList.add("height-bar");
  998. box.appendChild(heightBar);
  999. box.id = "entity-" + entityIndex;
  1000. box.dataset.key = entityIndex;
  1001. entity.view = view;
  1002. entity.priority = 0;
  1003. entities[entityIndex] = entity;
  1004. entity.index = entityIndex;
  1005. const world = document.querySelector("#entities");
  1006. world.appendChild(box);
  1007. const bottomName = document.createElement("div");
  1008. bottomName.classList.add("bottom-name");
  1009. bottomName.id = "bottom-name-" + entityIndex;
  1010. bottomName.innerText = entity.name;
  1011. bottomName.addEventListener("click", () => select(box));
  1012. world.appendChild(bottomName);
  1013. const topName = document.createElement("div");
  1014. topName.classList.add("top-name");
  1015. topName.id = "top-name-" + entityIndex;
  1016. topName.innerText = entity.name;
  1017. topName.addEventListener("click", () => select(box));
  1018. world.appendChild(topName);
  1019. const entityOption = document.createElement("option");
  1020. entityOption.id = "options-selected-entity-" + entityIndex;
  1021. entityOption.value = entityIndex;
  1022. entityOption.innerText = entity.name;
  1023. document.getElementById("options-selected-entity").appendChild(entityOption);
  1024. entityIndex += 1;
  1025. if (config.autoFit) {
  1026. fitWorld();
  1027. }
  1028. if (selectEntity)
  1029. select(box);
  1030. entity.dirty = true;
  1031. if (refresh && config.autoFitAdd) {
  1032. const x = parseFloat(selected.dataset.x);
  1033. const y = parseFloat(selected.dataset.y);
  1034. config.x = x;
  1035. config.y = y;
  1036. const entity = entities[selected.dataset.key];
  1037. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1038. setWorldHeight(config.height, height);
  1039. }
  1040. if (refresh)
  1041. updateSizes(true);
  1042. }
  1043. window.onblur = function () {
  1044. altHeld = false;
  1045. shiftHeld = false;
  1046. }
  1047. window.onfocus = function () {
  1048. window.dispatchEvent(new Event("keydown"));
  1049. }
  1050. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1051. function toggleFullScreen() {
  1052. var doc = window.document;
  1053. var docEl = doc.documentElement;
  1054. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1055. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1056. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1057. requestFullScreen.call(docEl);
  1058. }
  1059. else {
  1060. cancelFullScreen.call(doc);
  1061. }
  1062. }
  1063. function handleResize() {
  1064. const oldCanvasWidth = canvasWidth;
  1065. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1066. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1067. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1068. const change = oldCanvasWidth / canvasWidth;
  1069. doHorizReposition(change);
  1070. updateSizes();
  1071. }
  1072. function doHorizReposition(change) {
  1073. Object.keys(entities).forEach(key => {
  1074. const element = document.querySelector("#entity-" + key);
  1075. const x = element.dataset.x;
  1076. element.dataset.x = (x - 0.5) * change + 0.5;
  1077. });
  1078. }
  1079. function prepareSidebar() {
  1080. const menubar = document.querySelector("#sidebar-menu");
  1081. [
  1082. {
  1083. name: "Show/hide sidebar",
  1084. id: "menu-toggle-sidebar",
  1085. icon: "fas fa-chevron-circle-down",
  1086. rotates: true
  1087. },
  1088. {
  1089. name: "Fullscreen",
  1090. id: "menu-fullscreen",
  1091. icon: "fas fa-compress"
  1092. },
  1093. {
  1094. name: "Clear",
  1095. id: "menu-clear",
  1096. icon: "fas fa-file"
  1097. },
  1098. {
  1099. name: "Sort by height",
  1100. id: "menu-order-height",
  1101. icon: "fas fa-sort-numeric-up"
  1102. },
  1103. {
  1104. name: "Permalink",
  1105. id: "menu-permalink",
  1106. icon: "fas fa-link"
  1107. },
  1108. {
  1109. name: "Export to clipboard",
  1110. id: "menu-export",
  1111. icon: "fas fa-share"
  1112. },
  1113. {
  1114. name: "Import from clipboard",
  1115. id: "menu-import",
  1116. icon: "fas fa-share",
  1117. classes: ["flipped"]
  1118. },
  1119. {
  1120. name: "Save",
  1121. id: "menu-save",
  1122. icon: "fas fa-download"
  1123. },
  1124. {
  1125. name: "Load",
  1126. id: "menu-load",
  1127. icon: "fas fa-upload"
  1128. },
  1129. {
  1130. name: "Load Autosave",
  1131. id: "menu-load-autosave",
  1132. icon: "fas fa-redo"
  1133. },
  1134. {
  1135. name: "Add Image",
  1136. id: "menu-add-image",
  1137. icon: "fas fa-camera"
  1138. }
  1139. ].forEach(entry => {
  1140. const buttonHolder = document.createElement("div");
  1141. buttonHolder.classList.add("menu-button-holder");
  1142. const button = document.createElement("button");
  1143. button.id = entry.id;
  1144. button.classList.add("menu-button");
  1145. const icon = document.createElement("i");
  1146. icon.classList.add(...entry.icon.split(" "));
  1147. if (entry.rotates) {
  1148. icon.classList.add("rotate-backward", "transitions");
  1149. }
  1150. if (entry.classes) {
  1151. entry.classes.forEach(cls => icon.classList.add(cls));
  1152. }
  1153. const actionText = document.createElement("span");
  1154. actionText.innerText = entry.name;
  1155. actionText.classList.add("menu-text");
  1156. const srText = document.createElement("span");
  1157. srText.classList.add("sr-only");
  1158. srText.innerText = entry.name;
  1159. button.appendChild(icon);
  1160. button.appendChild(srText);
  1161. buttonHolder.appendChild(button);
  1162. buttonHolder.appendChild(actionText);
  1163. menubar.appendChild(buttonHolder);
  1164. });
  1165. }
  1166. function checkBodyClass(cls) {
  1167. return document.body.classList.contains(cls);
  1168. }
  1169. function toggleBodyClass(cls, setting) {
  1170. if (setting) {
  1171. document.body.classList.add(cls);
  1172. } else {
  1173. document.body.classList.remove(cls);
  1174. }
  1175. }
  1176. const settingsData = {
  1177. "auto-scale": {
  1178. name: "Auto-Size World",
  1179. desc: "Constantly zoom to fit the largest entity",
  1180. type: "toggle",
  1181. default: false,
  1182. get value() {
  1183. return config.autoFit;
  1184. },
  1185. set value(param) {
  1186. config.autoFit = param;
  1187. checkFitWorld();
  1188. }
  1189. },
  1190. "zoom-when-adding": {
  1191. name: "Zoom When Adding",
  1192. desc: "Zoom to fit when you add a new entity",
  1193. type: "toggle",
  1194. default: true,
  1195. get value() {
  1196. return config.autoFitAdd;
  1197. },
  1198. set value(param) {
  1199. config.autoFitAdd = param;
  1200. }
  1201. },
  1202. "zoom-when-sizing": {
  1203. name: "Zoom When Sizing",
  1204. desc: "Zoom to fit when you select an entity's size",
  1205. type: "toggle",
  1206. default: true,
  1207. get value() {
  1208. return config.autoFitSize;
  1209. },
  1210. set value(param) {
  1211. config.autoFitSize = param;
  1212. }
  1213. },
  1214. "names": {
  1215. name: "Show Names",
  1216. desc: "Display names over entities",
  1217. type: "toggle",
  1218. default: true,
  1219. get value() {
  1220. return checkBodyClass("toggle-entity-name");
  1221. },
  1222. set value(param) {
  1223. toggleBodyClass("toggle-entity-name", param);
  1224. }
  1225. },
  1226. "bottom-names": {
  1227. name: "Bottom Names",
  1228. desc: "Display names at the bottom",
  1229. type: "toggle",
  1230. default: false,
  1231. get value() {
  1232. return checkBodyClass("toggle-bottom-name");
  1233. },
  1234. set value(param) {
  1235. toggleBodyClass("toggle-bottom-name", param);
  1236. }
  1237. },
  1238. "top-names": {
  1239. name: "Show Arrows",
  1240. desc: "Point to entities that are much larger than the current view",
  1241. type: "toggle",
  1242. default: false,
  1243. get value() {
  1244. return checkBodyClass("toggle-top-name");
  1245. },
  1246. set value(param) {
  1247. toggleBodyClass("toggle-top-name", param);
  1248. }
  1249. },
  1250. "height-bars": {
  1251. name: "Height Bars",
  1252. desc: "Draw dashed lines to the top of each entity",
  1253. type: "toggle",
  1254. default: false,
  1255. get value() {
  1256. return checkBodyClass("toggle-height-bars");
  1257. },
  1258. set value(param) {
  1259. toggleBodyClass("toggle-height-bars", param);
  1260. }
  1261. },
  1262. "glowing-entities": {
  1263. name: "Glowing Edges",
  1264. desc: "Makes all entities glow",
  1265. type: "toggle",
  1266. default: false,
  1267. get value() {
  1268. return checkBodyClass("toggle-entity-glow");
  1269. },
  1270. set value(param) {
  1271. toggleBodyClass("toggle-entity-glow", param);
  1272. }
  1273. },
  1274. "solid-ground": {
  1275. name: "Solid Ground",
  1276. desc: "Draw solid ground at the y=0 line",
  1277. type: "toggle",
  1278. default: false,
  1279. get value() {
  1280. return checkBodyClass("toggle-bottom-cover");
  1281. },
  1282. set value(param) {
  1283. toggleBodyClass("toggle-bottom-cover", param);
  1284. }
  1285. },
  1286. "show-scale": {
  1287. name: "Show Scale",
  1288. desc: "Show the scale",
  1289. type: "toggle",
  1290. default: true,
  1291. get value() {
  1292. return checkBodyClass("toggle-scale");
  1293. },
  1294. set value(param) {
  1295. toggleBodyClass("toggle-scale", param);
  1296. }
  1297. },
  1298. }
  1299. function prepareSettings(userSettings) {
  1300. const menubar = document.querySelector("#settings-menu");
  1301. Object.entries(settingsData).forEach(([id, entry]) => {
  1302. const holder = document.createElement("label");
  1303. holder.classList.add("settings-holder");
  1304. const input = document.createElement("input");
  1305. input.id = "setting-" + id;
  1306. const name = document.createElement("label");
  1307. name.innerText = entry.name;
  1308. name.classList.add("settings-name");
  1309. name.setAttribute("for", input.id);
  1310. const desc = document.createElement("label");
  1311. desc.innerText = entry.desc;
  1312. desc.classList.add("settings-desc");
  1313. desc.setAttribute("for", input.id);
  1314. if (entry.type == "toggle") {
  1315. input.type = "checkbox";
  1316. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  1317. holder.setAttribute("for", input.id);
  1318. input.appendChild(name);
  1319. input.appendChild(desc);
  1320. holder.appendChild(input);
  1321. holder.appendChild(name);
  1322. holder.appendChild(desc);
  1323. menubar.appendChild(holder);
  1324. const update = () => {
  1325. if (input.checked) {
  1326. holder.classList.add("enabled");
  1327. holder.classList.remove("disabled");
  1328. } else {
  1329. holder.classList.remove("enabled");
  1330. holder.classList.add("disabled");
  1331. }
  1332. entry.value = input.checked;
  1333. }
  1334. update();
  1335. input.addEventListener("change", update);
  1336. }
  1337. })
  1338. }
  1339. function prepareMenu() {
  1340. prepareSidebar();
  1341. if (checkHelpDate()) {
  1342. document.querySelector("#open-help").classList.add("highlighted");
  1343. }
  1344. }
  1345. function getUserSettings() {
  1346. try {
  1347. const settings = JSON.parse(localStorage.getItem("settings"));
  1348. return settings === null ? {} : settings;
  1349. } catch {
  1350. return {};
  1351. }
  1352. }
  1353. function exportUserSettings() {
  1354. const settings = {};
  1355. Object.entries(settingsData).forEach(([id, entry]) => {
  1356. settings[id] = entry.value;
  1357. });
  1358. return settings;
  1359. }
  1360. function setUserSettings(settings) {
  1361. try {
  1362. localStorage.setItem("settings", JSON.stringify(settings));
  1363. } catch {
  1364. // :(
  1365. }
  1366. }
  1367. const lastHelpChange = 1587847743294;
  1368. function checkHelpDate() {
  1369. try {
  1370. const old = localStorage.getItem("help-viewed");
  1371. if (old === null || old < lastHelpChange) {
  1372. return true;
  1373. }
  1374. return false;
  1375. } catch {
  1376. console.warn("Could not set the help-viewed date");
  1377. return false;
  1378. }
  1379. }
  1380. function setHelpDate() {
  1381. try {
  1382. localStorage.setItem("help-viewed", Date.now());
  1383. } catch {
  1384. console.warn("Could not set the help-viewed date");
  1385. }
  1386. }
  1387. function doYScroll() {
  1388. const worldHeight = config.height.toNumber("meters");
  1389. config.y += scrollDirection * worldHeight / 180;
  1390. updateSizes();
  1391. scrollDirection *= 1.05;
  1392. }
  1393. function doXScroll() {
  1394. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1395. config.x += scrollDirection * worldWidth / 180 ;
  1396. updateSizes();
  1397. scrollDirection *= 1.05;
  1398. }
  1399. function doZoom() {
  1400. const oldHeight = config.height;
  1401. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1402. zoomDirection *= 1.05;
  1403. }
  1404. function doSize() {
  1405. if (selected) {
  1406. const entity = entities[selected.dataset.key];
  1407. const oldHeight = entity.views[entity.view].height;
  1408. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection / 20);
  1409. entity.dirty = true;
  1410. updateEntityOptions(entity, entity.view);
  1411. updateViewOptions(entity, entity.view);
  1412. updateSizes(true);
  1413. sizeDirection *= 1.05;
  1414. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1415. const worldHeight = config.height.toNumber("meters");
  1416. if (ownHeight > worldHeight) {
  1417. setWorldHeight(config.height, entity.views[entity.view].height)
  1418. } else if (ownHeight * 10 < worldHeight) {
  1419. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1420. }
  1421. }
  1422. }
  1423. function prepareHelp() {
  1424. const toc = document.querySelector("#table-of-contents");
  1425. const holder = document.querySelector("#help-contents-holder");
  1426. document.querySelectorAll("#help-contents h2").forEach(header => {
  1427. const li = document.createElement("li");
  1428. li.innerText = header.textContent;
  1429. li.addEventListener("click", e => {
  1430. holder.scrollTop = header.offsetTop;
  1431. });
  1432. toc.appendChild(li);
  1433. });
  1434. }
  1435. document.addEventListener("DOMContentLoaded", () => {
  1436. prepareMenu();
  1437. prepareEntities();
  1438. prepareHelp();
  1439. document.querySelector("#open-help").addEventListener("click", e => {
  1440. setHelpDate();
  1441. document.querySelector("#help-menu").classList.add("visible");
  1442. document.querySelector("#open-help").classList.remove("highlighted");
  1443. });
  1444. document.querySelector("#close-help").addEventListener("click", e => {
  1445. document.querySelector("#help-menu").classList.remove("visible");
  1446. });
  1447. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1448. copyScreenshot();
  1449. toast("Copied to clipboard!");
  1450. });
  1451. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1452. saveScreenshot();
  1453. });
  1454. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1455. const popoutMenu = document.querySelector("#sidebar-menu");
  1456. if (popoutMenu.classList.contains("visible")) {
  1457. popoutMenu.classList.remove("visible");
  1458. } else {
  1459. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1460. const rect = e.target.getBoundingClientRect();
  1461. popoutMenu.classList.add("visible");
  1462. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1463. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1464. }
  1465. e.stopPropagation();
  1466. });
  1467. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  1468. e.stopPropagation();
  1469. });
  1470. document.addEventListener("click", e => {
  1471. document.querySelector("#sidebar-menu").classList.remove("visible");
  1472. });
  1473. document.querySelector("#toggle-settings").addEventListener("click", e => {
  1474. const popoutMenu = document.querySelector("#settings-menu");
  1475. if (popoutMenu.classList.contains("visible")) {
  1476. popoutMenu.classList.remove("visible");
  1477. } else {
  1478. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1479. const rect = e.target.getBoundingClientRect();
  1480. popoutMenu.classList.add("visible");
  1481. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1482. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1483. }
  1484. e.stopPropagation();
  1485. });
  1486. document.querySelector("#settings-menu").addEventListener("click", e => {
  1487. e.stopPropagation();
  1488. });
  1489. document.addEventListener("click", e => {
  1490. document.querySelector("#settings-menu").classList.remove("visible");
  1491. });
  1492. window.addEventListener("unload", () => {
  1493. saveScene("autosave");
  1494. setUserSettings(exportUserSettings());
  1495. });
  1496. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1497. if (e.target.value == "None") {
  1498. deselect()
  1499. } else {
  1500. select(document.querySelector("#entity-" + e.target.value));
  1501. }
  1502. });
  1503. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1504. const sidebar = document.querySelector("#options");
  1505. if (sidebar.classList.contains("hidden")) {
  1506. sidebar.classList.remove("hidden");
  1507. e.target.classList.remove("rotate-forward");
  1508. e.target.classList.add("rotate-backward");
  1509. } else {
  1510. sidebar.classList.add("hidden");
  1511. e.target.classList.add("rotate-forward");
  1512. e.target.classList.remove("rotate-backward");
  1513. }
  1514. handleResize();
  1515. });
  1516. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1517. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1518. if (selected) {
  1519. entities[selected.dataset.key].priority += 1;
  1520. }
  1521. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1522. updateSizes();
  1523. });
  1524. document.querySelector("#options-order-back").addEventListener("click", e => {
  1525. if (selected) {
  1526. entities[selected.dataset.key].priority -= 1;
  1527. }
  1528. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1529. updateSizes();
  1530. });
  1531. const sceneChoices = document.querySelector("#scene-choices");
  1532. Object.entries(scenes).forEach(([id, scene]) => {
  1533. const option = document.createElement("option");
  1534. option.innerText = id;
  1535. option.value = id;
  1536. sceneChoices.appendChild(option);
  1537. });
  1538. document.querySelector("#load-scene").addEventListener("click", e => {
  1539. const chosen = sceneChoices.value;
  1540. removeAllEntities();
  1541. scenes[chosen]();
  1542. });
  1543. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1544. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1545. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1546. document.querySelector("#options-height-value").addEventListener("change", e => {
  1547. updateWorldHeight();
  1548. })
  1549. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1550. e.stopPropagation();
  1551. })
  1552. const unitSelector = document.querySelector("#options-height-unit");
  1553. unitChoices.length.forEach(lengthOption => {
  1554. const option = document.createElement("option");
  1555. option.innerText = lengthOption;
  1556. option.value = lengthOption;
  1557. if (lengthOption === "meters") {
  1558. option.selected = true;
  1559. }
  1560. unitSelector.appendChild(option);
  1561. });
  1562. unitSelector.setAttribute("oldUnit", "meters");
  1563. unitSelector.addEventListener("input", e => {
  1564. checkFitWorld();
  1565. const scaleInput = document.querySelector("#options-height-value");
  1566. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1567. setNumericInput(scaleInput, newVal);
  1568. updateWorldHeight();
  1569. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1570. });
  1571. param = new URL(window.location.href).searchParams.get("scene");
  1572. if (param === null) {
  1573. scenes["Default"]();
  1574. }
  1575. else {
  1576. try {
  1577. const data = JSON.parse(b64DecodeUnicode(param));
  1578. if (data.entities === undefined) {
  1579. return;
  1580. }
  1581. if (data.world === undefined) {
  1582. return;
  1583. }
  1584. importScene(data);
  1585. } catch (err) {
  1586. console.error(err);
  1587. scenes["Default"]();
  1588. // probably wasn't valid data
  1589. }
  1590. }
  1591. document.querySelector("#world").addEventListener("wheel", e => {
  1592. if (shiftHeld) {
  1593. if (selected) {
  1594. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1595. const entity = entities[selected.dataset.key];
  1596. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1597. entity.dirty = true;
  1598. updateEntityOptions(entity, entity.view);
  1599. updateViewOptions(entity, entity.view);
  1600. updateSizes(true);
  1601. } else {
  1602. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  1603. config.x += (e.deltaY > 0 ? 1 : -1) * worldWidth / 20 ;
  1604. updateSizes();
  1605. updateSizes();
  1606. }
  1607. } else {
  1608. if (config.autoFit) {
  1609. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  1610. } else {
  1611. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1612. setWorldHeight(config.height, math.multiply(config.height, dir));
  1613. updateWorldOptions();
  1614. }
  1615. }
  1616. checkFitWorld();
  1617. })
  1618. document.querySelector("#world").addEventListener("mousedown", e => {
  1619. // only middle mouse clicks
  1620. if (e.which == 2) {
  1621. panning = true;
  1622. panOffsetX = e.clientX;
  1623. panOffsetY = e.clientY;
  1624. }
  1625. });
  1626. document.querySelector("#world").addEventListener("mouseup", e => {
  1627. if (e.which == 2) {
  1628. panning = false;
  1629. }
  1630. });
  1631. document.querySelector("body").appendChild(testCtx.canvas);
  1632. updateSizes();
  1633. world.addEventListener("mousedown", e => deselect(e));
  1634. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1635. document.querySelector("#display").addEventListener("mousedown", deselect);
  1636. document.addEventListener("mouseup", e => clickUp(e));
  1637. document.addEventListener("touchend", e => {
  1638. const fakeEvent = {
  1639. target: e.target,
  1640. clientX: e.changedTouches[0].clientX,
  1641. clientY: e.changedTouches[0].clientY
  1642. };
  1643. clickUp(fakeEvent);
  1644. });
  1645. const viewList = document.querySelector("#entity-view");
  1646. document.querySelector("#entity-view").addEventListener("input", e => {
  1647. const entity = entities[selected.dataset.key];
  1648. entity.view = e.target.value;
  1649. const image = entities[selected.dataset.key].views[e.target.value].image;
  1650. selected.querySelector(".entity-image").src = image.source;
  1651. configViewOptions(entity, entity.view);
  1652. displayAttribution(image.source);
  1653. if (image.bottom !== undefined) {
  1654. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1655. } else {
  1656. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1657. }
  1658. updateSizes();
  1659. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1660. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1661. });
  1662. document.querySelector("#entity-view").addEventListener("input", e => {
  1663. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  1664. viewList.classList.add("nsfw");
  1665. } else {
  1666. viewList.classList.remove("nsfw");
  1667. }
  1668. })
  1669. clearViewList();
  1670. document.querySelector("#menu-clear").addEventListener("click", e => {
  1671. removeAllEntities();
  1672. });
  1673. document.querySelector("#delete-entity").disabled = true;
  1674. document.querySelector("#delete-entity").addEventListener("click", e => {
  1675. if (selected) {
  1676. removeEntity(selected);
  1677. selected = null;
  1678. }
  1679. });
  1680. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1681. const order = Object.keys(entities).sort((a, b) => {
  1682. const entA = entities[a];
  1683. const entB = entities[b];
  1684. const viewA = entA.view;
  1685. const viewB = entB.view;
  1686. const heightA = entA.views[viewA].height.to("meter").value;
  1687. const heightB = entB.views[viewB].height.to("meter").value;
  1688. return heightA - heightB;
  1689. });
  1690. arrangeEntities(order);
  1691. });
  1692. // TODO: write some generic logic for this lol
  1693. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1694. scrollDirection = -1;
  1695. clearInterval(scrollHandle);
  1696. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1697. e.stopPropagation();
  1698. });
  1699. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1700. scrollDirection = 1;
  1701. clearInterval(scrollHandle);
  1702. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1703. e.stopPropagation();
  1704. });
  1705. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1706. scrollDirection = 1;
  1707. clearInterval(scrollHandle);
  1708. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1709. e.stopPropagation();
  1710. });
  1711. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1712. scrollDirection = -1;
  1713. clearInterval(scrollHandle);
  1714. scrollHandle = setInterval(doXScroll, 1000 / 20);
  1715. e.stopPropagation();
  1716. });
  1717. document.querySelector("#scroll-up").addEventListener("mousedown", e => {
  1718. scrollDirection = 1;
  1719. clearInterval(scrollHandle);
  1720. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1721. e.stopPropagation();
  1722. });
  1723. document.querySelector("#scroll-down").addEventListener("mousedown", e => {
  1724. scrollDirection = -1;
  1725. clearInterval(scrollHandle);
  1726. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1727. e.stopPropagation();
  1728. });
  1729. document.querySelector("#scroll-up").addEventListener("touchstart", e => {
  1730. scrollDirection = 1;
  1731. clearInterval(scrollHandle);
  1732. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1733. e.stopPropagation();
  1734. });
  1735. document.querySelector("#scroll-down").addEventListener("touchstart", e => {
  1736. scrollDirection = -1;
  1737. clearInterval(scrollHandle);
  1738. scrollHandle = setInterval(doYScroll, 1000 / 20);
  1739. e.stopPropagation();
  1740. });
  1741. document.addEventListener("mouseup", e => {
  1742. clearInterval(scrollHandle);
  1743. scrollHandle = null;
  1744. });
  1745. document.addEventListener("touchend", e => {
  1746. clearInterval(scrollHandle);
  1747. scrollHandle = null;
  1748. });
  1749. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1750. zoomDirection = -1;
  1751. clearInterval(zoomHandle);
  1752. zoomHandle = setInterval(doZoom, 1000 / 20);
  1753. e.stopPropagation();
  1754. });
  1755. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1756. zoomDirection = 1;
  1757. clearInterval(zoomHandle);
  1758. zoomHandle = setInterval(doZoom, 1000 / 20);
  1759. e.stopPropagation();
  1760. });
  1761. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1762. zoomDirection = -1;
  1763. clearInterval(zoomHandle);
  1764. zoomHandle = setInterval(doZoom, 1000 / 20);
  1765. e.stopPropagation();
  1766. });
  1767. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1768. zoomDirection = 1;
  1769. clearInterval(zoomHandle);
  1770. zoomHandle = setInterval(doZoom, 1000 / 20);
  1771. e.stopPropagation();
  1772. });
  1773. document.addEventListener("mouseup", e => {
  1774. clearInterval(zoomHandle);
  1775. zoomHandle = null;
  1776. });
  1777. document.addEventListener("touchend", e => {
  1778. clearInterval(zoomHandle);
  1779. zoomHandle = null;
  1780. });
  1781. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1782. sizeDirection = -1;
  1783. clearInterval(sizeHandle);
  1784. sizeHandle = setInterval(doSize, 1000 / 20);
  1785. e.stopPropagation();
  1786. });
  1787. document.querySelector("#grow").addEventListener("mousedown", e => {
  1788. sizeDirection = 1;
  1789. clearInterval(sizeHandle);
  1790. sizeHandle = setInterval(doSize, 1000 / 20);
  1791. e.stopPropagation();
  1792. });
  1793. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1794. sizeDirection = -1;
  1795. clearInterval(sizeHandle);
  1796. sizeHandle = setInterval(doSize, 1000 / 20);
  1797. e.stopPropagation();
  1798. });
  1799. document.querySelector("#grow").addEventListener("touchstart", e => {
  1800. sizeDirection = 1;
  1801. clearInterval(sizeHandle);
  1802. sizeHandle = setInterval(doSize, 1000 / 20);
  1803. e.stopPropagation();
  1804. });
  1805. document.addEventListener("mouseup", e => {
  1806. clearInterval(sizeHandle);
  1807. sizeHandle = null;
  1808. });
  1809. document.addEventListener("touchend", e => {
  1810. clearInterval(sizeHandle);
  1811. sizeHandle = null;
  1812. });
  1813. document.querySelector("#fit").addEventListener("click", e => {
  1814. const x = parseFloat(selected.dataset.x);
  1815. const y = parseFloat(selected.dataset.y);
  1816. config.x = x;
  1817. config.y = y;
  1818. const entity = entities[selected.dataset.key];
  1819. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1820. setWorldHeight(config.height, height);
  1821. });
  1822. document.querySelector("#fit").addEventListener("mousedown", e => {
  1823. e.stopPropagation();
  1824. });
  1825. document.querySelector("#fit").addEventListener("touchstart", e => {
  1826. e.stopPropagation();
  1827. });
  1828. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1829. document.querySelector("#options-reset-pos-x").addEventListener("click", () => { config.x = 0; updateSizes(); });
  1830. document.querySelector("#options-reset-pos-y").addEventListener("click", () => { config.y = 0; updateSizes(); });
  1831. document.addEventListener("keydown", e => {
  1832. if (e.key == "Delete") {
  1833. if (selected) {
  1834. removeEntity(selected);
  1835. selected = null;
  1836. }
  1837. }
  1838. })
  1839. document.addEventListener("keydown", e => {
  1840. if (e.key == "Shift") {
  1841. shiftHeld = true;
  1842. e.preventDefault();
  1843. } else if (e.key == "Alt") {
  1844. altHeld = true;
  1845. e.preventDefault();
  1846. }
  1847. });
  1848. document.addEventListener("keyup", e => {
  1849. if (e.key == "Shift") {
  1850. shiftHeld = false;
  1851. e.preventDefault();
  1852. } else if (e.key == "Alt") {
  1853. altHeld = false;
  1854. e.preventDefault();
  1855. }
  1856. });
  1857. window.addEventListener("resize", handleResize);
  1858. // TODO: further investigate why the tool initially starts out with wrong
  1859. // values under certain circumstances (seems to be narrow aspect ratios -
  1860. // maybe the menu bar is animating when it shouldn't)
  1861. setTimeout(handleResize, 250);
  1862. setTimeout(handleResize, 500);
  1863. setTimeout(handleResize, 750);
  1864. setTimeout(handleResize, 1000);
  1865. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1866. linkScene();
  1867. });
  1868. document.querySelector("#menu-export").addEventListener("click", e => {
  1869. copyScene();
  1870. });
  1871. document.querySelector("#menu-import").addEventListener("click", e => {
  1872. pasteScene();
  1873. });
  1874. document.querySelector("#menu-save").addEventListener("click", e => {
  1875. saveScene();
  1876. });
  1877. document.querySelector("#menu-load").addEventListener("click", e => {
  1878. loadScene();
  1879. });
  1880. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1881. loadScene("autosave");
  1882. });
  1883. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1884. document.querySelector("#file-upload-picker").click();
  1885. });
  1886. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1887. if (e.target.files.length > 0) {
  1888. for (let i=0; i<e.target.files.length; i++) {
  1889. customEntityFromFile(e.target.files[i]);
  1890. }
  1891. }
  1892. })
  1893. document.addEventListener("paste", e => {
  1894. let index = 0;
  1895. let item = null;
  1896. let found = false;
  1897. for (; index < e.clipboardData.items.length; index++) {
  1898. item = e.clipboardData.items[index];
  1899. if (item.type == "image/png") {
  1900. found = true;
  1901. break;
  1902. }
  1903. }
  1904. if (!found) {
  1905. return;
  1906. }
  1907. let url = null;
  1908. const file = item.getAsFile();
  1909. customEntityFromFile(file);
  1910. });
  1911. document.querySelector("#world").addEventListener("dragover", e => {
  1912. e.preventDefault();
  1913. })
  1914. document.querySelector("#world").addEventListener("drop", e => {
  1915. e.preventDefault();
  1916. if (e.dataTransfer.files.length > 0) {
  1917. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1918. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1919. let coords = pix2pos({x: e.clientX-entX, y: e.clientY-entY});
  1920. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1921. }
  1922. })
  1923. clearEntityOptions();
  1924. clearViewOptions();
  1925. clearAttribution();
  1926. // we do this last because configuring settings can cause things
  1927. // to happen (e.g. auto-fit)
  1928. prepareSettings(getUserSettings());
  1929. });
  1930. function customEntityFromFile(file, x=0.5, y=0.5) {
  1931. file.arrayBuffer().then(buf => {
  1932. arr = new Uint8Array(buf);
  1933. blob = new Blob([arr], {type: file.type });
  1934. url = window.URL.createObjectURL(blob)
  1935. makeCustomEntity(url, x, y);
  1936. });
  1937. }
  1938. function makeCustomEntity(url, x=0.5, y=0.5) {
  1939. const maker = createEntityMaker(
  1940. {
  1941. name: "Custom Entity"
  1942. },
  1943. {
  1944. custom: {
  1945. attributes: {
  1946. height: {
  1947. name: "Height",
  1948. power: 1,
  1949. type: "length",
  1950. base: math.unit(6, "feet")
  1951. }
  1952. },
  1953. image: {
  1954. source: url
  1955. },
  1956. name: "Image",
  1957. info: {},
  1958. rename: false
  1959. }
  1960. },
  1961. []
  1962. );
  1963. const entity = maker.constructor();
  1964. entity.scale = config.height.toNumber("feet") / 20;
  1965. entity.ephemeral = true;
  1966. displayEntity(entity, "custom", x, y, true, true);
  1967. }
  1968. const filterDefs = {
  1969. none: {
  1970. id: "none",
  1971. name: "No Filter",
  1972. extract: maker => [],
  1973. render: name => name,
  1974. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  1975. },
  1976. author: {
  1977. id: "author",
  1978. name: "Authors",
  1979. extract: maker => maker.authors ? maker.authors : [],
  1980. render: author => attributionData.people[author].name,
  1981. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  1982. },
  1983. owner: {
  1984. id: "owner",
  1985. name: "Owners",
  1986. extract: maker => maker.owners ? maker.owners : [],
  1987. render: owner => attributionData.people[owner].name,
  1988. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  1989. },
  1990. species: {
  1991. id: "species",
  1992. name: "Species",
  1993. extract: maker => maker.info && maker.info.species ? getSpeciesInfo(maker.info.species) : [],
  1994. render: species => speciesData[species].name,
  1995. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  1996. },
  1997. tags: {
  1998. id: "tags",
  1999. name: "Tags",
  2000. extract: maker => maker.info && maker.info.tags ? maker.info.tags : [],
  2001. render: tag => tagDefs[tag],
  2002. sort: (tag1, tag2) => tag1[1].localeCompare(tag2[1])
  2003. },
  2004. size: {
  2005. id: "size",
  2006. name: "Normal Size",
  2007. extract: maker => maker.sizes && maker.sizes.length > 0 ? Array.from(maker.sizes.reduce((result, size) => {
  2008. if (result && !size.default) {
  2009. return result;
  2010. }
  2011. let meters = size.height.toNumber("meters");
  2012. if (meters < 1e-1) {
  2013. return ["micro"];
  2014. } else if (meters < 1e1) {
  2015. return ["moderate"];
  2016. } else {
  2017. return ["macro"];
  2018. }
  2019. }, null)) : [],
  2020. render: tag => { return {
  2021. "micro": "Micro",
  2022. "moderate": "Moderate",
  2023. "macro": "Macro"
  2024. }[tag]},
  2025. sort: (tag1, tag2) => {
  2026. const order = {
  2027. "micro": 0,
  2028. "moderate": 1,
  2029. "macro": 2
  2030. };
  2031. return order[tag1[0]] - order[tag2[0]];
  2032. }
  2033. },
  2034. allSizes: {
  2035. id: "allSizes",
  2036. name: "Possible Size",
  2037. extract: maker => maker.sizes ? Array.from(maker.sizes.reduce((set, size) => {
  2038. const height = size.height;
  2039. let result = Object.entries(sizeCategories).reduce((result, [name, value]) => {
  2040. if (result) {
  2041. return result;
  2042. } else {
  2043. if (math.compare(height, value) <= 0) {
  2044. return name;
  2045. }
  2046. }
  2047. }, null);
  2048. set.add(result ? result : "infinite");
  2049. return set;
  2050. }, new Set())) : [],
  2051. render: tag => tag[0].toUpperCase() + tag.slice(1),
  2052. sort: (tag1, tag2) => {
  2053. const order = [
  2054. "atomic", "microscopic", "tiny", "small", "moderate", "large", "macro", "megamacro", "planetary", "stellar",
  2055. "galactic", "universal", "omniversal", "infinite"
  2056. ]
  2057. return order.indexOf(tag1[0]) - order.indexOf(tag2[0]);
  2058. }
  2059. }
  2060. }
  2061. const sizeCategories = {
  2062. "atomic": math.unit(100, "angstroms"),
  2063. "microscopic": math.unit(100, "micrometers"),
  2064. "tiny": math.unit(100, "millimeters"),
  2065. "small": math.unit(1, "meter"),
  2066. "moderate": math.unit(3, "meters"),
  2067. "large": math.unit(10, "meters"),
  2068. "macro": math.unit(300, "meters"),
  2069. "megamacro": math.unit(1000, "kilometers"),
  2070. "planetary": math.unit(10, "earths"),
  2071. "stellar": math.unit(10, "solarradii"),
  2072. "galactic": math.unit(10, "galaxies"),
  2073. "universal": math.unit(10, "universes"),
  2074. "omniversal": math.unit(10, "multiverses")
  2075. };
  2076. function prepareEntities() {
  2077. availableEntities["buildings"] = makeBuildings();
  2078. availableEntities["characters"] = makeCharacters();
  2079. availableEntities["cities"] = makeCities();
  2080. availableEntities["fiction"] = makeFiction();
  2081. availableEntities["food"] = makeFood();
  2082. availableEntities["landmarks"] = makeLandmarks();
  2083. availableEntities["naturals"] = makeNaturals();
  2084. availableEntities["objects"] = makeObjects();
  2085. availableEntities["dildos"] = makeDildos();
  2086. availableEntities["pokemon"] = makePokemon();
  2087. availableEntities["species"] = makeSpecies();
  2088. availableEntities["vehicles"] = makeVehicles();
  2089. availableEntities["characters"].sort((x, y) => {
  2090. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  2091. });
  2092. const holder = document.querySelector("#spawners");
  2093. const filterHolder = document.querySelector("#filters");
  2094. const categorySelect = document.createElement("select");
  2095. categorySelect.id = "category-picker";
  2096. const filterSelect = document.createElement("select");
  2097. filterSelect.id = "filter-picker";
  2098. holder.appendChild(categorySelect);
  2099. filterHolder.appendChild(filterSelect);
  2100. const filterSets = {};
  2101. Object.values(filterDefs).forEach(filter => {
  2102. filterSets[filter.id] = new Set();
  2103. })
  2104. Object.entries(availableEntities).forEach(([category, entityList]) => {
  2105. const select = document.createElement("select");
  2106. select.id = "create-entity-" + category;
  2107. select.classList.add("entity-select");
  2108. for (let i = 0; i < entityList.length; i++) {
  2109. const entity = entityList[i];
  2110. const option = document.createElement("option");
  2111. option.value = i;
  2112. option.innerText = entity.name;
  2113. select.appendChild(option);
  2114. if (entity.nsfw) {
  2115. option.classList.add("nsfw");
  2116. }
  2117. Object.values(filterDefs).forEach(filter => {
  2118. filter.extract(entity).forEach(result => {
  2119. filterSets[filter.id].add(result);
  2120. });
  2121. });
  2122. availableEntitiesByName[entity.name] = entity;
  2123. };
  2124. select.addEventListener("change", e => {
  2125. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  2126. select.classList.add("nsfw");
  2127. } else {
  2128. select.classList.remove("nsfw");
  2129. }
  2130. })
  2131. const button = document.createElement("button");
  2132. button.id = "create-entity-" + category + "-button";
  2133. button.classList.add("entity-button");
  2134. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  2135. button.addEventListener("click", e => {
  2136. const newEntity = entityList[select.value].constructor()
  2137. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  2138. });
  2139. const categoryOption = document.createElement("option");
  2140. categoryOption.value = category
  2141. categoryOption.innerText = category;
  2142. if (category == "characters") {
  2143. categoryOption.selected = true;
  2144. select.classList.add("category-visible");
  2145. button.classList.add("category-visible");
  2146. }
  2147. categorySelect.appendChild(categoryOption);
  2148. holder.appendChild(select);
  2149. holder.appendChild(button);
  2150. });
  2151. Object.values(filterDefs).forEach(filter => {
  2152. const option = document.createElement("option");
  2153. option.innerText = filter.name;
  2154. option.value = filter.id;
  2155. filterSelect.appendChild(option);
  2156. const filterNameSelect = document.createElement("select");
  2157. filterNameSelect.classList.add("filter-select");
  2158. filterNameSelect.id = "filter-" + filter.id;
  2159. filterHolder.appendChild(filterNameSelect);
  2160. const button = document.createElement("button");
  2161. button.classList.add("filter-button");
  2162. button.id = "create-filtered-" + filter.id + "-button";
  2163. filterHolder.appendChild(button);
  2164. const counter = document.createElement("div");
  2165. counter.classList.add("button-counter");
  2166. counter.innerText = "10";
  2167. button.appendChild(counter);
  2168. const i = document.createElement("i");
  2169. i.classList.add("fas");
  2170. i.classList.add("fa-plus");
  2171. button.appendChild(i);
  2172. button.addEventListener("click", e => {
  2173. const makers = Array.from(document.querySelector(".entity-select.category-visible")).filter(element => !element.classList.contains("filtered"));
  2174. const count = makers.length + 2;
  2175. let index = 1;
  2176. if (makers.length > 50) {
  2177. if (!confirm("Really spawn " + makers.length + " things at once?")) {
  2178. return;
  2179. }
  2180. }
  2181. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2182. makers.map(element => {
  2183. const category = document.querySelector("#category-picker").value;
  2184. const maker = availableEntities[category][element.value];
  2185. const entity = maker.constructor()
  2186. displayEntity(entity, entity.view, -worldWidth * 0.45 + config.x + worldWidth * 0.9 * index / (count - 1), config.y);
  2187. index += 1;
  2188. });
  2189. updateSizes(true);
  2190. });
  2191. Array.from(filterSets[filter.id]).map(name => [name, filter.render(name)]).sort(filterDefs[filter.id].sort).forEach(name => {
  2192. const option = document.createElement("option");
  2193. option.innerText = name[1];
  2194. option.value = name[0];
  2195. filterNameSelect.appendChild(option);
  2196. });
  2197. filterNameSelect.addEventListener("change", e => {
  2198. updateFilter();
  2199. });
  2200. });
  2201. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  2202. categorySelect.addEventListener("input", e => {
  2203. const oldSelect = document.querySelector(".entity-select.category-visible");
  2204. oldSelect.classList.remove("category-visible");
  2205. const oldButton = document.querySelector(".entity-button.category-visible");
  2206. oldButton.classList.remove("category-visible");
  2207. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  2208. newSelect.classList.add("category-visible");
  2209. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  2210. newButton.classList.add("category-visible");
  2211. recomputeFilters();
  2212. updateFilter();
  2213. });
  2214. recomputeFilters();
  2215. filterSelect.addEventListener("input", e => {
  2216. const oldSelect = document.querySelector(".filter-select.category-visible");
  2217. if (oldSelect)
  2218. oldSelect.classList.remove("category-visible");
  2219. const newSelect = document.querySelector("#filter-" + e.target.value);
  2220. if (newSelect)
  2221. newSelect.classList.add("category-visible");
  2222. updateFilter();
  2223. });
  2224. }
  2225. // Only display authors and owners if they appear
  2226. // somewhere in the current entity list
  2227. function recomputeFilters() {
  2228. const category = document.querySelector("#category-picker").value;
  2229. const filterSets = {};
  2230. Object.values(filterDefs).forEach(filter => {
  2231. filterSets[filter.id] = new Set();
  2232. });
  2233. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2234. const entity = availableEntities[category][element.value];
  2235. Object.values(filterDefs).forEach(filter => {
  2236. filter.extract(entity).forEach(result => {
  2237. filterSets[filter.id].add(result);
  2238. });
  2239. });
  2240. });
  2241. Object.values(filterDefs).forEach(filter => {
  2242. // always show the "none" option
  2243. let found = filter.id == "none";
  2244. document.querySelectorAll("#filter-" + filter.id + " > option").forEach(element => {
  2245. if (filterSets[filter.id].has(element.value) || filter.id == "none") {
  2246. element.classList.remove("filtered");
  2247. element.disabled = false;
  2248. found = true;
  2249. } else {
  2250. element.classList.add("filtered");
  2251. element.disabled = true;
  2252. }
  2253. });
  2254. const filterOption = document.querySelector("#filter-picker > option[value='" + filter.id + "']");
  2255. if (found) {
  2256. filterOption.classList.remove("filtered");
  2257. filterOption.disabled = false;
  2258. } else {
  2259. filterOption.classList.add("filtered");
  2260. filterOption.disabled = true;
  2261. }
  2262. });
  2263. document.querySelector("#filter-picker").value = "none";
  2264. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  2265. }
  2266. function updateFilter() {
  2267. const category = document.querySelector("#category-picker").value;
  2268. const type = document.querySelector("#filter-picker").value;
  2269. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  2270. clearFilter();
  2271. if (!filterKeySelect) {
  2272. return;
  2273. }
  2274. const key = filterKeySelect.value;
  2275. let current = document.querySelector(".entity-select.category-visible").value;
  2276. let replace = false;
  2277. let first = null;
  2278. let count = 0;
  2279. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2280. let keep = type == "none";
  2281. if (filterDefs[type].extract(availableEntities[category][element.value]).indexOf(key) >= 0) {
  2282. keep = true;
  2283. }
  2284. if (!keep) {
  2285. element.classList.add("filtered");
  2286. element.disabled = true;
  2287. if (current == element.value) {
  2288. replace = true;
  2289. }
  2290. } else {
  2291. count += 1;
  2292. if (!first) {
  2293. first = element.value;
  2294. }
  2295. }
  2296. });
  2297. const button = document.querySelector(".filter-select.category-visible + button");
  2298. if (button) {
  2299. button.querySelector(".button-counter").innerText = count;
  2300. }
  2301. if (replace) {
  2302. document.querySelector(".entity-select.category-visible").value = first;
  2303. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  2304. }
  2305. }
  2306. function clearFilter() {
  2307. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2308. element.classList.remove("filtered");
  2309. element.disabled = false;
  2310. });
  2311. }
  2312. document.addEventListener("mousemove", (e) => {
  2313. if (clicked) {
  2314. const position = snapRel(pix2pos({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  2315. clicked.dataset.x = position.x;
  2316. clicked.dataset.y = position.y;
  2317. updateEntityElement(entities[clicked.dataset.key], clicked);
  2318. if (hoveringInDeleteArea(e)) {
  2319. document.querySelector("#menubar").classList.add("hover-delete");
  2320. } else {
  2321. document.querySelector("#menubar").classList.remove("hover-delete");
  2322. }
  2323. }
  2324. console.log(panning)
  2325. if (panning && panReady) {
  2326. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2327. const worldHeight = config.height.toNumber("meters");
  2328. config.x += (e.clientX - panOffsetX) / canvasWidth * worldWidth;
  2329. config.y -= (e.clientY - panOffsetY) / canvasHeight * worldHeight;
  2330. panOffsetX = e.clientX;
  2331. panOffsetY = e.clientY;
  2332. console.log(config.x, config.y)
  2333. updateSizes();
  2334. panReady = false;
  2335. setTimeout(() => panReady=true, 50);
  2336. }
  2337. });
  2338. document.addEventListener("touchmove", (e) => {
  2339. if (clicked) {
  2340. e.preventDefault();
  2341. let x = e.touches[0].clientX;
  2342. let y = e.touches[0].clientY;
  2343. const position = snapRel(pix2pos({ x: x - dragOffsetX, y: y - dragOffsetY }));
  2344. clicked.dataset.x = position.x;
  2345. clicked.dataset.y = position.y;
  2346. updateEntityElement(entities[clicked.dataset.key], clicked);
  2347. // what a hack
  2348. // I should centralize this 'fake event' creation...
  2349. if (hoveringInDeleteArea({ clientY: y })) {
  2350. document.querySelector("#menubar").classList.add("hover-delete");
  2351. } else {
  2352. document.querySelector("#menubar").classList.remove("hover-delete");
  2353. }
  2354. }
  2355. }, { passive: false });
  2356. function checkFitWorld() {
  2357. if (config.autoFit) {
  2358. fitWorld();
  2359. return true;
  2360. }
  2361. return false;
  2362. }
  2363. function fitWorld(manual = false, factor = 1.1) {
  2364. let minX = Infinity;
  2365. let maxX = -Infinity;
  2366. let minY = Infinity;
  2367. let maxY = -Infinity;
  2368. let count = 0;
  2369. const worldWidth = config.height.toNumber("meters") / canvasHeight * canvasWidth;
  2370. const worldHeight = config.height.toNumber("meters");
  2371. Object.entries(entities).forEach(([key, entity]) => {
  2372. const view = entity.view;
  2373. let extra = entity.views[view].image.extra;
  2374. extra = extra === undefined ? 1 : extra;
  2375. const image = document.querySelector("#entity-" + key + " > .entity-image");
  2376. const x = parseFloat(document.querySelector("#entity-" + key).dataset.x);
  2377. let width = image.width;
  2378. let height = image.height;
  2379. // only really relevant if the images haven't loaded in yet
  2380. if (height == 0) {
  2381. height = 100;
  2382. }
  2383. if (width == 0) {
  2384. width = height;
  2385. }
  2386. console.log(image)
  2387. console.log(image.width, image.height)
  2388. const xBottom = x - entity.views[view].height.toNumber("meters") * width / height / 2;
  2389. const xTop = x + entity.views[view].height.toNumber("meters") * width / height / 2;
  2390. const y = parseFloat(document.querySelector("#entity-" + key).dataset.y);
  2391. const yBottom = y;
  2392. const yTop = entity.views[view].height.toNumber("meters") + yBottom;
  2393. minX = Math.min(minX, xBottom);
  2394. maxX = Math.max(maxX, xTop);
  2395. minY = Math.min(minY, yBottom);
  2396. maxY = Math.max(maxY, yTop);
  2397. count += 1;
  2398. });
  2399. let ySize = (maxY - minY) * factor;
  2400. let xSize = (maxX - minX) * factor;
  2401. console.log(xSize, ySize, worldWidth, worldHeight)
  2402. if (xSize / ySize > worldWidth / worldHeight) {
  2403. ySize *= ((xSize / ySize) / (worldWidth / worldHeight));
  2404. }
  2405. config.x = (maxX + minX) / 2;
  2406. config.y = minY;
  2407. height = math.unit(ySize, "meter")
  2408. setWorldHeight(config.height, math.multiply(height, factor));
  2409. }
  2410. // TODO why am I doing this
  2411. function updateWorldHeight() {
  2412. const unit = document.querySelector("#options-height-unit").value;
  2413. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  2414. const oldHeight = config.height;
  2415. setWorldHeight(oldHeight, math.unit(value, unit));
  2416. }
  2417. function setWorldHeight(oldHeight, newHeight) {
  2418. worldSizeDirty = true;
  2419. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  2420. const unit = document.querySelector("#options-height-unit").value;
  2421. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  2422. Object.entries(entities).forEach(([key, entity]) => {
  2423. const element = document.querySelector("#entity-" + key);
  2424. let newPosition;
  2425. if (altHeld) {
  2426. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  2427. } else {
  2428. newPosition = { x: element.dataset.x, y: element.dataset.y };
  2429. }
  2430. element.dataset.x = newPosition.x;
  2431. element.dataset.y = newPosition.y;
  2432. });
  2433. updateSizes();
  2434. }
  2435. function loadScene(name = "default") {
  2436. try {
  2437. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  2438. if (data === null) {
  2439. return false;
  2440. }
  2441. importScene(data);
  2442. return true;
  2443. } catch (err) {
  2444. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2445. console.error(err);
  2446. return false;
  2447. }
  2448. }
  2449. function saveScene(name = "default") {
  2450. try {
  2451. const string = JSON.stringify(exportScene());
  2452. localStorage.setItem("macrovision-save-" + name, string);
  2453. } catch (err) {
  2454. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  2455. console.error(err);
  2456. }
  2457. }
  2458. function deleteScene(name = "default") {
  2459. try {
  2460. localStorage.removeItem("macrovision-save-" + name)
  2461. } catch (err) {
  2462. console.error(err);
  2463. }
  2464. }
  2465. function exportScene() {
  2466. const results = {};
  2467. results.entities = [];
  2468. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  2469. const element = document.querySelector("#entity-" + key);
  2470. results.entities.push({
  2471. name: entity.identifier,
  2472. scale: entity.scale,
  2473. view: entity.view,
  2474. x: element.dataset.x,
  2475. y: element.dataset.y
  2476. });
  2477. });
  2478. const unit = document.querySelector("#options-height-unit").value;
  2479. results.world = {
  2480. height: config.height.toNumber(unit),
  2481. unit: unit,
  2482. x: config.x,
  2483. y: config.y
  2484. }
  2485. results.version = migrationDefs.length;
  2486. return results;
  2487. }
  2488. // btoa doesn't like anything that isn't ASCII
  2489. // great
  2490. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  2491. // for providing an alternative
  2492. function b64EncodeUnicode(str) {
  2493. // first we use encodeURIComponent to get percent-encoded UTF-8,
  2494. // then we convert the percent encodings into raw bytes which
  2495. // can be fed into btoa.
  2496. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  2497. function toSolidBytes(match, p1) {
  2498. return String.fromCharCode('0x' + p1);
  2499. }));
  2500. }
  2501. function b64DecodeUnicode(str) {
  2502. // Going backwards: from bytestream, to percent-encoding, to original string.
  2503. return decodeURIComponent(atob(str).split('').map(function (c) {
  2504. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  2505. }).join(''));
  2506. }
  2507. function linkScene() {
  2508. loc = new URL(window.location);
  2509. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  2510. }
  2511. function copyScene() {
  2512. const results = exportScene();
  2513. navigator.clipboard.writeText(JSON.stringify(results));
  2514. }
  2515. function pasteScene() {
  2516. try {
  2517. navigator.clipboard.readText().then(text => {
  2518. const data = JSON.parse(text);
  2519. if (data.entities === undefined) {
  2520. return;
  2521. }
  2522. if (data.world === undefined) {
  2523. return;
  2524. }
  2525. importScene(data);
  2526. }).catch(err => alert(err));
  2527. } catch (err) {
  2528. console.error(err);
  2529. // probably wasn't valid data
  2530. }
  2531. }
  2532. // TODO - don't just search through every single entity
  2533. // probably just have a way to do lookups directly
  2534. function findEntity(name) {
  2535. return availableEntitiesByName[name];
  2536. }
  2537. const migrationDefs = [
  2538. /*
  2539. Migration: 0 -> 1
  2540. Adds x and y coordinates for the camera
  2541. */
  2542. data => {
  2543. data.world.x = 0;
  2544. data.world.y = 0;
  2545. }
  2546. ]
  2547. function migrateScene(data) {
  2548. if (data.version === undefined) {
  2549. alert("This save was created before save versions were tracked. The scene may import incorrectly.");
  2550. console.trace()
  2551. data.version = 0;
  2552. } else if (data.version < migrationDefs.length) {
  2553. migrationDefs[data.version](data);
  2554. data.version += 1;
  2555. migrateScene(data);
  2556. }
  2557. }
  2558. function importScene(data) {
  2559. removeAllEntities();
  2560. migrateScene(data);
  2561. data.entities.forEach(entityInfo => {
  2562. const entity = findEntity(entityInfo.name).constructor();
  2563. entity.scale = entityInfo.scale
  2564. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  2565. });
  2566. config.height = math.unit(data.world.height, data.world.unit);
  2567. config.x = data.world.x;
  2568. config.y = data.world.y;
  2569. document.querySelector("#options-height-unit").value = data.world.unit;
  2570. if (data.canvasWidth) {
  2571. doHorizReposition(data.canvasWidth / canvasWidth);
  2572. }
  2573. updateSizes();
  2574. }
  2575. function renderToCanvas() {
  2576. const ctx = document.querySelector("#display").getContext("2d");
  2577. Object.entries(entities).sort((ent1, ent2) => {
  2578. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  2579. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  2580. return z1 - z2;
  2581. }).forEach(([id, entity]) => {
  2582. element = document.querySelector("#entity-" + id);
  2583. img = element.querySelector("img");
  2584. let x = parseFloat(element.dataset.x);
  2585. let y = parseFloat(element.dataset.y);
  2586. let coords = pos2pix({x: x, y: y});
  2587. let offset = img.style.getPropertyValue("--offset");
  2588. offset = parseFloat(offset.substring(0, offset.length-1))
  2589. x = coords.x - img.getBoundingClientRect().width/2;
  2590. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  2591. let xSize = img.getBoundingClientRect().width;
  2592. let ySize = img.getBoundingClientRect().height;
  2593. ctx.drawImage(img, x, y, xSize, ySize);
  2594. });
  2595. }
  2596. function exportCanvas(callback) {
  2597. /** @type {CanvasRenderingContext2D} */
  2598. const ctx = document.querySelector("#display").getContext("2d");
  2599. const blob = ctx.canvas.toBlob(callback);
  2600. }
  2601. function generateScreenshot(callback) {
  2602. renderToCanvas();
  2603. /** @type {CanvasRenderingContext2D} */
  2604. const ctx = document.querySelector("#display").getContext("2d");
  2605. ctx.fillStyle = "#555";
  2606. ctx.font = "normal normal lighter 16pt coda";
  2607. ctx.fillText("macrovision.crux.sexy", 10, 25);
  2608. exportCanvas(blob => {
  2609. callback(blob);
  2610. });
  2611. }
  2612. function copyScreenshot() {
  2613. generateScreenshot(blob => {
  2614. navigator.clipboard.write([
  2615. new ClipboardItem({
  2616. "image/png": blob
  2617. })
  2618. ]);
  2619. });
  2620. drawScale(false);
  2621. }
  2622. function saveScreenshot() {
  2623. generateScreenshot(blob => {
  2624. const a = document.createElement("a");
  2625. a.href = URL.createObjectURL(blob);
  2626. a.setAttribute("download", "macrovision.png");
  2627. a.click();
  2628. });
  2629. drawScale(false);
  2630. }
  2631. const rateLimits = {};
  2632. function toast(msg) {
  2633. let div = document.createElement("div");
  2634. div.innerHTML = msg;
  2635. div.classList.add("toast");
  2636. document.body.appendChild(div);
  2637. setTimeout(() => {
  2638. document.body.removeChild(div);
  2639. }, 5000)
  2640. }
  2641. function toastRateLimit(msg, key, delay) {
  2642. if (!rateLimits[key]) {
  2643. toast(msg);
  2644. rateLimits[key] = setTimeout(() => {
  2645. delete rateLimits[key]
  2646. }, delay);
  2647. }
  2648. }