Files
wolf_dart/packages/wolf_3d_flutter/lib/wolf_3d_flutter.dart
T
hans 5a2681e89b Moved all widgets and logic from gui app to Flutter package
- Implemented DebugToolsScreen for navigation to asset galleries.
- Created GameScreen to manage gameplay and renderer integrations.
- Added NoGameDataScreen to handle scenarios with missing game data.
- Developed SpriteGallery for visual browsing of sprite assets.
- Introduced VgaGallery for displaying VGA images from game data.
- Added GalleryGameSelector widget for selecting game variants in galleries.
- Created Wolf3dApp as the main application shell for managing game states.
- Implemented WolfMenuShell for consistent menu layouts across screens.
- Enhanced Wolf3d class to support debug mode and related functionalities.
- Updated pubspec.yaml to include window_manager dependency.
- Added tests for game screen lifecycle and debug mode functionalities.

Signed-off-by: Hans Kokx <hans.d.kokx@gmail.com>
2026-03-23 18:44:32 +01:00

319 lines
10 KiB
Dart

/// High-level Flutter facade for discovering game data and sharing runtime services.
library;
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:wolf_3d_dart/wolf_3d_data.dart';
import 'package:wolf_3d_dart/wolf_3d_data_types.dart';
import 'package:wolf_3d_dart/wolf_3d_engine.dart';
import 'package:wolf_3d_flutter/audio/wolf3d_platform_audio.dart';
import 'package:wolf_3d_flutter/wolf_3d_input_flutter.dart';
export 'package:wolf_3d_dart/wolf_3d_audio.dart' show DebugMusicPlayer;
export 'audio/wolf3d_platform_audio.dart' show Wolf3dPlatformAudio;
export 'managers/desktop_windowing_support.dart' show supportsDesktopWindowing;
export 'managers/game_app_lifecycle_manager.dart' show GameAppLifecycleManager;
export 'managers/game_display_manager.dart' show GameDisplayManager;
export 'managers/game_persistence_manager.dart' show GamePersistenceManager;
export 'managers/game_renderer_mode_manager.dart'
show GameRendererMode, gameRendererModeFromSettings, handleGlslUnavailable;
export 'managers/game_screen_input_manager.dart'
show
HostShortcutBinding,
HostShortcutHandler,
HostShortcutIntent,
HostShortcutRegistry,
GameScreenInputManager,
isAltEnterShortcut;
export 'screens/audio_gallery.dart' show AudioGallery;
export 'screens/debug_tools_screen.dart' show DebugToolsScreen;
export 'screens/game_screen.dart' show GameScreen;
export 'screens/no_game_data_screen.dart' show NoGameDataScreen;
export 'screens/sprite_gallery.dart' show SpriteGallery;
export 'screens/vga_gallery.dart' show VgaGallery;
export 'widgets/gallery_game_selector.dart'
show GalleryGameSelector, formatGalleryGameTitle;
export 'widgets/wolf3d_app.dart' show Wolf3dApp;
export 'widgets/wolf_menu_shell.dart' show WolfMenuShell;
/// Coordinates asset discovery, audio initialization, and input reuse for apps.
class Wolf3d {
/// Creates an empty facade that must be initialized with [init].
Wolf3d({EngineAudio? audioBackend})
: audio = audioBackend ?? Wolf3dPlatformAudio();
/// All successfully discovered or bundled game data sets.
final List<WolfensteinData> availableGames = [];
WolfensteinData? _activeGame;
/// Shared engine audio backend used by menus and gameplay sessions.
final EngineAudio audio;
Future<void>? _audioShutdownFuture;
/// Engine menu background color as 24-bit RGB.
int menuBackgroundRgb = 0x890000;
/// Engine menu panel color as 24-bit RGB.
int menuPanelRgb = 0x590002;
/// Shared Flutter input adapter reused by gameplay screens.
final Wolf3dFlutterInput input = Wolf3dFlutterInput();
bool _debugEnabled = false;
/// Whether host-level debug affordances should be visible.
bool get isDebugEnabled => _debugEnabled;
/// Enables host-level debug affordances such as debug navigation UI.
Wolf3d enableDebug() {
_debugEnabled = true;
return this;
}
/// The currently selected game data set.
///
/// Throws a [StateError] until [setActiveGame] has been called.
WolfensteinData get activeGame {
if (_activeGame == null) {
throw StateError("No active game selected. Call setActiveGame() first.");
}
return _activeGame!;
}
/// Nullable access to the selected game, useful during menu bootstrap.
WolfensteinData? get maybeActiveGame => _activeGame;
// Episode selection lives on the facade so menus can configure gameplay
// before constructing a new engine instance.
int? _activeEpisode;
/// Index of the episode currently selected in the UI flow.
int? get activeEpisode => _activeEpisode;
Difficulty? _activeDifficulty;
/// The difficulty applied when [launchEngine] creates a new session.
Difficulty? get activeDifficulty => _activeDifficulty;
/// Stores [difficulty] so the next [launchEngine] call uses it.
void setActiveDifficulty(Difficulty difficulty) {
_activeDifficulty = difficulty;
}
/// Clears any previously selected difficulty so the engine can prompt for one.
void clearActiveDifficulty() {
_activeDifficulty = null;
}
WolfEngine? _engine;
/// The most recently launched engine.
///
/// Throws a [StateError] until [launchEngine] has been called.
WolfEngine get engine {
if (_engine == null) {
throw StateError('No engine launched. Call launchEngine() first.');
}
return _engine!;
}
/// Creates and initializes a [WolfEngine] for the current session config.
///
/// Uses [activeGame], [activeEpisode], and [activeDifficulty]. Stores the
/// engine so it can be retrieved via [engine]. [onGameWon] is invoked when
/// the player completes the final level of the episode.
WolfEngine launchEngine({
required void Function() onGameWon,
void Function()? onQuit,
SaveGamePersistence? saveGamePersistence,
WolfRendererCapabilities? rendererCapabilities,
WolfRendererSettings? rendererSettings,
void Function(WolfRendererSettings settings)? onRendererSettingsChanged,
}) {
if (availableGames.isEmpty) {
throw StateError(
'No game data was discovered. Add game files before launching the engine.',
);
}
_engine = WolfEngine(
availableGames: availableGames,
difficulty: _activeDifficulty,
startingEpisode: _activeEpisode,
frameBuffer: FrameBuffer(320, 200),
menuBackgroundRgb: menuBackgroundRgb,
menuPanelRgb: menuPanelRgb,
engineAudio: audio,
input: input,
onGameWon: onGameWon,
// In Flutter we keep the renderer screen active while browsing menus,
// so backing out of the top-level menu should not pop the route.
onMenuExit: () {},
onQuit: onQuit,
saveGamePersistence: saveGamePersistence,
rendererCapabilities: rendererCapabilities,
rendererSettings: rendererSettings,
onRendererSettingsChanged: onRendererSettingsChanged,
onGameSelected: (game) {
_activeGame = game;
audio.activeGame = game;
},
onEpisodeSelected: (episodeIndex) {
_activeEpisode = episodeIndex;
},
);
_engine!.init();
return _engine!;
}
/// Sets the active episode for the current [activeGame].
void setActiveEpisode(int episodeIndex) {
if (_activeGame == null) {
throw StateError("No active game selected. Call setActiveGame() first.");
}
if (episodeIndex < 0 || episodeIndex >= _activeGame!.episodes.length) {
throw RangeError("Episode index out of range for the active game.");
}
_activeEpisode = episodeIndex;
}
/// Clears any selected episode so menu flow starts fresh.
void clearActiveEpisode() {
_activeEpisode = null;
}
/// Convenience access to the active episode's level list.
List<WolfLevel> get levels {
if (_activeEpisode == null) {
throw StateError('No active episode selected.');
}
return activeGame.episodes[_activeEpisode!].levels;
}
/// Convenience access to the active game's wall textures.
List<Sprite> get walls => activeGame.walls;
/// Convenience access to the active game's sprite set.
List<Sprite> get sprites => activeGame.sprites;
/// Convenience access to digitized PCM effects.
List<PcmSound> get sounds => activeGame.sounds;
/// Convenience access to AdLib/OPL effect assets.
List<PcmSound> get adLibSounds => activeGame.adLibSounds;
/// Convenience access to level music tracks.
List<ImfMusic> get music => activeGame.music;
/// Convenience access to VGA UI and splash images.
List<VgaImage> get vgaImages => activeGame.vgaImages;
/// Makes [game] the active data set and points shared services at it.
void setActiveGame(WolfensteinData game) {
if (!availableGames.contains(game)) {
throw ArgumentError(
"The provided game data is not in the list of available games.",
);
}
if (_activeGame == game) {
return; // No change needed
}
_activeGame = game;
_activeEpisode = null;
audio.activeGame = game;
}
/// Initializes the engine by loading available game data.
///
/// Set [debug] to `true` to explicitly enable host-level debug affordances.
Future<Wolf3d> init({String? directory, bool debug = false}) async {
if (debug) {
_debugEnabled = true;
}
await audio.init();
availableGames.clear();
// Bundled assets let the GUI work out of the box on supported platforms.
final versionsToTry = [
(version: GameVersion.retail, path: 'retail'),
(version: GameVersion.shareware, path: 'shareware'),
];
for (final version in versionsToTry) {
try {
final ext = version.version.fileExtension;
final folder = 'packages/wolf_3d_assets/assets/${version.path}';
final data = WolfensteinLoader.loadFromBytes(
version: version.version,
vswap: await _tryLoad('$folder/VSWAP.$ext'),
mapHead: await _tryLoad('$folder/MAPHEAD.$ext'),
gameMaps: await _tryLoad('$folder/GAMEMAPS.$ext'),
vgaDict: await _tryLoad('$folder/VGADICT.$ext'),
vgaHead: await _tryLoad('$folder/VGAHEAD.$ext'),
vgaGraph: await _tryLoad('$folder/VGAGRAPH.$ext'),
audioHed: await _tryLoad('$folder/AUDIOHED.$ext'),
audioT: await _tryLoad('$folder/AUDIOT.$ext'),
);
availableGames.add(data);
} catch (e) {
debugPrint(e.toString());
}
}
// On non-web platforms, also scan the local filesystem for user-supplied
// data folders so the host can pick up extra versions automatically.
if (!kIsWeb) {
try {
final externalGames = await WolfensteinLoader.discover(
directoryPath: directory,
recursive: true,
);
for (var entry in externalGames.entries) {
if (!availableGames.any((g) => g.version == entry.key)) {
availableGames.add(entry.value);
}
}
} catch (e) {
debugPrint("External discovery failed: $e");
}
}
return this;
}
/// Stops and disposes shared audio exactly once for app shutdown.
///
/// Repeated calls return the same in-flight/completed future so hosts can
/// safely invoke shutdown from multiple lifecycle paths.
Future<void> shutdownAudio() {
final existing = _audioShutdownFuture;
if (existing != null) {
return existing;
}
final shutdown = () async {
await audio.stopAllAudio();
audio.dispose();
}();
_audioShutdownFuture = shutdown;
return shutdown;
}
/// Loads an asset from the Flutter bundle, returning `null` when absent.
Future<ByteData?> _tryLoad(String path) async {
try {
return await rootBundle.load(path);
} catch (e) {
debugPrint("Asset not found: $path");
return null;
}
}
}