gamengine3d 1.5.2__tar.gz → 1.7.0__tar.gz

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.
Files changed (29) hide show
  1. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/PKG-INFO +3 -1
  2. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/README.md +2 -0
  3. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/__init__.py +1 -0
  4. gamengine3d-1.7.0/gamengine3d/cli.py +34 -0
  5. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/context.py +5 -1
  6. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/engine.py +36 -1
  7. gamengine3d-1.7.0/gamengine3d/examples/basics.py +11 -0
  8. gamengine3d-1.7.0/gamengine3d/examples/player_movement.py +83 -0
  9. gamengine3d-1.7.0/gamengine3d/examples/scripts/cylinder.py +23 -0
  10. gamengine3d-1.7.0/gamengine3d/examples/scripts/player_movement.py +94 -0
  11. gamengine3d-1.7.0/gamengine3d/examples/scripts/settings.py +6 -0
  12. gamengine3d-1.7.0/gamengine3d/examples/the_everything_demo.py +44 -0
  13. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/game_objects.py +90 -9
  14. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/helper.py +112 -16
  15. gamengine3d-1.7.0/gamengine3d/shaders/__init__.py +0 -0
  16. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/shaders/default.frag +4 -3
  17. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d.egg-info/PKG-INFO +3 -1
  18. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d.egg-info/SOURCES.txt +9 -0
  19. gamengine3d-1.7.0/gamengine3d.egg-info/entry_points.txt +2 -0
  20. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/pyproject.toml +4 -1
  21. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/LICENSE.txt +0 -0
  22. {gamengine3d-1.5.2/gamengine3d/shaders → gamengine3d-1.7.0/gamengine3d/examples}/__init__.py +0 -0
  23. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/shaders/default.vert +0 -0
  24. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/shaders/depth.frag +0 -0
  25. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d/shaders/depth.vert +0 -0
  26. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d.egg-info/dependency_links.txt +0 -0
  27. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d.egg-info/requires.txt +0 -0
  28. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/gamengine3d.egg-info/top_level.txt +0 -0
  29. {gamengine3d-1.5.2 → gamengine3d-1.7.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gamengine3d
3
- Version: 1.5.2
3
+ Version: 1.7.0
4
4
  Summary: A Unity-like 3D engine in Python using pygame
5
5
  Author-email: Samarth Javagal <samarthjavagal@gmail.com>
6
6
  Classifier: Programming Language :: Python :: 3
@@ -75,4 +75,6 @@ class PlayerController:
75
75
  ```
76
76
  This minimal PlayerController shows how to attach a script to an object and respond to input.
77
77
 
78
+ You can run any built-in demo with ``gamengine3d demo <demo_name>`` and see all available options using ``gamengine3d demo -h``.
79
+
78
80
  The 2d version of ```gamengine3d``` is out under ``gamengine2d``
@@ -57,4 +57,6 @@ class PlayerController:
57
57
  ```
58
58
  This minimal PlayerController shows how to attach a script to an object and respond to input.
59
59
 
60
+ You can run any built-in demo with ``gamengine3d demo <demo_name>`` and see all available options using ``gamengine3d demo -h``.
61
+
60
62
  The 2d version of ```gamengine3d``` is out under ``gamengine2d``
@@ -4,6 +4,7 @@ from .game_objects import (
4
4
  GameObject,
5
5
  Cuboid,
6
6
  Cylinder,
7
+ Sphere,
7
8
  )
8
9
 
9
10
  from .helper import (
@@ -0,0 +1,34 @@
1
+
2
+ import argparse
3
+ import runpy
4
+ from pathlib import Path
5
+
6
+ def main():
7
+ parser = argparse.ArgumentParser(prog="gamengine3d")
8
+ sub = parser.add_subparsers(dest="command", required=True)
9
+
10
+ # Get the list of available demos from the examples folder
11
+ examples_dir = Path(__file__).parent / "examples"
12
+ available_demos = [
13
+ f.stem for f in examples_dir.glob("*.py") if f.is_file() and f.name != "__init__.py"
14
+ ]
15
+
16
+ demo_cmd = sub.add_parser("demo", help="Run a built-in example")
17
+ demo_cmd.add_argument(
18
+ "demo_name",
19
+ nargs="?",
20
+ default="basics",
21
+ choices=available_demos, # restrict to available demos
22
+ help=f"The name of the example to run. Available: {', '.join(available_demos)}"
23
+ )
24
+
25
+ args = parser.parse_args()
26
+
27
+ if args.command == "demo":
28
+ module = f"gamengine3d.examples.{args.demo_name}"
29
+ print(f"Running example: {args.demo_name}")
30
+ print(f"Path: {module}")
31
+ runpy.run_module(module, run_name="__main__")
32
+
33
+ if __name__ == "__main__":
34
+ main()
@@ -104,6 +104,9 @@ class ScheduledCaller:
104
104
  self.caller_id = caller_id
105
105
  self.finished = False
106
106
  self.delay_obj = Delay(self.delay, self.callback)
107
+ self.forever = False
108
+ if n_times == -1:
109
+ self.forever = True
107
110
 
108
111
  def update(self):
109
112
  self.delay_obj.update()
@@ -111,7 +114,8 @@ class ScheduledCaller:
111
114
  self.n_times -= 1
112
115
  self.delay_obj = Delay(self.delay, self.callback)
113
116
 
114
- self.finished = self.n_times < 0
117
+ if not self.forever:
118
+ self.finished = self.n_times <= 0
115
119
 
116
120
  class RuntimeVars:
117
121
  def from_settings(self, module_name):
@@ -1,8 +1,9 @@
1
+ import json
1
2
  from itertools import product
2
3
  from pyrr import Matrix44
3
4
  from .context import Context
4
5
  import pygame
5
- from .game_objects import Cuboid, GameObject, Sphere
6
+ from .game_objects import Cuboid, GameObject, Sphere, Cylinder
6
7
  from .helper import Renderer, vector3d, Color, Camera, Light, EngineError, Script
7
8
  import math
8
9
 
@@ -261,3 +262,37 @@ class Engine:
261
262
  def init_scripts(self):
262
263
  for script in self.scripts:
263
264
  script.init_instance()
265
+
266
+ def save_scene(self, filename):
267
+ all_gameobjects = []
268
+ for obj in self.gameobjects:
269
+ all_gameobjects.append(obj.serialize())
270
+
271
+ all_lights = []
272
+ for light in self.renderer.lights:
273
+ all_lights.append(light.serialize())
274
+
275
+ with open(filename, "w") as f:
276
+ json.dump({"game-objects": all_gameobjects, "lights": all_lights}, f, indent=4)
277
+
278
+ def load_scene(self, filename):
279
+ with open(filename, "r") as f:
280
+ data = json.load(f)
281
+
282
+ lights = data["lights"]
283
+ for light in lights:
284
+ self.renderer.add_light(Light.deserialize(light))
285
+
286
+ gameobjects = data["game-objects"]
287
+ for gameobject in gameobjects:
288
+ if gameobject["type"] == "cuboid":
289
+ obj = Cuboid.deserialize(gameobject, self.context)
290
+ self.add_object(obj)
291
+
292
+ elif gameobject["type"] == "sphere":
293
+ obj = Sphere.deserialize(gameobject, self.context)
294
+ self.add_object(obj)
295
+
296
+ elif gameobject["type"] == "cylinder":
297
+ obj = Cylinder.deserialize(gameobject, self.context)
298
+ self.add_object(obj)
@@ -0,0 +1,11 @@
1
+ from gamengine3d import Engine, Cuboid, vector3d, Light, Color # import all the classes
2
+
3
+ engine = Engine(500, 500, resizable=True, name="Basics Demo", background_color=Color.light_blue, ambient_light=0.4) # define the Engine object.
4
+
5
+ floor = Cuboid(pos=vector3d.zero, size=vector3d(10, .5, 10), color=Color.light_grey) # create the floor
6
+
7
+ engine.add_light(Light(position=vector3d(0, 4, .1), color=Color.white)) # create and add a light (x or z values of 0 don't create the light in this case, fixes are being made
8
+
9
+ engine.add_object(floor) # add the floor object
10
+
11
+ engine.run() # run the game
@@ -0,0 +1,83 @@
1
+ from pathlib import Path
2
+ from gamengine3d import Engine, vector3d, Color, Cuboid, Light
3
+
4
+ # Initialize engine
5
+ engine = Engine(
6
+ 1200, 800,
7
+ background_color=Color.light_blue,
8
+ ambient_light=0.3,
9
+ name="Player Movement Demo"
10
+ )
11
+
12
+ # Room setup
13
+ room_size = vector3d(5, 1.5, 2.5)
14
+ half_size = room_size / 2
15
+ room_color = Color.white
16
+ light_intensity = 0.3
17
+
18
+ # Camera positioning
19
+ engine.camera.move_to(vector3d(0.0, 1.4, 2.3))
20
+
21
+ # Floor
22
+ floor = Cuboid(
23
+ size=vector3d(room_size.x, 1, room_size.z),
24
+ color=Color.light_grey,
25
+ name="Floor",
26
+ pos=vector3d(0, 0.05 - 0.5)
27
+ )
28
+ engine.add_object(floor)
29
+
30
+ # Walls
31
+ left_wall = Cuboid(
32
+ pos=vector3d(-half_size.x, half_size.y, 0),
33
+ size=vector3d(0.1, room_size.y, room_size.z),
34
+ color=room_color,
35
+ name="Left"
36
+ )
37
+ engine.add_object(left_wall)
38
+
39
+ right_wall = Cuboid(
40
+ pos=vector3d(half_size.x, half_size.y, 0),
41
+ size=vector3d(0.1, room_size.y, room_size.z),
42
+ color=room_color,
43
+ name="Right"
44
+ )
45
+ engine.add_object(right_wall)
46
+
47
+ back_wall = Cuboid(
48
+ pos=vector3d(0, half_size.y, -half_size.z),
49
+ size=vector3d(room_size.x, room_size.y, 0.1),
50
+ color=room_color,
51
+ name="Back"
52
+ )
53
+ engine.add_object(back_wall)
54
+
55
+ # Player
56
+ player = Cuboid(
57
+ name="Player",
58
+ color=Color.light_red,
59
+ size=vector3d(0.2),
60
+ pos=vector3d(0, 1)
61
+ )
62
+ EXAMPLE_DIR = Path(__file__).parent
63
+ player_script = EXAMPLE_DIR / "scripts" / "player_movement.py" # get the player_movement script path
64
+
65
+ player.attach(player_script, engine.context) # attach movement script
66
+ # you can directly add a relative path like "scripts/player_movement.py"
67
+
68
+ engine.add_object(player)
69
+
70
+ # Lights
71
+ engine.add_light(Light(
72
+ vector3d(1/3 * room_size.x, room_size.y, 1),
73
+ Color.white,
74
+ light_intensity
75
+ ))
76
+ engine.add_light(Light(
77
+ vector3d(-1/3 * room_size.x, room_size.y, 1),
78
+ Color.white,
79
+ light_intensity
80
+ ))
81
+
82
+ # Run the demo
83
+ engine.run(dynamic_view=True)
@@ -0,0 +1,23 @@
1
+ from gamengine3d import *
2
+
3
+ class Cylinder:
4
+ def __init__(self, obj: Cylinder, context: Context):
5
+ self.obj = obj
6
+ self.context = context
7
+ self.color_idx = 0
8
+ self.obj.color = self.context.runtime_vars.cylinder_colors[0]
9
+ self.context.add_scheduled_caller(n_times=-1, delay=1, callback=self.switch_color)
10
+
11
+ def update(self, dt):
12
+ if "w" in self.context.keys_held:
13
+ self.context.functions.draw_cylinder(vector3d(4, 3, 5), 2, 1, Color.light_green, 32)
14
+
15
+ if "e" in self.context.keys_pressed:
16
+ self.context.functions.draw_sphere(vector3d(1, 5, 6), radius=1, color=Color.blue)
17
+
18
+ if "r" in self.context.keys_released:
19
+ self.context.functions.draw_cube(pos=vector3d(5, 1, 4), size=vector3d(.2, 1, .5), color=Color.orange)
20
+
21
+ def switch_color(self):
22
+ self.color_idx += 1
23
+ self.obj.color = self.context.runtime_vars.cylinder_colors[self.color_idx % self.context.runtime_vars.num_cylinder_colors]
@@ -0,0 +1,94 @@
1
+ from gamengine3d import vector3d, Context, Cuboid
2
+ import math
3
+
4
+
5
+ class PlayerMovement: # Class name must match file name in PascalCase
6
+ def __init__(self, obj: Cuboid, context: Context):
7
+ self.obj = obj
8
+ self.context = context
9
+
10
+ self.speed = 1 # units per second
11
+ self.rotate_speed = 100 # degrees per second
12
+ self.gravity = vector3d(0, -4.8, 0)
13
+ self.velocity = vector3d.zero
14
+
15
+ # Movement bindings
16
+ self.context.on_key_held("w", callback=self.handle_controls, dt=True, args=["forward"])
17
+ self.context.on_key_held("s", callback=self.handle_controls, dt=True, args=["backward"])
18
+ self.context.on_key_held("a", callback=self.handle_controls, dt=True, args=["left"])
19
+ self.context.on_key_held("d", callback=self.handle_controls, dt=True, args=["right"])
20
+ self.context.on_key_held("space", callback=self.handle_controls, dt=True, args=["up"])
21
+
22
+ self.obj.rotation = vector3d(0) # start facing forward
23
+
24
+
25
+ def update(self, dt):
26
+ # Gravity runs every frame
27
+ self.handle_gravity(dt)
28
+
29
+
30
+ def handle_controls(self, dt, direction):
31
+ forward = get_forward(self.obj.rotation) # forward relative to facing direction
32
+
33
+ if direction == "forward":
34
+ delta_pos = forward * self.speed * dt
35
+ self.obj.pos += delta_pos
36
+
37
+ # undo if hitting walls
38
+ if any([
39
+ self.context.functions.is_colliding(self.obj.name, "Left"),
40
+ self.context.functions.is_colliding(self.obj.name, "Right"),
41
+ self.context.functions.is_colliding(self.obj.name, "Back"),
42
+ ]):
43
+ self.obj.pos -= delta_pos
44
+
45
+ elif direction == "backward":
46
+ delta_pos = forward * self.speed * dt
47
+ self.obj.pos -= delta_pos
48
+
49
+ # undo if hitting walls
50
+ if any([
51
+ self.context.functions.is_colliding(self.obj.name, "Left"),
52
+ self.context.functions.is_colliding(self.obj.name, "Right"),
53
+ self.context.functions.is_colliding(self.obj.name, "Back"),
54
+ ]):
55
+ self.obj.pos += delta_pos
56
+
57
+ elif direction == "left":
58
+ self.obj.rotation.z -= self.rotate_speed * dt # turn left
59
+
60
+ elif direction == "right":
61
+ self.obj.rotation.z += self.rotate_speed * dt # turn right
62
+
63
+ elif direction == "up":
64
+ # jump only if grounded
65
+ if self.context.functions.is_colliding(self.obj.name, "Floor"):
66
+ self.velocity.y = 3
67
+ self.obj.pos.y += 0.1 # small lift to ensure gravity applies next frame
68
+
69
+
70
+ def handle_gravity(self, dt):
71
+ grounded = self.context.functions.is_colliding(self.obj.name, "Floor")
72
+
73
+ if not grounded:
74
+ self.velocity += self.gravity * dt # accelerate downward
75
+ else:
76
+ floor = self.context.functions.get_game_object("Floor")
77
+ self.obj.pos.y = floor.pos.y + floor.size.y/2 + self.obj.size.y/2 # snap to surface
78
+ self.velocity = vector3d.zero
79
+
80
+ # check predicted collision next frame
81
+ if self.context.functions.is_colliding_pos("Floor", self.obj.pos + self.velocity * dt):
82
+ floor = self.context.functions.get_game_object("Floor")
83
+ self.obj.pos.y = floor.pos.y + floor.size.y/2 + self.obj.size.y/2
84
+ else:
85
+ self.obj.pos += self.velocity * dt # apply gravity motion
86
+
87
+
88
+ def get_forward(rotation):
89
+ # Converts yaw (z rotation) into a directional vector on the XZ plane
90
+ yaw = math.radians(rotation.z)
91
+ fx = -math.sin(yaw)
92
+ fy = 0
93
+ fz = math.cos(yaw)
94
+ return vector3d(fx, fy, fz)
@@ -0,0 +1,6 @@
1
+ from gamengine3d import Color, vector3d
2
+
3
+ cylinder_colors = [Color.light_red, Color.light_green, Color.light_blue, Color.light_yellow, Color.orange, Color.magenta]
4
+ num_cylinder_colors = len(cylinder_colors)
5
+
6
+ sphere_pos = vector3d(0, 1, 4)
@@ -0,0 +1,44 @@
1
+ from gamengine3d import *
2
+ import random
3
+ from pathlib import Path
4
+
5
+ engine = Engine(1000, 800, name="The Everything DEMO", background_color=Color.grey)
6
+ engine.context.runtime_vars.from_settings("gamengine3d.examples.scripts.settings") # set the runtime vars from a module
7
+
8
+ positions = [
9
+ vector3d(0, 4, 0.5),
10
+ vector3d(-3, 2, 2),
11
+ vector3d(3, 3, -2),
12
+ vector3d(-2, 5, -3),
13
+ vector3d(4, 6, 4),
14
+ vector3d(1, 6, 7),
15
+ vector3d(-4, 3, 5),
16
+ vector3d(5, 5, 9),
17
+ vector3d(0, 7, -4),
18
+ vector3d(-5, 4, 3),
19
+ vector3d(2, 8, 2),
20
+ vector3d(3, 5, -5),
21
+ vector3d(-3, 6, 6),
22
+ vector3d(6, 3, 3)
23
+ ]
24
+
25
+ for pos in positions:
26
+ intensity = random.uniform(0.4, .8)
27
+ engine.add_light(Light(position=pos, color=Color.white, intensity=intensity))
28
+
29
+ EXAMPLE_DIR = Path(__file__).parent
30
+ scripts_dir = EXAMPLE_DIR / "scripts"
31
+
32
+ cylinder = Cylinder(vector3d.zero, 2, .5, Color.light_green, 64, vector3d(40, 60, 100), "Cylinder")
33
+ cylinder.attach(scripts_dir/"cylinder.py", engine.context)
34
+ engine.add_object(cylinder)
35
+
36
+ cuboid = Cuboid(vector3d(3, 2, 5), color=Color.orange, size=vector3d(2, 1, 3))
37
+ engine.add_object(cuboid)
38
+
39
+ sphere = Sphere(vector3d(0, 5, 2), color=Color.light_blue, radius=1, rings=32, segments=64)
40
+ engine.add_object(sphere)
41
+
42
+ engine.save_scene("scene.json")
43
+
44
+ engine.run()
@@ -9,6 +9,7 @@ class GameObject:
9
9
  def __init__(self, name):
10
10
  self.name = name
11
11
  self.scripts = []
12
+ self.script_paths = []
12
13
 
13
14
  def update(self, dt):
14
15
  for script in self.scripts:
@@ -18,10 +19,18 @@ class GameObject:
18
19
  pass
19
20
 
20
21
  def attach(self, file_path, context):
22
+ if isinstance(file_path, str):
23
+ self.script_paths.append(file_path)
24
+ else:
25
+ self.script_paths.append(str(file_path))
21
26
  script = Script(self, file_path, context)
22
27
  script.init_instance()
23
28
  self.scripts.append(script)
24
29
 
30
+ def attach_scripts(self, scripts, context):
31
+ for path in scripts:
32
+ self.attach(path, context)
33
+
25
34
  def init_scripts(self):
26
35
  for script in self.scripts:
27
36
  script.init_instance()
@@ -50,7 +59,6 @@ class Cuboid(GameObject):
50
59
  ]
51
60
 
52
61
  def get_rotation_matrix(self):
53
- """Return 3x3 rotation matrix (without translation)."""
54
62
  return Matrix44.from_eulers((
55
63
  math.radians(self.rotation.x),
56
64
  math.radians(self.rotation.y),
@@ -58,7 +66,6 @@ class Cuboid(GameObject):
58
66
  )).transpose()[:3, :3] # extract 3x3 rotation
59
67
 
60
68
  def get_corners(self):
61
- """Return the 8 corners of the cuboid with rotation applied."""
62
69
  corners = []
63
70
  half_size = self.size / 2
64
71
  rot = self.get_rotation_matrix()
@@ -72,22 +79,15 @@ class Cuboid(GameObject):
72
79
  return corners
73
80
 
74
81
  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
82
  p = np.array([point.x, point.y, point.z])
80
83
  center = np.array([self.pos.x, self.pos.y, self.pos.z])
81
84
  half = np.array([self.size.x / 2, self.size.y / 2, self.size.z / 2])
82
85
 
83
- # Get inverse rotation matrix (undo rotation)
84
86
  rot = self.get_rotation_matrix()
85
87
  inv_rot = rot.T # inverse of rotation matrix is its transpose
86
88
 
87
- # Transform point into cuboid's local coordinate system
88
89
  local_point = inv_rot @ (p - center)
89
90
 
90
- # Inside check in local space
91
91
  return np.all(np.abs(local_point) <= half + 1e-6)
92
92
 
93
93
  def draw(self, renderer: Renderer):
@@ -103,6 +103,31 @@ class Cuboid(GameObject):
103
103
  color=self.color
104
104
  )
