new Screensaver

Signed-off-by: Peter Siegmund <developer@mars3142.org>
This commit is contained in:
2025-06-24 21:24:55 +02:00
parent 0c8c831eea
commit 6260c7e62c
7 changed files with 415 additions and 403 deletions

View File

@@ -91,7 +91,7 @@ class InactivityTracker
* }); * });
* @endcode * @endcode
*/ */
InactivityTracker(uint64_t timeoutMs, std::function<void()> onTimeout); InactivityTracker(uint64_t timeoutMs, const std::function<void()> &onTimeout);
/** /**
* @brief Updates the inactivity timer and checks for timeout conditions * @brief Updates the inactivity timer and checks for timeout conditions

View File

@@ -0,0 +1,23 @@
#define road_horizontal_width 16
#define road_horizontal_height 16
static unsigned char road_horizontal_bits[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x8c, 0xc7, 0x8c, 0xc7, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
#define road_vertical_width 16
#define road_vertical_height 16
static unsigned char road_vertical_bits[] = {0x80, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0x01, 0x80, 0x01, 0x80, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00};
#define road_t_up_width 16
#define road_t_up_height 16
static unsigned char road_t_up_bits[] = {0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00,
0x03, 0xcc, 0xcf, 0xcc, 0xcc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
#define road_t_crossing_width 16
#define road_t_crossing_height 16
static unsigned char road_t_crossing_bits[] = {0x80, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0x80,
0x01, 0xe6, 0x67, 0xe6, 0x67, 0x80, 0x01, 0x80, 0x01, 0x00, 0x00,
0x00, 0x00, 0x80, 0x01, 0x80, 0x01, 0x00, 0x00, 0x00, 0x00};

View File

@@ -0,0 +1,55 @@
#pragma once
#define car_width 16
#define car_height 16
const unsigned char car_left_bits [] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x07, 0xf0, 0x0f, 0xee, 0x77, 0xee, 0x77, 0xee, 0x77,
0x2e, 0x74, 0xde, 0x78, 0x02, 0x40, 0x3c, 0x3c, 0x42, 0x42, 0xda, 0x5b, 0x18, 0x18, 0x00, 0x00
};
const unsigned char car_right_bits [] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe0, 0x07, 0xf0, 0x0f, 0xee, 0x77, 0xee, 0x77, 0xee, 0x77,
0x2e, 0x74, 0x1e, 0x7b, 0x02, 0x40, 0x3c, 0x3c, 0x42, 0x42, 0xda, 0x5b, 0x18, 0x18, 0x00, 0x00
};
#define convertable_width 16
#define convertable_height 16
static unsigned char convertable_left_bits[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x30, 0x0c, 0xee,
0x77, 0x2e, 0x74, 0xae, 0x75, 0xae, 0x75, 0xfe, 0x7f, 0x82, 0x41,
0x3c, 0x3c, 0x42, 0x42, 0xda, 0x5b, 0x18, 0x18, 0x00, 0x00};
static unsigned char convertable_right_bits[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x30, 0x0c, 0xee,
0x77, 0x2e, 0x74, 0xae, 0x75, 0xae, 0x75, 0xfe, 0x7f, 0x82, 0x41,
0x3c, 0x3c, 0x42, 0x42, 0xda, 0x5b, 0x18, 0x18, 0x00, 0x00};
#define lorry_width 32
#define lorry_height 16
const unsigned char lorry_left_bits[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0xe0,
0x0b, 0x00, 0x00, 0xf0, 0x0b, 0x00, 0x00, 0xee, 0x0b, 0x00, 0x00, 0xee, 0x0f,
0xbc, 0x07, 0x2e, 0xfa, 0xff, 0x7f, 0xae, 0xfa, 0xff, 0x7f, 0xbe, 0x0a, 0x00,
0x60, 0x02, 0x0a, 0x00, 0x60, 0x3c, 0x0a, 0xbc, 0x67, 0x42, 0xfe, 0x43, 0x78,
0xda, 0xff, 0x5b, 0x7b, 0x18, 0x00, 0x18, 0x03, 0x00, 0x00, 0x00, 0x00};
const unsigned char lorry_right_bits[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x00, 0x00,
0x00, 0xd0, 0x07, 0x00, 0x00, 0xd0, 0x0f, 0x00, 0x00, 0xd0, 0x77, 0xe0, 0x3d,
0xf0, 0x77, 0xfe, 0xff, 0x5f, 0x74, 0xfe, 0xff, 0x5f, 0x75, 0x06, 0x00, 0x50,
0x7d, 0x06, 0x00, 0x50, 0x40, 0xe6, 0x3d, 0x50, 0x3c, 0x1e, 0xc2, 0x7f, 0x42,
0xde, 0xda, 0xff, 0x5b, 0xc0, 0x18, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00};
#define suv_width 16
#define suv_height 16
const unsigned char suv_left_bits[] = {0x00, 0x00, 0x00, 0x00, 0xe0, 0x07, 0xf0, 0x0f, 0xee, 0x77, 0xee,
0x77, 0xee, 0x77, 0x2e, 0x74, 0xde, 0x78, 0x02, 0x40, 0x02, 0x40,
0x3c, 0x3c, 0x42, 0x42, 0xda, 0x5b, 0x18, 0x18, 0x00, 0x00};
const unsigned char suv_right_bits[] = {0x00, 0x00, 0x00, 0x00, 0xe0, 0x07, 0xf0, 0x0f, 0xee, 0x77, 0xee,
0x77, 0xee, 0x77, 0x2e, 0x74, 0x1e, 0x7b, 0x02, 0x40, 0x02, 0x40,
0x3c, 0x3c, 0x42, 0x42, 0xda, 0x5b, 0x18, 0x18, 0x00, 0x00};
#define truck_width 32
#define truck_height 16
const unsigned char truck_left_bits[] = {0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x3f, 0x00, 0xff, 0xff, 0x7f, 0xe0,
0xff, 0xff, 0x7f, 0xf0, 0xff, 0xff, 0x7f, 0xee, 0xff, 0xff, 0x7f, 0xee, 0x03,
0x00, 0x60, 0x2e, 0x02, 0x00, 0x40, 0xae, 0x02, 0x00, 0x40, 0xbe, 0x02, 0x00,
0x40, 0x02, 0x02, 0x00, 0x40, 0x3c, 0x02, 0xbc, 0x47, 0x42, 0x02, 0x42, 0x48,
0xda, 0xff, 0x5b, 0x7b, 0x18, 0x38, 0x18, 0x03, 0x00, 0x00, 0x00, 0x00};
const unsigned char truck_right_bits[] = {0x00, 0x00, 0x00, 0x00, 0xfc, 0xff, 0xff, 0x00, 0xfe, 0xff, 0xff, 0x00, 0xfe,
0xff, 0xff, 0x07, 0xfe, 0xff, 0xff, 0x0f, 0xfe, 0xff, 0xff, 0x77, 0x06, 0x00,
0xc0, 0x77, 0x02, 0x00, 0x40, 0x74, 0x02, 0x00, 0x40, 0x75, 0x02, 0x00, 0x40,
0x7d, 0x02, 0x00, 0x40, 0x40, 0xe2, 0x3d, 0x40, 0x3c, 0x12, 0x42, 0x40, 0x42,
0xde, 0xda, 0xff, 0x5b, 0xc0, 0x18, 0x1c, 0x18, 0x00, 0x00, 0x00, 0x00};

View File

@@ -1,9 +1,9 @@
/** /**
* @file ScreenSaver.h * @file ScreenSaver.h
* @brief Animated screensaver implementation with starfield effect * @brief Animated screensaver implementation with vehicle effect
* @details This header defines the ScreenSaver class which provides an animated * @details This header defines the ScreenSaver class which provides an animated
* starfield screensaver that activates during periods of user inactivity. * vehicle screensaver that activates during periods of user inactivity.
* The screensaver displays moving stars to prevent screen burn-in while * The screensaver displays moving vehicles to prevent screen burn-in while
* providing visual feedback that the system is still active and responsive. * providing visual feedback that the system is still active and responsive.
* @author System Control Team * @author System Control Team
* @date 2025-06-14 * @date 2025-06-14
@@ -17,381 +17,117 @@
/** /**
* @class ScreenSaver * @class ScreenSaver
* @brief Animated starfield screensaver widget for system idle periods * @brief Animated vehicle screensaver widget for system idle periods
* @details This final class inherits from Widget and implements an interactive
* screensaver featuring an animated starfield effect. The screensaver
* activates automatically during periods of user inactivity to prevent
* screen burn-in while maintaining visual indication of system activity.
*
* The ScreenSaver class provides:
* - Dynamic starfield animation with pseudo-3D depth effect
* - Configurable star count and animation speed parameters
* - Automatic activation during idle periods
* - Immediate deactivation on any user input
* - Smooth star movement and regeneration system
* - Memory-efficient star management with object pooling
*
* Key features include:
* - 3D-style starfield with depth-based speed variation
* - Continuous star recycling for infinite animation
* - Responsive user input handling for immediate exit
* - Optimized rendering for smooth animation performance
* - Configurable animation parameters for different visual effects
*
* The starfield effect simulates movement through space by moving stars
* from the center outward at speeds proportional to their depth (z-coordinate).
* Stars that move beyond the screen boundaries are automatically recycled
* to new random positions, creating an infinite scrolling effect.
*
* @note This class is marked as final and cannot be inherited from.
* @note The screensaver automatically exits on any button press, returning
* control to the previous screen or main menu interface.
*
* @see Widget for base widget functionality
* @see menu_options_t for configuration structure
* @see InactivityTracker for automatic screensaver activation
*/ */
class ScreenSaver final : public Widget class ScreenSaver final : public Widget
{ {
public: public:
/**
* @brief Constructs the screensaver with specified configuration
* @param options Pointer to menu options configuration structure
*
* @pre options must not be nullptr and must remain valid for the screensaver's lifetime
* @pre options->u8g2 must be initialized and ready for graphics operations
* @pre Screen transition callbacks in options must be properly configured
* @post ScreenSaver is initialized with starfield ready for animation
*
* @details The constructor initializes the screensaver by:
* - Setting up the star field with initial random positions
* - Configuring animation timing and speed parameters
* - Preparing graphics context for efficient rendering
* - Initializing the animation counter for smooth timing
* - Allocating and positioning all star objects
*
* During initialization, all stars are placed at random positions within
* the 3D space defined by Z_NEAR and Z_FAR constants. Each star receives
* random x, y coordinates and a z-depth that determines its movement speed
* and visual appearance. The animation system is prepared for immediate
* activation when the screensaver becomes active.
*
* @note The screensaver does not take ownership of the options structure
* and assumes it remains valid throughout the screensaver's lifetime.
* @note Initial star positions are randomized to create immediate visual
* interest when the screensaver first activates.
*
* @see Widget::Widget for base class construction details
* @see initStars for star field initialization process
*/
explicit ScreenSaver(menu_options_t *options); explicit ScreenSaver(menu_options_t *options);
/**
* @brief Updates the screensaver animation and star positions
* @param dt Delta time in milliseconds since the last update call
*
* @details Overrides the base Widget update method to handle screensaver-specific
* animation logic including:
* - Advancing the animation counter for smooth timing control
* - Updating individual star positions based on their speed and depth
* - Moving stars outward from center based on their z-coordinate
* - Recycling stars that move beyond screen boundaries
* - Maintaining consistent animation frame rate regardless of system load
*
* The update method implements the core starfield animation by:
* - Incrementing each star's position based on its depth-determined speed
* - Checking boundary conditions for stars moving off-screen
* - Resetting off-screen stars to new random positions near the center
* - Applying speed multipliers for smooth, consistent motion
* - Managing the animation counter for timing-dependent effects
*
* Star movement calculation:
* - Stars closer to the camera (smaller z values) move faster
* - Movement speed is inversely proportional to z-coordinate
* - Stars maintain consistent outward direction from screen center
* - Boundary checking ensures smooth recycling without visual gaps
*
* @note This method is called every frame while the screensaver is active
* and must be efficient to maintain smooth 60+ FPS animation.
* @note The animation continues indefinitely until user input is received.
*
* @see Widget::update for the base update interface
* @see resetStar for star recycling implementation
*/
void update(uint64_t dt) override; void update(uint64_t dt) override;
/**
* @brief Renders the animated starfield to the display
*
* @details Overrides the base Widget render method to draw the animated starfield
* effect. The rendering process includes:
* - Clearing the display buffer for clean animation frames
* - Calculating screen positions for each star based on 3D coordinates
* - Applying perspective projection to simulate depth
* - Drawing stars with size/brightness based on distance
* - Optimizing drawing operations for smooth frame rates
*
* The render method creates a convincing 3D starfield effect by:
* - Converting 3D star coordinates to 2D screen positions
* - Scaling star positions based on perspective projection
* - Varying star appearance (size, brightness) based on depth
* - Drawing only stars within the visible screen area
* - Using efficient drawing primitives for optimal performance
*
* Rendering optimizations include:
* - Culling stars outside the visible area
* - Using simple pixel/point drawing for maximum speed
* - Minimizing graphics context switches
* - Batching drawing operations where possible
*
* The visual effect simulates movement through a star field by:
* - Making distant stars appear smaller and dimmer
* - Scaling star positions relative to screen center
* - Creating smooth motion blur effects for fast-moving stars
*
* @pre u8g2 display context must be initialized and ready for drawing
* @post Starfield animation frame is drawn to the display buffer
*
* @note This method is called every frame and must be highly optimized
* to maintain smooth animation performance on embedded systems.
* @note The visual design provides an engaging screensaver that clearly
* indicates system activity while preventing screen burn-in.
*
* @see Widget::render for the base render interface
*/
void render() override; void render() override;
/**
* @brief Handles user input to exit the screensaver immediately
* @param button The type of button that was pressed by the user
*
* @details Overrides the base Widget button handling to provide immediate
* screensaver exit functionality. Any button press while the screensaver
* is active will:
* - Immediately terminate the screensaver animation
* - Return to the previous screen or main menu
* - Reset any inactivity timers to prevent immediate reactivation
* - Ensure responsive system behavior for user interaction
*
* The method handles all button types uniformly since the screensaver should
* exit on any user input regardless of the specific button pressed. This
* ensures maximum responsiveness and intuitive behavior - users expect any
* interaction to wake the system from screensaver mode.
*
* Button handling includes:
* - Immediate screensaver termination regardless of button type
* - Automatic transition back to the previous active screen
* - Inactivity timer reset to prevent immediate screensaver reactivation
* - Proper state cleanup to ensure system stability
*
* @note This method ensures the screensaver never interferes with normal
* system operation - any user input immediately restores full functionality.
* @note The screensaver exit process is designed to be instantaneous to
* provide the most responsive user experience possible.
*
* @see Widget::onButtonClicked for the base input handling interface
* @see ButtonType for available button input types
*/
void onButtonClicked(ButtonType button) override; void onButtonClicked(ButtonType button) override;
private: private:
/** /**
* @struct Star * @enum VehicleType
* @brief Individual star object structure for starfield animation * @brief Types of available vehicles
* @details Defines the properties and state of a single star in the animated
* starfield. Each star maintains its position in 3D space and movement
* characteristics needed for realistic animation and perspective effects.
*
* The Star structure contains:
* - 3D spatial coordinates (x, y, z) for position tracking
* - Individual speed multiplier for varied animation effects
* - All data needed for perspective projection and movement calculation
*
* Star coordinate system:
* - x, y: Screen-relative coordinates (can be negative for off-screen positioning)
* - z: Depth coordinate determining speed and perspective (Z_NEAR to Z_FAR range)
* - speed: Individual multiplier for varied star movement rates
*
* @note This structure is designed for efficient memory usage and fast
* mathematical operations during animation updates.
* @note All coordinates use float precision for smooth animation interpolation.
*/ */
struct Star enum class VehicleType
{ {
float x; ///< Horizontal position coordinate (screen-relative) CAR,
float y; ///< Vertical position coordinate (screen-relative) CONVERTABLE,
float z; ///< Depth coordinate (determines speed and perspective) SUV,
float speed; ///< Individual speed multiplier for animation variation LORRY,
TRUCK
}; };
/** /**
* @brief Pointer to menu options configuration structure * @enum Direction
* @details Stores a reference to the menu configuration passed during construction. * @brief Movement direction for vehicles
* Provides access to the display context for rendering operations and
* screen transition callbacks for exiting the screensaver on user input.
*
* The configuration enables:
* - Display context (u8g2) for starfield graphics rendering
* - Screen transition callbacks for returning to previous screen
* - System integration for proper screensaver lifecycle management
*
* @note This pointer is not owned by the ScreenSaver and must remain valid
* throughout the screensaver's lifetime.
*/ */
enum class Direction
{
LEFT,
RIGHT
};
/**
* @struct Vehicle
* @brief Individual vehicle object for animation
*/
struct Vehicle
{
int x; // X position on screen
int y; // Y position on screen
float speed; // Movement speed
VehicleType type; // Type of vehicle
Direction direction; // Movement direction
bool active; // Whether a vehicle is currently active
};
static constexpr int MAX_LEFT_VEHICLES = 2;
static constexpr int MAX_RIGHT_VEHICLES = 2;
static constexpr int MAX_VEHICLES = MAX_LEFT_VEHICLES + MAX_RIGHT_VEHICLES;
static constexpr int VEHICLE_SPAWN_DELAY = 1000; // milliseconds
static constexpr float MIN_SPEED = 1.0f;
static constexpr float MAX_SPEED = 2.0f;
menu_options_t *m_options; menu_options_t *m_options;
/**
* @brief Animation timing counter for smooth frame rate control
* @details Tracks elapsed time for animation timing and frame rate calculations.
* Used to ensure consistent star movement regardless of system load
* variations and to provide smooth interpolation between animation frames.
*
* The counter enables:
* - Frame rate independent animation timing
* - Smooth interpolation for fluid star movement
* - Consistent animation speed across different hardware platforms
* - Precise timing control for animation effects
*/
uint64_t m_animationCounter; uint64_t m_animationCounter;
uint64_t m_lastSpawnTime;
std::vector<Vehicle> m_vehicles;
int m_leftVehicleCount;
int m_rightVehicleCount;
int m_sceneOffsetX = 0;
int m_sceneOffsetY = 0;
uint64_t m_sceneShiftTimer = 0;
/** /**
* @brief Vector container for all star objects in the starfield * @brief Initialize vehicle system
* @details Manages the collection of Star objects that comprise the animated
* starfield effect. The vector provides efficient storage and iteration
* for the star animation system while maintaining good cache locality
* for optimal performance during update and render operations.
*
* The vector contains:
* - Fixed number of Star objects (NUM_STARS) allocated at initialization
* - Contiguous memory layout for efficient iteration during animation
* - Dynamic management capabilities for potential future enhancements
*
* @note The vector size is fixed at construction to avoid memory allocations
* during animation, ensuring consistent frame timing performance.
*/ */
std::vector<Star> m_stars; void initVehicles();
/** /**
* @brief Total number of stars in the animated starfield * @brief Spawn a new vehicle if conditions are met
* @details Defines the constant number of star objects that will be created
* and animated in the starfield effect. This value balances visual
* richness with performance requirements for smooth animation.
*
* The star count affects:
* - Visual density and richness of the starfield effect
* - Performance requirements for update and rendering operations
* - Memory usage for star object storage
* - Overall visual impact of the screensaver
*
* @note This value is tuned for optimal performance on target hardware
* while providing an engaging visual effect.
*/ */
static constexpr int NUM_STARS = 10; void trySpawnVehicle();
/** /**
* @brief Global speed multiplier for star animation * @brief Get a random vehicle type
* @details Controls the overall speed of star movement in the starfield animation. * @return Random VehicleType
* This multiplier is applied to all star movement calculations to provide
* consistent, smooth animation at an appropriate visual speed.
*
* The speed multiplier affects:
* - Overall pace of the starfield animation
* - Visual impact and engagement level of the screensaver
* - Performance requirements for smooth animation
* - User perception of system responsiveness
*
* @note This value is carefully tuned to provide engaging animation without
* being distracting or causing motion sickness effects.
*/ */
static constexpr float SPEED_MULTIPLIER = 0.02f; static VehicleType getRandomVehicleType();
/** /**
* @brief Near clipping plane for 3D starfield depth range * @brief Get a random direction with constraint checking
* @details Defines the closest distance (minimum z-coordinate) at which stars * @return Direction for new vehicle
* can exist in the 3D starfield space. Stars closer than this distance
* are considered too close to the viewer and are recycled to new positions.
*
* The near plane affects:
* - Minimum depth for star positioning and recycling
* - Perspective calculation range for realistic depth effects
* - Star recycling triggers for continuous animation
* - Visual depth range of the starfield effect
*
* @note This value works with Z_FAR to define the 3D space within which
* stars exist and animate, creating realistic depth perception.
*/ */
static constexpr float Z_NEAR = 0.1f; static Direction getRandomDirection();
/** /**
* @brief Far clipping plane for 3D starfield depth range * @brief Draw a vehicle at a specified position
* @details Defines the farthest distance (maximum z-coordinate) at which stars * @param vehicle Vehicle to draw
* can exist in the 3D starfield space. This establishes the back
* boundary of the starfield volume and affects initial star placement.
*
* The far plane affects:
* - Maximum depth for initial star positioning
* - Perspective calculation range for depth effects
* - Visual depth range and scale of the starfield
* - Initial star placement during system initialization
*
* @note This value works with Z_NEAR to create a realistic 3D space
* that provides convincing depth perception in the starfield animation.
*/ */
static constexpr float Z_FAR = 10.0f; void drawVehicle(const Vehicle &vehicle) const;
/** /**
* @brief Initializes all stars with random positions and properties * @brief Draw a bitmap with transparency (black pixels are transparent)
* @details Private helper method that sets up the initial starfield by placing * @param x X position
* all stars at random positions within the defined 3D space. Called * @param y Y position
* during construction to prepare the starfield for immediate animation. * @param width Bitmap width
* * @param height Bitmap height
* The initialization process: * @param bitmap Bitmap data
* - Assigns random x, y coordinates within screen boundaries
* - Sets random z-depth within the Z_NEAR to Z_FAR range
* - Configures individual speed multipliers for animation variation
* - Ensures even distribution of stars throughout the 3D volume
*
* Random placement creates:
* - Natural, non-uniform star distribution for realistic appearance
* - Varied star depths for convincing 3D perspective effects
* - Immediate visual interest when screensaver first activates
* - Foundation for smooth continuous animation
*
* @note This method is called only once during construction to establish
* the initial starfield state before animation begins.
*
* @see resetStar for individual star repositioning during animation
*/ */
void initStars(); void drawTransparentBitmap(int x, int y, int width, int height, const unsigned char *bitmap) const;
/** /**
* @brief Resets a single star to a new random position for recycling * @brief Get vehicle bitmap data
* @param star Reference to the Star object to be reset and repositioned * @param type Vehicle type
* * @param direction Movement direction
* @details Private helper method that recycles individual stars that have * @param width Output parameter for bitmap width
* moved beyond the visible screen boundaries. This enables infinite * @param height Output parameter for bitmap height
* starfield animation by continuously introducing new stars while * @return Pointer to bitmap data
* removing those that are no longer visible.
*
* The reset process:
* - Places the star at a new random position near the screen center
* - Assigns a new random depth (z-coordinate) for varied movement speed
* - Configures new speed multiplier for animation variation
* - Ensures smooth transition without visual discontinuities
*
* Star recycling maintains:
* - Continuous starfield animation without visual gaps
* - Consistent star count throughout animation lifecycle
* - Varied star properties for natural, non-repetitive effects
* - Efficient memory usage through object reuse
*
* @pre star parameter must be a valid Star object reference
* @post star object is repositioned with new random properties ready for animation
*
* @note This method is called frequently during animation as stars move
* off-screen and must be efficient to maintain smooth frame rates.
* @note The repositioning algorithm ensures stars appear to emerge naturally
* from the center of the starfield for convincing 3D movement effects.
*/ */
void resetStar(Star &star); static const unsigned char *getVehicleBitmap(VehicleType type, Direction direction, int &width, int &height);
}; };

