% Bouncing Ball Hybrid System Simulation (Real-Time)
clear; clc; close all;

% Parameters 
g = 9.81;         % Gravity (m/s^2)
e = 0.99;          % Coefficient of restitution 
c = 0.05;         % Air drag coefficient
m = 1.0;          % Mass (kg)
dt = 0.016;       % Time step (s) ~ 60fps
t_end = 30;        % Total simulation time (s)

% Initial State 
y = 10;           
v = 0;            
t = 0;

t_hist = t;
y_hist = y;

% Figure 1: Animation 
fig1 = figure('Name', 'Bouncing Ball Animation', 'Position', [100, 300, 300, 500]);
hold on;
plot([-1, 1], [0, 0], 'k-', 'LineWidth', 3);
ball_marker = plot(0, y, 'ro', 'MarkerSize', 20, 'MarkerFaceColor', '#e74c3c');
xlim([-1, 1]);
ylim([0, 11]);
title('Physical Simulation');
ylabel('Height (m)');
set(gca, 'XTick', []); 
grid on;

% Figure 2: Trajectory Plot 
fig2 = figure('Name', 'Height Trajectory', 'Position', [420, 300, 600, 500]);
trajectory_line = plot(t_hist, y_hist, 'b-', 'LineWidth', 2);
xlim([0, t_end]);
ylim([0, 11]);
title('Height vs. Time State');
xlabel('Time (s)');
ylabel('Height (m)');
grid on;


while t < t_end
    
    % Flow Map (Continuous phase)
    a = -g - (c/m)*v;
    v = v + a * dt;
    y = y + v * dt;
    
    % Jump Map (Discrete phase)
    if y <= 0 && v < 0
        y = 0;          
        v = -e * v;     
        
        if abs(v) < 0.2
            v = 0;
        end
    end
    
    % Update history
    t = t + dt;
    t_hist = [t_hist, t];
    y_hist = [y_hist, y];
    
    % -- Real-time Rendering Update --
    set(ball_marker, 'YData', y);
    set(trajectory_line, 'XData', t_hist, 'YData', y_hist);
    
    drawnow;       % Flush the graphics queue immediately
    pause(dt);     % Force MATLAB to wait, syncing simulation with real time
end