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

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