105
105
 
106
+ def serialize(self):
107
+ return {
108
+ "type": "cuboid",
109
+ "pos": self.pos.totuple(),
110
+ "size": self.size.totuple(),
111
+ "color": self.color.to_rgb(),
112
+ "name": self.name,
113
+ "rotation": self.rotation.totuple(),
114
+ "scripts": self.script_paths,
115
+ }
116
+
117
+ @staticmethod
118
+ def deserialize(data, context):
119
+ pos = data["pos"]
120
+ size = data["size"]
121
+ color = data["color"]
122
+ name = data["name"]
123
+ rotation = data["rotation"]
124
+ scripts = data["scripts"]
125
+
126
+ obj = Cuboid(pos=vector3d.fromtuple(pos), color=Color.RGB(*color), size=vector3d.fromtuple(size), name=name, rotation=vector3d.fromtuple(rotation))
127
+ obj.attach_scripts(scripts, context)
128
+
129
+ return obj
130
+
106
131
  class Sphere(GameObject):
107
132
  def __init__(self, pos: vector3d = vector3d.zero,
108
133
  radius: float = 5,
@@ -131,6 +156,33 @@ class Sphere(GameObject):
131
156
  return
132
157
  renderer.render_sphere(self.pos, self.radius, self.color, self.segments, self.rings)
133
158
 
159
+ def serialize(self):
160
+ return {
161
+ "type": "sphere",
162
+ "pos": self.pos.totuple(),
163
+ "color": self.color.to_rgb(),
164
+ "radius": self.radius,
165
+ "segments": self.segments,
166
+ "rings": self.rings,
167
+ "name": self.name,
168
+ "scripts": self.script_paths
169
+ }
170
+
171
+ @staticmethod
172
+ def deserialize(data, context):
173
+ pos = data["pos"]
174
+ color = data["color"]
175
+ radius = data["radius"]
176
+ segments = data["segments"]
177
+ rings = data["rings"]
178
+ name = data["name"]
179
+ scripts = data["scripts"]
180
+
181
+ obj = Sphere(pos=vector3d.fromtuple(pos), color=Color.RGB(*color), radius=radius, segments=segments, rings=rings, name=name)
182
+ obj.attach_scripts(scripts, context)
183
+
184
+ return obj
185
+
134
186
  class Cylinder(GameObject):
135
187
  def __init__(self, pos: vector3d = vector3d.zero,
136
188
  length: float = 2,
@@ -183,3 +235,32 @@ class Cylinder(GameObject):
183
235
  return
184
236
  renderer.render_cylinder(center=self.pos, height=self.length, radius=self.radius,
185
237
  color=self.color, segments=self.segments, rotation=self.rotation)
238
+
239
+ def serialize(self):
240
+ return {
241
+ "type": "cylinder",
242
+ "pos": self.pos.totuple(),
243
+ "length": self.length,
244
+ "radius": self.radius,
245
+ "color": self.color.to_rgb(),
246
+ "segments": self.segments,
247
+ "rotation": self.rotation.totuple(),
248
+ "name": self.name,
249
+ "scripts": self.script_paths
250
+ }
251
+
252
+ @staticmethod
253
+ def deserialize(data, context):
254
+ pos = data["pos"]
255
+ length = data["length"]
256
+ radius = data["radius"]
257
+ color = data["color"]
258
+ segments = data["segments"]
259
+ rotation = data["rotation"]
260
+ name = data["name"]
261
+ scripts = data["scripts"]
262
+
263
+ obj = Cylinder(pos=vector3d.fromtuple(pos), length=length, radius=radius, color=Color.RGB(*color), segments=segments, rotation=vector3d.fromtuple(rotation), name=name)
264
+ obj.attach_scripts(scripts, context)
265
+
266
+ return obj
@@ -227,6 +227,24 @@ class Light:
227
227
  self.show = show
228
228
  self.name = name
229
229
 
230
+ def serialize(self):
231
+ return {
232
+ "position": self.position.totuple(),
233
+ "color": self.color.to_rgb(),
234
+ "intensity": self.intensity,
235
+ "show": self.show,
236
+ "name": self.name,
237
+ }
238
+
239
+ @staticmethod
240
+ def deserialize(data):
241
+ position = data["position"]
242
+ color = data["color"]
243
+ intensity = data["intensity"]
244
+ show = data["show"]
245
+ name = data["name"]
246
+
247
+ return Light(position=vector3d.fromtuple(position), color=Color.RGB(*color), intensity=intensity, show=show, name=name)
230
248
 
231
249
  class Renderer:
232
250
  def __init__(self, width=800, height=600, flags=DOUBLEBUF | OPENGL):
@@ -268,9 +286,6 @@ class Renderer:
268
286
  self.depth_prog = self._load_shader("depth.vert", "depth.frag")
269
287
  self.light_space_matrix = np.eye(4, dtype="f4")
270
288
 
271
- # ------------------------------------------
272
- # Window / Resize Handling
273
- # ------------------------------------------
274
289
  def resize(self, width, height):
275
290
  self.width = width
276
291
  self.height = height
@@ -308,9 +323,6 @@ class Renderer:
308
323
 
309
324
  self._send_lights()
310
325
 
311
- # ------------------------------------------
312
- # Light & Matrix
313
- # ------------------------------------------
314
326
  def add_light(self, light: Light):
315
327
  self.lights.append(light)
316
328
 
@@ -321,7 +333,7 @@ class Renderer:
321
333
 
322
334
  def compute_light_matrix(self, light: Light):
323
335
  """Compute light-space projection * view for shadow mapping."""
324
- light_proj = Matrix44.orthogonal_projection(-10, 10, -10, 10, 1, 30)
336
+ light_proj = Matrix44.orthogonal_projection(-20, 20, -20, 20, 1, 30)
325
337
  light_view = Matrix44.look_at(
326
338
  eye=light.position.totuple(),
327
339
  target=(0, 0, 0),
@@ -329,9 +341,6 @@ class Renderer:
329
341
  )
330
342
  return light_proj * light_view
331
343
 
332
- # ------------------------------------------
333
- # Shadow Pass
334
- # ------------------------------------------
335
344
  def render_shadow_pass(self, objects):
336
345
  """Render depth map from light's POV."""
337
346
  if not self.lights:
@@ -365,9 +374,6 @@ class Renderer:
365
374
 
366
375
  self.ctx.screen.use()
367
376
 
368
- # ------------------------------------------
369
- # Render Functions
370
- # ------------------------------------------
371
377
  def render_plane(self, p1, p2, p3, color):
372
378
  normal = self._compute_normal(p1, p2, p3)
373
379
  vertices = np.array([
@@ -387,6 +393,99 @@ class Renderer:
387
393
  vao.release()
388
394
  vbo.release()
389
395
 
396
+ def render_cylinder(self, center, height, radius, color, segments=32, rotation=vector3d(0, 0, 0)):
397
+ vertices = []
398
+
399
+ def apply_matrix(v: vector3d, m: Matrix44) -> vector3d:
400
+ vec4 = np.array([v.x, v.y, v.z, 1.0], dtype="f4")
401
+ transformed = m @ vec4
402
+ return vector3d(*transformed[:3])
403
+
404
+ def apply_matrix_normal(n: vector3d, m: Matrix44) -> vector3d:
405
+ vec4 = np.array([n.x, n.y, n.z, 0.0], dtype="f4") # w=0 for direction
406
+ transformed = m @ vec4
407
+ return vector3d(*transformed[:3]).normalized
408
+
409
+ # Precompute rotation matrix if rotation is provided
410
+ rot_x = Matrix44.from_x_rotation(math.radians(rotation.x))
411
+ rot_y = Matrix44.from_y_rotation(math.radians(rotation.y))
412
+ rot_z = Matrix44.from_z_rotation(math.radians(rotation.z))
413
+ rot_matrix = rot_z * rot_y * rot_x
414
+
415
+ for i in range(segments):
416
+ theta1 = 2 * math.pi * i / segments
417
+ theta2 = 2 * math.pi * (i + 1) / segments
418
+
419
+ # Top circle vertices
420
+ top1 = vector3d(radius * math.cos(theta1), height / 2, radius * math.sin(theta1))
421
+ top2 = vector3d(radius * math.cos(theta2), height / 2, radius * math.sin(theta2))
422
+
423
+ # Bottom circle vertices
424
+ bottom1 = vector3d(radius * math.cos(theta1), -height / 2, radius * math.sin(theta1))
425
+ bottom2 = vector3d(radius * math.cos(theta2), -height / 2, radius * math.sin(theta2))
426
+
427
+ # Apply rotation
428
+ top1 = apply_matrix(top1, rot_matrix)
429
+ top2 = apply_matrix(top2, rot_matrix)
430
+ bottom1 = apply_matrix(bottom1, rot_matrix)
431
+ bottom2 = apply_matrix(bottom2, rot_matrix)
432
+
433
+ # Translate to center
434
+ top1 += center
435
+ top2 += center
436
+ bottom1 += center
437
+ bottom2 += center
438
+
439
+ # Compute normals for sides
440
+ normal1 = vector3d(math.cos(theta1), 0, math.sin(theta1))
441
+ normal2 = vector3d(math.cos(theta2), 0, math.sin(theta2))
442
+ normal1 = apply_matrix_normal(normal1, rot_matrix)
443
+ normal2 = apply_matrix_normal(normal2, rot_matrix)
444
+
445
+ # Side quad (two triangles)
446
+ for tri in [(top1, bottom1, bottom2), (top1, bottom2, top2)]:
447
+ n1 = (tri[0] - center).normalized
448
+ n2 = (tri[1] - center).normalized
449
+ n3 = (tri[2] - center).normalized
450
+ vertices.extend([
451
+ *tri[0].totuple(), *color.to_rgb(), *n1.totuple(),
452
+ *tri[1].totuple(), *color.to_rgb(), *n2.totuple(),
453
+ *tri[2].totuple(), *color.to_rgb(), *n3.totuple(),
454
+ ])
455
+
456
+ # Top cap
457
+ top_center = vector3d(0, height / 2, 0)
458
+ top_center = apply_matrix(top_center, rot_matrix) + center
459
+ normal_top = apply_matrix_normal(vector3d(0, 1, 0), rot_matrix)
460
+ vertices.extend([
461
+ *top_center.totuple(), *color.to_rgb(), *normal_top.totuple(),
462
+ *top2.totuple(), *color.to_rgb(), *normal_top.totuple(),
463
+ *top1.totuple(), *color.to_rgb(), *normal_top.totuple(),
464
+ ])
465
+
466
+ # Bottom cap
467
+ bottom_center = vector3d(0, -height / 2, 0)
468
+ bottom_center = apply_matrix(bottom_center, rot_matrix) + center
469
+ normal_bottom = apply_matrix_normal(vector3d(0, -1, 0), rot_matrix)
470
+ vertices.extend([
471
+ *bottom_center.totuple(), *color.to_rgb(), *normal_bottom.totuple(),
472
+ *bottom1.totuple(), *color.to_rgb(), *normal_bottom.totuple(),
473
+ *bottom2.totuple(), *color.to_rgb(), *normal_bottom.totuple(),
474
+ ])
475
+
476
+ vertices = np.array(vertices, dtype="f4")
477
+ vbo = self.ctx.buffer(vertices.tobytes())
478
+ vao = self.ctx.vertex_array(
479
+ self.prog, [(vbo, "3f 3f 3f", "in_vert", "in_color", "in_normal")]
480
+ )
481
+ self._send_lights()
482
+ self.prog["light_space_matrix"].write(self.light_space_matrix.astype("f4").tobytes())
483
+ self.shadow_depth_tex.use(location=0)
484
+ self.prog["shadow_map"].value = 0
485
+ vao.render()
486
+ vao.release()
487
+ vbo.release()
488
+
390
489
  def render_quad(self, p1, p2, p3, p4, color):
391
490
  normal = self._compute_normal(p1, p2, p3)
392
491
  vertices = np.array([
@@ -451,9 +550,6 @@ class Renderer:
451
550
  vao.release()
452
551
  vbo.release()
453
552
 
454
- # ------------------------------------------
455
- # Utility
456
- # ------------------------------------------
457
553
  def _send_lights(self):
458
554
  max_lights = 8
459
555
  num_lights = min(len(self.lights), max_lights)
File without changes
@@ -27,7 +27,8 @@ void main() {
27
27
 
28
28
  for (int i = 0; i < num_lights; i++) {
29
29
  vec3 light_dir = normalize(lights[i].position - frag_pos);
30
- float diff = max(dot(normal, light_dir), 0.0);
30
+ float ndotl = dot(normal, light_dir);
31
+ float diff = max(ndotl, 0.05); // stable at grazing angles
31
32
 
32
33
  // Project to [0,1] for shadow sampling
33
34
  vec3 proj_coords = frag_pos_light_space.xyz / frag_pos_light_space.w;
@@ -38,8 +39,8 @@ void main() {
38
39
  if (proj_coords.x >= 0.0 && proj_coords.x <= 1.0 &&
39
40
  proj_coords.y >= 0.0 && proj_coords.y <= 1.0) {
40
41
 
41
- float bias = max(0.02 * (1.0 - dot(normal, light_dir)), 0.005);
42
-
42
+ float ndotl = dot(normal, light_dir);
43
+ float bias = mix(0.002, 0.02, 1.0 - clamp(ndotl, 0.0, 1.0));
43
44
  // Simple 3x3 PCF
44
45
  ivec2 texSize = textureSize(shadow_map, 0);
45
46
  float texelSizeX = 1.0 / float(texSize.x);
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gamengine3d
3
- Version: 1.5.2
3
+ Version: 1.7.0
4
4
  Summary: A Unity-like 3D engine in Python using pygame
5
5
  Author-email: Samarth Javagal <samarthjavagal@gmail.com>
6
6
  Classifier: Programming Language :: Python :: 3
@@ -75,4 +75,6 @@ class PlayerController:
75
75
  ```
76
76
  This minimal PlayerController shows how to attach a script to an object and respond to input.
77
77
 
78
+ You can run any built-in demo with ``gamengine3d demo <demo_name>`` and see all available options using ``gamengine3d demo -h``.
79
+
78
80
  The 2d version of ```gamengine3d``` is out under ``gamengine2d``
@@ -2,6 +2,7 @@ LICENSE.txt
2
2
  README.md
3
3
  pyproject.toml
4
4
  gamengine3d/__init__.py
5
+ gamengine3d/cli.py
5
6
  gamengine3d/context.py
6
7
  gamengine3d/engine.py
7
8
  gamengine3d/game_objects.py
@@ -9,8 +10,16 @@ gamengine3d/helper.py
9
10
  gamengine3d.egg-info/PKG-INFO
10
11
  gamengine3d.egg-info/SOURCES.txt
11
12
  gamengine3d.egg-info/dependency_links.txt
13
+ gamengine3d.egg-info/entry_points.txt
12
14
  gamengine3d.egg-info/requires.txt
13
15
  gamengine3d.egg-info/top_level.txt
16
+ gamengine3d/examples/__init__.py
17
+ gamengine3d/examples/basics.py
18
+ gamengine3d/examples/player_movement.py
19
+ gamengine3d/examples/the_everything_demo.py
20
+ gamengine3d/examples/scripts/cylinder.py
21
+ gamengine3d/examples/scripts/player_movement.py
22
+ gamengine3d/examples/scripts/settings.py
14
23
  gamengine3d/shaders/__init__.py
15
24
  gamengine3d/shaders/default.frag
16
25
  gamengine3d/shaders/default.vert
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ gamengine3d = gamengine3d.cli:main
@@ -5,7 +5,7 @@ build-backend = "setuptools.build_meta"
5
5
 
6
6
  [project]
7
7
  name = "gamengine3d"
8
- version = "1.5.2"
8
+ version = "1.7.0"
9
9
  description = "A Unity-like 3D engine in Python using pygame"
10
10
  authors = [
11
11
  { name = "Samarth Javagal", email = "samarthjavagal@gmail.com" }
@@ -31,5 +31,8 @@ classifiers = [
31
31
  where = ["."]
32
32
  include = ["gamengine3d*"]
33
33
 
34
+ [project.scripts]
35
+ gamengine3d = "gamengine3d.cli:main"
36
+
34
37
  [tool.setuptools.package-data]
35
38
  "gamengine3d" = ["shaders/*.vert", "shaders/*.frag"]
File without changes
File without changes