View File

@@ -1,6 +1,6 @@
#include "common/InactivityTracker.h" #include "common/InactivityTracker.h"
InactivityTracker::InactivityTracker(uint64_t timeoutMs, std::function<void()> onTimeout) InactivityTracker::InactivityTracker(const uint64_t timeoutMs, const std::function<void()> &onTimeout)
: m_timeoutMs(timeoutMs), m_elapsedTime(0), m_enabled(true), m_onTimeout(onTimeout) : m_timeoutMs(timeoutMs), m_elapsedTime(0), m_enabled(true), m_onTimeout(onTimeout)
{ {
} }

View File

@@ -1,86 +1,284 @@
#include "ui/ScreenSaver.h" #include "ui/ScreenSaver.h"
#include <cmath> #include <cstdlib>
#include "data/roads.h"
#include "data/vehicles.h"
ScreenSaver::ScreenSaver(menu_options_t *options) : Widget(options->u8g2), m_options(options), m_animationCounter(0) ScreenSaver::ScreenSaver(menu_options_t *options)
: Widget(options->u8g2),
m_options(options),
m_animationCounter(0),
m_lastSpawnTime(0),
m_leftVehicleCount(0),
m_rightVehicleCount(0)
{ {
initStars(); initVehicles();
} }
void ScreenSaver::initStars() void ScreenSaver::initVehicles()
{ {
m_stars.resize(NUM_STARS); m_vehicles.resize(MAX_VEHICLES);
for (auto &star : m_stars) for (auto &vehicle : m_vehicles)
{ {
resetStar(star); vehicle.active = false;
star.z = Z_NEAR + (static_cast<float>(rand()) / RAND_MAX) * (Z_FAR - Z_NEAR);
} }
} }
void ScreenSaver::resetStar(Star &star)
{
star.x = (static_cast<float>(rand()) / RAND_MAX - 0.5f) * 2.0f;
star.y = (static_cast<float>(rand()) / RAND_MAX - 0.5f) * 2.0f;
star.z = Z_FAR;
star.speed = 0.5f + (static_cast<float>(rand()) / RAND_MAX) * 1.5f;
}
void ScreenSaver::update(const uint64_t dt) void ScreenSaver::update(const uint64_t dt)
{ {
m_animationCounter += dt; m_animationCounter += dt;
m_lastSpawnTime += dt;
m_sceneShiftTimer += dt;
if (m_animationCounter > 8) // Shift entire scene every 30 seconds
if (m_sceneShiftTimer > 30000)
{
m_sceneOffsetX = (random() % 7) - 3; // -3 to +3 pixels
m_sceneOffsetY = (random() % 7) - 3; // -3 to +3 pixels
m_sceneShiftTimer = 0;
}
// Try to spawn a new vehicle every few seconds
if (m_lastSpawnTime > VEHICLE_SPAWN_DELAY)
{
trySpawnVehicle();
m_lastSpawnTime = 0;
}
// Update vehicle positions
if (m_animationCounter > 16) // ~60 FPS
{ {
m_animationCounter = 0; m_animationCounter = 0;
for (auto &star : m_stars) for (auto &vehicle : m_vehicles)
{ {
star.z -= star.speed * SPEED_MULTIPLIER; if (!vehicle.active)
continue;
if (star.z < Z_NEAR) // Move vehicle
if (vehicle.direction == Direction::LEFT)
{ {
resetStar(star); vehicle.x -= static_cast<int>(vehicle.speed);
// Remove the vehicle if it goes off-screen
if (vehicle.x <= -32) // Allow for largest vehicle width
{
vehicle.active = false;
m_leftVehicleCount--;
}
}
else // Direction::RIGHT
{
vehicle.x += static_cast<int>(vehicle.speed);
// Remove the vehicle if it goes off-screen
if (vehicle.x >= (u8g2->width + 32)) // Allow for largest vehicle width
{
vehicle.active = false;
m_rightVehicleCount--;
} }
} }
} }
} }
}
void ScreenSaver::trySpawnVehicle()
{
// Check if we can spawn a new vehicle
int activeVehicles = 0;
int availableSlot = -1;
for (int i = 0; i < MAX_VEHICLES; i++)
{
if (m_vehicles[i].active)
{
activeVehicles++;
}
else if (availableSlot == -1)
{
availableSlot = i;
}
}
// Don't spawn if we're at max capacity or no slot available
if (activeVehicles >= MAX_VEHICLES || availableSlot == -1)
{
return;
}
Direction direction = getRandomDirection();
// Check direction constraints
if ((direction == Direction::LEFT && m_leftVehicleCount >= MAX_LEFT_VEHICLES) ||
(direction == Direction::RIGHT && m_rightVehicleCount >= MAX_RIGHT_VEHICLES))
{
return;
}
// Create new vehicle
Vehicle &newVehicle = m_vehicles[availableSlot];
newVehicle.type = getRandomVehicleType();
newVehicle.direction = direction;
newVehicle.speed = MIN_SPEED + (static_cast<float>(random()) / RAND_MAX) * (MAX_SPEED - MIN_SPEED);
// Set Y position based on direction (simulate opposing traffic lanes)
const int halfHeight = u8g2->height / 2;
if (direction == Direction::RIGHT)
{
// Vehicles going LEFT use bottom half of screen
newVehicle.y = halfHeight + 8 + (random() % (halfHeight - 24));
m_rightVehicleCount++;
}
else // Direction::RIGHT
{
// Vehicles going RIGHT use top half of screen
newVehicle.y = 8 + (random() % (halfHeight - 24));
m_leftVehicleCount++;
}
// Set starting X position based on direction
if (direction == Direction::LEFT)
{
// Vehicles going LEFT (from right to left) start from RIGHT side of screen
newVehicle.x = u8g2->width + 16;
}
else // Direction::RIGHT
{
// Vehicles going RIGHT (from left to right) start from LEFT side of screen
newVehicle.x = -32; // Account for largest vehicle width
}
newVehicle.active = true;
}
ScreenSaver::VehicleType ScreenSaver::getRandomVehicleType()
{
switch (random() % 5)
{
case 0:
return VehicleType::CAR;
case 1:
return VehicleType::CONVERTABLE;
case 2:
return VehicleType::SUV;
case 3:
return VehicleType::LORRY;
case 4:
return VehicleType::TRUCK;
default:
return VehicleType::CAR;
}
}
ScreenSaver::Direction ScreenSaver::getRandomDirection()
{
// Simple 50/50 chance for each direction
return (random() % 2 == 0) ? Direction::LEFT : Direction::RIGHT;
}
void ScreenSaver::render() void ScreenSaver::render()
{ {
// Verwende Page-Buffer Mode statt Full-Buffer für bessere Performance // Clear screen with a black background
// Schwarzer Hintergrund
u8g2_SetDrawColor(u8g2, 0); u8g2_SetDrawColor(u8g2, 0);
u8g2_DrawBox(u8g2, 0, 0, u8g2->width, u8g2->height); u8g2_DrawBox(u8g2, 0, 0, u8g2->width, u8g2->height);
u8g2_SetDrawColor(u8g2, 1); u8g2_SetDrawColor(u8g2, 1);
const int centerX = u8g2->width / 2; // Calculate offsets
const int centerY = u8g2->height / 2; const int roadOffset = (m_animationCounter / 100) % road_horizontal_width;
// Zeichne nur sichtbare Sterne (Clipping) // Draw all active vehicles with scene offset
for (const auto &star : m_stars) for (const auto &vehicle : m_vehicles)
{ {
// 3D zu 2D Projektion if (vehicle.active)
int screenX = centerX + static_cast<int>((star.x / star.z) * centerX);
int screenY = centerY + static_cast<int>((star.y / star.z) * centerY);
// Frühe Prüfung für Performance
if (screenX < -5 || screenX >= u8g2->width + 5 || screenY < -5 || screenY >= u8g2->height + 5)
{ {
continue; Vehicle offsetVehicle = vehicle;
offsetVehicle.x += m_sceneOffsetX;
offsetVehicle.y += m_sceneOffsetY;
drawVehicle(offsetVehicle);
}
} }
// Vereinfachte Sterndarstellung für bessere Performance // Draw road with offsets
int size = static_cast<int>((1.0f - (star.z - Z_NEAR) / (Z_FAR - Z_NEAR)) * 2.0f); const int y = u8g2->height / 2 - road_horizontal_height / 2 + m_sceneOffsetY;
for (int x = -road_horizontal_width + roadOffset + m_sceneOffsetX; x <= u8g2->width; x += road_horizontal_width)
{
drawTransparentBitmap(x, y, road_horizontal_width, road_horizontal_height, road_horizontal_bits);
}
}
if (size <= 0) void ScreenSaver::drawVehicle(const Vehicle &vehicle) const
{
int width, height;
if (const unsigned char *bitmap = getVehicleBitmap(vehicle.type, vehicle.direction, width, height))
{
drawTransparentBitmap(vehicle.x, vehicle.y, width, height, bitmap);
// u8g2_DrawXBM(u8g2, vehicle.x, vehicle.y, width, height, bitmap);
}
}
void ScreenSaver::drawTransparentBitmap(const int x, const int y, const int width, const int height,
const unsigned char *bitmap) const
{
for (int py = 0; py < height; py++)
{
for (int px = 0; px < width; px++)
{
// Calculate byte and a bit of position in bitmap
const int byteIndex = (py * ((width + 7) / 8)) + (px / 8);
// Check if the pixel is set (white)
if (const int bitIndex = px % 8; bitmap[byteIndex] & (1 << bitIndex))
{
// Only draw white pixels, skip black (transparent) pixels
const int screenX = x + px;
// Bounds checking
if (const int screenY = y + py; screenX >= 0 && screenX < u8g2->width &&
screenY >= 0 && screenY < u8g2->height)
{ {
u8g2_DrawPixel(u8g2, screenX, screenY); u8g2_DrawPixel(u8g2, screenX, screenY);
} }
else
{
// Verwende u8g2_DrawCircle für größere Sterne (schneller)
u8g2_DrawCircle(u8g2, screenX, screenY, size, U8G2_DRAW_ALL);
} }
// Black pixels are simply not drawn (transparent)
}
}
}
const unsigned char *ScreenSaver::getVehicleBitmap(const VehicleType type, const Direction direction, int &width,
int &height)
{
switch (type)
{
case VehicleType::CAR:
width = car_width;
height = car_height;
return (direction == Direction::LEFT) ? car_left_bits : car_right_bits;
case VehicleType::CONVERTABLE:
width = convertable_width;
height = convertable_height;
return (direction == Direction::LEFT) ? convertable_left_bits : convertable_right_bits;
case VehicleType::SUV:
width = suv_width;
height = suv_height;
return (direction == Direction::LEFT) ? suv_left_bits : suv_right_bits;
case VehicleType::LORRY:
width = lorry_width;
height = lorry_height;
return (direction == Direction::LEFT) ? lorry_left_bits : lorry_right_bits;
case VehicleType::TRUCK:
width = truck_width;
height = truck_height;
return (direction == Direction::LEFT) ? truck_left_bits : truck_right_bits;
default:
width = car_width;
height = car_height;
return car_left_bits;
} }
} }

View File

@@ -88,7 +88,7 @@ Device::Device(void *appstate) : UIWidget(appstate)
options.persistenceManager->Load(); options.persistenceManager->Load();
m_widget = std::make_shared<SplashScreen>(&options); m_widget = std::make_shared<SplashScreen>(&options);
m_inactivityTracker = std::make_unique<InactivityTracker>(60000, []() { m_inactivityTracker = std::make_unique<InactivityTracker>(6000, []() {
const auto screensaver = std::make_shared<ScreenSaver>(&options); const auto screensaver = std::make_shared<ScreenSaver>(&options);
options.pushScreen(screensaver); options.pushScreen(screensaver);
}); });