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

2905 строки
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. if (typeof value == "string") {
  718. input.value = value.toPrecision(round);
  719. }
  720. function getSortedEntities() {
  721. return Object.keys(entities).sort((a, b) => {
  722. const entA = entities[a];
  723. const entB = entities[b];
  724. const viewA = entA.view;
  725. const viewB = entB.view;
  726. const heightA = entA.views[viewA].height.to("meter").value;
  727. const heightB = entB.views[viewB].height.to("meter").value;
  728. return heightA - heightB;
  729. });
  730. }
  731. function clearViewOptions() {
  732. document.querySelector("#view-category-header").style.display = "none";
  733. document.querySelector("#view-category").style.display = "none";
  734. }
  735. // this is a crime against humanity, and also stolen from
  736. // stack overflow
  737. // https://stackoverflow.com/questions/38487569/click-through-png-image-only-if-clicked-coordinate-is-transparent
  738. const testCanvas = document.createElement("canvas");
  739. testCanvas.id = "test-canvas";
  740. const testCtx = testCanvas.getContext("2d");
  741. function testClick(event) {
  742. // oh my god I can't believe I'm doing this
  743. const target = event.target;
  744. if (navigator.userAgent.indexOf("Firefox") != -1) {
  745. clickDown(target.parentElement, event.clientX, event.clientY);
  746. return;
  747. }
  748. // Get click coordinates
  749. let w = target.width;
  750. let h = target.height;
  751. let ratioW = 1, ratioH = 1;
  752. // Limit the size of the canvas so that very large images don't cause problems)
  753. if (w > 1000) {
  754. ratioW = w / 1000;
  755. w /= ratioW;
  756. h /= ratioW;
  757. }
  758. if (h > 1000) {
  759. ratioH = h / 1000;
  760. w /= ratioH;
  761. h /= ratioH;
  762. }
  763. const ratio = ratioW * ratioH;
  764. var x = event.clientX - target.getBoundingClientRect().x,
  765. y = event.clientY - target.getBoundingClientRect().y,
  766. alpha;
  767. testCtx.canvas.width = w;
  768. testCtx.canvas.height = h;
  769. // Draw image to canvas
  770. // and read Alpha channel value
  771. testCtx.drawImage(target, 0, 0, w, h);
  772. alpha = testCtx.getImageData(Math.floor(x / ratio), Math.floor(y / ratio), 1, 1).data[3]; // [0]R [1]G [2]B [3]A
  773. // If pixel is transparent,
  774. // retrieve the element underneath and trigger its click event
  775. if (alpha === 0) {
  776. const oldDisplay = target.style.display;
  777. target.style.display = "none";
  778. const newTarget = document.elementFromPoint(event.clientX, event.clientY);
  779. newTarget.dispatchEvent(new MouseEvent(event.type, {
  780. "clientX": event.clientX,
  781. "clientY": event.clientY
  782. }));
  783. target.style.display = oldDisplay;
  784. } else {
  785. clickDown(target.parentElement, event.clientX, event.clientY);
  786. }
  787. }
  788. function arrangeEntities(order) {
  789. let x = 0.1;
  790. order.forEach(key => {
  791. document.querySelector("#entity-" + key).dataset.x = x;
  792. x += 0.8 / (order.length - 1);
  793. });
  794. updateSizes();
  795. }
  796. function removeAllEntities() {
  797. Object.keys(entities).forEach(key => {
  798. removeEntity(document.querySelector("#entity-" + key));
  799. });
  800. }
  801. function clearAttribution() {
  802. document.querySelector("#attribution-category-header").style.display = "none";
  803. document.querySelector("#options-attribution").style.display = "none";
  804. }
  805. function displayAttribution(file) {
  806. document.querySelector("#attribution-category-header").style.display = "block";
  807. document.querySelector("#options-attribution").style.display = "inline";
  808. const authors = authorsOfFull(file);
  809. const owners = ownersOfFull(file);
  810. const source = sourceOf(file);
  811. const authorHolder = document.querySelector("#options-attribution-authors");
  812. const ownerHolder = document.querySelector("#options-attribution-owners");
  813. const sourceHolder = document.querySelector("#options-attribution-source");
  814. if (authors === []) {
  815. const div = document.createElement("div");
  816. div.innerText = "Unknown";
  817. authorHolder.innerHTML = "";
  818. authorHolder.appendChild(div);
  819. } else if (authors === undefined) {
  820. const div = document.createElement("div");
  821. div.innerText = "Not yet entered";
  822. authorHolder.innerHTML = "";
  823. authorHolder.appendChild(div);
  824. } else {
  825. authorHolder.innerHTML = "";
  826. const list = document.createElement("ul");
  827. authorHolder.appendChild(list);
  828. authors.forEach(author => {
  829. const authorEntry = document.createElement("li");
  830. if (author.url) {
  831. const link = document.createElement("a");
  832. link.href = author.url;
  833. link.innerText = author.name;
  834. authorEntry.appendChild(link);
  835. } else {
  836. const div = document.createElement("div");
  837. div.innerText = author.name;
  838. authorEntry.appendChild(div);
  839. }
  840. list.appendChild(authorEntry);
  841. });
  842. }
  843. if (owners === []) {
  844. const div = document.createElement("div");
  845. div.innerText = "Unknown";
  846. ownerHolder.innerHTML = "";
  847. ownerHolder.appendChild(div);
  848. } else if (owners === undefined) {
  849. const div = document.createElement("div");
  850. div.innerText = "Not yet entered";
  851. ownerHolder.innerHTML = "";
  852. ownerHolder.appendChild(div);
  853. } else {
  854. ownerHolder.innerHTML = "";
  855. const list = document.createElement("ul");
  856. ownerHolder.appendChild(list);
  857. owners.forEach(owner => {
  858. const ownerEntry = document.createElement("li");
  859. if (owner.url) {
  860. const link = document.createElement("a");
  861. link.href = owner.url;
  862. link.innerText = owner.name;
  863. ownerEntry.appendChild(link);
  864. } else {
  865. const div = document.createElement("div");
  866. div.innerText = owner.name;
  867. ownerEntry.appendChild(div);
  868. }
  869. list.appendChild(ownerEntry);
  870. });
  871. }
  872. if (source === null) {
  873. const div = document.createElement("div");
  874. div.innerText = "No link";
  875. sourceHolder.innerHTML = "";
  876. sourceHolder.appendChild(div);
  877. } else if (source === undefined) {
  878. const div = document.createElement("div");
  879. div.innerText = "Not yet entered";
  880. sourceHolder.innerHTML = "";
  881. sourceHolder.appendChild(div);
  882. } else {
  883. sourceHolder.innerHTML = "";
  884. const link = document.createElement("a");
  885. link.style.display = "block";
  886. link.href = source;
  887. link.innerText = new URL(source).host;
  888. sourceHolder.appendChild(link);
  889. }
  890. }
  891. function removeEntity(element) {
  892. if (selected == element) {
  893. deselect();
  894. }
  895. const option = document.querySelector("#options-selected-entity-" + element.dataset.key);
  896. option.parentElement.removeChild(option);
  897. delete entities[element.dataset.key];
  898. const bottomName = document.querySelector("#bottom-name-" + element.dataset.key);
  899. const topName = document.querySelector("#top-name-" + element.dataset.key);
  900. bottomName.parentElement.removeChild(bottomName);
  901. topName.parentElement.removeChild(topName);
  902. element.parentElement.removeChild(element);
  903. }
  904. function checkEntity(entity) {
  905. Object.values(entity.views).forEach(view => {
  906. if (authorsOf(view.image.source) === undefined) {
  907. console.warn("No authors: " + view.image.source);
  908. }
  909. });
  910. }
  911. function displayEntity(entity, view, x, y, selectEntity = false, refresh = false) {
  912. checkEntity(entity);
  913. const box = document.createElement("div");
  914. box.classList.add("entity-box");
  915. const img = document.createElement("img");
  916. img.classList.add("entity-image");
  917. img.addEventListener("dragstart", e => {
  918. e.preventDefault();
  919. });
  920. const nameTag = document.createElement("div");
  921. nameTag.classList.add("entity-name");
  922. nameTag.innerText = entity.name;
  923. box.appendChild(img);
  924. box.appendChild(nameTag);
  925. const image = entity.views[view].image;
  926. img.src = image.source;
  927. if (image.bottom !== undefined) {
  928. img.style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  929. } else {
  930. img.style.setProperty("--offset", ((-1) * 100) + "%")
  931. }
  932. box.dataset.x = x;
  933. box.dataset.y = y;
  934. img.addEventListener("mousedown", e => { testClick(e); e.stopPropagation() });
  935. img.addEventListener("touchstart", e => {
  936. const fakeEvent = {
  937. target: e.target,
  938. clientX: e.touches[0].clientX,
  939. clientY: e.touches[0].clientY
  940. };
  941. testClick(fakeEvent);
  942. });
  943. const heightBar = document.createElement("div");
  944. heightBar.classList.add("height-bar");
  945. box.appendChild(heightBar);
  946. box.id = "entity-" + entityIndex;
  947. box.dataset.key = entityIndex;
  948. entity.view = view;
  949. entity.priority = 0;
  950. entities[entityIndex] = entity;
  951. entity.index = entityIndex;
  952. const world = document.querySelector("#entities");
  953. world.appendChild(box);
  954. const bottomName = document.createElement("div");
  955. bottomName.classList.add("bottom-name");
  956. bottomName.id = "bottom-name-" + entityIndex;
  957. bottomName.innerText = entity.name;
  958. bottomName.addEventListener("click", () => select(box));
  959. world.appendChild(bottomName);
  960. const topName = document.createElement("div");
  961. topName.classList.add("top-name");
  962. topName.id = "top-name-" + entityIndex;
  963. topName.innerText = entity.name;
  964. topName.addEventListener("click", () => select(box));
  965. world.appendChild(topName);
  966. const entityOption = document.createElement("option");
  967. entityOption.id = "options-selected-entity-" + entityIndex;
  968. entityOption.value = entityIndex;
  969. entityOption.innerText = entity.name;
  970. document.getElementById("options-selected-entity").appendChild(entityOption);
  971. entityIndex += 1;
  972. if (config.autoFit) {
  973. fitWorld();
  974. }
  975. if (selectEntity)
  976. select(box);
  977. entity.dirty = true;
  978. if (refresh && config.autoFitAdd) {
  979. const x = parseFloat(selected.dataset.x);
  980. Object.keys(entities).forEach(id => {
  981. const element = document.querySelector("#entity-" + id);
  982. const newX = parseFloat(element.dataset.x) - x + 0.5;
  983. element.dataset.x = newX;
  984. });
  985. const entity = entities[selected.dataset.key];
  986. const height = math.multiply(entity.views[entity.view].height, 1.1);
  987. setWorldHeight(config.height, height);
  988. }
  989. if (refresh)
  990. updateSizes(true);
  991. }
  992. window.onblur = function () {
  993. altHeld = false;
  994. shiftHeld = false;
  995. }
  996. window.onfocus = function () {
  997. window.dispatchEvent(new Event("keydown"));
  998. }
  999. // thanks to https://developers.google.com/web/fundamentals/native-hardware/fullscreen
  1000. function toggleFullScreen() {
  1001. var doc = window.document;
  1002. var docEl = doc.documentElement;
  1003. var requestFullScreen = docEl.requestFullscreen || docEl.mozRequestFullScreen || docEl.webkitRequestFullScreen || docEl.msRequestFullscreen;
  1004. var cancelFullScreen = doc.exitFullscreen || doc.mozCancelFullScreen || doc.webkitExitFullscreen || doc.msExitFullscreen;
  1005. if (!doc.fullscreenElement && !doc.mozFullScreenElement && !doc.webkitFullscreenElement && !doc.msFullscreenElement) {
  1006. requestFullScreen.call(docEl);
  1007. }
  1008. else {
  1009. cancelFullScreen.call(doc);
  1010. }
  1011. }
  1012. function handleResize() {
  1013. const oldCanvasWidth = canvasWidth;
  1014. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1015. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1016. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1017. const change = oldCanvasWidth / canvasWidth;
  1018. doHorizReposition(change);
  1019. updateSizes();
  1020. }
  1021. function doHorizReposition(change) {
  1022. Object.keys(entities).forEach(key => {
  1023. const element = document.querySelector("#entity-" + key);
  1024. const x = element.dataset.x;
  1025. element.dataset.x = (x - 0.5) * change + 0.5;
  1026. });
  1027. }
  1028. function prepareSidebar() {
  1029. const menubar = document.querySelector("#sidebar-menu");
  1030. [
  1031. {
  1032. name: "Show/hide sidebar",
  1033. id: "menu-toggle-sidebar",
  1034. icon: "fas fa-chevron-circle-down",
  1035. rotates: true
  1036. },
  1037. {
  1038. name: "Fullscreen",
  1039. id: "menu-fullscreen",
  1040. icon: "fas fa-compress"
  1041. },
  1042. {
  1043. name: "Clear",
  1044. id: "menu-clear",
  1045. icon: "fas fa-file"
  1046. },
  1047. {
  1048. name: "Sort by height",
  1049. id: "menu-order-height",
  1050. icon: "fas fa-sort-numeric-up"
  1051. },
  1052. {
  1053. name: "Permalink",
  1054. id: "menu-permalink",
  1055. icon: "fas fa-link"
  1056. },
  1057. {
  1058. name: "Export to clipboard",
  1059. id: "menu-export",
  1060. icon: "fas fa-share"
  1061. },
  1062. {
  1063. name: "Import from clipboard",
  1064. id: "menu-import",
  1065. icon: "fas fa-share",
  1066. classes: ["flipped"]
  1067. },
  1068. {
  1069. name: "Save",
  1070. id: "menu-save",
  1071. icon: "fas fa-download"
  1072. },
  1073. {
  1074. name: "Load",
  1075. id: "menu-load",
  1076. icon: "fas fa-upload"
  1077. },
  1078. {
  1079. name: "Load Autosave",
  1080. id: "menu-load-autosave",
  1081. icon: "fas fa-redo"
  1082. },
  1083. {
  1084. name: "Add Image",
  1085. id: "menu-add-image",
  1086. icon: "fas fa-camera"
  1087. }
  1088. ].forEach(entry => {
  1089. const buttonHolder = document.createElement("div");
  1090. buttonHolder.classList.add("menu-button-holder");
  1091. const button = document.createElement("button");
  1092. button.id = entry.id;
  1093. button.classList.add("menu-button");
  1094. const icon = document.createElement("i");
  1095. icon.classList.add(...entry.icon.split(" "));
  1096. if (entry.rotates) {
  1097. icon.classList.add("rotate-backward", "transitions");
  1098. }
  1099. if (entry.classes) {
  1100. entry.classes.forEach(cls => icon.classList.add(cls));
  1101. }
  1102. const actionText = document.createElement("span");
  1103. actionText.innerText = entry.name;
  1104. actionText.classList.add("menu-text");
  1105. const srText = document.createElement("span");
  1106. srText.classList.add("sr-only");
  1107. srText.innerText = entry.name;
  1108. button.appendChild(icon);
  1109. button.appendChild(srText);
  1110. buttonHolder.appendChild(button);
  1111. buttonHolder.appendChild(actionText);
  1112. menubar.appendChild(buttonHolder);
  1113. });
  1114. }
  1115. function checkBodyClass(cls) {
  1116. return document.body.classList.contains(cls);
  1117. }
  1118. function toggleBodyClass(cls, setting) {
  1119. if (setting) {
  1120. document.body.classList.add(cls);
  1121. } else {
  1122. document.body.classList.remove(cls);
  1123. }
  1124. }
  1125. const settingsData = {
  1126. "auto-scale": {
  1127. name: "Auto-Size World",
  1128. desc: "Constantly zoom to fit the largest entity",
  1129. type: "toggle",
  1130. default: false,
  1131. get value() {
  1132. return config.autoFit;
  1133. },
  1134. set value(param) {
  1135. config.autoFit = param;
  1136. checkFitWorld();
  1137. }
  1138. },
  1139. "zoom-when-adding": {
  1140. name: "Zoom When Adding",
  1141. desc: "Zoom to fit when you add a new entity",
  1142. type: "toggle",
  1143. default: true,
  1144. get value() {
  1145. return config.autoFitAdd;
  1146. },
  1147. set value(param) {
  1148. config.autoFitAdd = param;
  1149. }
  1150. },
  1151. "zoom-when-sizing": {
  1152. name: "Zoom When Sizing",
  1153. desc: "Zoom to fit when you select an entity's size",
  1154. type: "toggle",
  1155. default: true,
  1156. get value() {
  1157. return config.autoFitSize;
  1158. },
  1159. set value(param) {
  1160. config.autoFitSize = param;
  1161. }
  1162. },
  1163. "names": {
  1164. name: "Show Names",
  1165. desc: "Display names over entities",
  1166. type: "toggle",
  1167. default: true,
  1168. get value() {
  1169. return checkBodyClass("toggle-entity-name");
  1170. },
  1171. set value(param) {
  1172. toggleBodyClass("toggle-entity-name", param);
  1173. }
  1174. },
  1175. "bottom-names": {
  1176. name: "Bottom Names",
  1177. desc: "Display names at the bottom",
  1178. type: "toggle",
  1179. default: false,
  1180. get value() {
  1181. return checkBodyClass("toggle-bottom-name");
  1182. },
  1183. set value(param) {
  1184. toggleBodyClass("toggle-bottom-name", param);
  1185. }
  1186. },
  1187. "top-names": {
  1188. name: "Show Arrows",
  1189. desc: "Point to entities that are much larger than the current view",
  1190. type: "toggle",
  1191. default: false,
  1192. get value() {
  1193. return checkBodyClass("toggle-top-name");
  1194. },
  1195. set value(param) {
  1196. toggleBodyClass("toggle-top-name", param);
  1197. }
  1198. },
  1199. "height-bars": {
  1200. name: "Height Bars",
  1201. desc: "Draw dashed lines to the top of each entity",
  1202. type: "toggle",
  1203. default: false,
  1204. get value() {
  1205. return checkBodyClass("toggle-height-bars");
  1206. },
  1207. set value(param) {
  1208. toggleBodyClass("toggle-height-bars", param);
  1209. }
  1210. },
  1211. "glowing-entities": {
  1212. name: "Glowing Edges",
  1213. desc: "Makes all entities glow",
  1214. type: "toggle",
  1215. default: false,
  1216. get value() {
  1217. return checkBodyClass("toggle-entity-glow");
  1218. },
  1219. set value(param) {
  1220. toggleBodyClass("toggle-entity-glow", param);
  1221. }
  1222. },
  1223. "solid-ground": {
  1224. name: "Solid Ground",
  1225. desc: "Draw solid ground at the y=0 line",
  1226. type: "toggle",
  1227. default: false,
  1228. get value() {
  1229. return checkBodyClass("toggle-bottom-cover");
  1230. },
  1231. set value(param) {
  1232. toggleBodyClass("toggle-bottom-cover", param);
  1233. }
  1234. },
  1235. "show-scale": {
  1236. name: "Show Scale",
  1237. desc: "Show the scale",
  1238. type: "toggle",
  1239. default: true,
  1240. get value() {
  1241. return checkBodyClass("toggle-scale");
  1242. },
  1243. set value(param) {
  1244. toggleBodyClass("toggle-scale", param);
  1245. }
  1246. },
  1247. }
  1248. function prepareSettings(userSettings) {
  1249. const menubar = document.querySelector("#settings-menu");
  1250. Object.entries(settingsData).forEach(([id, entry]) => {
  1251. const holder = document.createElement("label");
  1252. holder.classList.add("settings-holder");
  1253. const input = document.createElement("input");
  1254. input.id = "setting-" + id;
  1255. const name = document.createElement("label");
  1256. name.innerText = entry.name;
  1257. name.classList.add("settings-name");
  1258. name.setAttribute("for", input.id);
  1259. const desc = document.createElement("label");
  1260. desc.innerText = entry.desc;
  1261. desc.classList.add("settings-desc");
  1262. desc.setAttribute("for", input.id);
  1263. if (entry.type == "toggle") {
  1264. input.type = "checkbox";
  1265. input.checked = userSettings[id] === undefined ? entry.default : userSettings[id];
  1266. holder.setAttribute("for", input.id);
  1267. input.appendChild(name);
  1268. input.appendChild(desc);
  1269. holder.appendChild(input);
  1270. holder.appendChild(name);
  1271. holder.appendChild(desc);
  1272. menubar.appendChild(holder);
  1273. const update = () => {
  1274. if (input.checked) {
  1275. holder.classList.add("enabled");
  1276. holder.classList.remove("disabled");
  1277. } else {
  1278. holder.classList.remove("enabled");
  1279. holder.classList.add("disabled");
  1280. }
  1281. entry.value = input.checked;
  1282. }
  1283. update();
  1284. input.addEventListener("change", update);
  1285. }
  1286. })
  1287. }
  1288. function prepareMenu() {
  1289. prepareSidebar();
  1290. if (checkHelpDate()) {
  1291. document.querySelector("#open-help").classList.add("highlighted");
  1292. }
  1293. }
  1294. function getUserSettings() {
  1295. try {
  1296. const settings = JSON.parse(localStorage.getItem("settings"));
  1297. return settings === null ? {} : settings;
  1298. } catch {
  1299. return {};
  1300. }
  1301. }
  1302. function exportUserSettings() {
  1303. const settings = {};
  1304. Object.entries(settingsData).forEach(([id, entry]) => {
  1305. settings[id] = entry.value;
  1306. });
  1307. return settings;
  1308. }
  1309. function setUserSettings(settings) {
  1310. try {
  1311. localStorage.setItem("settings", JSON.stringify(settings));
  1312. } catch {
  1313. // :(
  1314. }
  1315. }
  1316. const lastHelpChange = 1587847743294;
  1317. function checkHelpDate() {
  1318. try {
  1319. const old = localStorage.getItem("help-viewed");
  1320. if (old === null || old < lastHelpChange) {
  1321. return true;
  1322. }
  1323. return false;
  1324. } catch {
  1325. console.warn("Could not set the help-viewed date");
  1326. return false;
  1327. }
  1328. }
  1329. function setHelpDate() {
  1330. try {
  1331. localStorage.setItem("help-viewed", Date.now());
  1332. } catch {
  1333. console.warn("Could not set the help-viewed date");
  1334. }
  1335. }
  1336. function doScroll() {
  1337. document.querySelectorAll(".entity-box").forEach(element => {
  1338. element.dataset.x = parseFloat(element.dataset.x) + scrollDirection / 180;
  1339. });
  1340. updateSizes();
  1341. scrollDirection *= 1.05;
  1342. }
  1343. function doZoom() {
  1344. const oldHeight = config.height;
  1345. setWorldHeight(oldHeight, math.multiply(oldHeight, 1 + zoomDirection / 10));
  1346. zoomDirection *= 1.05;
  1347. }
  1348. function doSize() {
  1349. if (selected) {
  1350. const entity = entities[selected.dataset.key];
  1351. const oldHeight = entity.views[entity.view].height;
  1352. entity.views[entity.view].height = math.multiply(oldHeight, 1 + sizeDirection / 20);
  1353. entity.dirty = true;
  1354. updateEntityOptions(entity, entity.view);
  1355. updateViewOptions(entity, entity.view);
  1356. updateSizes(true);
  1357. sizeDirection *= 1.05;
  1358. const ownHeight = entity.views[entity.view].height.toNumber("meters");
  1359. const worldHeight = config.height.toNumber("meters");
  1360. if (ownHeight > worldHeight) {
  1361. setWorldHeight(config.height, entity.views[entity.view].height)
  1362. } else if (ownHeight * 10 < worldHeight) {
  1363. setWorldHeight(config.height, math.multiply(entity.views[entity.view].height, 10));
  1364. }
  1365. }
  1366. }
  1367. function prepareHelp() {
  1368. const toc = document.querySelector("#table-of-contents");
  1369. const holder = document.querySelector("#help-contents-holder");
  1370. document.querySelectorAll("#help-contents h2").forEach(header => {
  1371. const li = document.createElement("li");
  1372. li.innerText = header.textContent;
  1373. li.addEventListener("click", e => {
  1374. holder.scrollTop = header.offsetTop;
  1375. });
  1376. toc.appendChild(li);
  1377. });
  1378. }
  1379. document.addEventListener("DOMContentLoaded", () => {
  1380. prepareMenu();
  1381. prepareEntities();
  1382. prepareHelp();
  1383. document.querySelector("#open-help").addEventListener("click", e => {
  1384. setHelpDate();
  1385. document.querySelector("#help-menu").classList.add("visible");
  1386. document.querySelector("#open-help").classList.remove("highlighted");
  1387. });
  1388. document.querySelector("#close-help").addEventListener("click", e => {
  1389. document.querySelector("#help-menu").classList.remove("visible");
  1390. });
  1391. document.querySelector("#copy-screenshot").addEventListener("click", e => {
  1392. copyScreenshot();
  1393. toast("Copied to clipboard!");
  1394. });
  1395. document.querySelector("#save-screenshot").addEventListener("click", e => {
  1396. saveScreenshot();
  1397. });
  1398. document.querySelector("#toggle-menu").addEventListener("click", e => {
  1399. const popoutMenu = document.querySelector("#sidebar-menu");
  1400. if (popoutMenu.classList.contains("visible")) {
  1401. popoutMenu.classList.remove("visible");
  1402. } else {
  1403. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1404. const rect = e.target.getBoundingClientRect();
  1405. popoutMenu.classList.add("visible");
  1406. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1407. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1408. }
  1409. e.stopPropagation();
  1410. });
  1411. document.querySelector("#sidebar-menu").addEventListener("click", e => {
  1412. e.stopPropagation();
  1413. });
  1414. document.addEventListener("click", e => {
  1415. document.querySelector("#sidebar-menu").classList.remove("visible");
  1416. });
  1417. document.querySelector("#toggle-settings").addEventListener("click", e => {
  1418. const popoutMenu = document.querySelector("#settings-menu");
  1419. if (popoutMenu.classList.contains("visible")) {
  1420. popoutMenu.classList.remove("visible");
  1421. } else {
  1422. document.querySelectorAll(".popout-menu").forEach(menu => menu.classList.remove("visible"));
  1423. const rect = e.target.getBoundingClientRect();
  1424. popoutMenu.classList.add("visible");
  1425. popoutMenu.style.left = rect.x + rect.width + 10 + "px";
  1426. popoutMenu.style.top = rect.y + rect.height + 10 + "px";
  1427. }
  1428. e.stopPropagation();
  1429. });
  1430. document.querySelector("#settings-menu").addEventListener("click", e => {
  1431. e.stopPropagation();
  1432. });
  1433. document.addEventListener("click", e => {
  1434. document.querySelector("#settings-menu").classList.remove("visible");
  1435. });
  1436. window.addEventListener("unload", () => {
  1437. saveScene("autosave");
  1438. setUserSettings(exportUserSettings());
  1439. });
  1440. document.querySelector("#options-selected-entity").addEventListener("input", e => {
  1441. if (e.target.value == "None") {
  1442. deselect()
  1443. } else {
  1444. select(document.querySelector("#entity-" + e.target.value));
  1445. }
  1446. });
  1447. document.querySelector("#menu-toggle-sidebar").addEventListener("click", e => {
  1448. const sidebar = document.querySelector("#options");
  1449. if (sidebar.classList.contains("hidden")) {
  1450. sidebar.classList.remove("hidden");
  1451. e.target.classList.remove("rotate-forward");
  1452. e.target.classList.add("rotate-backward");
  1453. } else {
  1454. sidebar.classList.add("hidden");
  1455. e.target.classList.add("rotate-forward");
  1456. e.target.classList.remove("rotate-backward");
  1457. }
  1458. handleResize();
  1459. });
  1460. document.querySelector("#menu-fullscreen").addEventListener("click", toggleFullScreen);
  1461. document.querySelector("#options-order-forward").addEventListener("click", e => {
  1462. if (selected) {
  1463. entities[selected.dataset.key].priority += 1;
  1464. }
  1465. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1466. updateSizes();
  1467. });
  1468. document.querySelector("#options-order-back").addEventListener("click", e => {
  1469. if (selected) {
  1470. entities[selected.dataset.key].priority -= 1;
  1471. }
  1472. document.querySelector("#options-order-display").innerText = entities[selected.dataset.key].priority;
  1473. updateSizes();
  1474. });
  1475. const sceneChoices = document.querySelector("#scene-choices");
  1476. Object.entries(scenes).forEach(([id, scene]) => {
  1477. const option = document.createElement("option");
  1478. option.innerText = id;
  1479. option.value = id;
  1480. sceneChoices.appendChild(option);
  1481. });
  1482. document.querySelector("#load-scene").addEventListener("click", e => {
  1483. const chosen = sceneChoices.value;
  1484. removeAllEntities();
  1485. scenes[chosen]();
  1486. });
  1487. entityX = document.querySelector("#entities").getBoundingClientRect().x;
  1488. canvasWidth = document.querySelector("#display").clientWidth - 100;
  1489. canvasHeight = document.querySelector("#display").clientHeight - 50;
  1490. document.querySelector("#options-height-value").addEventListener("change", e => {
  1491. updateWorldHeight();
  1492. })
  1493. document.querySelector("#options-height-value").addEventListener("keydown", e => {
  1494. e.stopPropagation();
  1495. })
  1496. const unitSelector = document.querySelector("#options-height-unit");
  1497. unitChoices.length.forEach(lengthOption => {
  1498. const option = document.createElement("option");
  1499. option.innerText = lengthOption;
  1500. option.value = lengthOption;
  1501. if (lengthOption === "meters") {
  1502. option.selected = true;
  1503. }
  1504. unitSelector.appendChild(option);
  1505. });
  1506. unitSelector.setAttribute("oldUnit", "meters");
  1507. unitSelector.addEventListener("input", e => {
  1508. checkFitWorld();
  1509. const scaleInput = document.querySelector("#options-height-value");
  1510. const newVal = math.unit(scaleInput.value, unitSelector.getAttribute("oldUnit")).toNumber(e.target.value);
  1511. setNumericInput(scaleInput, newVal);
  1512. updateWorldHeight();
  1513. unitSelector.setAttribute("oldUnit", unitSelector.value);
  1514. });
  1515. param = new URL(window.location.href).searchParams.get("scene");
  1516. if (param === null) {
  1517. scenes["Default"]();
  1518. }
  1519. else {
  1520. try {
  1521. const data = JSON.parse(b64DecodeUnicode(param));
  1522. if (data.entities === undefined) {
  1523. return;
  1524. }
  1525. if (data.world === undefined) {
  1526. return;
  1527. }
  1528. importScene(data);
  1529. } catch (err) {
  1530. console.error(err);
  1531. scenes["Default"]();
  1532. // probably wasn't valid data
  1533. }
  1534. }
  1535. document.querySelector("#world").addEventListener("wheel", e => {
  1536. if (shiftHeld) {
  1537. if (selected) {
  1538. const dir = e.deltaY > 0 ? 10 / 11 : 11 / 10;
  1539. const entity = entities[selected.dataset.key];
  1540. entity.views[entity.view].height = math.multiply(entity.views[entity.view].height, dir);
  1541. entity.dirty = true;
  1542. updateEntityOptions(entity, entity.view);
  1543. updateViewOptions(entity, entity.view);
  1544. updateSizes(true);
  1545. } else {
  1546. document.querySelectorAll(".entity-box").forEach(element => {
  1547. element.dataset.x = parseFloat(element.dataset.x) + (e.deltaY < 0 ? 0.1 : -0.1);
  1548. });
  1549. updateSizes();
  1550. }
  1551. } else {
  1552. if (config.autoFit) {
  1553. toastRateLimit("Zoom is locked! Check Settings to disable.", "zoom-lock", 1000);
  1554. } else {
  1555. const dir = e.deltaY < 0 ? 10 / 11 : 11 / 10;
  1556. setWorldHeight(config.height, math.multiply(config.height, dir));
  1557. updateWorldOptions();
  1558. }
  1559. }
  1560. checkFitWorld();
  1561. })
  1562. document.querySelector("body").appendChild(testCtx.canvas);
  1563. updateSizes();
  1564. world.addEventListener("mousedown", e => deselect());
  1565. document.querySelector("#entities").addEventListener("mousedown", deselect);
  1566. document.querySelector("#display").addEventListener("mousedown", deselect);
  1567. document.addEventListener("mouseup", e => clickUp(e));
  1568. document.addEventListener("touchend", e => {
  1569. const fakeEvent = {
  1570. target: e.target,
  1571. clientX: e.changedTouches[0].clientX,
  1572. clientY: e.changedTouches[0].clientY
  1573. };
  1574. clickUp(fakeEvent);
  1575. });
  1576. const viewList = document.querySelector("#entity-view");
  1577. document.querySelector("#entity-view").addEventListener("input", e => {
  1578. const entity = entities[selected.dataset.key];
  1579. entity.view = e.target.value;
  1580. const image = entities[selected.dataset.key].views[e.target.value].image;
  1581. selected.querySelector(".entity-image").src = image.source;
  1582. configViewOptions(entity, entity.view);
  1583. displayAttribution(image.source);
  1584. if (image.bottom !== undefined) {
  1585. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1 + image.bottom) * 100) + "%")
  1586. } else {
  1587. selected.querySelector(".entity-image").style.setProperty("--offset", ((-1) * 100) + "%")
  1588. }
  1589. updateSizes();
  1590. updateEntityOptions(entities[selected.dataset.key], e.target.value);
  1591. updateViewOptions(entities[selected.dataset.key], e.target.value);
  1592. });
  1593. document.querySelector("#entity-view").addEventListener("input", e => {
  1594. if (viewList.options[viewList.selectedIndex].classList.contains("nsfw")) {
  1595. viewList.classList.add("nsfw");
  1596. } else {
  1597. viewList.classList.remove("nsfw");
  1598. }
  1599. })
  1600. clearViewList();
  1601. document.querySelector("#menu-clear").addEventListener("click", e => {
  1602. removeAllEntities();
  1603. });
  1604. document.querySelector("#delete-entity").disabled = true;
  1605. document.querySelector("#delete-entity").addEventListener("click", e => {
  1606. if (selected) {
  1607. removeEntity(selected);
  1608. selected = null;
  1609. }
  1610. });
  1611. document.querySelector("#menu-order-height").addEventListener("click", e => {
  1612. const order = Object.keys(entities).sort((a, b) => {
  1613. const entA = entities[a];
  1614. const entB = entities[b];
  1615. const viewA = entA.view;
  1616. const viewB = entB.view;
  1617. const heightA = entA.views[viewA].height.to("meter").value;
  1618. const heightB = entB.views[viewB].height.to("meter").value;
  1619. return heightA - heightB;
  1620. });
  1621. arrangeEntities(order);
  1622. });
  1623. // TODO: write some generic logic for this lol
  1624. document.querySelector("#scroll-left").addEventListener("mousedown", e => {
  1625. scrollDirection = 1;
  1626. clearInterval(scrollHandle);
  1627. scrollHandle = setInterval(doScroll, 1000 / 20);
  1628. e.stopPropagation();
  1629. });
  1630. document.querySelector("#scroll-right").addEventListener("mousedown", e => {
  1631. scrollDirection = -1;
  1632. clearInterval(scrollHandle);
  1633. scrollHandle = setInterval(doScroll, 1000 / 20);
  1634. e.stopPropagation();
  1635. });
  1636. document.querySelector("#scroll-left").addEventListener("touchstart", e => {
  1637. scrollDirection = 1;
  1638. clearInterval(scrollHandle);
  1639. scrollHandle = setInterval(doScroll, 1000 / 20);
  1640. e.stopPropagation();
  1641. });
  1642. document.querySelector("#scroll-right").addEventListener("touchstart", e => {
  1643. scrollDirection = -1;
  1644. clearInterval(scrollHandle);
  1645. scrollHandle = setInterval(doScroll, 1000 / 20);
  1646. e.stopPropagation();
  1647. });
  1648. document.addEventListener("mouseup", e => {
  1649. clearInterval(scrollHandle);
  1650. scrollHandle = null;
  1651. });
  1652. document.addEventListener("touchend", e => {
  1653. clearInterval(scrollHandle);
  1654. scrollHandle = null;
  1655. });
  1656. document.querySelector("#zoom-in").addEventListener("mousedown", e => {
  1657. zoomDirection = -1;
  1658. clearInterval(zoomHandle);
  1659. zoomHandle = setInterval(doZoom, 1000 / 20);
  1660. e.stopPropagation();
  1661. });
  1662. document.querySelector("#zoom-out").addEventListener("mousedown", e => {
  1663. zoomDirection = 1;
  1664. clearInterval(zoomHandle);
  1665. zoomHandle = setInterval(doZoom, 1000 / 20);
  1666. e.stopPropagation();
  1667. });
  1668. document.querySelector("#zoom-in").addEventListener("touchstart", e => {
  1669. zoomDirection = -1;
  1670. clearInterval(zoomHandle);
  1671. zoomHandle = setInterval(doZoom, 1000 / 20);
  1672. e.stopPropagation();
  1673. });
  1674. document.querySelector("#zoom-out").addEventListener("touchstart", e => {
  1675. zoomDirection = 1;
  1676. clearInterval(zoomHandle);
  1677. zoomHandle = setInterval(doZoom, 1000 / 20);
  1678. e.stopPropagation();
  1679. });
  1680. document.addEventListener("mouseup", e => {
  1681. clearInterval(zoomHandle);
  1682. zoomHandle = null;
  1683. });
  1684. document.addEventListener("touchend", e => {
  1685. clearInterval(zoomHandle);
  1686. zoomHandle = null;
  1687. });
  1688. document.querySelector("#shrink").addEventListener("mousedown", e => {
  1689. sizeDirection = -1;
  1690. clearInterval(sizeHandle);
  1691. sizeHandle = setInterval(doSize, 1000 / 20);
  1692. e.stopPropagation();
  1693. });
  1694. document.querySelector("#grow").addEventListener("mousedown", e => {
  1695. sizeDirection = 1;
  1696. clearInterval(sizeHandle);
  1697. sizeHandle = setInterval(doSize, 1000 / 20);
  1698. e.stopPropagation();
  1699. });
  1700. document.querySelector("#shrink").addEventListener("touchstart", e => {
  1701. sizeDirection = -1;
  1702. clearInterval(sizeHandle);
  1703. sizeHandle = setInterval(doSize, 1000 / 20);
  1704. e.stopPropagation();
  1705. });
  1706. document.querySelector("#grow").addEventListener("touchstart", e => {
  1707. sizeDirection = 1;
  1708. clearInterval(sizeHandle);
  1709. sizeHandle = setInterval(doSize, 1000 / 20);
  1710. e.stopPropagation();
  1711. });
  1712. document.addEventListener("mouseup", e => {
  1713. clearInterval(sizeHandle);
  1714. sizeHandle = null;
  1715. });
  1716. document.addEventListener("touchend", e => {
  1717. clearInterval(sizeHandle);
  1718. sizeHandle = null;
  1719. });
  1720. document.querySelector("#fit").addEventListener("click", e => {
  1721. const x = parseFloat(selected.dataset.x);
  1722. Object.keys(entities).forEach(id => {
  1723. const element = document.querySelector("#entity-" + id);
  1724. const newX = parseFloat(element.dataset.x) - x + 0.5;
  1725. element.dataset.x = newX;
  1726. });
  1727. const entity = entities[selected.dataset.key];
  1728. const height = math.multiply(entity.views[entity.view].height, 1.1);
  1729. setWorldHeight(config.height, height);
  1730. });
  1731. document.querySelector("#fit").addEventListener("mousedown", e => {
  1732. e.stopPropagation();
  1733. });
  1734. document.querySelector("#fit").addEventListener("touchstart", e => {
  1735. e.stopPropagation();
  1736. });
  1737. document.querySelector("#options-world-fit").addEventListener("click", () => fitWorld(true));
  1738. document.addEventListener("keydown", e => {
  1739. if (e.key == "Delete") {
  1740. if (selected) {
  1741. removeEntity(selected);
  1742. selected = null;
  1743. }
  1744. }
  1745. })
  1746. document.addEventListener("keydown", e => {
  1747. if (e.key == "Shift") {
  1748. shiftHeld = true;
  1749. e.preventDefault();
  1750. } else if (e.key == "Alt") {
  1751. altHeld = true;
  1752. e.preventDefault();
  1753. }
  1754. });
  1755. document.addEventListener("keyup", e => {
  1756. if (e.key == "Shift") {
  1757. shiftHeld = false;
  1758. e.preventDefault();
  1759. } else if (e.key == "Alt") {
  1760. altHeld = false;
  1761. e.preventDefault();
  1762. }
  1763. });
  1764. window.addEventListener("resize", handleResize);
  1765. // TODO: further investigate why the tool initially starts out with wrong
  1766. // values under certain circumstances (seems to be narrow aspect ratios -
  1767. // maybe the menu bar is animating when it shouldn't)
  1768. setTimeout(handleResize, 250);
  1769. setTimeout(handleResize, 500);
  1770. setTimeout(handleResize, 750);
  1771. setTimeout(handleResize, 1000);
  1772. document.querySelector("#menu-permalink").addEventListener("click", e => {
  1773. linkScene();
  1774. });
  1775. document.querySelector("#menu-export").addEventListener("click", e => {
  1776. copyScene();
  1777. });
  1778. document.querySelector("#menu-import").addEventListener("click", e => {
  1779. pasteScene();
  1780. });
  1781. document.querySelector("#menu-save").addEventListener("click", e => {
  1782. saveScene();
  1783. });
  1784. document.querySelector("#menu-load").addEventListener("click", e => {
  1785. loadScene();
  1786. });
  1787. document.querySelector("#menu-load-autosave").addEventListener("click", e => {
  1788. loadScene("autosave");
  1789. });
  1790. document.querySelector("#menu-add-image").addEventListener("click", e => {
  1791. document.querySelector("#file-upload-picker").click();
  1792. });
  1793. document.querySelector("#file-upload-picker").addEventListener("change", e => {
  1794. if (e.target.files.length > 0) {
  1795. for (let i=0; i<e.target.files.length; i++) {
  1796. customEntityFromFile(e.target.files[i]);
  1797. }
  1798. }
  1799. })
  1800. document.addEventListener("paste", e => {
  1801. let index = 0;
  1802. let item = null;
  1803. let found = false;
  1804. for (; index < e.clipboardData.items.length; index++) {
  1805. item = e.clipboardData.items[index];
  1806. if (item.type == "image/png") {
  1807. found = true;
  1808. break;
  1809. }
  1810. }
  1811. if (!found) {
  1812. return;
  1813. }
  1814. let url = null;
  1815. const file = item.getAsFile();
  1816. customEntityFromFile(file);
  1817. });
  1818. document.querySelector("#world").addEventListener("dragover", e => {
  1819. e.preventDefault();
  1820. })
  1821. document.querySelector("#world").addEventListener("drop", e => {
  1822. e.preventDefault();
  1823. if (e.dataTransfer.files.length > 0) {
  1824. let entX = document.querySelector("#entities").getBoundingClientRect().x;
  1825. let entY = document.querySelector("#entities").getBoundingClientRect().y;
  1826. let coords = abs2rel({x: e.clientX-entX, y: e.clientY-entY});
  1827. customEntityFromFile(e.dataTransfer.files[0], coords.x, coords.y);
  1828. }
  1829. })
  1830. clearEntityOptions();
  1831. clearViewOptions();
  1832. clearAttribution();
  1833. // we do this last because configuring settings can cause things
  1834. // to happen (e.g. auto-fit)
  1835. prepareSettings(getUserSettings());
  1836. });
  1837. function customEntityFromFile(file, x=0.5, y=0.5) {
  1838. file.arrayBuffer().then(buf => {
  1839. arr = new Uint8Array(buf);
  1840. blob = new Blob([arr], {type: file.type });
  1841. url = window.URL.createObjectURL(blob)
  1842. makeCustomEntity(url, x, y);
  1843. });
  1844. }
  1845. function makeCustomEntity(url, x=0.5, y=0.5) {
  1846. const maker = createEntityMaker(
  1847. {
  1848. name: "Custom Entity"
  1849. },
  1850. {
  1851. custom: {
  1852. attributes: {
  1853. height: {
  1854. name: "Height",
  1855. power: 1,
  1856. type: "length",
  1857. base: math.unit(6, "feet")
  1858. }
  1859. },
  1860. image: {
  1861. source: url
  1862. },
  1863. name: "Image",
  1864. info: {},
  1865. rename: false
  1866. }
  1867. },
  1868. []
  1869. );
  1870. const entity = maker.constructor();
  1871. entity.scale = config.height.toNumber("feet") / 20;
  1872. entity.ephemeral = true;
  1873. displayEntity(entity, "custom", x, y, true, true);
  1874. }
  1875. function prepareEntities() {
  1876. availableEntities["buildings"] = makeBuildings();
  1877. availableEntities["characters"] = makeCharacters();
  1878. availableEntities["cities"] = makeCities();
  1879. availableEntities["fiction"] = makeFiction();
  1880. availableEntities["food"] = makeFood();
  1881. availableEntities["landmarks"] = makeLandmarks();
  1882. availableEntities["naturals"] = makeNaturals();
  1883. availableEntities["objects"] = makeObjects();
  1884. availableEntities["dildos"] = makeDildos();
  1885. availableEntities["pokemon"] = makePokemon();
  1886. availableEntities["species"] = makeSpecies();
  1887. availableEntities["vehicles"] = makeVehicles();
  1888. availableEntities["characters"].sort((x, y) => {
  1889. return x.name.toLowerCase() < y.name.toLowerCase() ? -1 : 1
  1890. });
  1891. const holder = document.querySelector("#spawners");
  1892. const filterHolder = document.querySelector("#filters");
  1893. const categorySelect = document.createElement("select");
  1894. categorySelect.id = "category-picker";
  1895. const filterSelect = document.createElement("select");
  1896. filterSelect.id = "filter-picker";
  1897. holder.appendChild(categorySelect);
  1898. filterHolder.appendChild(filterSelect);
  1899. const authorSet = new Set();
  1900. const ownerSet = new Set();
  1901. Object.entries(availableEntities).forEach(([category, entityList]) => {
  1902. const select = document.createElement("select");
  1903. select.id = "create-entity-" + category;
  1904. select.classList.add("entity-select");
  1905. for (let i = 0; i < entityList.length; i++) {
  1906. const entity = entityList[i];
  1907. const option = document.createElement("option");
  1908. option.value = i;
  1909. option.innerText = entity.name;
  1910. select.appendChild(option);
  1911. if (entity.nsfw) {
  1912. option.classList.add("nsfw");
  1913. }
  1914. if (entity.authors) {
  1915. entity.authors.forEach(a => {
  1916. authorSet.add(a);
  1917. })
  1918. }
  1919. if (entity.owners) {
  1920. entity.owners.forEach(o => {
  1921. ownerSet.add(o);
  1922. })
  1923. }
  1924. availableEntitiesByName[entity.name] = entity;
  1925. };
  1926. select.addEventListener("change", e => {
  1927. if (select.options[select.selectedIndex].classList.contains("nsfw")) {
  1928. select.classList.add("nsfw");
  1929. } else {
  1930. select.classList.remove("nsfw");
  1931. }
  1932. })
  1933. const button = document.createElement("button");
  1934. button.id = "create-entity-" + category + "-button";
  1935. button.classList.add("entity-button");
  1936. button.innerHTML = "<i class=\"far fa-plus-square\"></i>";
  1937. button.addEventListener("click", e => {
  1938. const newEntity = entityList[select.value].constructor()
  1939. displayEntity(newEntity, newEntity.defaultView, 0.5, 1, true, true);
  1940. });
  1941. const categoryOption = document.createElement("option");
  1942. categoryOption.value = category
  1943. categoryOption.innerText = category;
  1944. if (category == "characters") {
  1945. categoryOption.selected = true;
  1946. select.classList.add("category-visible");
  1947. button.classList.add("category-visible");
  1948. }
  1949. categorySelect.appendChild(categoryOption);
  1950. holder.appendChild(select);
  1951. holder.appendChild(button);
  1952. });
  1953. const noFilter = document.createElement("option");
  1954. noFilter.innerText = "No Filter";
  1955. noFilter.value = "none";
  1956. const authorFilter = document.createElement("option");
  1957. authorFilter.innerText = "Author";
  1958. authorFilter.value = "author";
  1959. const ownerFilter = document.createElement("option");
  1960. ownerFilter.innerText = "Owner";
  1961. ownerFilter.value = "owner";
  1962. filterSelect.appendChild(noFilter);
  1963. filterSelect.appendChild(authorFilter);
  1964. filterSelect.appendChild(ownerFilter);
  1965. const authorFilterSelect = document.createElement("select");
  1966. authorFilterSelect.classList.add("filter-select");
  1967. authorFilterSelect.id = "filter-author";
  1968. filterHolder.appendChild(authorFilterSelect);
  1969. Array.from(authorSet).map(author => [author, attributionData.people[author].name]).sort((e1, e2) => e1[1].toLowerCase().localeCompare(e2[1].toLowerCase())).forEach(author => {
  1970. const option = document.createElement("option");
  1971. option.innerText = author[1];
  1972. option.value = author[0];
  1973. authorFilterSelect.appendChild(option);
  1974. });
  1975. authorFilterSelect.addEventListener("change", e => {
  1976. updateFilter();
  1977. });
  1978. const ownerFilterSelect = document.createElement("select");
  1979. ownerFilterSelect.classList.add("filter-select");
  1980. ownerFilterSelect.id = "filter-owner";
  1981. filterHolder.appendChild(ownerFilterSelect);
  1982. Array.from(ownerSet).map(owner => [owner, attributionData.people[owner].name]).sort((e1, e2) => e1[1].toLowerCase().localeCompare(e2[1].toLowerCase())).forEach(owner => {
  1983. const option = document.createElement("option");
  1984. option.innerText = owner[1];
  1985. option.value = owner[0];
  1986. ownerFilterSelect.appendChild(option);
  1987. });
  1988. ownerFilterSelect.addEventListener("change", e => {
  1989. updateFilter();
  1990. });
  1991. console.log("Loaded " + Object.keys(availableEntitiesByName).length + " entities");
  1992. categorySelect.addEventListener("input", e => {
  1993. const oldSelect = document.querySelector(".entity-select.category-visible");
  1994. oldSelect.classList.remove("category-visible");
  1995. const oldButton = document.querySelector(".entity-button.category-visible");
  1996. oldButton.classList.remove("category-visible");
  1997. const newSelect = document.querySelector("#create-entity-" + e.target.value);
  1998. newSelect.classList.add("category-visible");
  1999. const newButton = document.querySelector("#create-entity-" + e.target.value + "-button");
  2000. newButton.classList.add("category-visible");
  2001. recomputeFilters();
  2002. updateFilter();
  2003. });
  2004. recomputeFilters();
  2005. filterSelect.addEventListener("input", e => {
  2006. const oldSelect = document.querySelector(".filter-select.category-visible");
  2007. if (oldSelect)
  2008. oldSelect.classList.remove("category-visible");
  2009. const newSelect = document.querySelector("#filter-" + e.target.value);
  2010. if (newSelect)
  2011. newSelect.classList.add("category-visible");
  2012. updateFilter();
  2013. });
  2014. }
  2015. // Only display authors and owners if they appear
  2016. // somewhere in the current entity list
  2017. function recomputeFilters() {
  2018. const category = document.querySelector("#category-picker").value;
  2019. const authorSet = new Set();
  2020. const ownerSet = new Set();
  2021. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2022. const entity = availableEntities[category][element.value];
  2023. if (entity.authors)
  2024. entity.authors.forEach(author => authorSet.add(author));
  2025. if (entity.owners)
  2026. entity.owners.forEach(owner => ownerSet.add(owner));
  2027. });
  2028. let authorFound = false;
  2029. document.querySelectorAll("#filter-author > option").forEach(element => {
  2030. if (authorSet.has(element.value)) {
  2031. element.classList.remove("filtered");
  2032. authorFound = true;
  2033. } else {
  2034. element.classList.add("filtered");
  2035. }
  2036. })
  2037. let ownerFound = false;
  2038. document.querySelectorAll("#filter-owner > option").forEach(element => {
  2039. if (ownerSet.has(element.value)) {
  2040. element.classList.remove("filtered");
  2041. ownerFound = true;
  2042. } else {
  2043. element.classList.add("filtered");
  2044. }
  2045. })
  2046. if (authorFound) {
  2047. document.querySelector("#filter-picker > option[value='author']").classList.remove("filtered");
  2048. } else {
  2049. document.querySelector("#filter-picker > option[value='author']").classList.add("filtered");
  2050. }
  2051. if (ownerFound) {
  2052. document.querySelector("#filter-picker > option[value='owner']").classList.remove("filtered");
  2053. } else {
  2054. document.querySelector("#filter-picker > option[value='owner']").classList.add("filtered");
  2055. }
  2056. document.querySelector("#filter-picker").value = "none";
  2057. document.querySelector("#filter-picker").dispatchEvent(new Event("input"));
  2058. }
  2059. function updateFilter() {
  2060. const category = document.querySelector("#category-picker").value;
  2061. const type = document.querySelector("#filter-picker").value;
  2062. const filterKeySelect = document.querySelector(".filter-select.category-visible");
  2063. clearFilter();
  2064. if (!filterKeySelect) {
  2065. return;
  2066. }
  2067. const key = filterKeySelect.value;
  2068. let current = document.querySelector(".entity-select.category-visible").value;
  2069. let replace = false;
  2070. let first = null;
  2071. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2072. let keep = false;
  2073. if (type == "author") {
  2074. const authorList = availableEntities[category][element.value].authors;
  2075. if (authorList && authorList.indexOf(key) >= 0) {
  2076. keep = true;
  2077. }
  2078. }
  2079. if (type == "owner") {
  2080. const ownerList = availableEntities[category][element.value].owners;
  2081. if (ownerList && ownerList.indexOf(key) >= 0) {
  2082. keep = true;
  2083. }
  2084. }
  2085. if (!keep) {
  2086. element.classList.add("filtered");
  2087. if (current == element.value) {
  2088. replace = true;
  2089. }
  2090. } else if (!first) {
  2091. first = element.value;
  2092. }
  2093. });
  2094. if (replace) {
  2095. document.querySelector(".entity-select.category-visible").value = first;
  2096. document.querySelector("#create-entity-" + category).dispatchEvent(new Event("change"));
  2097. }
  2098. }
  2099. function clearFilter() {
  2100. document.querySelectorAll(".entity-select.category-visible > option").forEach(element => {
  2101. element.classList.remove("filtered");
  2102. });
  2103. }
  2104. document.addEventListener("mousemove", (e) => {
  2105. if (clicked) {
  2106. const position = snapRel(abs2rel({ x: e.clientX - dragOffsetX, y: e.clientY - dragOffsetY }));
  2107. clicked.dataset.x = position.x;
  2108. clicked.dataset.y = position.y;
  2109. updateEntityElement(entities[clicked.dataset.key], clicked);
  2110. if (hoveringInDeleteArea(e)) {
  2111. document.querySelector("#menubar").classList.add("hover-delete");
  2112. } else {
  2113. document.querySelector("#menubar").classList.remove("hover-delete");
  2114. }
  2115. }
  2116. });
  2117. document.addEventListener("touchmove", (e) => {
  2118. if (clicked) {
  2119. e.preventDefault();
  2120. let x = e.touches[0].clientX;
  2121. let y = e.touches[0].clientY;
  2122. const position = snapRel(abs2rel({ x: x - dragOffsetX, y: y - dragOffsetY }));
  2123. clicked.dataset.x = position.x;
  2124. clicked.dataset.y = position.y;
  2125. updateEntityElement(entities[clicked.dataset.key], clicked);
  2126. // what a hack
  2127. // I should centralize this 'fake event' creation...
  2128. if (hoveringInDeleteArea({ clientY: y })) {
  2129. document.querySelector("#menubar").classList.add("hover-delete");
  2130. } else {
  2131. document.querySelector("#menubar").classList.remove("hover-delete");
  2132. }
  2133. }
  2134. }, { passive: false });
  2135. function checkFitWorld() {
  2136. if (config.autoFit) {
  2137. fitWorld();
  2138. return true;
  2139. }
  2140. return false;
  2141. }
  2142. const fitModes = {
  2143. "max": {
  2144. start: 0,
  2145. binop: Math.max,
  2146. final: (total, count) => total
  2147. },
  2148. "arithmetic mean": {
  2149. start: 0,
  2150. binop: math.add,
  2151. final: (total, count) => total / count
  2152. },
  2153. "geometric mean": {
  2154. start: 1,
  2155. binop: math.multiply,
  2156. final: (total, count) => math.pow(total, 1 / count)
  2157. }
  2158. }
  2159. function fitWorld(manual = false, factor = 1.1) {
  2160. const fitMode = fitModes[config.autoFitMode]
  2161. let max = fitMode.start
  2162. let count = 0;
  2163. Object.entries(entities).forEach(([key, entity]) => {
  2164. const view = entity.view;
  2165. let extra = entity.views[view].image.extra;
  2166. extra = extra === undefined ? 1 : extra;
  2167. max = fitMode.binop(max, math.multiply(extra, entity.views[view].height.toNumber("meter")));
  2168. count += 1;
  2169. });
  2170. max = fitMode.final(max, count)
  2171. max = math.unit(max, "meter")
  2172. if (manual)
  2173. altHeld = true;
  2174. setWorldHeight(config.height, math.multiply(max, factor));
  2175. if (manual)
  2176. altHeld = false;
  2177. }
  2178. // TODO why am I doing this
  2179. function updateWorldHeight() {
  2180. const unit = document.querySelector("#options-height-unit").value;
  2181. const value = Math.max(0.000000001, document.querySelector("#options-height-value").value);
  2182. const oldHeight = config.height;
  2183. setWorldHeight(oldHeight, math.unit(value, unit));
  2184. }
  2185. function setWorldHeight(oldHeight, newHeight) {
  2186. worldSizeDirty = true;
  2187. config.height = newHeight.to(document.querySelector("#options-height-unit").value)
  2188. const unit = document.querySelector("#options-height-unit").value;
  2189. setNumericInput(document.querySelector("#options-height-value"), config.height.toNumber(unit));
  2190. Object.entries(entities).forEach(([key, entity]) => {
  2191. const element = document.querySelector("#entity-" + key);
  2192. let newPosition;
  2193. if (!altHeld) {
  2194. newPosition = adjustAbs({ x: element.dataset.x, y: element.dataset.y }, oldHeight, config.height);
  2195. } else {
  2196. newPosition = { x: element.dataset.x, y: element.dataset.y };
  2197. }
  2198. element.dataset.x = newPosition.x;
  2199. element.dataset.y = newPosition.y;
  2200. });
  2201. updateSizes();
  2202. }
  2203. function loadScene(name = "default") {
  2204. try {
  2205. const data = JSON.parse(localStorage.getItem("macrovision-save-" + name));
  2206. if (data === null) {
  2207. return false;
  2208. }
  2209. importScene(data);
  2210. return true;
  2211. } catch (err) {
  2212. alert("Something went wrong while loading (maybe you didn't have anything saved. Check the F12 console for the error.")
  2213. console.error(err);
  2214. return false;
  2215. }
  2216. }
  2217. function saveScene(name = "default") {
  2218. try {
  2219. const string = JSON.stringify(exportScene());
  2220. localStorage.setItem("macrovision-save-" + name, string);
  2221. } catch (err) {
  2222. alert("Something went wrong while saving (maybe I don't have localStorage permissions, or exporting failed). Check the F12 console for the error.")
  2223. console.error(err);
  2224. }
  2225. }
  2226. function deleteScene(name = "default") {
  2227. try {
  2228. localStorage.removeItem("macrovision-save-" + name)
  2229. } catch (err) {
  2230. console.error(err);
  2231. }
  2232. }
  2233. function exportScene() {
  2234. const results = {};
  2235. results.entities = [];
  2236. Object.entries(entities).filter(([key, entity]) => entity.ephemeral !== true).forEach(([key, entity]) => {
  2237. const element = document.querySelector("#entity-" + key);
  2238. results.entities.push({
  2239. name: entity.identifier,
  2240. scale: entity.scale,
  2241. view: entity.view,
  2242. x: element.dataset.x,
  2243. y: element.dataset.y
  2244. });
  2245. });
  2246. const unit = document.querySelector("#options-height-unit").value;
  2247. results.world = {
  2248. height: config.height.toNumber(unit),
  2249. unit: unit
  2250. }
  2251. results.canvasWidth = canvasWidth;
  2252. return results;
  2253. }
  2254. // btoa doesn't like anything that isn't ASCII
  2255. // great
  2256. // thanks to https://stackoverflow.com/questions/30106476/using-javascripts-atob-to-decode-base64-doesnt-properly-decode-utf-8-strings
  2257. // for providing an alternative
  2258. function b64EncodeUnicode(str) {
  2259. // first we use encodeURIComponent to get percent-encoded UTF-8,
  2260. // then we convert the percent encodings into raw bytes which
  2261. // can be fed into btoa.
  2262. return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
  2263. function toSolidBytes(match, p1) {
  2264. return String.fromCharCode('0x' + p1);
  2265. }));
  2266. }
  2267. function b64DecodeUnicode(str) {
  2268. // Going backwards: from bytestream, to percent-encoding, to original string.
  2269. return decodeURIComponent(atob(str).split('').map(function (c) {
  2270. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  2271. }).join(''));
  2272. }
  2273. function linkScene() {
  2274. loc = new URL(window.location);
  2275. window.location = loc.protocol + "//" + loc.host + loc.pathname + "?scene=" + b64EncodeUnicode(JSON.stringify(exportScene()));
  2276. }
  2277. function copyScene() {
  2278. const results = exportScene();
  2279. navigator.clipboard.writeText(JSON.stringify(results));
  2280. }
  2281. function pasteScene() {
  2282. try {
  2283. navigator.clipboard.readText().then(text => {
  2284. const data = JSON.parse(text);
  2285. if (data.entities === undefined) {
  2286. return;
  2287. }
  2288. if (data.world === undefined) {
  2289. return;
  2290. }
  2291. importScene(data);
  2292. }).catch(err => alert(err));
  2293. } catch (err) {
  2294. console.error(err);
  2295. // probably wasn't valid data
  2296. }
  2297. }
  2298. // TODO - don't just search through every single entity
  2299. // probably just have a way to do lookups directly
  2300. function findEntity(name) {
  2301. return availableEntitiesByName[name];
  2302. }
  2303. function importScene(data) {
  2304. removeAllEntities();
  2305. data.entities.forEach(entityInfo => {
  2306. const entity = findEntity(entityInfo.name).constructor();
  2307. entity.scale = entityInfo.scale
  2308. displayEntity(entity, entityInfo.view, entityInfo.x, entityInfo.y);
  2309. });
  2310. config.height = math.unit(data.world.height, data.world.unit);
  2311. document.querySelector("#options-height-unit").value = data.world.unit;
  2312. if (data.canvasWidth) {
  2313. doHorizReposition(data.canvasWidth / canvasWidth);
  2314. }
  2315. updateSizes();
  2316. }
  2317. function renderToCanvas() {
  2318. const ctx = document.querySelector("#display").getContext("2d");
  2319. Object.entries(entities).sort((ent1, ent2) => {
  2320. z1 = document.querySelector("#entity-" + ent1[0]).style.zIndex;
  2321. z2 = document.querySelector("#entity-" + ent2[0]).style.zIndex;
  2322. return z1 - z2;
  2323. }).forEach(([id, entity]) => {
  2324. element = document.querySelector("#entity-" + id);
  2325. img = element.querySelector("img");
  2326. let x = parseFloat(element.dataset.x);
  2327. let y = parseFloat(element.dataset.y);
  2328. let coords = rel2abs({x: x, y: y});
  2329. let offset = img.style.getPropertyValue("--offset");
  2330. offset = parseFloat(offset.substring(0, offset.length-1))
  2331. x = coords.x - img.getBoundingClientRect().width/2;
  2332. y = coords.y - img.getBoundingClientRect().height * (-offset/100);
  2333. let xSize = img.getBoundingClientRect().width;
  2334. let ySize = img.getBoundingClientRect().height;
  2335. ctx.drawImage(img, x, y, xSize, ySize);
  2336. });
  2337. }
  2338. function exportCanvas(callback) {
  2339. /** @type {CanvasRenderingContext2D} */
  2340. const ctx = document.querySelector("#display").getContext("2d");
  2341. const blob = ctx.canvas.toBlob(callback);
  2342. }
  2343. function generateScreenshot(callback) {
  2344. renderToCanvas();
  2345. /** @type {CanvasRenderingContext2D} */
  2346. const ctx = document.querySelector("#display").getContext("2d");
  2347. ctx.fillStyle = "#555";
  2348. ctx.font = "normal normal lighter 16pt coda";
  2349. ctx.fillText("macrovision.crux.sexy", 10, 25);
  2350. exportCanvas(blob => {
  2351. callback(blob);
  2352. });
  2353. }
  2354. function copyScreenshot() {
  2355. generateScreenshot(blob => {
  2356. navigator.clipboard.write([
  2357. new ClipboardItem({
  2358. "image/png": blob
  2359. })
  2360. ]);
  2361. });
  2362. drawScale(false);
  2363. }
  2364. function saveScreenshot() {
  2365. generateScreenshot(blob => {
  2366. const a = document.createElement("a");
  2367. a.href = URL.createObjectURL(blob);
  2368. a.setAttribute("download", "macrovision.png");
  2369. a.click();
  2370. });
  2371. drawScale(false);
  2372. }
  2373. const rateLimits = {};
  2374. function toast(msg) {
  2375. let div = document.createElement("div");
  2376. div.innerHTML = msg;
  2377. div.classList.add("toast");
  2378. document.body.appendChild(div);
  2379. setTimeout(() => {
  2380. document.body.removeChild(div);
  2381. }, 5000)
  2382. }
  2383. function toastRateLimit(msg, key, delay) {
  2384. if (!rateLimits[key]) {
  2385. toast(msg);
  2386. rateLimits[key] = setTimeout(() => {
  2387. delete rateLimits[key]
  2388. }, delay);
  2389. }
  2390. }