less copy protection, more size visualization
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

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