Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 | 32x 32x 32x 32x 32x 17x 2x 65x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 105x 5x 74x 3x 2x 5x 5x 5x 3x 1x 1x 2x 2x 2x 2x 2x 3x 3x 3x 4x 4x 5x 5x 5x 254x 112x 112x 22x 22x 16x 16x 22x 12x 103x 103x 103x 103x 103x 103x 103x 103x 9x 4x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 118x 118x 118x 100x 98x 98x 97x 118x 94x 94x 17x 17x 4x 4x 1x 1x 12x 12x 2x 2x 2x 11x 8x 8x 8x 8x 8x 3x 1x 1x 2x 2x 2x 1x 2x 2x 2x 1x 1x 4x 4x 1x 1x 4x 3x 3x 2x 1x 1x 3x 3x 2x 2x 3x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 3x 3x 91x 91x 91x 91x 91x 91x 29x 7x 22x 29x 10x 10x 9x 9x 4x 4x 1x 1x 15x 15x 15x 2x 2x 4x 4x 3x 3x 14x 14x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 253x 177x 177x 253x 253x 261x 94x 94x 5x 2x 3x 2x 2x 5x 89x 89x 89x 89x 89x 89x 57x 57x 57x 89x 89x 89x 24x 24x 24x 22x 22x 2x 2x 2x 2x 2x 24x 24x 24x 7x 10x 10x 9x 261x 261x 25x 25x 25x 13x 25x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 6x 6x 6x 3x 3x 3x 12x 11x 11x 20x 20x 20x 18x 18x 2x 20x 20x 253x 253x 4x 2x 2x 2x 20x 20x 20x 1x 1x 19x 18x 18x 18x 18x 1x 1x 17x 17x 3x 3x 3x 1x 1x 2x 1x 3x 1x 1x 1x 253x 253x 1x 1x 1x 3x 2x 2x 3x 3x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 14x 14x 3x 14x 14x 14x 3x 14x 3x 3x 3x 4x 4x 3x 3x 4x 2x 2x 2x 4x 4x 4x 11x 11x 11x 11x 3x 3x 8x 8x 8x 11x 6x 1x 1x 5x 1x 1x 1x 4x 21x 19x 19x 19x 21x 21x 19x 8x 6x 6x 6x 6x 6x 7x 7x 7x 14x 14x 14x 14x 14x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 2x 2x 7x 5x 5x 5x 5x 2x 2x 3x 3x 3x 3x 3x 1x 1x 2x 2x 2x 6x 6x 5x 5x 5x 4x 4x 4x 1x 1x 1x 1x 1x 150x 150x 103x 103x 17x 17x 86x 356x 356x 356x 356x 83x 83x 76x 4x | import { firstReplaySlot, snapClassicHiSpeed, stepClassicHiSpeed, stepReplaySlot } from '@be-music/player-scene-model';
/**
* The select screen's behaviour, whatever family draws it: where the player is in the library, as the browse model of
* `@be-music/player-scene-model` keeps it (`BrowseState`, changed by `reduceBrowse`, its list derived by `browseEntries`), the
* play options and the option panels, the search, the README dialog, starting a chart or a course, and the screen's
* sound. What the browse model leaves to the screen comes from the family's select policy (`select-policy.ts`).
*
* The sound goes through the audio service: the select BGM (ducked under the chart preview) and the preview of the
* chart under the cursor belong to the session and stop when the screen leaves the stage; the cues and the decide
* jingle have no owner and play out, so the jingle rings on through the decide screen into the play, as LR2's does.
*
* Keys come in as plain data (`select-keys.ts`), the view's pointer input as intents; each tick the session answers with
* a frame, and with what happened since the last one, for the view's slides and timers.
*/
import type { CourseChartRecord } from '@be-music/player-engine/course';
import {
browseCursor,
browseEntries,
browseSearchError,
browseSystemSound,
captureBrowse,
chartFolderLabel,
clampHiSpeed,
clampFloatingHiSpeed,
cyclePlayOptionValue,
DEFAULT_PLAY_OPTIONS,
focusedChart,
focusedEntry,
HISPEED_STEP,
isListPlayOption,
KEYS_FILTER_CYCLE,
libraryEntryKey,
reduceBrowse,
resolvePlayOptions,
resolvePlayOptionValue,
sameBrowseListOptions,
SORT_CYCLE,
startSystemSound,
type BrowseCommand,
type BrowseEvent,
type BrowseListOptions,
type BrowseSnapshot,
type BrowseState,
type Library,
type LibraryChart,
type LibraryCourse,
type LibraryEntry,
type PlayOptions,
type SystemSoundSet,
type SystemSoundSlot,
} from '@be-music/player-scene-model';
import { resolveChartSource } from '../../collection/collection.ts';
import { createCourseChartRecord } from '../../collection/course.ts';
import type { BrowserChartCollection } from '../../collection/types.ts';
import type { AudioService } from '../../runtime/audio-service.ts';
import type { CourseMaker } from '../../collection/course-maker.ts';
import type {
SelectCourseMakerAction,
SelectCourseMakerState,
SelectFrame,
SelectReadText,
SelectIntent,
SelectRecords,
SelectViewEvent,
} from '../../view/types.ts';
import type { SceneSession, SessionKeyEvent } from '../session-scene.ts';
import { resolveSelectKeyAction } from './select-keys.ts';
import { nextDifficultyIndex } from './select-difficulty.ts';
import { DEFAULT_CONTROL_ACTIONS, type ControlActionMap } from '../controls/control-actions.ts';
import { controlButtonsOfKey, DEFAULT_CONTROL_BUTTONS } from '../controls/control-buttons.ts';
import { createControlButtonTracker, isStartAndSelectDown } from '../controls/button-tracker.ts';
import { openLibrary, restoreSelectBrowse, SELECT_POLICIES, type SelectPolicy } from './select-policy.ts';
import { findReadtextsForChart } from '../../collection/readtext.ts';
/** A bar the player starts: a chart or a course. */
export type SelectStartEntry = Exclude<LibraryEntry, { kind: 'folder' }>;
/** Where the select screen leads, and what it tells the host. */
/** How long LR2's key 6 is held for the saved replay instead of AUTO, as LR2 holds it (`> 2000`). */
export const REPLAY_HOLD_MS = 2000;
/** How long LR2's key 4 is held for the chart's ranking. */
export const RANKING_HOLD_MS = 300;
/** How long the panel key is held for the panel to show only while it is (LR2's), rather than stay open. */
export const PANEL_HOLD_MS = 300;
export interface SelectSessionEvents {
/**
* The player started a chart or a course (in AUTO with `autoPlay`). A course with a stage missing is handed over too,
* so the host can say why it does not start. Return `false` when the entry starts no play (the course being made
* takes the chart, the course cannot start): the screen then plays no decide sound.
*/
start(entry: SelectStartEntry, options: { readonly autoPlay: boolean; readonly replaySlot?: number }): boolean | void;
/**
* A chart was picked and the skin's launch outro begins; `start` follows once it has played. The host can start
* loading what comes next (the play) from here instead of waiting out the outro. Not called for a start without an
* outro, which goes to `start` at once.
*/
launch?(entry: SelectStartEntry, options: { readonly autoPlay: boolean; readonly replaySlot?: number }): void;
/**
* The bar under the cursor changed, or the screen came on the stage (`undefined` on an empty list): the host's own
* surfaces for it (the replay slots' card) follow it. Reported from the frame.
*/
focus?(entry: LibraryEntry | undefined): void;
practice?(chart: LibraryChart): void;
/** The player changed the play options on the screen; the host's own `setPlayOptions` is not reported. */
playOptions?(options: PlayOptions): void;
/** The player asked to type a search: the host lays its text field over the skin's search box. */
search?(): void;
/**
* Shows a chart's text file in the host's own way. Without it, the view shows its README dialog over the screen.
*/
readtext?(chart: LibraryChart): void;
/** The course maker: name the course being made, or delete the player's own course under the cursor. */
courseMaker?(action: 'name' | 'delete', course: LibraryCourse | undefined): void;
/** The player asked for the skin's options. */
skinConfig?(): void;
/** The player left the screen (a back-out at the root, under a policy that leaves). */
exit?(): void;
/**
* The player backed out at the root: the host asks whether to leave (That-Which-Must-Not-Be-Named PC's exit menu).
* With it, a back-out at the root does only this, whatever the policy says.
*/
exitMenu?(): void;
/** The player asked to read the library's folders again (LR2's F8, beatoraja's F2). Without it the key does nothing. */
reload?(): void;
/** LR2's F2: the host shows the LR2 mania options. Absent when the host has no place for them. */
maniaOptions?(): void;
/** The player held LR2's key 4 on a chart: show its ranking (LR2's IR). */
ranking?(chart: LibraryChart): void;
/**
* The player stepped a chart's difficulty (`#DIFFICULTY`) or level (`#PLAYLEVEL`) with LR2's F3 + the arrows: the
* host keeps the edit and gives the screen the library again.
*/
levelEdit?(chart: LibraryChart, part: 'difficulty' | 'level', step: 1 | -1): void;
/** The player asked for the focused chart's MD5 or SHA-256 (beatoraja's Ctrl+F3 / Ctrl+Shift+F3): the host copies it. */
copyChartHash?(chart: LibraryChart, hash: 'md5' | 'sha256'): void;
/**
* The player asked to play the charts of the focused folder in AUTO one after the other (beatoraja's F10): the host
* plays them in this order. Without it the key does nothing.
*/
autoplayFolder?(charts: readonly LibraryChart[]): void;
}
/** The part of the audio service the select screen uses. */
export type SelectAudio = Pick<
AudioService,
'playBGM' | 'stopBGM' | 'playCue' | 'playJingle' | 'stopOwned' | 'resume' | 'preview' | 'analyzer'
>;
export interface SelectSessionOptions {
/** The library to browse, with its charts' files (the preview's samples, the text files). */
readonly library: BrowserChartCollection;
/** Where to open it: a saved browse position. Without one, a library of one chart folder opens it. */
readonly browse?: BrowseSnapshot;
/** The play options to start from, over `DEFAULT_PLAY_OPTIONS`; their sort and filters shape the list. */
readonly playOptions?: Partial<PlayOptions>;
/** The player's best records, for the bars and panels. */
readonly records?: SelectRecords;
/** The theme's sounds: the select BGM, the cues and the decide jingle (`decideBGM`). */
readonly sounds: SystemSoundSet;
readonly audio: SelectAudio;
/** What the browse model leaves to the screen. Defaults to LR2's (the built-in and LR2 families). */
readonly policy?: SelectPolicy;
/** The player's keys for the screen's operations, on the policy's key map. Defaults to the map's default keys. */
readonly actions?: ControlActionMap;
/** How long the skin's launch outro plays before a started chart is handed on (`SelectView.launchOutroMs`). */
readonly launchOutroMs?: () => number;
/** The clock events are stamped with when no key timestamp is at hand. Defaults to `performance.now()`. */
readonly now?: () => number;
/** The random draw in [0, 1) a random select takes (beatoraja's R key). Defaults to `Math.random`. */
readonly random?: () => number;
/**
* The player's own courses and the course being made (LR2's course maker): its finish, cancel and connection buttons
* run on it, and its state shows in the frame.
*/
readonly courseMaker?: SelectCourseMaker;
readonly on: SelectSessionEvents;
}
/** The part of the course maker the select screen drives. */
export type SelectCourseMaker = Pick<
CourseMaker,
| 'draft'
| 'defaultConnection'
| 'owns'
| 'finish'
| 'cancel'
| 'stepDefaultConnection'
| 'stepConnection'
| 'releaseCourse'
> &
/** The RANDOM MIX settings and their buttons, for a host that lists RANDOM MIX bars. */
Partial<Pick<CourseMaker, 'randomMixSettings' | 'stepRandomMixSetting'>>;
/** The select BGM's level: about -6 dB, under the cues and the preview, as the select scenes always played it. */
const SELECT_BGM_VOLUME = 0.5;
const NO_RECORDS: SelectRecords = {
chart: () => undefined,
course: () => undefined,
};
/** The list options the play options hold. */
function listOptionsOf(options: PlayOptions): BrowseListOptions {
return { sort: options.sort, keysFilter: options.keysFilter, difficultyFilter: options.difficultyFilter };
}
/** A launch waiting for the skin's outro to finish. */
interface PendingLaunch {
readonly atMs: number;
readonly entry: SelectStartEntry;
readonly autoPlay: boolean;
readonly replaySlot?: number;
}
/** The select screen's session. See the module comment. */
export class SelectSession implements SceneSession<SelectFrame, SelectIntent> {
public readonly kind = 'select' as const;
private readonly options: SelectSessionOptions;
private readonly policy: SelectPolicy;
private readonly now: () => number;
private readonly random: () => number;
private library: BrowserChartCollection;
/**
* The library as the browse model reads it: the collection, with the reader a chart filter search (`?…`) sees each
* chart through. Made again when the library or the records change, so a search lists by the records as they are.
*/
private browseLibrary: Library;
/** Each chart's filter record, resolved once: only its `score` row is read again, from the records in force. */
private readonly filterRecords = new WeakMap<LibraryChart, CourseChartRecord>();
private browse: BrowseState;
private playOptions: PlayOptions;
private records: SelectRecords;
private sounds: SystemSoundSet;
private panel: number | undefined;
/** The control buttons held, for beatoraja's START + SELECT. */
private readonly buttonsHeld = createControlButtonTracker();
/** LR2's key 4 or 6 held: which, its key, when it went down, and whether its hold has acted. */
private heldKey:
| { readonly kind: 'auto' | 'ranking'; readonly code: string; readonly atMs: number; fired?: boolean }
| undefined;
/** Whether LR2's F3 is held, which turns the arrows to the level edit. */
private levelEditHeld = false;
/** When the panel key that opened the panel went down, while it is still held. */
private panelPressedAtMs: number | undefined;
private searchEditing = false;
private readText: SelectReadText | undefined;
/** Bumped by each README lookup, so a lookup that lands after a newer one (or a close) is dropped. */
private readTextLookup = 0;
private launch: PendingLaunch | undefined;
private entered = false;
private disposed = false;
private enteredAtMs = 0;
private nowMs = 0;
private revision = 0;
private events: SelectViewEvent[] = [];
/**
* The chart (and its source) the preview was last pointed at, kept while the screen is off the stage. Coming back with
* the cursor on the same chart does not start its preview again, as the select scene always did; moving onto another
* chart does.
*/
private previewKey: string | undefined;
/** The replay slot picked for the bar it was picked on (beatoraja's `selectedreplay`), reset when the bar changes. */
private replayPick: { readonly entry: SelectStartEntry; readonly slot: number } | undefined;
/** The bar last reported through `on.focus`; `null` before the first report of an entry. */
private reportedFocus: LibraryEntry | undefined | null = null;
public constructor(options: SelectSessionOptions) {
this.options = options;
this.policy = options.policy ?? SELECT_POLICIES.lr2;
this.now = options.now ?? (() => performance.now());
this.random = options.random ?? Math.random;
this.library = options.library;
this.records = options.records ?? NO_RECORDS;
this.browseLibrary = this.createBrowseLibrary();
this.sounds = options.sounds;
this.playOptions = resolvePlayOptions({ ...DEFAULT_PLAY_OPTIONS, ...options.playOptions });
// Under a policy that keeps the sort and the filters in the browse position (beatoraja's MODE and SORT), the play
// options' do not shape the list.
const base = openLibrary(
this.browseLibrary,
this.policy,
this.policy.listOptions === 'play-options' ? { list: listOptionsOf(this.playOptions) } : {},
);
this.browse =
options.browse === undefined
? base
: restoreSelectBrowse(this.browseLibrary, options.browse, base, this.policy).state;
}
// ---------------------------------------------------------------------------------------------------------------------
// What the host reads and sets
// ---------------------------------------------------------------------------------------------------------------------
/** The browse position as plain data (`captureBrowse`), to open the screen on again later. */
public snapshot(): BrowseSnapshot {
return captureBrowse(this.browseLibrary, this.browse);
}
/** The bar under the cursor, or `undefined` when the list is empty. */
public focused(): LibraryEntry | undefined {
return focusedEntry(this.browseLibrary, this.browse);
}
/** Whether a chart was picked and the skin's launch outro is playing: the screen is about to hand it on. */
public launching(): boolean {
return this.launch !== undefined;
}
/** The play options in force. */
public getPlayOptions(): PlayOptions {
return { ...this.playOptions };
}
/**
* Takes play options from the host (a settings menu): merged onto the ones in force and checked
* (`resolvePlayOptions`). A sort or a filter reshapes the list, keeping the cursor on its bar, under a policy that
* keeps them in the play options. Not reported back through `on.playOptions`, and no cue plays.
*/
public setPlayOptions(partial: Partial<PlayOptions>): void {
this.playOptions = resolvePlayOptions({ ...this.playOptions, ...partial });
this.syncListOptions();
this.changed();
}
/**
* Takes a library. The same one again only redraws (the course being made, the records). A new one keeps the
* player's place over it, restored by folder label and bar key; a first library with one chart folder opens it.
*/
public setLibrary(library: BrowserChartCollection): void {
if (library === this.library) {
this.changed();
return;
}
const previous = this.library;
const place = captureBrowse(this.browseLibrary, this.browse);
this.library = library;
this.browseLibrary = this.createBrowseLibrary();
const empty = previous.charts.length === 0 && (previous.courseFolders?.length ?? 0) === 0;
this.browse = empty
? openLibrary(this.browseLibrary, this.policy, { searchText: this.browse.searchText, list: this.browse.list })
: restoreSelectBrowse(this.browseLibrary, place, this.browse, this.policy).state;
this.readText = undefined;
this.changed();
}
/** Puts the player back where a snapshot says, over the library as it is now (`restoreSelectBrowse`). */
public restore(snapshot: BrowseSnapshot): void {
this.browse = restoreSelectBrowse(this.browseLibrary, snapshot, this.browse, this.policy).state;
this.changed();
}
/** The records changed: the bars and panels draw them again. */
public refreshRecords(records?: SelectRecords): void {
Iif (records !== undefined) this.records = records;
this.browseLibrary = this.createBrowseLibrary();
this.changed();
}
/** The error of the chart filter expression searched for, when it does not parse (`browseSearchError`). */
public searchError(): string | undefined {
return browseSearchError(this.browse.searchText);
}
/** {@link browseLibrary} for the library and the records in force. */
private createBrowseLibrary(): Library {
const { charts, courseFolders } = this.library;
return {
charts,
...(courseFolders !== undefined ? { courseFolders } : {}),
chartFilterRecord: (chart) => {
let record = this.filterRecords.get(chart);
if (record === undefined) {
record = createCourseChartRecord(chart, {}, () => this.records.chart(chart));
this.filterRecords.set(chart, record);
}
return record;
},
};
}
/** Searches for `text` (`reduceBrowse`'s `search`): a changed query puts the cursor on the top of the new list. */
public setSearch(text: string): void {
this.applyBrowse({ type: 'search', text }, this.now());
}
/** The host's text field is over the search box (`true`) or has left it: skins leave the box's text to it. */
public setSearchEditing(editing: boolean): void {
if (this.searchEditing === editing) return;
this.searchEditing = editing;
this.changed();
}
/** Takes the theme's new sounds; a BGM playing changes to the new one. */
public setSounds(sounds: SystemSoundSet): void {
this.sounds = sounds;
if (this.entered) this.playBGM();
}
// ---------------------------------------------------------------------------------------------------------------------
// The scene session
// ---------------------------------------------------------------------------------------------------------------------
public enter(nowMs: number): void {
Iif (this.disposed) return;
this.entered = true;
this.enteredAtMs = nowMs;
this.nowMs = nowMs;
this.events = [];
this.changed();
this.playBGM();
this.refreshPreview();
}
/** Stops the BGM and the preview (the cues and the decide jingle play out); the state is kept for the next entry. */
public exit(): void {
if (!this.entered) return;
this.entered = false;
this.launch = undefined;
this.reportedFocus = null;
this.heldKey = undefined;
this.levelEditHeld = false;
this.buttonsHeld.reset();
this.options.audio.stopOwned(this);
}
public dispose(): void {
Iif (this.disposed) return;
this.exit();
this.disposed = true;
this.readTextLookup += 1;
}
public handleKey(event: SessionKeyEvent): boolean {
Iif (!this.entered) return false;
this.buttonsHeld.handle({
...event,
buttons: event.buttons ?? controlButtonsOfKey(event, DEFAULT_CONTROL_BUTTONS),
});
if (event.type === 'up') return this.releaseHeldKey(event) || this.releasePanelKey(event);
// LR2's F3 held: the arrows edit the chart's difficulty (↑ / ↓) and level (← / →).
if (this.levelEditHeld && event.code.startsWith('Arrow')) return this.editLevel(event.code);
// A key is a gesture: the browser lets the BGM start once one came.
this.options.audio.resume();
// The chart is chosen while a launch outro plays.
if (this.launch !== undefined) return false;
const action = resolveSelectKeyAction(
event,
{
panel: this.panel,
readTextOpen: this.readText !== undefined,
doublePlayFilter: this.playOptions.keysFilter === 'KEYS_10' || this.playOptions.keysFilter === 'KEYS_14',
},
this.policy.keys,
this.options.actions ?? DEFAULT_CONTROL_ACTIONS[this.policy.keys],
);
if (action === undefined) return false;
const atMs = event.timeStamp;
switch (action.type) {
case 'step':
this.stepCursor(action.direction, atMs);
return true;
case 'browse':
this.applyBrowse(action.command, atMs);
return true;
case 'random':
this.applyBrowse({ type: 'random', value: this.random() }, atMs);
return true;
case 'activate':
this.activate(atMs);
return true;
case 'replay-slot':
return this.stepReplayPick(action.step);
case 'replay':
this.replay(undefined, atMs);
return true;
case 'back':
// Backing out of nothing leaves the key to the page.
return this.back(atMs, action.inFolder === true);
case 'panel': {
Iif (event.repeat) return true;
// beatoraja's START and SELECT held together open its panel 3.
const panel = this.policy.keys === 'beatoraja' && isStartAndSelectDown(this.buttonsHeld) ? 3 : action.panel;
this.panelPressedAtMs = this.panel === undefined || this.panel !== panel ? atMs : undefined;
this.togglePanel(panel, atMs);
return true;
}
case 'open-folder':
// LR2's → opens a folder, and on a chart changes the difficulty.
if (this.focused()?.kind === 'folder') {
this.activate(atMs);
return true;
}
return this.policy.keys === 'lr2' && this.switchDifficulty(atMs);
case 'difficulty':
return this.switchDifficulty(atMs);
case 'auto':
if (this.focused()?.kind === 'folder') this.activate(atMs);
// LR2's key 6 waits for its release: let go, it starts in AUTO; held for REPLAY_HOLD_MS, the saved replay.
else if (this.policy.keys === 'lr2') this.heldKey ??= { kind: 'auto', code: event.code, atMs };
else Ethis.start(true, atMs);
return true;
case 'ranking':
// LR2's key 4: held, the chart's ranking opens (in `frame`); a tap backs out on its release.
this.heldKey ??= { kind: 'ranking', code: event.code, atMs };
return true;
case 'level-edit':
this.levelEditHeld = true;
return true;
case 'list':
this.stepList(action.option);
return true;
case 'ln-mode':
this.stepPlayOption('longNoteMode', 1);
return true;
case 'battle':
this.setPlayOption('battleMode', toggleACBattle(this.playOptions.battleMode));
return true;
case 'm-ran': {
const key = action.side === '1P' ? 'mRan1P' : 'mRan2P';
this.setPlayOption(key, !this.playOptions[key]);
return true;
}
case 'search':
this.options.on.search?.();
return true;
case 'reload':
if (this.options.on.reload === undefined) return false;
this.options.on.reload();
return true;
case 'mania-options':
if (this.options.on.maniaOptions === undefined) return false;
this.options.on.maniaOptions();
return true;
case 'favorite':
this.applyBrowse({ type: 'favorite', list: action.list }, atMs);
return true;
case 'copy-hash': {
const chart = focusedChart(this.browseLibrary, this.browse);
if (chart === undefined || this.options.on.copyChartHash === undefined) return false;
this.options.on.copyChartHash(chart, action.hash);
return true;
}
case 'autoplay-folder':
return this.autoplayFolder();
case 'same-folder':
this.openChartFolder();
return true;
case 'readme':
this.toggleReadText();
return true;
case 'play-option':
this.stepPlayOption(action.key, action.step);
return true;
case 'readtext-scroll':
this.events.push({ kind: 'readtext-scroll', delta: action.delta });
return true;
case 'readtext-close':
this.closeReadText(true);
return true;
case 'readtext-tab':
Eif (this.readText !== undefined) this.selectReadText(this.readText.selected + action.step);
return true;
case 'swallow':
return false;
}
}
public dispatch(intent: SelectIntent): void {
Iif (!this.entered) return;
this.options.audio.resume();
Iif (intent.type === 'gesture') return;
Iif (this.launch !== undefined) return;
const atMs = this.now();
switch (intent.type) {
case 'browse':
// A one-bar move is a step (a wheel notch, a swipe across a row): it slides even a list of one bar.
if (intent.command.type === 'move' && Math.abs(intent.command.delta) === 1) {
this.stepCursor(intent.command.delta > 0 ? 1 : -1, atMs);
} else {
this.applyBrowse(intent.command, atMs);
}
return;
case 'activate':
this.activate(atMs);
return;
case 'start':
this.start(intent.autoPlay === true, atMs);
return;
case 'practice': {
const entry = this.focused();
if (entry?.kind === 'chart') this.options.on.practice?.(entry.chart);
return;
}
case 'replay':
this.replay(intent.slot, atMs);
return;
case 'replay-slot':
this.stepReplayPick(intent.step);
return;
case 'play-option':
this.stepPlayOption(intent.key, intent.step);
return;
case 'set-play-option':
const value =
intent.key === 'hiSpeed' && this.playOptions.floatingHiSpeed && typeof intent.value === 'number'
? clampFloatingHiSpeed(intent.value)
: resolvePlayOptionValue(intent.key, intent.value);
this.setPlayOption(intent.key, value);
return;
case 'panel':
this.togglePanel(intent.panel ?? this.panel, atMs);
return;
case 'search':
this.options.on.search?.();
return;
case 'readtext':
this.toggleReadText();
return;
case 'readtext-tab':
this.selectReadText(intent.index);
return;
case 'course-maker':
this.runCourseMaker(intent.action);
return;
case 'skin-config':
this.options.on.skinConfig?.();
return;
case 'exit':
this.options.on.exit?.();
return;
}
}
public frame(nowMs: number): SelectFrame {
const analyzer = this.options.audio.analyzer;
Eif (this.entered) {
this.nowMs = Math.max(this.nowMs, nowMs);
this.settleLaunch();
this.settleHeldKey();
this.refreshPreview();
}
const events = this.events;
this.events = [];
const entries = browseEntries(this.browseLibrary, this.browse);
const searchError = this.searchError();
const focused = entries[browseCursor(this.browse)];
if (this.entered && focused !== this.reportedFocus) {
this.reportedFocus = focused;
this.options.on.focus?.(focused);
}
const replaySlots = this.replaySlotsOf(focused);
return {
clock: { nowMs, enteredAtMs: this.enteredAtMs },
library: this.library,
browse: this.browse,
entries,
cursor: browseCursor(this.browse),
revision: this.revision,
events,
playOptions: this.playOptions,
...(this.panel !== undefined ? { panel: this.panel } : {}),
records: this.records,
searchEditing: this.searchEditing,
...(searchError !== undefined ? { searchError } : {}),
...(this.launch !== undefined ? { startedAtMs: this.launch.atMs } : {}),
...(this.readText !== undefined ? { readText: this.readText } : {}),
...(this.options.courseMaker !== undefined
? { courseMaker: this.courseMakerState(this.options.courseMaker) }
: {}),
...(replaySlots !== undefined ? { replaySlots } : {}),
// Analysed only when a view reads it (an audio-reactive skin with its effects on).
get audio() {
return analyzer.sample(nowMs);
},
};
}
// ---------------------------------------------------------------------------------------------------------------------
// Browsing
// ---------------------------------------------------------------------------------------------------------------------
/** Something the frame shows changed. */
private changed(): void {
this.revision += 1;
}
/**
* Applies a browse command (`reduceBrowse`), reports what it did to the view and plays its cue (`browseSystemSound`).
* A back-out at the root follows the policy: the built-in and LR2 screens stay, silently.
*/
private applyBrowse(command: BrowseCommand, atMs: number): BrowseEvent {
const { state, event } = reduceBrowse(this.browseLibrary, this.browse, command);
if (event.kind === 'at-root') {
if (this.options.on.exitMenu !== undefined) {
this.options.on.exitMenu();
} else if (this.policy.atRoot === 'exit') {
this.playCue('cancel');
this.options.on.exit?.();
}
return event;
}
Iif (event.kind === 'none' && state === this.browse) return event;
this.browse = state;
this.changed();
Iif (event.kind === 'none') return event;
this.events.push({ kind: 'browse', event, atMs });
if (event.kind === 'cursor' || event.kind === 'folder-opened' || event.kind === 'folder-closed') {
// The README shown belongs to the bar left; it closes without a cue, as the cursor cue plays.
this.readText = undefined;
this.readTextLookup += 1;
// On LR2 the cursor cue plays with every slide of the list, a folder opened or closed included; beatoraja plays
// the folder's cue alone.
if (event.kind === 'cursor' || this.policy.folderCursorCue) this.playCue('cursor');
}
const slot = browseSystemSound(command, event);
if (slot !== undefined && slot !== 'cursor') this.playCue(slot);
return event;
}
/**
* Moves the cursor one bar, wrapping past either end, as the arrow keys and a wheel notch do. On a list of one bar the
* cursor stays but the list still slides and cues, as LR2's rail scrolls.
*/
private stepCursor(direction: 1 | -1, atMs: number): void {
const count = browseEntries(this.browseLibrary, this.browse).length;
Iif (count === 0) return;
if (count > 1) {
this.applyBrowse({ type: 'move', delta: direction }, atMs);
return;
}
const cursor = browseCursor(this.browse);
this.events.push({ kind: 'browse', event: { kind: 'cursor', from: cursor, to: cursor, delta: direction }, atMs });
this.readText = undefined;
this.playCue('cursor');
this.changed();
}
/** Enter: opens the folder under the cursor, or starts its chart or course. */
private activate(atMs: number): void {
const entry = this.focused();
Iif (entry === undefined) return;
if (entry.kind === 'folder') this.applyBrowse({ type: 'open' }, atMs);
else this.launchEntry(entry, false, atMs);
}
/** PLAY / AUTO: starts the chart or course under the cursor; a folder bar does nothing. */
private start(autoPlay: boolean, atMs: number): void {
const entry = this.focused();
if (entry === undefined || entry.kind === 'folder') return;
this.launchEntry(entry, autoPlay, atMs);
}
// ---------------------------------------------------------------------------------------------------------------------
// Replay slots
// ---------------------------------------------------------------------------------------------------------------------
/**
* The replay slots of `entry` and the one picked, when the host keeps replay slots and `entry` is a chart or a course.
* The pick starts on the first slot holding a replay whenever the bar changes (beatoraja's `RESET_REPLAY`), and again
* when the slot picked no longer holds one (the slots load after the screen shows, or a replay was removed).
*/
private replaySlotsOf(entry: LibraryEntry | undefined): { exists: readonly boolean[]; selected: number } | undefined {
const lookup = this.records.replaySlots;
if (lookup === undefined || entry === undefined || entry.kind === 'folder') return undefined;
const exists = lookup.call(this.records, entry);
const pick = this.replayPick;
if (pick === undefined || pick.entry !== entry || pick.slot < 0 || exists[pick.slot] !== true) {
this.replayPick = { entry, slot: firstReplaySlot(exists) };
}
return { exists, selected: this.replayPick!.slot };
}
/** Picks the next or previous replay slot holding a replay of the bar under the cursor. Returns whether it could. */
private stepReplayPick(step: 1 | -1): boolean {
const entry = this.focused();
const slots = this.replaySlotsOf(entry);
Iif (slots === undefined || entry === undefined || entry.kind === 'folder') return false;
const slot = stepReplaySlot(slots.exists, slots.selected, step);
Eif (slot !== slots.selected) {
this.replayPick = { entry, slot };
this.changed();
}
return true;
}
/**
* Replays the chart or course under the cursor from `slot`, or from the slot picked when none is named. The REPLAY key
* plays the bar as PLAY does when no slot holds a replay, as beatoraja's does; a button naming an empty slot starts
* nothing.
*/
private replay(slot: number | undefined, atMs: number): void {
const entry = this.focused();
Iif (entry === undefined || entry.kind === 'folder') return;
const slots = this.replaySlotsOf(entry);
const target = slot ?? slots?.selected ?? -1;
if (target >= 0 && slots?.exists[target] === true) {
this.launchEntry(entry, false, atMs, target);
return;
}
if (slot === undefined) this.launchEntry(entry, false, atMs);
}
/**
* Escape, Backspace, ←: backs out of the folder shown, or at the root does what the policy says, unless `inFolder`
* limits the key to a folder. Returns whether it did something.
*/
private back(atMs: number, inFolder: boolean): boolean {
if (inFolder && this.browse.path.length === 0) return false;
const event = this.applyBrowse({ type: 'close' }, atMs);
return (
event.kind === 'folder-closed' ||
(event.kind === 'at-root' && (this.options.on.exitMenu !== undefined || this.policy.atRoot === 'exit'))
);
}
// ---------------------------------------------------------------------------------------------------------------------
// Starting
// ---------------------------------------------------------------------------------------------------------------------
/**
* Starts `entry`: a chart waits for the skin's launch outro, if any (input waits too); a course is handed on at once,
* as it has no outro.
*/
private launchEntry(entry: SelectStartEntry, autoPlay: boolean, atMs: number, replaySlot?: number): void {
Iif (this.launch !== undefined) return;
const outroMs = entry.kind === 'chart' ? (this.options.launchOutroMs?.() ?? 0) : 0;
if (outroMs <= 0) {
this.handOn(entry, autoPlay, replaySlot);
return;
}
this.launch = { atMs, entry, autoPlay, ...(replaySlot !== undefined ? { replaySlot } : {}) };
this.changed();
this.options.on.launch?.(entry, { autoPlay, ...(replaySlot !== undefined ? { replaySlot } : {}) });
}
/** Hands a launch whose outro has played on to the host. */
private settleLaunch(): void {
const launch = this.launch;
if (launch === undefined) return;
if (this.nowMs - launch.atMs < (this.options.launchOutroMs?.() ?? 0)) return;
this.launch = undefined;
this.changed();
this.handOn(launch.entry, launch.autoPlay, launch.replaySlot);
}
/**
* Tells the host the entry started, then plays the start cue (`startSystemSound`): a course that cannot start plays
* the cancel cue; one that starts a play plays the decide cue and the decide jingle. Neither has an owner, so they
* play out while the screen leaves: the jingle rings on through the decide screen into the play.
*/
private handOn(entry: SelectStartEntry, autoPlay: boolean, replaySlot?: number): void {
const started =
this.options.on.start(entry, { autoPlay, ...(replaySlot !== undefined ? { replaySlot } : {}) }) !== false;
const cue = startSystemSound(entry);
if (cue === 'cancel') {
this.playCue('cancel');
return;
}
if (!started) return;
Eif (cue !== undefined) this.playCue(cue);
const jingle = this.sounds.decideBGM;
if (jingle !== undefined) void this.options.audio.playJingle(jingle);
}
// ---------------------------------------------------------------------------------------------------------------------
// Play options and panels
// ---------------------------------------------------------------------------------------------------------------------
/** Opens `panel` (closing the one open), or closes it when it is the one open; `undefined` changes nothing. */
/** A held key's release (LR2's keys 4 and 6, and F3): what it does depends on how long it was held. */
private releaseHeldKey(event: SessionKeyEvent): boolean {
if (this.levelEditHeld && event.code === this.levelEditCode(event)) {
this.levelEditHeld = false;
return true;
}
const held = this.heldKey;
if (held === undefined || held.code !== event.code) return false;
this.heldKey = undefined;
const heldMs = event.timeStamp - held.atMs;
if (held.kind === 'auto') {
Iif (heldMs >= REPLAY_HOLD_MS && (this.replaySlotsOf(this.focused())?.exists.some(Boolean) ?? false)) {
this.replay(undefined, event.timeStamp);
} else {
this.start(true, event.timeStamp);
}
} else if (held.fired !== true) {
this.back(event.timeStamp, false);
}
return true;
}
/** The F3 key that started the level edit, for its release (any key the operation takes). */
private levelEditCode(event: SessionKeyEvent): string | undefined {
const actions = this.options.actions ?? DEFAULT_CONTROL_ACTIONS[this.policy.keys];
const buttons = event.buttons ?? controlButtonsOfKey(event, DEFAULT_CONTROL_BUTTONS);
return actions.is('select.level-edit', { ...event, buttons }) ? event.code : undefined;
}
/** LR2's key 4 held for RANKING_HOLD_MS opens the focused chart's ranking, once. */
private settleHeldKey(): void {
const held = this.heldKey;
if (held?.kind !== 'ranking' || held.fired === true || this.nowMs - held.atMs < RANKING_HOLD_MS) return;
held.fired = true;
const chart = this.focused();
Eif (chart?.kind === 'chart') this.options.on.ranking?.(chart.chart);
}
/**
* beatoraja's F10: the charts of the focused folder, or of the list shown when the cursor is on a chart, played in AUTO
* one after the other by the host.
*/
private autoplayFolder(): boolean {
if (this.options.on.autoplayFolder === undefined) return false;
const entry = this.focused();
const charts =
entry?.kind === 'folder'
? entry.folder.charts
: browseEntries(this.browseLibrary, this.browse).flatMap((bar) => (bar.kind === 'chart' ? [bar.chart] : []));
Iif (charts.length === 0) return true;
this.options.on.autoplayFolder(charts);
return true;
}
/**
* beatoraja's 8: opens the root folder the focused chart is in, with the cursor on it, out of a search or a list the
* chart was found in. Already there, nothing happens.
*/
private openChartFolder(): void {
const entry = this.focused();
Iif (entry?.kind !== 'chart') return;
const label = chartFolderLabel(entry.chart);
const path = this.browse.path;
Iif (path.length === 1 && path[0]?.label === label && this.browse.searchText === '') return;
this.restore({
...captureBrowse(this.browseLibrary, this.browse),
folderPath: [label],
cursors: [0, 0],
focusKey: libraryEntryKey(entry),
searchText: '',
});
this.playCue('folderOpen');
}
/** Asks the host to step the focused chart's difficulty (↑ / ↓) or level (← / →). */
private editLevel(arrow: string): boolean {
const chart = this.focused();
Iif (chart?.kind !== 'chart' || this.options.on.levelEdit === undefined) return true;
const step = arrow === 'ArrowUp' || arrow === 'ArrowRight' ? 1 : -1;
const part = arrow === 'ArrowUp' || arrow === 'ArrowDown' ? 'difficulty' : 'level';
this.options.on.levelEdit(chart.chart, part, step);
this.playCue('optionChange');
return true;
}
/**
* The panel key coming up: a panel it opened and held for {@link PANEL_HOLD_MS} or longer closes (it showed while
* held, as LR2's does), and one tapped open stays open until the next press (That-Which-Must-Not-Be-Named PC's).
*/
private releasePanelKey(event: SessionKeyEvent): boolean {
const pressedAtMs = this.panelPressedAtMs;
if (pressedAtMs === undefined || this.panel === undefined) return false;
const actions = this.options.actions ?? DEFAULT_CONTROL_ACTIONS[this.policy.keys];
const buttons = event.buttons ?? controlButtonsOfKey(event, DEFAULT_CONTROL_BUTTONS);
const keyEvent = { ...event, buttons };
const panelKey = (['select.option-panel', 'select.option-panel-2', 'select.option-panel-3'] as const).some((id) =>
actions.is(id, keyEvent),
);
Iif (!panelKey) return false;
this.panelPressedAtMs = undefined;
if (event.timeStamp - pressedAtMs >= PANEL_HOLD_MS) this.togglePanel(this.panel, event.timeStamp);
return true;
}
/** Moves the cursor to the next chart of the focused chart's track (`select-difficulty.ts`); whether there was one. */
private switchDifficulty(atMs: number): boolean {
const index = nextDifficultyIndex(browseEntries(this.browseLibrary, this.browse), browseCursor(this.browse));
if (index === undefined) return false;
this.applyBrowse({ type: 'jump', index }, atMs);
return true;
}
/** Steps the sort or the key mode filter, in the play options or the browse position as the policy keeps them. */
private stepList(option: 'sort' | 'keysFilter'): void {
if (this.policy.listOptions === 'play-options') {
this.stepPlayOption(option, 1);
return;
}
const cycle: readonly string[] =
option === 'sort'
? (this.policy.listCycles?.sort ?? SORT_CYCLE)
: (this.policy.listCycles?.keysFilter ?? KEYS_FILTER_CYCLE);
const current = this.browse.list[option];
const next = cycle[(cycle.indexOf(current) + 1) % cycle.length]!;
this.applyBrowse({ type: 'list', options: { [option]: next } }, this.now());
}
private togglePanel(panel: number | undefined, atMs: number): void {
Iif (panel === undefined || panel < 1 || panel > 9) return;
const previous = this.panel;
if (previous !== undefined) this.events.push({ kind: 'panel', panel: previous, open: false, atMs });
if (previous === panel) {
this.panel = undefined;
this.playCue('optionClose');
} else {
this.panel = panel;
this.events.push({ kind: 'panel', panel, open: true, atMs });
// Swapping to another panel plays the open cue only: the other's close is implied.
this.playCue('optionOpen');
}
this.changed();
}
/** Steps a play option through its choices, or the hi-speed by its step. */
private stepPlayOption(key: keyof PlayOptions, step: number): void {
// beatoraja's panel 3 steps the visible time and the judge timing by 1 ms.
if (key === 'noteDurationMs' || key === 'judgeTimingMs') {
this.setPlayOption(key, resolvePlayOptionValue(key, this.playOptions[key] + step));
return;
}
if (key === 'hiSpeed') {
const value = this.playOptions.classicHiSpeed
? stepClassicHiSpeed(this.playOptions.hiSpeed, step)
: clampHiSpeed(this.playOptions.hiSpeed + (step < 0 ? -1 : 1) * HISPEED_STEP);
this.setPlayOption('hiSpeed', value);
return;
}
this.setPlayOption(key, cyclePlayOptionValue(key, this.playOptions[key], step));
}
/** The player's change of a play option: reported to the host, with the option-change cue. */
private setPlayOption<K extends keyof PlayOptions>(key: K, value: PlayOptions[K] | undefined): void {
if (value === undefined || this.playOptions[key] === value) return;
this.playOptions = { ...this.playOptions, [key]: value };
Iif (this.playOptions.classicHiSpeed) {
this.playOptions.hiSpeed = snapClassicHiSpeed(this.playOptions.hiSpeed)!;
this.playOptions.hsFix = 'OFF';
}
this.options.on.playOptions?.({ ...this.playOptions });
this.playCue('optionChange');
if (isListPlayOption(key)) this.syncListOptions();
this.changed();
}
/**
* Shapes the list by the play options' sort and filters, when they changed, under a policy that keeps them there:
* the cursor stays on the bar it was on while it is still listed, else on its row, clamped.
*/
private syncListOptions(): void {
if (this.policy.listOptions !== 'play-options') return;
const list = listOptionsOf(this.playOptions);
Iif (sameBrowseListOptions(list, this.browse.list)) return;
const { state, event } = reduceBrowse(this.browseLibrary, this.browse, { type: 'list', options: list });
this.browse = state;
Eif (event.kind !== 'none') this.events.push({ kind: 'browse', event, atMs: this.now() });
}
// ---------------------------------------------------------------------------------------------------------------------
// The course maker
// ---------------------------------------------------------------------------------------------------------------------
private courseMakerState(maker: SelectCourseMaker): SelectCourseMakerState {
const draft = maker.draft;
const randomMixSettings = maker.randomMixSettings;
return {
...(draft !== undefined ? { draft } : {}),
defaultConnection: maker.defaultConnection,
...(randomMixSettings !== undefined ? { randomMixSettings } : {}),
};
}
/**
* Runs a course-maker action: finishing or cancelling the course being made, stepping the default connection and a
* RANDOM MIX setting run
* on the course maker; deleting a course, flagging it for IR, or stepping one of its connections, only on a course of
* the player's own under the cursor; naming the course being made (or the player's course under the cursor) is the host's.
*/
private runCourseMaker(action: SelectCourseMakerAction): void {
const maker = this.options.courseMaker;
const entry = this.focused();
const course = entry?.kind === 'course' ? entry.course : undefined;
const own = course?.editable === true && maker?.owns(course.definition) === true ? course : undefined;
switch (action.kind) {
case 'name':
if (maker?.draft !== undefined || course?.editable === true) this.options.on.courseMaker?.('name', course);
return;
case 'delete':
// LR2 asks before it deletes: the host confirms.
if (own !== undefined) this.options.on.courseMaker?.('delete', own);
return;
case 'ir':
// LR2's button 253 turns the flag on and plays `option_change`; on a flagged course it does nothing (OpenLR2
// L11141-L11153).
if (own === undefined || maker?.releaseCourse(own.definition) === undefined) return;
this.playCue('optionChange');
break;
case 'finish':
maker?.finish();
break;
case 'cancel':
maker?.cancel();
break;
case 'default-connection':
maker?.stepDefaultConnection(action.step);
break;
case 'random-mix':
// LR2's buttons 260-266 play `option_change` as they step (OpenLR2 L11155-L11222).
if (maker?.stepRandomMixSetting === undefined) return;
maker.stepRandomMixSetting(action.setting, action.step);
this.playCue('optionChange');
break;
case 'connection':
if (own !== undefined) maker?.stepConnection(own.definition, action.slot, action.step);
break;
}
this.changed();
}
// ---------------------------------------------------------------------------------------------------------------------
// The README dialog
// ---------------------------------------------------------------------------------------------------------------------
/** Shows the text file of the chart under the cursor, or closes the one shown. */
private toggleReadText(): void {
Iif (this.readText !== undefined) {
this.closeReadText(true);
return;
}
const chart = focusedChart(this.browseLibrary, this.browse);
Iif (chart === undefined) return;
if (this.options.on.readtext !== undefined) {
this.options.on.readtext(chart);
return;
}
const lookup = ++this.readTextLookup;
const library = this.library;
void findReadtextsForChart(library, chart).then((files) => {
Iif (lookup !== this.readTextLookup || this.disposed) return;
if (files.length === 0) {
// No text file: a short cue says the click registered.
this.playCue('optionChange');
return;
}
// The likeliest README comes first.
this.readText = { chart, files, selected: 0 };
this.playCue('optionOpen');
this.changed();
});
}
/** Shows the README dialog's text file at `index`, wrapping around either end. */
private selectReadText(index: number): void {
const readText = this.readText;
if (readText === undefined || readText.files.length < 2 || !Number.isInteger(index)) return;
const count = readText.files.length;
const selected = ((index % count) + count) % count;
if (selected === readText.selected) return;
this.readText = { ...readText, selected };
this.playCue('optionChange');
this.changed();
}
private closeReadText(cue: boolean): void {
this.readTextLookup += 1;
Iif (this.readText === undefined) return;
this.readText = undefined;
Eif (cue) this.playCue('optionClose');
this.changed();
}
// ---------------------------------------------------------------------------------------------------------------------
// Sound
// ---------------------------------------------------------------------------------------------------------------------
/** Plays a cue of the theme's sounds, without an owner: it plays out when the screen leaves. */
private playCue(slot: SystemSoundSlot): void {
const sound = this.sounds[slot];
if (sound !== undefined) void this.options.audio.playCue(sound);
}
/** Starts the theme's select BGM, as the session's own, or stops the one playing when the theme has none. */
private playBGM(): void {
const bgm = this.sounds.selectBGM;
if (bgm === undefined) {
this.options.audio.stopBGM(this);
return;
}
void this.options.audio.playBGM(bgm, { owner: this, volume: SELECT_BGM_VOLUME });
}
/** Points the chart preview at the chart under the cursor, when that changed since it was last pointed. */
private refreshPreview(): void {
const chart = focusedChart(this.browseLibrary, this.browse);
const source = chart === undefined ? undefined : resolveChartSource(this.library, chart);
const key = chart === undefined || source === undefined ? undefined : `${source.id}\n${chart.id}`;
if (key === this.previewKey) return;
this.previewKey = key;
if (chart === undefined || source === undefined) this.options.audio.preview.focus(undefined);
else this.options.audio.preview.focus({ chart: chart, source }, this);
}
}
/** AC's one-player BATTLE switched by its key: on from any other battle mode, off from itself. */
export function toggleACBattle(battleMode: PlayOptions['battleMode']): PlayOptions['battleMode'] {
return battleMode === '____:BATTLE' ? 'OFF' : '____:BATTLE';
}
|