gamengine3d 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ from .context import Context
2
+ from .engine import Engine
3
+ from .game_objects import (
4
+ GameObject,
5
+ Cuboid,
6
+ Cylinder,
7
+ )
8
+
9
+ from .helper import (
10
+ Color,
11
+ vector3d,
12
+ Light,
13
+ Camera
14
+ )
gamengine3d/context.py ADDED
@@ -0,0 +1,119 @@
1
+ from .game_objects import GameObject
2
+ from .helper import Color, vector3d, Light, Camera, Renderer
3
+ from pygame.time import Clock
4
+
5
+ class Functions:
6
+ def __init__(self):
7
+ self.draw_cube = lambda pos=vector3d.zero, size=vector3d(3), color=Color.light_blue: None
8
+ self.draw_sphere = lambda pos=vector3d.zero, radius=2, color=Color.light_red, segments=32, rings=16: None
9
+ self.draw_cylinder = lambda pos=vector3d.zero, length=2, radius=.5, color=Color.light_yellow, segments=32: None
10
+ self.add_light = lambda light: None
11
+ self.add_object = lambda obj: None
12
+ self.is_colliding = lambda name1, name2: None
13
+ self.get_game_object = lambda name: None
14
+ self.remove_object = lambda name: None
15
+ self.remove_light = lambda name: None
16
+
17
+ class KeyCallback:
18
+ def __init__(self, key, event_type, callback, args=None, dt=False):
19
+ self.callback = callback
20
+ self.key = key
21
+ self.event_type = event_type
22
+ self.dt = dt
23
+ if not args:
24
+ args = []
25
+ self.args = args
26
+
27
+ def update(self, pressed_keys, held_keys, released_keys, dt):
28
+ if self.event_type == "pressed":
29
+ if self.key in pressed_keys:
30
+ if self.dt:
31
+ self.callback(dt, *self.args)
32
+ else:
33
+ self.callback(*self.args)
34
+
35
+ elif self.event_type == "held":
36
+ if self.key in held_keys:
37
+ if self.dt:
38
+ self.callback(dt, *self.args)
39
+ else:
40
+ self.callback(*self.args)
41
+
42
+ elif self.event_type == "released":
43
+ if self.key in released_keys:
44
+ if self.dt:
45
+ self.callback(dt, *self.args)
46
+ else:
47
+ self.callback(*self.args)
48
+
49
+ class KeyCallbackVar:
50
+ def __init__(self, key, event_type, obj, attr, value):
51
+ self.key = key
52
+ self.event_type = event_type
53
+ self.obj = obj
54
+ self.attr = attr
55
+ self.value = value
56
+
57
+ def update(self, pressed_keys, held_keys, releaed_keys):
58
+ if self.event_type == "pressed":
59
+ if self.key in pressed_keys:
60
+ setattr(self.obj, self.attr, self.value)
61
+
62
+ elif self.event_type == "held":
63
+ if self.key in held_keys:
64
+ setattr(self.obj, self.attr, self.value)
65
+
66
+ elif self.event_type == "released":
67
+ if self.key in releaed_keys:
68
+ setattr(self.obj, self.attr, self.value)
69
+
70
+ class Context:
71
+ def __init__(self):
72
+ self.functions: Functions = Functions()
73
+ self.ambient_light: float = .2
74
+ self.lights: list[Light] = []
75
+ self.game_objects: list[GameObject] = []
76
+ self.mouse_sensitivity: float = 0.3
77
+ self.pan_sensitivity: float = 0.005
78
+ self.fps: int | float = 0
79
+ self.engine = None
80
+ self.camera: Camera | None = None
81
+ self.clock: Clock | None = None
82
+ self.renderer: Renderer | None = None
83
+ self.keys_held: list[str] = []
84
+ self.keys_pressed: list[str] = []
85
+ self.keys_released: list[str] = []
86
+ self.key_callbacks: list[KeyCallback] = []
87
+ self.key_callback_vars: list[KeyCallbackVar] = []
88
+ self.exit = False
89
+
90
+ def on_key_press(self, key, callback, args=None, dt=False):
91
+ if args is None:
92
+ args = []
93
+ self.key_callbacks.append(KeyCallback(key, "pressed", callback, args, dt))
94
+
95
+ def on_key_held(self, key, callback, args=None, dt=False):
96
+ if args is None:
97
+ args = []
98
+ self.key_callbacks.append(KeyCallback(key, "held", callback, args, dt))
99
+
100
+ def on_key_released(self, key, callback, args=None, dt=False):
101
+ if args is None:
102
+ args = []
103
+ self.key_callbacks.append(KeyCallback(key, "released", callback, args, dt))
104
+
105
+ def on_key_press_var(self, key, obj, attr, value):
106
+ self.key_callback_vars.append(KeyCallbackVar(key, "pressed", obj, attr, value))
107
+
108
+ def on_key_held_var(self, key, obj, attr, value):
109
+ self.key_callback_vars.append(KeyCallbackVar(key, "held", obj, attr, value))
110
+
111
+ def on_key_released_var(self, key, obj, attr, value):
112
+ self.key_callback_vars.append(KeyCallbackVar(key, "released", obj, attr, value))
113
+
114
+ def update(self, dt):
115
+ for callback in self.key_callbacks:
116
+ callback.update(self.keys_pressed, self.keys_held, self.keys_released, dt)
117
+
118
+ for callback_var in self.key_callback_vars:
119
+ callback_var.update(self.keys_pressed, self.keys_held, self.keys_released, dt)
gamengine3d/engine.py ADDED
@@ -0,0 +1,249 @@
1
+ from itertools import product
2
+ from pyrr import Matrix44
3
+ from .context import Context
4
+ import pygame
5
+ from .game_objects import Cuboid, GameObject, Sphere
6
+ from .helper import Renderer, vector3d, Color, Camera, Light, EngineError, Script
7
+ import math
8
+
9
+ class Engine:
10
+ def __init__(self, width=500, height=500, resizable=True, name="GamEngine3d", background_color=Color.light_grey, ambient_light=.2):
11
+ self.width = width
12
+ self.height = height
13
+ self.resizable = resizable
14
+ self.window_name = name
15
+ self.background_color = background_color
16
+ self.scripts = []
17
+
18
+ flags = pygame.DOUBLEBUF | pygame.OPENGL
19
+ if self.resizable:
20
+ flags |= pygame.RESIZABLE
21
+
22
+ pygame.display.set_caption(self.window_name)
23
+ self.renderer = Renderer(width, height, flags=flags)
24
+ self.renderer.ambient = ambient_light
25
+ self.clock = pygame.time.Clock()
26
+
27
+ self.camera = Camera(position=vector3d(0, 1.5, 3),
28
+ target=vector3d(0, 0, 0),
29
+ aspect_ratio=self.width / self.height)
30
+
31
+ self.last_mouse_pos = None
32
+ self.mouse_sensitivity = 0.3
33
+ self.pan_sensitivity = 0.005
34
+ self.active_button = None
35
+
36
+ self.gameobjects = []
37
+
38
+ self.context = Context()
39
+
40
+ self.context.functions.draw_cube = self.draw_cuboid
41
+ self.context.functions.draw_sphere = self.draw_sphere
42
+ self.context.functions.add_light = self.add_light
43
+ self.context.functions.add_object = self.add_object
44
+ self.context.functions.draw_cylinder = self.draw_cylinder
45
+ self.context.functions.get_game_object = self.get_object
46
+ self.context.functions.is_colliding = self.is_colliding
47
+ self.context.functions.remove_light = self.remove_light
48
+ self.context.functions.remove_object = self.remove_object
49
+
50
+ self.context.game_objects = self.gameobjects
51
+ self.context.engine = self
52
+ self.context.camera = self.camera
53
+ self.context.renderer = self.renderer
54
+ self.context.clock = self.clock
55
+
56
+ self.context.lights = self.renderer.lights
57
+
58
+ def run(self, fps=60, dynamic_view=True):
59
+ running = True
60
+ self.context.fps = fps
61
+ keys_held = []
62
+ self.context.keys_held = keys_held
63
+ self.init_scripts()
64
+
65
+ for script in self.scripts:
66
+ script.run("on_start")
67
+
68
+ while running:
69
+ keys_pressed = []
70
+ keys_released = []
71
+ dt = self.clock.get_time() / 1000
72
+ self.mouse_sensitivity = self.context.mouse_sensitivity
73
+ self.pan_sensitivity = self.context.pan_sensitivity
74
+ self.context.fps = self.clock.get_fps()
75
+
76
+ for event in pygame.event.get():
77
+ if event.type == pygame.QUIT:
78
+ running = False
79
+
80
+ if self.resizable and event.type == pygame.VIDEORESIZE:
81
+ self.width, self.height = event.w, event.h
82
+ self.renderer.resize(self.width, self.height)
83
+ self.camera.aspect_ratio = self.width / self.height
84
+
85
+ if dynamic_view:
86
+ if event.type == pygame.MOUSEBUTTONDOWN:
87
+ if event.button in (1, 3): # Left or right
88
+ self.last_mouse_pos = pygame.mouse.get_pos()
89
+ self.active_button = event.button
90
+ elif event.type == pygame.MOUSEBUTTONUP:
91
+ if event.button in (1, 3):
92
+ self.last_mouse_pos = None
93
+ self.active_button = None
94
+
95
+ elif event.type == pygame.MOUSEMOTION:
96
+ if self.last_mouse_pos is not None:
97
+ x, y = pygame.mouse.get_pos()
98
+ dx = x - self.last_mouse_pos[0]
99
+ dy = y - self.last_mouse_pos[1]
100
+ self.last_mouse_pos = (x, y)
101
+
102
+ if self.active_button == 3:
103
+ self.camera.rotate_around_target(-dx * self.mouse_sensitivity, dy * self.mouse_sensitivity)
104
+
105
+ elif self.active_button == 1:
106
+ self._pan_camera(dx, dy)
107
+
108
+ elif event.type == pygame.MOUSEWHEEL:
109
+ self.camera.zoom(event.y * 0.5)
110
+
111
+ if event.type == pygame.KEYDOWN:
112
+ key_name = pygame.key.name(event.key)
113
+ keys_pressed.append(key_name)
114
+ keys_held.append(key_name)
115
+
116
+ elif event.type == pygame.KEYUP:
117
+ key_name = pygame.key.name(event.key)
118
+ keys_held.remove(key_name)
119
+ keys_released.append(key_name)
120
+
121
+ self.context.keys_pressed = keys_pressed
122
+ self.context.keys_released = keys_released
123
+ self.context.update(dt)
124
+
125
+ self.renderer.clear(self.background_color)
126
+ self.camera.update_renderer(self.renderer)
127
+
128
+ self.renderer.ambient = self.context.ambient_light
129
+
130
+ for script in self.scripts:
131
+ script.update(dt)
132
+
133
+ for obj in self.gameobjects:
134
+ obj.update(dt)
135
+ obj.draw(self.renderer)
136
+
137
+ if self.context.exit:
138
+ running = False
139
+
140
+ self.renderer.swap()
141
+ self.clock.tick(fps)
142
+
143
+ for script in self.scripts:
144
+ script.run("on_exit")
145
+ self.renderer.quit()
146
+
147
+ def _pan_camera(self, dx, dy):
148
+ forward = (self.camera.target - self.camera.position).normalized
149
+ right = forward.cross(self.camera.up).normalized
150
+ up = self.camera.up.normalized
151
+
152
+ pan = (right * -dx + up * dy) * self.pan_sensitivity * self.camera.radius
153
+ self.camera.target += pan
154
+ self.camera.position += pan
155
+ self.camera._update_position()
156
+
157
+ def add_light(self, light):
158
+ self.renderer.add_light(light)
159
+ if light.show:
160
+ self.add_object(Sphere(pos=light.position, color=light.color, radius=.1))
161
+
162
+ def add_object(self, obj: GameObject):
163
+ self.gameobjects.append(obj)
164
+
165
+ def remove_object(self, name):
166
+ obj = self.get_object(name)
167
+ self.gameobjects.remove(obj)
168
+
169
+ def remove_light(self, name):
170
+ for light in self.renderer.lights:
171
+ if light.name == name:
172
+ self.renderer.lights.remove(light)
173
+ return
174
+
175
+ raise EngineError(f"No Light Object Named {name}")
176
+
177
+ def get_object(self, name):
178
+ for obj in self.gameobjects:
179
+ if obj.name == name:
180
+ return obj
181
+
182
+ raise EngineError(f"Game Object with name {name} not found")
183
+
184
+ def is_colliding(self, name1, name2):
185
+ obj1 = self.get_object(name1)
186
+ obj2 = self.get_object(name2)
187
+
188
+ if not (isinstance(obj1, Cuboid) and isinstance(obj2, Cuboid)):
189
+ raise NotImplementedError(f"Cylinder And Sphere Collision Not Implemented")
190
+
191
+ corners = obj1.get_corners()
192
+ for corner in corners:
193
+ if obj2.is_point_in(corner):
194
+ return True
195
+
196
+ return False
197
+
198
+ def draw_cuboid(self, pos: vector3d=vector3d.zero, size: vector3d=vector3d(2), rotation: vector3d=vector3d.zero, color: Color = Color.light_blue):
199
+ faces = [
200
+ [0, 1, 3, 2],
201
+ [4, 6, 7, 5],
202
+ [0, 4, 5, 1],
203
+ [2, 3, 7, 6],
204
+ [0, 2, 6, 4],
205
+ [1, 5, 7, 3],
206
+ ]
207
+
208
+ half_size = size / 2
209
+
210
+ rot_matrix = Matrix44.from_eulers((
211
+ math.radians(rotation.x),
212
+ math.radians(rotation.y),
213
+ math.radians(rotation.z)
214
+ ))
215
+
216
+ corners = []
217
+ for dx, dy, dz in product([-1, 1], repeat=3):
218
+ local = vector3d(dx * half_size.x, dy * half_size.y, dz * half_size.z)
219
+
220
+ rotated = vector3d(
221
+ *(rot_matrix @ [local.x, local.y, local.z, 1.0])[:3]
222
+ )
223
+
224
+ world = pos + rotated
225
+ corners.append(world)
226
+
227
+ for face_idx in faces:
228
+ self.renderer.render_quad(
229
+ corners[face_idx[0]],
230
+ corners[face_idx[1]],
231
+ corners[face_idx[2]],
232
+ corners[face_idx[3]],
233
+ color=color
234
+ )
235
+
236
+ def draw_sphere(self, pos: vector3d=vector3d.zero, radius: int=2, color: Color=Color.light_red, segments=32, rings=16):
237
+ self.renderer.render_sphere(center=pos, radius=radius, color=color, segments=segments, rings=rings)
238
+
239
+ def draw_cylinder(self, pos: vector3d=vector3d.zero, length: int=2, radius: int=.5, color: Color=Color.light_yellow, segments: int=32, rotation: vector3d=vector3d.zero):
240
+ self.renderer.render_cylinder(center=pos, height=length, radius=radius, color=color, segments=segments, rotation=rotation)
241
+
242
+ def attach(self, path):
243
+ script = Script(self, path, self.context)
244
+ script.init_instance()
245
+ self.scripts.append(script)
246
+
247
+ def init_scripts(self):
248
+ for script in self.scripts:
249
+ script.init_instance()
@@ -0,0 +1,185 @@
1
+ import numpy as np
2
+ from itertools import product
3
+ from pyrr import Matrix44
4
+ import math
5
+
6
+ from .helper import Color, vector3d, Renderer, Script
7
+
8
+ class GameObject:
9
+ def __init__(self, name):
10
+ self.name = name
11
+ self.scripts = []
12
+
13
+ def update(self, dt):
14
+ for script in self.scripts:
15
+ script.update(dt)
16
+
17
+ def draw(self, renderer: Renderer):
18
+ pass
19
+
20
+ def attach(self, file_path, context):
21
+ script = Script(self, file_path, context)
22
+ script.init_instance()
23
+ self.scripts.append(script)
24
+
25
+ def init_scripts(self):
26
+ for script in self.scripts:
27
+ script.init_instance()
28
+
29
+ class Cuboid(GameObject):
30
+ def __init__(self, pos: vector3d = vector3d.zero,
31
+ size: vector3d = vector3d(5),
32
+ color: Color = Color.green,
33
+ name: str = "Cuboid",
34
+ rotation: vector3d = vector3d.zero):
35
+ super().__init__(name)
36
+ self.name = name
37
+ self.pos = pos
38
+ self.size = size
39
+ self.color = color
40
+ self.rotation = rotation
41
+ self.visible = True
42
+
43
+ self.faces = [
44
+ [0, 1, 3, 2],
45
+ [4, 6, 7, 5],
46
+ [0, 4, 5, 1],
47
+ [2, 3, 7, 6],
48
+ [0, 2, 6, 4],
49
+ [1, 5, 7, 3],
50
+ ]
51
+
52
+ def get_rotation_matrix(self):
53
+ """Return 3x3 rotation matrix (without translation)."""
54
+ return Matrix44.from_eulers((
55
+ math.radians(self.rotation.x),
56
+ math.radians(self.rotation.y),
57
+ math.radians(self.rotation.z)
58
+ )).transpose()[:3, :3] # extract 3x3 rotation
59
+
60
+ def get_corners(self):
61
+ """Return the 8 corners of the cuboid with rotation applied."""
62
+ corners = []
63
+ half_size = self.size / 2
64
+ rot = self.get_rotation_matrix()
65
+
66
+ for dx, dy, dz in product([-1, 1], repeat=3):
67
+ local = np.array([dx * half_size.x, dy * half_size.y, dz * half_size.z])
68
+ rotated = rot @ local
69
+ world = self.pos + vector3d(*rotated)
70
+ corners.append(world)
71
+
72
+ return corners
73
+
74
+ def is_point_in(self, point: vector3d) -> bool:
75
+ """
76
+ Checks if a point is inside the cuboid, accounting for full 3D rotation.
77
+ """
78
+ # Convert to numpy for math
79
+ p = np.array([point.x, point.y, point.z])
80
+ center = np.array([self.pos.x, self.pos.y, self.pos.z])
81
+ half = np.array([self.size.x / 2, self.size.y / 2, self.size.z / 2])
82
+
83
+ # Get inverse rotation matrix (undo rotation)
84
+ rot = self.get_rotation_matrix()
85
+ inv_rot = rot.T # inverse of rotation matrix is its transpose
86
+
87
+ # Transform point into cuboid's local coordinate system
88
+ local_point = inv_rot @ (p - center)
89
+
90
+ # Inside check in local space
91
+ return np.all(np.abs(local_point) <= half + 1e-6)
92
+
93
+ def draw(self, renderer: Renderer):
94
+ if not self.visible:
95
+ return
96
+ corners = self.get_corners()
97
+ for face_idx in self.faces:
98
+ renderer.render_quad(
99
+ corners[face_idx[0]],
100
+ corners[face_idx[1]],
101
+ corners[face_idx[2]],
102
+ corners[face_idx[3]],
103
+ color=self.color
104
+ )
105
+
106
+ class Sphere(GameObject):
107
+ def __init__(self, pos: vector3d = vector3d.zero,
108
+ radius: float = 5,
109
+ color: Color = Color.green,
110
+ segments: int = 32,
111
+ rings: int = 16,
112
+ name: str = "Sphere"):
113
+ super().__init__(name)
114
+ self.name = name
115
+ self.pos = pos
116
+ self.radius = radius
117
+ self.color = color
118
+ self.segments = segments
119
+ self.rings = rings
120
+ self.visible = True
121
+
122
+ def is_point_in(self, point: vector3d) -> bool:
123
+ dx = point.x - self.pos.x
124
+ dy = point.y - self.pos.y
125
+ dz = point.z - self.pos.z
126
+ distance_squared = dx*dx + dy*dy + dz*dz
127
+ return distance_squared <= self.radius * self.radius
128
+
129
+ def draw(self, renderer: Renderer):
130
+ if not self.visible:
131
+ return
132
+ renderer.render_sphere(self.pos, self.radius, self.color, self.segments, self.rings)
133
+
134
+ class Cylinder(GameObject):
135
+ def __init__(self, pos: vector3d = vector3d.zero,
136
+ length: float = 2,
137
+ radius: float = 0.5,
138
+ color: Color = Color.light_yellow,
139
+ segments: int = 32,
140
+ rotation: vector3d = vector3d.zero,
141
+ name: str = "Cylinder"):
142
+ super().__init__(name)
143
+ self.name = name
144
+ self.pos = pos
145
+ self.length = length
146
+ self.radius = radius
147
+ self.color = color
148
+ self.segments = segments
149
+ self.rotation = rotation # Euler angles in degrees
150
+ self.visible = True
151
+
152
+ def get_rotation_matrix(self):
153
+ rx, ry, rz = math.radians(self.rotation.x), math.radians(self.rotation.y), math.radians(self.rotation.z)
154
+ cx, sx = math.cos(rx), math.sin(rx)
155
+ cy, sy = math.cos(ry), math.sin(ry)
156
+ cz, sz = math.cos(rz), math.sin(rz)
157
+ # Rotation matrices
158
+ Rx = np.array([[1,0,0],[0,cx,-sx],[0,sx,cx]])
159
+ Ry = np.array([[cy,0,sy],[0,1,0],[-sy,0,cy]])
160
+ Rz = np.array([[cz,-sz,0],[sz,cz,0],[0,0,1]])
161
+ return Rz @ Ry @ Rx # apply in XYZ order
162
+
163
+ def is_point_in(self, point: vector3d, eps=1e-9) -> bool:
164
+ p = np.array([point.x, point.y, point.z])
165
+ center = np.array([self.pos.x, self.pos.y, self.pos.z])
166
+
167
+ # Transform point into cylinder local space
168
+ R = self.get_rotation_matrix()
169
+ invR = R.T # inverse rotation
170
+ local = invR @ (p - center)
171
+
172
+ # Check axial bounds (Y axis)
173
+ half_length = self.length / 2
174
+ if not (-half_length - eps <= local[1] <= half_length + eps):
175
+ return False
176
+
177
+ # Check radial distance in XZ plane
178
+ radial_dist_sq = local[0]**2 + local[2]**2
179
+ return radial_dist_sq <= (self.radius + eps)**2
180
+
181
+ def draw(self, renderer: Renderer):
182
+ if not self.visible:
183
+ return
184
+ renderer.render_cylinder(center=self.pos, height=self.length, radius=self.radius,
185
+ color=self.color, segments=self.segments, rotation=self.rotation)
gamengine3d/helper.py ADDED
@@ -0,0 +1,649 @@
1
+ import sys
2
+ import importlib.util
3
+ import math
4
+ import moderngl
5
+ import pygame
6
+ from pygame.locals import DOUBLEBUF, OPENGL
7
+ import importlib.resources as pkg_resources
8
+ import numpy as np
9
+ from pyrr import Matrix44
10
+ import os
11
+
12
+ class classproperty(property):
13
+ def __get__(self, cls, owner):
14
+ return self.fget(owner)
15
+
16
+ class vector3d:
17
+ def __init__(self, x, y=None, z=None):
18
+ self.x = x
19
+ self.y = y
20
+ self.z = z
21
+
22
+ if y is None and z is None:
23
+ self.y = self.x
24
+ self.z = self.x
25
+ elif z is None:
26
+ self.z = 0.0
27
+
28
+ @property
29
+ def magnitude(self):
30
+ return math.sqrt(self.x**2 + self.y**2 + self.z**2)
31
+
32
+ @property
33
+ def sqr_magnitude(self):
34
+ return self.x**2 + self.y**2 + self.z**2
35
+
36
+ def normalize(self):
37
+ magnitude = self.magnitude
38
+ if magnitude != 0:
39
+ self.x /= magnitude
40
+ self.y /= magnitude
41
+ self.z /= magnitude
42
+
43
+ @property
44
+ def normalized(self):
45
+ magnitude = self.magnitude
46
+ if magnitude == 0:
47
+ return vector3d(0, 0, 0)
48
+ return vector3d(self.x / magnitude, self.y / magnitude, self.z / magnitude)
49
+
50
+ def dot(self, other):
51
+ return self.x * other.x + self.y * other.y + self.z * other.z
52
+
53
+ def cross(self, other):
54
+ return vector3d(
55
+ self.y * other.z - self.z * other.y,
56
+ self.z * other.x - self.x * other.z,
57
+ self.x * other.y - self.y * other.x,
58
+ )
59
+
60
+ def __add__(self, other):
61
+ if isinstance(other, vector3d):
62
+ return vector3d(self.x + other.x, self.y + other.y, self.z + other.z)
63
+ else:
64
+ return vector3d(self.x + other, self.y + other, self.z + other)
65
+
66
+ def __sub__(self, other):
67
+ if isinstance(other, vector3d):
68
+ return vector3d(self.x - other.x, self.y - other.y, self.z - other.z)
69
+ else:
70
+ return vector3d(self.x - other, self.y - other, self.z - other)
71
+
72
+ def __mul__(self, other):
73
+ if isinstance(other, vector3d):
74
+ return vector3d(self.x * other.x, self.y * other.y, self.z * other.z)
75
+ else:
76
+ return vector3d(self.x * other, self.y * other, self.z * other)
77
+
78
+ def __truediv__(self, other):
79
+ if isinstance(other, vector3d):
80
+ return vector3d(self.x / other.x, self.y / other.y, self.z / other.z)
81
+ else:
82
+ return vector3d(self.x / other, self.y / other, self.z / other)
83
+
84
+ def totuple(self):
85
+ return (self.x, self.y, self.z)
86
+
87
+ def __radd__(self, other):
88
+ return vector3d(self.x + other, self.y + other, self.z + other)
89
+
90
+ def __rsub__(self, other):
91
+ return vector3d(self.x - other, self.y - other, self.z - other)
92
+
93
+ def __rtruediv__(self, other):
94
+ return vector3d(self.x / other, self.y / other, self.z / other)
95
+
96
+ def __rmul__(self, other):
97
+ return vector3d(self.x * other, self.y * other, self.z * other)
98
+
99
+ @classmethod
100
+ def fromtuple(cls, tuple):
101
+ return cls(*tuple)
102
+
103
+ def __repr__(self):
104
+ return f"vector3d({self.x}, {self.y}, {self.z})"
105
+
106
+ def copy(self):
107
+ return vector3d(self.x, self.y, self.z)
108
+
109
+ def __neg__(self):
110
+ return vector3d(-self.x, -self.y, -self.z)
111
+
112
+ @classproperty
113
+ def up(cls):
114
+ return cls(0, 1, 0)
115
+
116
+ @classproperty
117
+ def down(cls):
118
+ return cls(0, -1, 0)
119
+
120
+ @classproperty
121
+ def right(cls):
122
+ return cls(1, 0, 0)
123
+
124
+ @classproperty
125
+ def left(cls):
126
+ return cls(-1, 0, 0)
127
+
128
+ @classproperty
129
+ def forward(cls):
130
+ return cls(0, 0, 1)
131
+
132
+ @classproperty
133
+ def back(cls):
134
+ return cls(0, 0, -1)
135
+
136
+ @classproperty
137
+ def one(cls):
138
+ return cls(1, 1, 1)
139
+
140
+ @classproperty
141
+ def zero(cls):
142
+ return cls(0, 0, 0)
143
+
144
+ class Color:
145
+ def __init__(self, r, g, b):
146
+ self.r = r
147
+ self.g = g
148
+ self.b = b
149
+
150
+ @staticmethod
151
+ def RGB(r, g, b): return Color(r, g, b)
152
+
153
+ @staticmethod
154
+ def hex(hex_string):
155
+ if not hex_string.startswith("#"): raise Exception("String must start with #")
156
+ if not len(hex_string) == 7: raise Exception("String must contain 7 characters")
157
+ r = int(hex_string[1:3], 16)
158
+ g = int(hex_string[3:5], 16)
159
+ b = int(hex_string[5:7], 16)
160
+ return Color(r, g, b)
161
+
162
+ def __eq__(self, other):
163
+ if self.r == other.r and self.g == other.g and self.b == other.b:
164
+ return True
165
+ return False
166
+
167
+ def to_hex(self):
168
+ if not all(0 <= x <= 255 for x in (self.r, self.g, self.b)):
169
+ raise ValueError("RGB values must be in the range 0-255")
170
+ return "#{:02X}{:02X}{:02X}".format(self.r, self.g, self.b)
171
+
172
+ def to_rgb(self):
173
+ return self.r, self.g, self.b
174
+
175
+ @classproperty
176
+ def black(cls):
177
+ return cls(0, 0, 0)
178
+
179
+ @classproperty
180
+ def white(cls):
181
+ return cls(255, 255, 255)
182
+
183
+ @classproperty
184
+ def red(cls): return cls(255, 0, 0)
185
+
186
+ @classproperty
187
+ def green(cls): return cls(0, 255, 0)
188
+
189
+ @classproperty
190
+ def blue(cls): return cls(0, 0, 255)
191
+
192
+ @classproperty
193
+ def yellow(cls): return cls(255, 255, 0)
194
+
195
+ @classproperty
196
+ def cyan(cls): return cls(0, 255, 255)
197
+
198
+ @classproperty
199
+ def magenta(cls): return cls(255, 0, 255)
200
+
201
+ @classproperty
202
+ def grey(cls): return cls(33, 33, 33)
203
+
204
+ @classproperty
205
+ def light_grey(cls): return cls(80, 80, 80)
206
+
207
+ @classproperty
208
+ def light_red(cls): return cls(253, 89, 111)
209
+
210
+ @classproperty
211
+ def light_green(cls): return cls(0, 190, 160)
212
+
213
+ @classproperty
214
+ def light_yellow(cls): return cls(254, 208, 95)
215
+
216
+ @classproperty
217
+ def orange(cls): return cls(254, 166, 93)
218
+
219
+ @classproperty
220
+ def light_blue(cls): return cls(109, 154, 218)
221
+
222
+ class Light:
223
+ def __init__(self, position: vector3d, color: Color, intensity: float = 1.0, show=False, name="Light"):
224
+ self.position = position
225
+ self.color = color
226
+ self.intensity = intensity
227
+ self.show = show
228
+ self.name = name
229
+
230
+ class Renderer:
231
+ def __init__(self, width=800, height=600, flags=DOUBLEBUF | OPENGL):
232
+ pygame.init()
233
+ self.screen = pygame.display.set_mode((width, height), flags)
234
+ self.ctx = moderngl.create_context()
235
+ self.lights = []
236
+ self.width = width
237
+ self.height = height
238
+
239
+ self.ambient = 0.2
240
+
241
+ self.ctx.enable(moderngl.DEPTH_TEST)
242
+
243
+ self.prog = self._load_shader("default.vert", "default.frag")
244
+ self.prog["model"].write(np.eye(4, dtype="f4").tobytes())
245
+
246
+ self.proj = Matrix44.perspective_projection(60.0, width / height, 0.1, 100.0)
247
+ self.view = Matrix44.look_at(
248
+ eye=(3.0, 2.0, 3.0),
249
+ target=(0.0, 0.0, 0.0),
250
+ up=(0.0, 1.0, 0.0)
251
+ )
252
+
253
+ self.mvp = self.proj * self.view
254
+ self.prog["mvp"].write(self.mvp.astype("f4").tobytes())
255
+ self.prog["ambient"].value = self.ambient
256
+
257
+ def resize(self, width, height):
258
+ self.width = width
259
+ self.height = height
260
+ pygame.display.set_mode((width, height), pygame.OPENGL | pygame.DOUBLEBUF | (
261
+ pygame.RESIZABLE if self.width and self.height else 0))
262
+ self.ctx.viewport = (0, 0, width, height)
263
+
264
+ self.proj = Matrix44.perspective_projection(60.0, width / height, 0.1, 100.0)
265
+ self.mvp = self.proj * self.view
266
+ self.prog["mvp"].write(self.mvp.astype("f4").tobytes())
267
+
268
+ def add_light(self, light: Light):
269
+ self.lights.append(light)
270
+
271
+ def _compute_normal(self, p1, p2, p3):
272
+ u = p2 - p1
273
+ v = p3 - p1
274
+ return u.cross(v).normalized
275
+
276
+ def render_plane(self, p1, p2, p3, color):
277
+ normal = self._compute_normal(p1, p2, p3)
278
+
279
+ vertices = np.array([
280
+ *p1.totuple(), *color.to_rgb(), *normal.totuple(),
281
+ *p2.totuple(), *color.to_rgb(), *normal.totuple(),
282
+ *p3.totuple(), *color.to_rgb(), *normal.totuple()
283
+ ], dtype="f4")
284
+
285
+ vbo = self.ctx.buffer(vertices.tobytes())
286
+ vao = self.ctx.vertex_array(
287
+ self.prog,
288
+ [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
289
+ )
290
+
291
+ self._send_lights()
292
+ vao.render()
293
+ vao.release()
294
+ vbo.release()
295
+
296
+ def render_quad(self, p1, p2, p3, p4, color):
297
+ normal = self._compute_normal(p1, p2, p3)
298
+
299
+ vertices = np.array([
300
+ *p1.totuple(), *color.to_rgb(), *normal.totuple(),
301
+ *p2.totuple(), *color.to_rgb(), *normal.totuple(),
302
+ *p3.totuple(), *color.to_rgb(), *normal.totuple(),
303
+ *p1.totuple(), *color.to_rgb(), *normal.totuple(),
304
+ *p3.totuple(), *color.to_rgb(), *normal.totuple(),
305
+ *p4.totuple(), *color.to_rgb(), *normal.totuple()
306
+ ], dtype="f4")
307
+
308
+ vbo = self.ctx.buffer(vertices.tobytes())
309
+ vao = self.ctx.vertex_array(
310
+ self.prog,
311
+ [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
312
+ )
313
+
314
+ self._send_lights()
315
+ vao.render()
316
+ vao.release()
317
+ vbo.release()
318
+
319
+ def render_sphere(self, center, radius, color, segments=32, rings=16):
320
+ vertices = []
321
+ normals = []
322
+
323
+ for i in range(rings):
324
+ theta1 = math.pi * i / rings
325
+ theta2 = math.pi * (i + 1) / rings
326
+
327
+ for j in range(segments):
328
+ phi1 = 2 * math.pi * j / segments
329
+ phi2 = 2 * math.pi * (j + 1) / segments
330
+
331
+ p1 = vector3d(
332
+ radius * math.sin(theta1) * math.cos(phi1),
333
+ radius * math.cos(theta1),
334
+ radius * math.sin(theta1) * math.sin(phi1)
335
+ ) + center
336
+
337
+ p2 = vector3d(
338
+ radius * math.sin(theta2) * math.cos(phi1),
339
+ radius * math.cos(theta2),
340
+ radius * math.sin(theta2) * math.sin(phi1)
341
+ ) + center
342
+
343
+ p3 = vector3d(
344
+ radius * math.sin(theta2) * math.cos(phi2),
345
+ radius * math.cos(theta2),
346
+ radius * math.sin(theta2) * math.sin(phi2)
347
+ ) + center
348
+
349
+ p4 = vector3d(
350
+ radius * math.sin(theta1) * math.cos(phi2),
351
+ radius * math.cos(theta1),
352
+ radius * math.sin(theta1) * math.sin(phi2)
353
+ ) + center
354
+
355
+ for tri in [(p1, p2, p3), (p1, p3, p4)]:
356
+ n1 = (tri[0] - center).normalized
357
+ n2 = (tri[1] - center).normalized
358
+ n3 = (tri[2] - center).normalized
359
+
360
+ vertices.extend([
361
+ *tri[0].totuple(), *color.to_rgb(), *n1.totuple(),
362
+ *tri[1].totuple(), *color.to_rgb(), *n2.totuple(),
363
+ *tri[2].totuple(), *color.to_rgb(), *n3.totuple(),
364
+ ])
365
+
366
+ vertices = np.array(vertices, dtype="f4")
367
+
368
+ vbo = self.ctx.buffer(vertices.tobytes())
369
+ vao = self.ctx.vertex_array(
370
+ self.prog,
371
+ [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
372
+ )
373
+
374
+ self._send_lights()
375
+ vao.render()
376
+ vao.release()
377
+ vbo.release()
378
+
379
+
380
+ def render_cylinder(self, center, height, radius, color, segments=32, rotation=vector3d.zero):
381
+ vertices = []
382
+
383
+ half_h = height / 2.0
384
+
385
+ rx, ry, rz = map(math.radians, (rotation.x, rotation.y, rotation.z))
386
+
387
+ rot_x = np.array([
388
+ [1, 0, 0],
389
+ [0, math.cos(rx), -math.sin(rx)],
390
+ [0, math.sin(rx), math.cos(rx)]
391
+ ], dtype="f4")
392
+
393
+ rot_y = np.array([
394
+ [ math.cos(ry), 0, math.sin(ry)],
395
+ [0, 1, 0],
396
+ [-math.sin(ry), 0, math.cos(ry)]
397
+ ], dtype="f4")
398
+
399
+ rot_z = np.array([
400
+ [math.cos(rz), -math.sin(rz), 0],
401
+ [math.sin(rz), math.cos(rz), 0],
402
+ [0, 0, 1]
403
+ ], dtype="f4")
404
+
405
+ # Combined rotation matrix (Z * Y * X)
406
+ rotation_matrix = rot_z @ rot_y @ rot_x
407
+
408
+ def apply_rotation(v: vector3d):
409
+ vec = np.array([[v.x], [v.y], [v.z]], dtype="f4")
410
+ rotated = rotation_matrix @ vec
411
+ return vector3d(rotated[0][0], rotated[1][0], rotated[2][0])
412
+
413
+ for i in range(segments):
414
+ theta1 = 2 * math.pi * i / segments
415
+ theta2 = 2 * math.pi * (i + 1) / segments
416
+
417
+ x1, z1 = radius * math.cos(theta1), radius * math.sin(theta1)
418
+ x2, z2 = radius * math.cos(theta2), radius * math.sin(theta2)
419
+
420
+ # Cylinder face vertices
421
+ p1 = vector3d(x1, -half_h, z1)
422
+ p2 = vector3d(x2, -half_h, z2)
423
+ p3 = vector3d(x2, half_h, z2)
424
+ p4 = vector3d(x1, half_h, z1)
425
+
426
+ # Apply rotation
427
+ p1 = apply_rotation(p1) + center
428
+ p2 = apply_rotation(p2) + center
429
+ p3 = apply_rotation(p3) + center
430
+ p4 = apply_rotation(p4) + center
431
+
432
+ n1 = apply_rotation(vector3d(x1, 0, z1).normalized)
433
+ n2 = apply_rotation(vector3d(x2, 0, z2).normalized)
434
+
435
+ # Side faces
436
+ vertices.extend([
437
+ *p1.totuple(), *color.to_rgb(), *n1.totuple(),
438
+ *p2.totuple(), *color.to_rgb(), *n2.totuple(),
439
+ *p3.totuple(), *color.to_rgb(), *n2.totuple(),
440
+
441
+ *p1.totuple(), *color.to_rgb(), *n1.totuple(),
442
+ *p3.totuple(), *color.to_rgb(), *n2.totuple(),
443
+ *p4.totuple(), *color.to_rgb(), *n1.totuple(),
444
+ ])
445
+
446
+ # Base
447
+ base_normal = apply_rotation(vector3d(0, -1, 0))
448
+ vertices.extend([
449
+ *apply_rotation(vector3d(0, -half_h, 0) + center).totuple(), *color.to_rgb(), *base_normal.totuple(),
450
+ *p2.totuple(), *color.to_rgb(), *base_normal.totuple(),
451
+ *p1.totuple(), *color.to_rgb(), *base_normal.totuple(),
452
+ ])
453
+
454
+ # Top
455
+ top_normal = apply_rotation(vector3d(0, 1, 0))
456
+ vertices.extend([
457
+ *apply_rotation(vector3d(0, half_h, 0) + center).totuple(), *color.to_rgb(), *top_normal.totuple(),
458
+ *p4.totuple(), *color.to_rgb(), *top_normal.totuple(),
459
+ *p3.totuple(), *color.to_rgb(), *top_normal.totuple(),
460
+ ])
461
+
462
+ vertices = np.array(vertices, dtype="f4")
463
+ vbo = self.ctx.buffer(vertices.tobytes())
464
+ vao = self.ctx.vertex_array(
465
+ self.prog,
466
+ [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
467
+ )
468
+
469
+ self._send_lights()
470
+ vao.render()
471
+ vao.release()
472
+ vbo.release()
473
+
474
+ def _send_lights(self):
475
+ max_lights = 8
476
+ num_lights = min(len(self.lights), max_lights)
477
+ self.prog["num_lights"].value = num_lights
478
+ self.prog["ambient"].value = self.ambient
479
+ for i in range(num_lights):
480
+ light = self.lights[i]
481
+ self.prog[f"lights[{i}].position"].value = light.position.totuple()
482
+ self.prog[f"lights[{i}].color"].value = tuple(c / 255 for c in light.color.to_rgb())
483
+ self.prog[f"lights[{i}].intensity"].value = light.intensity
484
+
485
+ def clear(self, color=Color(26, 26, 31)):
486
+ color_f = np.array(color.to_rgb(), dtype="f4") / 255.0
487
+ self.ctx.clear(*color_f, depth=1.0)
488
+
489
+ def swap(self):
490
+ pygame.display.flip()
491
+
492
+ def quit(self):
493
+ pygame.quit()
494
+
495
+ def _load_shader(self, vert_name, frag_name):
496
+ vert_src = pkg_resources.read_text(f"{__package__}.shaders", "default.vert")
497
+ frag_src = pkg_resources.read_text(f"{__package__}.shaders", "default.frag")
498
+ return self.ctx.program(vertex_shader=vert_src, fragment_shader=frag_src)
499
+
500
+ class Camera:
501
+ def __init__(self, position=None, target=None, up=None, fov=60.0, aspect_ratio=4/3, near=0.1, far=100.0, orbiting=True):
502
+ self.orbiting = orbiting # New: toggle automatic look-at behavior
503
+ self.target = target or vector3d(0, 0, 0)
504
+ self.up = up or vector3d.up
505
+ self.fov = fov
506
+ self.aspect_ratio = aspect_ratio
507
+ self.near = near
508
+ self.far = far
509
+
510
+ # Compute spherical coordinates from initial position
511
+ pos = position or vector3d(3, 2, 3)
512
+ if self.orbiting:
513
+ self._update_spherical(pos)
514
+ self.position = pos
515
+
516
+ self._update_position()
517
+
518
+ def move_to(self, new_position: vector3d):
519
+ """
520
+ Move the camera to a new position.
521
+ If orbiting is enabled, updates spherical coordinates.
522
+ If orbiting is disabled, just sets position directly.
523
+ """
524
+ self.position = new_position
525
+ if self.orbiting:
526
+ self._update_spherical(new_position)
527
+ self._update_position()
528
+
529
+ def set_orbiting(self, orbiting: bool):
530
+ """Enable or disable automatic look-at behavior."""
531
+ self.orbiting = orbiting
532
+
533
+ def _update_spherical(self, pos):
534
+ """Convert position to spherical coordinates relative to target."""
535
+ dir_vec = pos - self.target
536
+ self.radius = dir_vec.magnitude
537
+ self.azimuth = math.atan2(dir_vec.z, dir_vec.x) # yaw
538
+ self.elevation = math.asin(dir_vec.y / self.radius) # pitch
539
+
540
+ def _update_position(self):
541
+ """Update Cartesian position and view/projection matrices."""
542
+ if self.orbiting:
543
+ x = self.radius * math.cos(self.elevation) * math.cos(self.azimuth)
544
+ y = self.radius * math.sin(self.elevation)
545
+ z = self.radius * math.cos(self.elevation) * math.sin(self.azimuth)
546
+ self.position = self.target + vector3d(x, y, z)
547
+
548
+ look_at = self.target if self.orbiting else self.position + getattr(self, "look_dir", vector3d(0, 0, -1))
549
+
550
+ self.view_matrix = Matrix44.look_at(
551
+ self.position.totuple(),
552
+ look_at.totuple(),
553
+ self.up.totuple()
554
+ )
555
+ self.projection_matrix = Matrix44.perspective_projection(
556
+ self.fov, self.aspect_ratio, self.near, self.far
557
+ )
558
+
559
+ def rotate_around_target(self, delta_azimuth_degrees, delta_elevation_degrees):
560
+ if not self.orbiting:
561
+ return # rotation disabled in free mode
562
+
563
+ self.azimuth += math.radians(delta_azimuth_degrees)
564
+ self.elevation += math.radians(delta_elevation_degrees)
565
+
566
+ # Handle elevation wrapping to allow full rotation without flipping
567
+ while self.elevation > math.pi / 2:
568
+ self.elevation = math.pi - self.elevation
569
+ self.azimuth += math.pi
570
+ self.up = -self.up # flip up vector
571
+
572
+ while self.elevation < -math.pi / 2:
573
+ self.elevation = -math.pi - self.elevation
574
+ self.azimuth += math.pi
575
+ self.up = -self.up # flip up vector
576
+
577
+ self._update_position()
578
+
579
+ def zoom(self, amount):
580
+ self.radius = max(self.radius - amount, 0.01)
581
+ self._update_position()
582
+
583
+ def update_renderer(self, renderer: Renderer):
584
+ renderer.view = self.view_matrix
585
+ renderer.proj = self.projection_matrix
586
+ renderer.mvp = renderer.proj * renderer.view
587
+ renderer.prog["mvp"].write(renderer.mvp.astype("f4").tobytes())
588
+
589
+ class Script:
590
+ def __init__(self, obj, script_path, context):
591
+ self.obj = obj
592
+ self.context = context
593
+ self.script_path = script_path
594
+ self.module = None
595
+ self.cls = None
596
+ self.instance = None
597
+ self.load(script_path)
598
+
599
+ def load(self, path):
600
+ if not os.path.exists(path):
601
+ print(f"[Script] File not found: {path}")
602
+ return
603
+ module_name = os.path.splitext(os.path.basename(path))[0]
604
+ spec = importlib.util.spec_from_file_location(module_name, path)
605
+ module = importlib.util.module_from_spec(spec)
606
+ sys.modules[module_name] = module
607
+ try:
608
+ spec.loader.exec_module(module)
609
+ except Exception as e:
610
+ print(f"[Script] Error loading module {path}: {e}")
611
+ return
612
+ self.module = module
613
+
614
+ # Class is PascalCase version of file name
615
+ class_name = ''.join(word.capitalize() for word in module_name.split('_'))
616
+ if hasattr(module, class_name):
617
+ self.cls = getattr(module, class_name)
618
+ else:
619
+ print(f"[Script] No class '{class_name}' found in {path}")
620
+
621
+ def init_instance(self):
622
+ if self.cls is None or self.instance is not None:
623
+ return
624
+ try:
625
+ self.instance = self.cls(self.obj, self.context)
626
+ except Exception as e:
627
+ print(f"[Script] Failed to instantiate script for {self.obj.name if hasattr(self.obj, "name") else "Engine"}: {e}")
628
+ self.instance = None
629
+
630
+ if self.instance and hasattr(self.instance, "start"):
631
+ try:
632
+ self.instance.start()
633
+ except Exception:
634
+ pass
635
+
636
+ def update(self, dt):
637
+ if self.instance is None:
638
+ return
639
+ self.instance.update(dt)
640
+
641
+ def run(self, func_name):
642
+ if self.instance is None:
643
+ return
644
+
645
+ func = getattr(self.instance, func_name)
646
+ func()
647
+
648
+ class EngineError(Exception):
649
+ pass
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: gamengine3d
3
+ Version: 1.0.0
4
+ Summary: A Unity-like 3D engine in Python using pygame
5
+ Author-email: Samarth Javagal <samarthjavagal@gmail.com>
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Classifier: Topic :: Games/Entertainment
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE.txt
13
+ Requires-Dist: moderngl==5.12.0
14
+ Requires-Dist: numpy==2.3.3
15
+ Requires-Dist: pygame==2.6.1
16
+ Requires-Dist: pyrr==0.10.3
17
+ Dynamic: license-file
18
+
19
+ GamEngine3D is a Python 3D engine for creating interactive 3D scenes. This README focuses on basic usage.
20
+
21
+ Quick Start
22
+
23
+ ```python
24
+ from gamengine3d import *
25
+
26
+ # 1. Initialize the engine
27
+ engine = Engine(1200, 800, background_color=Color.light_blue)
28
+
29
+ # 2. Create objects
30
+ floor = Cuboid(size=vector3d(5, 0.1, 5), color=Color.light_grey, name="Floor")
31
+ player = Cuboid(name="Player", color=Color.light_red, size=vector3d(0.2), pos=vector3d(0, 1))
32
+
33
+ # 3. Add objects to the engine
34
+ engine.add_object(floor)
35
+ engine.add_object(player)
36
+
37
+ # 4. Attach behavior to objects
38
+ player.attach("player_controller.py", engine.context)
39
+
40
+ # 5. Run the engine
41
+ engine.run(dynamic_view=True)
42
+ ```
43
+
44
+ Notes
45
+
46
+ Engine: Manages rendering, lights, and the main loop.
47
+
48
+ Objects: Add cubes, spheres, or custom shapes with Cuboid(), Sphere(), etc.
49
+
50
+ Attach Scripts: Use .attach("script.py", context) to add movement, input, or custom logic.
51
+
52
+ Run: engine.run() starts the simulation; dynamic_view=True enables interactive camera movement.
53
+
54
+ Example: player_controller.py
55
+
56
+ ```python
57
+ from gamengine3d import *
58
+ import math
59
+
60
+ class PlayerController:
61
+ def __init__(self, obj, context):
62
+ self.obj = obj
63
+ self.context = context
64
+ self.speed = 1
65
+ self.context.on_key_held("up", callback=self.move_forward, dt=True)
66
+
67
+ def update(self, dt):
68
+ pass # called every frame
69
+
70
+ def move_forward(self, dt):
71
+ # simple forward movement
72
+ yaw = math.radians(self.obj.rotation.z)
73
+ forward = vector3d(-math.sin(yaw), 0, math.cos(yaw))
74
+ self.obj.pos += forward * self.speed * dt
75
+ ```
76
+ This minimal PlayerController shows how to attach a script to an object and respond to input.
77
+
78
+ The 2d version of ```gamengine3d``` is out under ``gamengine2d``
@@ -0,0 +1,10 @@
1
+ gamengine3d/__init__.py,sha256=a3Gi4PXRfY-zbMva7vFGrBCuQIfmIFVEPRCCoIKFDDI,214
2
+ gamengine3d/context.py,sha256=on9Bn4IW66GKowjBYrNoxDGGZJZV9q05wof9OIdqPYI,4698
3
+ gamengine3d/engine.py,sha256=Z05f4us8thhdt40V543KF_OcaYj_u0fN_qGptgkSXMo,9395
4
+ gamengine3d/game_objects.py,sha256=eYj-Me65Yw5wk1M50SLsq4g2H7nFnBjdFoKhyWYdPIU,6471
5
+ gamengine3d/helper.py,sha256=mpA_gNByKsjnq1Hc5o_5kUaBPzrEthUcOnnQHeRj_j8,21822
6
+ gamengine3d-1.0.0.dist-info/licenses/LICENSE.txt,sha256=EN9ZVE9CW9_PQcxi9Ea_bdcac6nmoDcY2iUBvUCtzRE,1093
7
+ gamengine3d-1.0.0.dist-info/METADATA,sha256=WVPUR7ot5jQkOLYorkM3G7B5v6eSZQHGyPNYpcCbk6s,2402
8
+ gamengine3d-1.0.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ gamengine3d-1.0.0.dist-info/top_level.txt,sha256=Ec9K4OMz5AOSWcyjMk1bYkLxj0rHEu8jCcAYtbPofQs,12
10
+ gamengine3d-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Samarth Javagal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ gamengine3d