File size: 10,229 Bytes
9905550
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from mpl_toolkits.mplot3d import Axes3D, art3d
import random

# Parameters
WORLD_SIZE = 100000
AIRCRAFT_COUNT = 100
RADAR_RANGE = 70000
RADAR_ALTITUDE_LIMIT = 20000  # max altitude radar covers in meters
SCAN_SPEED = 2.0  # degrees per frame
BEAM_WIDTH = 5.0  # degrees width of radar beam
TRACK_LENGTH = 20  # length of tail/track for aircrafts
MAX_ACCELERATION = 5  # m/s^2 max change in velocity per frame

# Aircraft types with properties
AIRCRAFT_TYPES = {
    'commercial': {'rcs_range': (10, 20), 'color': 'cyan', 'size': 30},
    'military': {'rcs_range': (5, 12), 'color': 'red', 'size': 40},
    'drone': {'rcs_range': (1, 4), 'color': 'yellow', 'size': 20},
    'unknown': {'rcs_range': (0.5, 2), 'color': 'magenta', 'size': 25}
}

# Event Class with motion
class MovingEvent3D:
    def __init__(self, evt_type, center, radius, altitude, velocity):
        self.type = evt_type
        self.center = np.array(center, dtype=float)
        self.radius = radius
        self.altitude = altitude
        self.velocity = np.array(velocity, dtype=float)
        self.active = True
    
    def update(self):
        self.center += self.velocity
        # Bounce inside world bounds for x,y
        for i in [0, 1]:
            if self.center[i] < 0 or self.center[i] > WORLD_SIZE:
                self.velocity[i] = -self.velocity[i]
                self.center[i] = np.clip(self.center[i], 0, WORLD_SIZE)
        # Bounce altitude inside radar altitude limit
        if self.altitude < 0 or self.altitude > RADAR_ALTITUDE_LIMIT:
            self.velocity[2] = -self.velocity[2]
            self.altitude = np.clip(self.altitude, 0, RADAR_ALTITUDE_LIMIT)
        # Random on/off toggle for event activity
        if random.random() < 0.001:
            self.active = not self.active

def generate_moving_events_3d():
    events = []
    for _ in range(4):
        evt_type = random.choice(['storm', 'no-fly-zone', 'jamming', 'interference'])
        center = np.random.uniform(0, WORLD_SIZE, 2)
        altitude = np.random.uniform(0, RADAR_ALTITUDE_LIMIT)
        radius = {'storm': 15000, 'no-fly-zone': 10000, 'jamming': 8000, 'interference':12000}[evt_type]
        velocity = np.random.uniform(-50, 50, 3)
        events.append(MovingEvent3D(evt_type, center, radius, altitude, velocity))
    return events

world_events = generate_moving_events_3d()

# Generate aircrafts with altitude, track history, type and variable velocity
def generate_aircraft_3d():
    aircrafts = []
    for i in range(AIRCRAFT_COUNT):
        ac_type = random.choices(list(AIRCRAFT_TYPES.keys()), weights=[0.5,0.3,0.15,0.05])[0]
        rcs_min, rcs_max = AIRCRAFT_TYPES[ac_type]['rcs_range']
        ac = {
            'id': i,
            'type': ac_type,
            'position': np.array([*np.random.uniform(0, WORLD_SIZE, 2), np.random.uniform(0, RADAR_ALTITUDE_LIMIT)]),
            'velocity': np.random.uniform(-50, 50, 3),
            'rcs': random.uniform(rcs_min, rcs_max),
            'callsign': f"{ac_type[:2].upper()}{i:03}",
            'emergency': random.random() < 0.03,
            'track': [],
            'acceleration': np.zeros(3),
        }
        aircrafts.append(ac)
    return aircrafts

aircrafts = generate_aircraft_3d()
radar_angle = [0]
radar_pos = np.array([WORLD_SIZE/2, WORLD_SIZE/2, 0])
paused = [False]

