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

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