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

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