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

2927 строки
88 KiB

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