def is_event_active_3d(pos):
    for evt in world_events:
        if evt.active:
            d_xy = np.linalg.norm(pos[:2] - evt.center)
            dz = abs(pos[2] - evt.altitude)
            if d_xy < evt.radius and dz < evt.radius / 2:
                return evt.type
    return None

def detect_3d(ac, radar_pos):
    delta = ac['position'] - radar_pos
    rng = np.linalg.norm(delta)
    if rng > RADAR_RANGE or ac['position'][2] > RADAR_ALTITUDE_LIMIT:
        return False
    bearing = (np.degrees(np.arctan2(delta[1], delta[0])) + 360) % 360
    diff = abs((bearing - radar_angle[0] + 180) % 360 - 180)
    if diff > BEAM_WIDTH / 2:
        return False
    evt = is_event_active_3d(ac['position'])
    snr_val = 20 - 20*np.log10(rng + 1) + ac['rcs']
    if evt == 'jamming':
        snr_val -= 50
    elif evt == 'storm':
        snr_val -= 15
    elif evt == 'interference':
        snr_val -= 25
    prob = 1 / (1 + np.exp(-(snr_val - 10)))
    # Introduce random detection noise
    noise = np.random.normal(0, 0.1)
    return np.random.rand() < (prob + noise)

# Setup plot
fig = plt.figure(figsize=(14, 10))
ax = fig.add_subplot(111, projection='3d')
ax.set_xlim(0, WORLD_SIZE)
ax.set_ylim(0, WORLD_SIZE)
ax.set_zlim(0, RADAR_ALTITUDE_LIMIT)
ax.set_facecolor('black')

# Scatter for different types of aircrafts (dynamic update)
all_scatter = ax.scatter([], [], [], c=[], s=[], label='Aircraft')
detected_scatter = ax.scatter([], [], [], c='lime', s=60, label='Detected')
emergency_scatter = ax.scatter([], [], [], c='orange', s=80, marker='^', label='Emergency')
radar_sweep_line, = ax.plot([], [], [], c='cyan', linewidth=3, label='Radar Sweep')

# Track lines for aircrafts
track_lines = [ax.plot([], [], [], c='white', alpha=0.3, linewidth=1)[0] for _ in range(AIRCRAFT_COUNT)]

event_spheres = []
event_colors = {'storm':'blue', 'no-fly-zone':'yellow', 'jamming':'magenta', 'interference':'purple'}

def plot_sphere(center, radius, color):
    u = np.linspace(0, 2*np.pi, 20)
    v = np.linspace(0, np.pi, 20)
    x = center[0] + radius * np.outer(np.cos(u), np.sin(v))
    y = center[1] + radius * np.outer(np.sin(u), np.sin(v))
    z = center[2] + radius * np.outer(np.ones(np.size(u)), np.cos(v))
    return ax.plot_surface(x, y, z, color=color, alpha=0.15)

for evt in world_events:
    sphere = plot_sphere(np.array([*evt.center, evt.altitude]), evt.radius, event_colors[evt.type])
    event_spheres.append(sphere)

# Radar range circle on ground
radar_circle = plt.Circle((radar_pos[0], radar_pos[1]), RADAR_RANGE, color='cyan', alpha=0.1)
ax.add_patch(radar_circle)
art3d.pathpatch_2d_to_3d(radar_circle, z=0, zdir="z")

