File size: 16,539 Bytes
1f7470c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

# import numpy as np
# import streamlit as st
# import plotly.express as px
# import plotly.graph_objects as go
# import pandas as pd

# # Soccer field dimensions (in meters)
# WIDTH = 80  # Width of the field
# LENGTH = 120  # Length of the field
# GOAL_HEIGHT = 2.44  # Standard goal height
# PENALTY_AREA_WIDTH = 40.3
# PENALTY_AREA_DEPTH = 16.5
# GOAL_AREA_WIDTH = 18.32
# GOAL_AREA_DEPTH = 5.5
# GOAL_WIDTH = 7.32  # Standard width of a soccer goal

# def create_field_df():
#     """Create dataframes for different parts of the soccer field."""
#     field_perimeter_bounds = [[0, 0, 0], [WIDTH, 0, 0], [WIDTH, LENGTH, 0], [0, LENGTH, 0], [0, 0, 0]]
#     field_df = pd.DataFrame(field_perimeter_bounds, columns=['x', 'y', 'z'])
#     field_df['line_group'] = 'field_perimeter'
#     field_df['color'] = 'field'

#     half_field_bounds = [[0, LENGTH / 2, 0], [WIDTH, LENGTH / 2, 0]]
#     half_df = pd.DataFrame(half_field_bounds, columns=['x', 'y', 'z'])
#     half_df['line_group'] = 'half_field'
#     half_df['color'] = 'field'

#     left_penalty_df = create_rectangle_df((WIDTH - PENALTY_AREA_WIDTH) / 2, 0, PENALTY_AREA_WIDTH, PENALTY_AREA_DEPTH, 'left_penalty_area')
#     right_penalty_df = create_rectangle_df((WIDTH - PENALTY_AREA_WIDTH) / 2, LENGTH - PENALTY_AREA_DEPTH, PENALTY_AREA_WIDTH, PENALTY_AREA_DEPTH, 'right_penalty_area')
#     left_goal_df = create_rectangle_df((WIDTH - GOAL_AREA_WIDTH) / 2, 0, GOAL_AREA_WIDTH, GOAL_AREA_DEPTH, 'left_goal_area')
#     right_goal_df = create_rectangle_df((WIDTH - GOAL_AREA_WIDTH) / 2, LENGTH - GOAL_AREA_DEPTH, GOAL_AREA_WIDTH, GOAL_AREA_DEPTH, 'right_goal_area')

#     return pd.concat([field_df, half_df, left_penalty_df, right_penalty_df, left_goal_df, right_goal_df])

# def create_rectangle_df(start_x, start_y, width, height, line_group):
#     """Create a dataframe representing a rectangle on the field."""
#     rectangle_bounds = [
#         [start_x, start_y, 0],
#         [start_x + width, start_y, 0],
#         [start_x + width, start_y + height, 0],
#         [start_x, start_y + height, 0],
#         [start_x, start_y, 0]
#     ]
#     df = pd.DataFrame(rectangle_bounds, columns=['x', 'y', 'z'])
#     df['line_group'] = line_group
#     df['color'] = 'field'
#     return df

# def create_center_circle():
#     """Create a 3D line trace for the center circle."""
#     theta = np.linspace(0, 2 * np.pi, 100)
#     x = [(WIDTH / 2) + (9.15 * np.cos(t)) for t in theta]
#     y = [(LENGTH / 2) + (9.15 * np.sin(t)) for t in theta]
#     z = [0] * 100
#     return go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='white', width=2))

# def create_goalposts():
#     """Create goalpost lines for both ends of the field."""
#     goalposts = []

#     goalposts.extend([
#         go.Scatter3d(x=[(WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) - (GOAL_WIDTH / 2)], y=[LENGTH, LENGTH], z=[0, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4)),
#         go.Scatter3d(x=[(WIDTH / 2) + (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2)], y=[LENGTH, LENGTH], z=[0, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4)),
#         go.Scatter3d(x=[(WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2)], y=[LENGTH, LENGTH], z=[GOAL_HEIGHT, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4))
#     ])

#     goalposts.extend([
#         go.Scatter3d(x=[(WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) - (GOAL_WIDTH / 2)], y=[0, 0], z=[0, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4)),
#         go.Scatter3d(x=[(WIDTH / 2) + (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2)], y=[0, 0], z=[0, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4)),
#         go.Scatter3d(x=[(WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2)], y=[0, 0], z=[GOAL_HEIGHT, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4))
#     ])

#     return goalposts

