Files
wolf_dart/lib/features/renderer/renderer.dart
2026-03-13 19:31:40 +01:00

436 lines
12 KiB
Dart

import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:wolf_dart/classes/difficulty.dart';
import 'package:wolf_dart/classes/entity.dart';
import 'package:wolf_dart/classes/linear_coordinates.dart';
import 'package:wolf_dart/classes/matrix.dart';
import 'package:wolf_dart/features/map/wolf_map.dart';
import 'package:wolf_dart/features/renderer/raycast_painter.dart';
import 'package:wolf_dart/sprite_gallery.dart';
class WolfRenderer extends StatefulWidget {
const WolfRenderer({
super.key,
required this.difficulty,
this.showSpriteGallery = false,
this.isDemo = true,
});
final Difficulty difficulty;
final bool showSpriteGallery;
final bool isDemo;
@override
State<WolfRenderer> createState() => _WolfRendererState();
}
class _WolfRendererState extends State<WolfRenderer>
with SingleTickerProviderStateMixin {
late Ticker _gameLoop;
final FocusNode _focusNode = FocusNode();
late WolfMap gameMap;
late Matrix<int> currentLevel;
final double fov = math.pi / 3;
late LinearCoordinates player;
late double playerAngle;
bool _isLoading = true;
bool _spaceWasPressed = false;
List<Entity> entities = [];
// Track door animations
// Key is "X,Y" coordinate. Value is how far open it is (0.0 to 1.0)
Map<String, double> doorOffsets = {};
Map<String, int> doorStates = {}; // 1 = opening, 2 = fully open
@override
void initState() {
super.initState();
_initGame(demo: widget.isDemo);
}
Future<void> _initGame({bool demo = true}) async {
// 1. Load the entire WL1 (demo)/WL6 (retail) data
gameMap = demo ? await WolfMap.loadDemo() : await WolfMap.load();
// 2. Extract Level 1 (E1M1)
currentLevel = gameMap.levels[0].wallGrid;
final Matrix<int> objectLevel = gameMap.levels[0].objectGrid;
// 1. SCAN FOR PLAYER SPAWN & ENTITIES
for (int y = 0; y < 64; y++) {
for (int x = 0; x < 64; x++) {
int objId = objectLevel[y][x];
// Player Spawn
if (objId >= 19 && objId <= 22) {
player = (x: x + 0.5, y: y + 0.5);
switch (objId) {
case 19:
playerAngle = 3 * math.pi / 2;
case 20:
playerAngle = 0.0;
case 21:
playerAngle = math.pi / 2;
case 22:
playerAngle = math.pi;
}
}
// NEW: Populate the Entities!
else if (objId >= 23 && objId <= 70) {
int calculatedSpriteIndex = objId - 21;
if (calculatedSpriteIndex >= 0 &&
calculatedSpriteIndex < gameMap.sprites.length) {
entities.add(
Entity(
x: x + 0.5,
y: y + 0.5,
spriteIndex: calculatedSpriteIndex,
state: EntityState.staticObj,
mapId: objId,
),
);
}
}
// NEW: The Dead Guard (FIXED INDEX)
else if (objId == 124) {
if (95 < gameMap.sprites.length) {
entities.add(
Entity(
x: x + 0.5,
y: y + 0.5,
spriteIndex: 95,
state: EntityState.dead,
mapId: objId,
),
);
}
} else if (_isGuardForDifficulty(objId)) {
if (50 < gameMap.sprites.length) {
entities.add(
Entity(
x: x + 0.5,
y: y + 0.5,
spriteIndex: 50, // Will be overridden dynamically in tick!
state: EntityState.idle,
angle: _getGuardAngle(objId), // NEW!
mapId: objId,
),
);
}
}
}
}
// 2. CLEAN UP WALLS / PRESERVE DOORS
for (int y = 0; y < 64; y++) {
for (int x = 0; x < 64; x++) {
int id = currentLevel[y][x];
if ((id >= 1 && id <= 63) || (id >= 90 && id <= 101)) {
// Leave walls and doors solid
} else {
currentLevel[y][x] = 0;
}
}
}
// 4. Start the game!
_bumpPlayerIfStuck();
_gameLoop = createTicker(_tick)..start();
_focusNode.requestFocus();
setState(() {
_isLoading = false;
});
}
@override
void dispose() {
_gameLoop.dispose();
_focusNode.dispose();
super.dispose();
}
void _bumpPlayerIfStuck() {
int pX = player.x.toInt();
int pY = player.y.toInt();
if (pY < 0 ||
pY >= currentLevel.length ||
pX < 0 ||
pX >= currentLevel[0].length ||
currentLevel[pY][pX] > 0) {
double shortestDist = double.infinity;
LinearCoordinates nearestSafeSpot = (x: 1.5, y: 1.5);
for (int y = 0; y < currentLevel.length; y++) {
for (int x = 0; x < currentLevel[y].length; x++) {
if (currentLevel[y][x] == 0) {
double safeX = x + 0.5;
double safeY = y + 0.5;
double dist = math.sqrt(
math.pow(safeX - player.x, 2) + math.pow(safeY - player.y, 2),
);
if (dist < shortestDist) {
shortestDist = dist;
nearestSafeSpot = (x: safeX, y: safeY);
}
}
}
}
player = nearestSafeSpot;
}
}
bool _isWalkable(int x, int y) {
if (currentLevel[y][x] == 0) return true; // Empty space
if (currentLevel[y][x] >= 90) {
String key = '$x,$y';
// Allow the player to walk through if the door is > 70% open
if (doorOffsets[key] != null && doorOffsets[key]! > 0.7) {
return true;
}
}
return false;
}
void _tick(Duration elapsed) {
const double moveSpeed = 0.12;
const double turnSpeed = 0.08;
// 1. ANIMATE DOORS
doorStates.forEach((key, state) {
if (state == 1) {
// If opening
doorOffsets[key] = (doorOffsets[key] ?? 0.0) + 0.02; // Slide speed
if (doorOffsets[key]! >= 1.0) {
doorOffsets[key] = 1.0;
doorStates[key] = 2; // Mark as fully open
}
}
});
double moveStepX = 0;
double moveStepY = 0;
final pressedKeys = HardwareKeyboard.instance.logicalKeysPressed;
if (pressedKeys.contains(LogicalKeyboardKey.keyW)) {
moveStepX += math.cos(playerAngle) * moveSpeed;
moveStepY += math.sin(playerAngle) * moveSpeed;
}
if (pressedKeys.contains(LogicalKeyboardKey.keyS)) {
moveStepX -= math.cos(playerAngle) * moveSpeed;
moveStepY -= math.sin(playerAngle) * moveSpeed;
}
if (pressedKeys.contains(LogicalKeyboardKey.keyA)) {
playerAngle -= turnSpeed;
}
if (pressedKeys.contains(LogicalKeyboardKey.keyD)) {
playerAngle += turnSpeed;
}
if (playerAngle < 0) playerAngle += 2 * math.pi;
if (playerAngle > 2 * math.pi) playerAngle -= 2 * math.pi;
// 2. UPDATED WALL COLLISION
const double margin = 0.3;
double newX = player.x + moveStepX;
int checkX = (moveStepX > 0)
? (newX + margin).toInt()
: (newX - margin).toInt();
if (_isWalkable(checkX, player.y.toInt())) {
player = (x: newX, y: player.y);
}
double newY = player.y + moveStepY;
int checkY = (moveStepY > 0)
? (newY + margin).toInt()
: (newY - margin).toInt();
if (_isWalkable(player.x.toInt(), checkY)) {
player = (x: player.x, y: newY);
}
// 3. UPDATED DOOR INTERACTION
bool isSpacePressed = pressedKeys.contains(LogicalKeyboardKey.space);
if (isSpacePressed && !_spaceWasPressed) {
int targetX = (player.x + math.cos(playerAngle)).toInt();
int targetY = (player.y + math.sin(playerAngle)).toInt();
if (targetY > 0 &&
targetY < currentLevel.length &&
targetX > 0 &&
targetX < currentLevel[0].length) {
if (currentLevel[targetY][targetX] >= 90) {
String key = '$targetX,$targetY';
// Start the animation if it isn't already opening!
if (!doorStates.containsKey(key) || doorStates[key] == 0) {
doorStates[key] = 1;
}
}
}
}
_spaceWasPressed = isSpacePressed;
// --- 4. UPDATE ENTITY LOGIC ---
for (Entity entity in entities) {
// 1. Wake up if the player is spotted!
if (entity.state == EntityState.idle) {
if (_hasLineOfSight(entity)) {
// "Halt!"
entity.state = EntityState.patrolling;
print("A guard spotted you!"); // Just for debugging
}
}
// 2. Visuals: 8-Way Directional Tracking
if (entity.state == EntityState.idle ||
entity.state == EntityState.patrolling) {
double dx = player.x - entity.x;
double dy = player.y - entity.y;
double angleToPlayer = math.atan2(dy, dx);
double diff = entity.angle - angleToPlayer;
while (diff <= -math.pi) {
diff += 2 * math.pi;
}
while (diff > math.pi) {
diff -= 2 * math.pi;
}
int octant = ((diff + (math.pi / 8)) / (math.pi / 4)).floor() % 8;
if (octant < 0) octant += 8;
// Base sprite for the Brown Guard
entity.spriteIndex = 50 + octant;
}
}
setState(() {});
}
bool _isGuardForDifficulty(int objId) {
switch (widget.difficulty.level) {
case 0: // Baby
return objId >= 108 && objId <= 115;
case 1: // Easy
return objId >= 144 && objId <= 151;
case 2: // Normal
return objId >= 180 && objId <= 187;
case 3: // Hard
return objId >= 216 && objId <= 223;
default:
return false;
}
}
// Decodes the Map ID to figure out which way the guard is facing
double _getGuardAngle(int objId) {
// Normalizes the ID across the 4 difficulty tiers
int normalizedId = (objId - 108) % 36;
int direction = normalizedId % 4; // 0=East, 1=North, 2=West, 3=South
// Matches the player spawn angles you already set up
switch (direction) {
case 0:
return 0.0; // East
case 1:
return 3 * math.pi / 2; // North
case 2:
return math.pi; // West
case 3:
return math.pi / 2; // South
default:
return 0.0;
}
}
bool _hasLineOfSight(Entity guard) {
double dx = player.x - guard.x;
double dy = player.y - guard.y;
double distance = math.sqrt(dx * dx + dy * dy);
// 1. FOV Check (Are you in front of them?)
double angleToPlayer = math.atan2(dy, dx);
double diff = guard.angle - angleToPlayer;
while (diff <= -math.pi) {
diff += 2 * math.pi;
}
while (diff > math.pi) {
diff -= 2 * math.pi;
}
// A standard guard FOV is about 180 degrees (90 degrees left/right)
if (diff.abs() > math.pi / 2) {
return false; // You are behind them!
}
// 2. Line of Sight Check (Are there walls in the way?)
double dirX = dx / distance;
double dirY = dy / distance;
// Step along the ray in small increments to check for solid blocks
double stepSize = 0.2;
for (double i = 0; i < distance; i += stepSize) {
int checkX = (guard.x + dirX * i).toInt();
int checkY = (guard.y + dirY * i).toInt();
// If we hit a solid wall or closed door, vision is blocked
if (!_isWalkable(checkX, checkY)) {
return false;
}
}
// If we made it all the way to the player without hitting a wall...
return true;
}
@override
Widget build(BuildContext context) {
if (_isLoading) {
return const Center(child: CircularProgressIndicator(color: Colors.teal));
}
if (widget.showSpriteGallery) {
return SpriteGallery(sprites: gameMap.sprites);
}
return Scaffold(
backgroundColor: Colors.black,
body: KeyboardListener(
focusNode: _focusNode,
autofocus: true,
onKeyEvent: (_) {},
child: LayoutBuilder(
builder: (context, constraints) {
return CustomPaint(
size: Size(constraints.maxWidth, constraints.maxHeight),
painter: RaycasterPainter(
map: currentLevel,
textures: gameMap.textures,
player: player,
playerAngle: playerAngle,
fov: fov,
doorOffsets: doorOffsets,
entities: entities,
sprites: gameMap.sprites,
),
);
},
),
),
);
}
}