def update(frame):
    if paused[0]:
        return
    
    # به‌روزرسانی زاویه رادار
    radar_angle[0] = (radar_angle[0] + 1) % 360

    all_pos = []
    all_colors = []
    all_sizes = []

    detected_pos = []
    emergency_pos = []

    for ac in aircrafts:
        # محدود کردن سرعت
        v_mag = np.linalg.norm(ac['velocity'])
        max_speed = 250  # m/s
        if v_mag > max_speed:
            ac['velocity'] = (ac['velocity'] / v_mag) * max_speed
        
        # به‌روزرسانی موقعیت
        ac['position'] += ac['velocity']
        
        # برخورد به دیواره‌های جهان
        for i in [0, 1]:
            if ac['position'][i] < 0 or ac['position'][i] > WORLD_SIZE:
                ac['velocity'][i] = -ac['velocity'][i]
                ac['position'][i] = np.clip(ac['position'][i], 0, WORLD_SIZE)
        if ac['position'][2] < 0 or ac['position'][2] > RADAR_ALTITUDE_LIMIT:
            ac['velocity'][2] = -ac['velocity'][2]
            ac['position'][2] = np.clip(ac['position'][2], 0, RADAR_ALTITUDE_LIMIT)
        
        # ثبت رد حرکت
        ac['track'].append(ac['position'].copy())
        if len(ac['track']) > TRACK_LENGTH:
            ac['track'].pop(0)
        
        all_pos.append(ac['position'])
        all_colors.append(AIRCRAFT_TYPES[ac['type']]['color'])
        all_sizes.append(AIRCRAFT_TYPES[ac['type']]['size'])
        
        if detect_3d(ac, radar_pos):
            detected_pos.append(ac['position'])
            if ac['emergency']:
                emergency_pos.append(ac['position'])

    # تبدیل به np.array
    all_pos = np.array(all_pos)
    detected_pos = np.array(detected_pos)
    emergency_pos = np.array(emergency_pos)

    # آپدیت scatter کل هواپیماها
    if len(all_pos) > 0:
        all_scatter._offsets3d = (all_pos[:,0], all_pos[:,1], all_pos[:,2])
        all_scatter.set_color(all_colors)
        all_scatter.set_sizes(all_sizes)
    else:
        all_scatter._offsets3d = ([], [], [])
        all_scatter.set_color([])
        all_scatter.set_sizes([])

    # آپدیت scatter هواپیماهای تشخیص داده شده
    if len(detected_pos) > 0:
        detected_scatter._offsets3d = (detected_pos[:,0], detected_pos[:,1], detected_pos[:,2])
        detected_scatter.set_sizes([60]*len(detected_pos))
    else:
        detected_scatter._offsets3d = ([], [], [])
        detected_scatter.set_sizes([])

    # آپدیت scatter هواپیماهای اضطراری
    if len(emergency_pos) > 0:
        emergency_scatter._offsets3d = (emergency_pos[:,0], emergency_pos[:,1], emergency_pos[:,2])
        emergency_scatter.set_sizes([80]*len(emergency_pos))
    else:
        emergency_scatter._offsets3d = ([], [], [])
        emergency_scatter.set_sizes([])

    # به‌روزرسانی خطوط رد حرکت
    for i, ac in enumerate(aircrafts):
        if len(ac['track']) >= 2:
            track_arr = np.array(ac['track'])
            track_lines[i].set_data(track_arr[:,0], track_arr[:,1])
            track_lines[i].set_3d_properties(track_arr[:,2])
        else:
            track_lines[i].set_data([], [])
            track_lines[i].set_3d_properties([])

    # به‌روزرسانی خط اسکن رادار
    angle_rad = np.radians(radar_angle[0])
    x = [radar_pos[0], radar_pos[0] + RADAR_RANGE * np.cos(angle_rad)]
    y = [radar_pos[1], radar_pos[1] + RADAR_RANGE * np.sin(angle_rad)]
    z = [0, 0]
    radar_sweep_line.set_data(x, y)
    radar_sweep_line.set_3d_properties(z)

    ax.set_title(f"3D Radar Simulation - Scan Angle: {radar_angle[0]:.1f}°")

    
def on_key(event):
    if event.key == ' ':
        paused[0] = not paused[0]

fig.canvas.mpl_connect('key_press_event', on_key)

ani = FuncAnimation(fig, update, interval=50)
plt.legend(loc='upper right')
plt.show()