# def generate_trajectory(start_point, end_point, peak_height=10, num_coords=100, trajectory_type='parabolic'):
#     """Generate a trajectory (parabolic or linear) between start and end points."""
#     shot_start_x, shot_start_y, start_z = start_point
#     hoop_x, hoop_y, end_z = end_point

#     if trajectory_type == 'parabolic':
#         distance_x = hoop_x - shot_start_x
#         a = -4 * peak_height / (distance_x ** 2)

#         shot_path_coords = []
#         for index, x in enumerate(np.linspace(shot_start_x, hoop_x, num_coords + 1)):
#             z = a * (x - (shot_start_x + hoop_x) / 2) ** 2 + peak_height
#             y = shot_start_y + (hoop_y - shot_start_y) * (index / num_coords)
#             shot_path_coords.append([x, y, z])

#         shot_path_coords[0][2] = start_z  # Ensure start z is as specified
#         shot_path_coords[-1][2] = end_z  # Ensure end z is as specified

#     elif trajectory_type == 'linear':
#         shot_path_coords = []
#         for index, x in enumerate(np.linspace(shot_start_x, hoop_x, num_coords + 1)):
#             y = shot_start_y + (hoop_y - shot_start_y) * (index / num_coords)
#             z = start_z + (end_z - start_z) * (index / num_coords)
#             shot_path_coords.append([x, y, z])

#     return pd.DataFrame(shot_path_coords, columns=['x', 'y', 'z'])

# def plot_trajectories(fig, start_points, end_points, trajectory_type='parabolic', peak_height=10, num_coords=100):
#     """Plot multiple trajectories on the field."""
#     for start_point, end_point in zip(start_points, end_points):
#         trajectory_df = generate_trajectory(start_point, end_point, peak_height, num_coords, trajectory_type)
#         fig.add_trace(go.Scatter3d(
#             y=trajectory_df['x'],
#             x=trajectory_df['y'],
#             z=trajectory_df['z'],
#             mode='lines',
#             line=dict(color='red', width=4)
#         ))
#         fig.add_trace(go.Scatter3d(
#             y=[trajectory_df['x'].iloc[0], trajectory_df['x'].iloc[-1]],
#             x=[trajectory_df['y'].iloc[0], trajectory_df['y'].iloc[-1]],
#             z=[trajectory_df['z'].iloc[0], trajectory_df['z'].iloc[-1]],
#             mode='markers',
#             marker=dict(size=3, color='red')
#         ))

# def create_soccer_field_plot():
#     """Create a 3D soccer field plot with trajectories."""
#     field_df = create_field_df()

#     fig = px.line_3d(
#         data_frame=field_df, x='x', y='y', z='z', line_group='line_group', color='color',
#         color_discrete_map={'field': '#FFFFFF'}
#     )

#     fig.add_trace(go.Mesh3d(
#         x=[0, WIDTH, WIDTH, 0],
#         y=[0, 0, LENGTH, LENGTH],
#         z=[0, 0, 0, 0],
#         color='rgb(0, 128, 0)',
#         opacity=0.5
#     ))

#     fig.add_trace(create_center_circle())
#     for goalpost in create_goalposts():
#         fig.add_trace(goalpost)

#     max_dimension = max(WIDTH, LENGTH, GOAL_HEIGHT)
#     fig.update_layout(
#         scene=dict(
#             aspectmode="manual",
#             aspectratio=dict(x=1, y=1, z=0.125),
#             xaxis=dict(
#                 range=[-10, max_dimension + 10],
#                 visible=False
#             ),
#             yaxis=dict(
#                 range=[-10, max_dimension + 10],
#                 visible=False
#             ),
#             zaxis=dict(
#                 range=[0, 15],
#                 visible=False
#             ),
#             camera=dict(
#                 eye=dict(x=0.34, y=0, z=0.45)
#             ),
#         ),
#         paper_bgcolor='rgba(0,0,0,0)',
#         plot_bgcolor='rgba(0,0,0,0)',
#         showlegend=False,
#     )

#     return fig

# def main_3D_pitch(start_points, end_points, trajectory_type='linear'):
#     st.title("3D Soccer Field Trajectory Visualization")

#     fig = create_soccer_field_plot()

#     plot_trajectories(fig, start_points, end_points, trajectory_type=trajectory_type, peak_height=5, num_coords=100)

#     st.plotly_chart(fig)
import numpy as np
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd

