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

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