# Soccer field dimensions (in meters)
WIDTH = 80  # Width of the field
LENGTH = 120  # Length of the field
GOAL_HEIGHT = 2.44  # Standard goal height
PENALTY_AREA_WIDTH = 40.3
PENALTY_AREA_DEPTH = 16.5
GOAL_AREA_WIDTH = 18.32
GOAL_AREA_DEPTH = 5.5
GOAL_WIDTH = 7.32  # Standard width of a soccer goal

def create_field_df():
    """Create dataframes for different parts of the soccer field."""
    field_perimeter_bounds = [[0, 0, 0], [WIDTH, 0, 0], [WIDTH, LENGTH, 0], [0, LENGTH, 0], [0, 0, 0]]
    field_df = pd.DataFrame(field_perimeter_bounds, columns=['x', 'y', 'z'])
    field_df['line_group'] = 'field_perimeter'
    field_df['color'] = 'field'

    half_field_bounds = [[0, LENGTH / 2, 0], [WIDTH, LENGTH / 2, 0]]
    half_df = pd.DataFrame(half_field_bounds, columns=['x', 'y', 'z'])
    half_df['line_group'] = 'half_field'
    half_df['color'] = 'field'

    left_penalty_df = create_rectangle_df((WIDTH - PENALTY_AREA_WIDTH) / 2, 0, PENALTY_AREA_WIDTH, PENALTY_AREA_DEPTH, 'left_penalty_area')
    right_penalty_df = create_rectangle_df((WIDTH - PENALTY_AREA_WIDTH) / 2, LENGTH - PENALTY_AREA_DEPTH, PENALTY_AREA_WIDTH, PENALTY_AREA_DEPTH, 'right_penalty_area')
    left_goal_df = create_rectangle_df((WIDTH - GOAL_AREA_WIDTH) / 2, 0, GOAL_AREA_WIDTH, GOAL_AREA_DEPTH, 'left_goal_area')
    right_goal_df = create_rectangle_df((WIDTH - GOAL_AREA_WIDTH) / 2, LENGTH - GOAL_AREA_DEPTH, GOAL_AREA_WIDTH, GOAL_AREA_DEPTH, 'right_goal_area')

    return pd.concat([field_df, half_df, left_penalty_df, right_penalty_df, left_goal_df, right_goal_df])

def create_rectangle_df(start_x, start_y, width, height, line_group):
    """Create a dataframe representing a rectangle on the field."""
    rectangle_bounds = [
        [start_x, start_y, 0],
        [start_x + width, start_y, 0],
        [start_x + width, start_y + height, 0],
        [start_x, start_y + height, 0],
        [start_x, start_y, 0]
    ]
    df = pd.DataFrame(rectangle_bounds, columns=['x', 'y', 'z'])
    df['line_group'] = line_group
    df['color'] = 'field'
    return df

def create_center_circle():
    """Create a 3D line trace for the center circle."""
    theta = np.linspace(0, 2 * np.pi, 100)
    x = [(WIDTH / 2) + (9.15 * np.cos(t)) for t in theta]
    y = [(LENGTH / 2) + (9.15 * np.sin(t)) for t in theta]
    z = [0] * 100
    return go.Scatter3d(x=x, y=y, z=z, mode='lines', line=dict(color='white', width=2))

def create_goalposts():
    """Create goalpost lines for both ends of the field."""
    goalposts = []

    goalposts.extend([
        go.Scatter3d(x=[(WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) - (GOAL_WIDTH / 2)], y=[LENGTH, LENGTH], z=[0, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4)),
        go.Scatter3d(x=[(WIDTH / 2) + (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2)], y=[LENGTH, LENGTH], z=[0, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4)),
        go.Scatter3d(x=[(WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2)], y=[LENGTH, LENGTH], z=[GOAL_HEIGHT, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4))
    ])

    goalposts.extend([
        go.Scatter3d(x=[(WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) - (GOAL_WIDTH / 2)], y=[0, 0], z=[0, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4)),
        go.Scatter3d(x=[(WIDTH / 2) + (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2)], y=[0, 0], z=[0, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4)),
        go.Scatter3d(x=[(WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2)], y=[0, 0], z=[GOAL_HEIGHT, GOAL_HEIGHT], mode='lines', line=dict(color='black', width=4))
    ])

    return goalposts

def create_goal_net(start_x, end_x, start_y, end_y, height, width):
    """Create a 3D mesh for the goal net."""
    x = [start_x, end_x, end_x, start_x, start_x]
    y = [start_y, start_y, end_y, end_y, start_y]
    z = [height, height, height, height, height]
    return go.Mesh3d(x=x, y=y, z=z, opacity=0.1, color='blue')

def generate_trajectory(start_point, end_point, peak_height=10, num_coords=100, trajectory_type='parabolic'):
    """Generate a trajectory (parabolic or linear) between start and end points."""
    shot_start_x, shot_start_y, start_z = start_point
    hoop_x, hoop_y, end_z = end_point

    if trajectory_type == 'parabolic':
        distance_x = hoop_x - shot_start_x
        a = -4 * peak_height / (distance_x ** 2)

        shot_path_coords = []
        for index, x in enumerate(np.linspace(shot_start_x, hoop_x, num_coords + 1)):
            z = a * (x - (shot_start_x + hoop_x) / 2) ** 2 + peak_height
            y = shot_start_y + (hoop_y - shot_start_y) * (index / num_coords)
            shot_path_coords.append([x, y, z])

        shot_path_coords[0][2] = start_z  # Ensure start z is as specified
        shot_path_coords[-1][2] = end_z  # Ensure end z is as specified

    elif trajectory_type == 'linear':
        shot_path_coords = []
        for index, x in enumerate(np.linspace(shot_start_x, hoop_x, num_coords + 1)):
            y = shot_start_y + (hoop_y - shot_start_y) * (index / num_coords)
            z = start_z + (end_z - start_z) * (index / num_coords)
            shot_path_coords.append([x, y, z])

    return pd.DataFrame(shot_path_coords, columns=['x', 'y', 'z'])

def plot_trajectories(fig, start_points, end_points, trajectory_type='parabolic', peak_height=10, num_coords=100):
    """Plot multiple trajectories on the field."""
    for start_point, end_point in zip(start_points, end_points):
        trajectory_df = generate_trajectory(start_point, end_point, peak_height, num_coords, trajectory_type)
        fig.add_trace(go.Scatter3d(
            y=trajectory_df['x'],
            x=trajectory_df['y'],
            z=trajectory_df['z'],
            mode='lines',
            line=dict(color='red', width=4)
        ))
        fig.add_trace(go.Scatter3d(
            y=[trajectory_df['x'].iloc[0], trajectory_df['x'].iloc[-1]],
            x=[trajectory_df['y'].iloc[0], trajectory_df['y'].iloc[-1]],
            z=[trajectory_df['z'].iloc[0], trajectory_df['z'].iloc[-1]],
            mode='markers',
            marker=dict(size=3, color='red')
        ))

def create_soccer_field_plot():
    """Create a 3D soccer field plot with trajectories."""
    field_df = create_field_df()

    fig = px.line_3d(
        data_frame=field_df, x='x', y='y', z='z', line_group='line_group', color='color',
        color_discrete_map={'field': '#FFFFFF'}
    )

    fig.add_trace(go.Mesh3d(
        x=[0, WIDTH, WIDTH, 0],
        y=[0, 0, LENGTH, LENGTH],
        z=[0, 0, 0, 0],
        color='rgb(0, 128, 0)',
        opacity=0.5
    ))

    fig.add_trace(create_center_circle())
    for goalpost in create_goalposts():
        fig.add_trace(goalpost)

    # # Add goal nets
    # fig.add_trace(create_goal_net((WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2), 0, -GOAL_HEIGHT, GOAL_HEIGHT, GOAL_WIDTH))
    # fig.add_trace(create_goal_net((WIDTH / 2) - (GOAL_WIDTH / 2), (WIDTH / 2) + (GOAL_WIDTH / 2), LENGTH, LENGTH + GOAL_HEIGHT, GOAL_HEIGHT, GOAL_WIDTH))

    max_dimension = max(WIDTH, LENGTH, GOAL_HEIGHT)
    fig.update_layout(
        scene=dict(
            aspectmode="manual",
            aspectratio=dict(x=1, y=1, z=0.125),
            xaxis=dict(
                range=[-10, max_dimension + 10],
                visible=False
            ),
            yaxis=dict(
                range=[-10, max_dimension + 10],
                visible=False
            ),
            zaxis=dict(
                range=[0, 15],
                visible=False
            ),
            camera=dict(
                eye=dict(x=0.34, y=0, z=0.45)
            ),
        ),
        paper_bgcolor='rgba(0,0,0,0)',
        plot_bgcolor='rgba(0,0,0,0)',
        showlegend=False,
    )

    return fig

def main_3D_pitch(start_points, end_points, trajectory_type='linear'):
    st.title("3D Soccer Field Trajectory Visualization")

    fig = create_soccer_field_plot()

    plot_trajectories(fig, start_points, end_points, trajectory_type=trajectory_type, peak_height=5, num_coords=100)

    st.plotly_chart(fig)