cosmo3d 0.0.1__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,234 @@
1
+ Metadata-Version: 2.4
2
+ Name: cosmo3d
3
+ Version: 0.0.1
4
+ Summary: Engine 3D em um único arquivo
5
+ Requires-Python: >=3.8
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: pygame-ce
8
+
9
+ # 🪐 Cosmo3D — Documentação Oficial
10
+
11
+ > **v0.1.0 • Single-File Engine**
12
+
13
+ Uma micro-engine 3D em Python inspirada na simplicidade do Ursina. Arquitetura monolítica de arquivo único (`cosmo3d.py`) com física AABB, auto-step e prefabs prontos para prototipagem rápida.
14
+
15
+ ---
16
+
17
+ ## Sumário
18
+
19
+ * [Visão Geral](#visão-geral)
20
+ * [Instalação & Setup](#instalação--setup)
21
+ * [Primeiro Jogo (Quickstart)](#primeiro-jogo-quickstart)
22
+ * [Prefabs: Entity & Box](#prefabs-entity--box)
23
+ * [Prefab: MenPlayer](#prefab-menplayer)
24
+ * [Prefab: floor (Terreno)](#prefab-floor-terreno)
25
+ * [Câmera: Camera3 (3ª Pessoa)](#câmera-camera3-3ª-pessoa)
26
+ * [Física AABB & Step-Up](#física-aabb--step-up)
27
+ * [Paleta de Cores](#paleta-de-cores)
28
+ * [Loop & `on_update` / `set_update()`](#loop--on_update--set_update)
29
+ * [Controles Padrão](#controles-padrão)
30
+
31
+ ---
32
+
33
+ ## Visão Geral
34
+
35
+ A **Cosmo3D** foi projetada para permitir a criação de protótipos e jogos 3D em Python com o mínimo de código possível, concentrando toda a engine em um único arquivo (`cosmo3d.py`).
36
+
37
+ ---
38
+
39
+ ## Instalação & Setup
40
+
41
+ Instale diretamente via `pip` pelo PyPI:
42
+
43
+ ```bash
44
+ pip install cosmo3d
45
+ ```
46
+
47
+ Caso prefira instalar as dependências gráficas manualmente (recomendado para Python 3.12 até 3.15+):
48
+
49
+ ```bash
50
+ python -m pip install pygame-ce PyOpenGL
51
+ ```
52
+
53
+ > **Por que `pygame-ce`?** A edição comunitária do Pygame possui pacotes binários pré-compilados para as versões mais recentes do Python no Windows, evitando erros de compilação C++. A importação no código continua sendo `import pygame`.
54
+
55
+ ---
56
+
57
+ ## Primeiro Jogo (Quickstart)
58
+
59
+ Crie um arquivo `main.py`. Com poucas linhas você já tem câmera orbital em terceira pessoa, personagem articulado com animação de caminhada, gravidade e plataformas de parkour:
60
+
61
+ ```python
62
+ import cosmo3d
63
+ from cosmo3d import RigBody, color
64
+
65
+ # 1. Câmera em terceira pessoa (vincula-se automaticamente ao player)
66
+ cam = cosmo3d.Camera3()
67
+
68
+ # 2. Personagem jogável com física, gravidade e colisão
69
+ player = cosmo3d.MenPlayer(gravity=1, collision=1, base=RigBody)
70
+
71
+ # 3. Chão sólido
72
+ floor = cosmo3d.floor(gravity=1, collision=1)
73
+
74
+ # 4. Plataformas de parkour
75
+ plat1 = cosmo3d.Box(position=(0, 1.2, -5), scale=(4, 0.5, 4), color=color.orange)
76
+ plat2 = cosmo3d.Box(position=(5, 2.6, -8), scale=(4, 0.5, 4), color=color.yellow)
77
+
78
+ # 5. Inicia o loop da engine (opcional se auto_run=True)
79
+ cosmo3d.run(title="Meu Jogo Cosmo3D")
80
+ ```
81
+
82
+ ---
83
+
84
+ ## Prefabs: Entity & Box
85
+
86
+ Todos os objetos visíveis da cena herdam de `Entity`. Os prefabs `Box` / `Cube` criam blocos 3D sólidos prontos para paredes, obstáculos, plataformas e caixas dinâmicas.
87
+
88
+ ```python
89
+ cosmo3d.Box(
90
+ position=(0, 1, -4), # Coordenadas (X, Y, Z) no mundo
91
+ scale=(2, 2, 2), # Largura, Altura e Profundidade
92
+ color=color.orange, # Cor RGB ou nome da paleta
93
+ gravity=0, # Multiplicador de gravidade (0 = sem gravidade)
94
+ collision=1, # 1 = sólido | 0 = atravessável
95
+ base=StaticBody # StaticBody (fixo) ou RigBody (dinâmico)
96
+ )
97
+ ```
98
+
99
+ | Parâmetro / Propriedade | Tipo | Padrão | Descrição |
100
+ | :--- | :--- | :--- | :--- |
101
+ | `position` | `tuple(x, y, z)` | `(0, 0, 0)` | Posição central da entidade no espaço 3D. |
102
+ | `scale` | `tuple(sx, sy, sz)` | `(1, 1, 1)` | Dimensões da malha visual e da caixa de colisão AABB. |
103
+ | `rotation` | `tuple(rx, ry, rz)` | `(0, 0, 0)` | Rotação em graus nos eixos X, Y e Z. |
104
+ | `color` | `tuple` / `str` | `color.white` | Cor RGB, hexadecimal (`"#ff8800"`) ou nome (`"orange"`). |
105
+ | `gravity` | `float \| int` | `0` | Intensidade da gravidade aplicada quando `base=RigBody`. |
106
+ | `collision` | `bool \| int` | `1` (Box) | Define se a entidade bloqueia e sofre colisões físicas. |
107
+ | `base` | `const / class` | `StaticBody` | `StaticBody` mantém o objeto imóvel; `RigBody` ativa física dinâmica. |
108
+
109
+ ---
110
+
111
+ ## Prefab: MenPlayer
112
+
113
+ Cria um personagem humanoide 3D articulado (cabeça, tronco, braços e pernas animados conforme a velocidade) com movimentação relativa à câmera e pulo integrado.
114
+
115
+ ```python
116
+ player = cosmo3d.MenPlayer(
117
+ position=(0, 3, 0),
118
+ speed=7.0,
119
+ jump_force=9.5,
120
+ gravity=1,
121
+ collision=1,
122
+ base=cosmo3d.RigBody
123
+ )
124
+ ```
125
+
126
+ | Parâmetro | Tipo | Padrão | Descrição |
127
+ | :--- | :--- | :--- | :--- |
128
+ | `position` | `tuple(x, y, z)` | `(0, 0, 0)` | Posição inicial do personagem no mundo. |
129
+ | `speed` | `float` | `7.0` | Velocidade horizontal de deslocamento. |
130
+ | `jump_force` | `float` | `9.5` | Impulso vertical aplicado ao pressionar espaço no chão. |
131
+ | `gravity` | `float \| int` | `1` | Multiplicador da gravidade aplicada ao jogador. |
132
+ | `collision` | `bool \| int` | `1` | Ativa colisão AABB contra o chão e obstáculos. |
133
+ | `base` | `class` | `RigBody` | Corpo rígido responsável pela simulação física. |
134
+
135
+ ---
136
+
137
+ ## Prefab: floor (Terreno)
138
+
139
+ Gera um plano de chão sólido em padrão xadrez para servir de base ao cenário.
140
+
141
+ ```python
142
+ floor = cosmo3d.floor(
143
+ position=(0, 0, 0),
144
+ size=80,
145
+ tile=4,
146
+ color="#5cae5c",
147
+ collision=1
148
+ )
149
+ ```
150
+
151
+ | Parâmetro | Tipo | Padrão | Descrição |
152
+ | :--- | :--- | :--- | :--- |
153
+ | `position` | `tuple(x, y, z)` | `(0, 0, 0)` | Coordenada da superfície superior do chão. |
154
+ | `size` | `float \| int` | `80` | Largura e profundidade total do terreno. |
155
+ | `tile` | `float \| int` | `4` | Tamanho de cada quadrado do padrão xadrez. |
156
+ | `color` | `tuple` / `str` | `"#5cae5c"` | Cor principal do piso (a cor secundária é gerada automaticamente). |
157
+ | `collision` | `bool \| int` | `1` | Define se o piso é sólido para entidades com física. |
158
+
159
+ ---
160
+
161
+ ## Câmera: Camera3 (3ª Pessoa)
162
+
163
+ Câmera orbital em terceira pessoa que segue suavemente o alvo (`MenPlayer` ou `target` customizado) com controle de rotação pelo mouse e zoom pela roda de rolagem.
164
+
165
+ ```python
166
+ cam = cosmo3d.Camera3(distance=7.0, height=1.5, fov=70.0)
167
+ ```
168
+
169
+ | Propriedade | Padrão | Descrição |
170
+ | :--- | :--- | :--- |
171
+ | `distance` | `7.0` | Distância entre a câmera e o personagem. |
172
+ | `height` | `1.5` | Altura do ponto de foco em relação à base do alvo. |
173
+ | `smooth` | `14.0` | Suavização do movimento de perseguição da câmera. |
174
+ | `fov` | `70.0` | Campo de visão (*Field of View*) em graus. |
175
+ | `sensitivity` | `0.0025` | Sensibilidade de rotação ao mover o mouse. |
176
+ | `target` | `None` | Entidade seguida pela câmera (se `None`, usa `scene.player`). |
177
+
178
+ ---
179
+
180
+ ## Física AABB & Step-Up
181
+
182
+ Entidades configuradas com `base=cosmo3d.RigBody` recebem simulação física automática:
183
+
184
+ * **Gravidade contínua:** Aceleração vertical controlada por `cosmo3d.GRAVITY` (padrão `24.0`) multiplicada pelo `gravity` da entidade.
185
+ * **Colisão AABB:** Resolução separada por eixos (`X`, `Z`, `Y`), permitindo deslizar contra paredes sem travar o movimento.
186
+ * **Auto-Step (`step_height`):** Quando o personagem está no chão e encontra um degrau ou desnível de até `0.45` unidades, sobe automaticamente sem precisar pular.
187
+ * **Respawn automático:** Caso a entidade caia abaixo de `Y = -60`, retorna automaticamente para sua posição inicial (`spawn`).
188
+
189
+ ---
190
+
191
+ ## Paleta de Cores
192
+
193
+ A classe `color` oferece cores prontas para uso direto, além de aceitar strings com nome (`"red"`), códigos hexadecimais (`"#ff8800"`) ou tuplas RGB:
194
+
195
+ * `color.white`, `color.black`, `color.gray`
196
+ * `color.red`, `color.green`, `color.blue`
197
+ * `color.yellow`, `color.orange`, `color.purple`, `color.pink`
198
+ * `color.cyan`, `color.azure`, `color.skyblue`, `color.royalblue`
199
+ * `color.brown`, `color.lime`, `color.gold`, `color.beige`
200
+
201
+ ---
202
+
203
+ ## Loop & `on_update` / `set_update()`
204
+
205
+ Você pode executar lógica personalizada a cada frame usando o decorador `@cosmo3d.on_update` (ou passando `update=` diretamente na criação da entidade):
206
+
207
+ ```python
208
+ cubo = cosmo3d.Box(position=(0, 2, -6), color=cosmo3d.color.cyan)
209
+
210
+ @cosmo3d.on_update
211
+ def atualizar(dt):
212
+ cubo.rotation_y += 90 * dt
213
+ ```
214
+
215
+ Para iniciar o loop manualmente caso `cosmo3d.auto_run = False`:
216
+
217
+ ```python
218
+ cosmo3d.run()
219
+ ```
220
+
221
+ ---
222
+
223
+ ## Controles Padrão
224
+
225
+ | Tecla / Ação | Função |
226
+ | :--- | :--- |
227
+ | **W A S D** / **Setas** | Mover personagem (relativo à direção da câmera) |
228
+ | **ESPAÇO** | Pular |
229
+ | **Mouse** | Girar câmera orbital |
230
+ | **Roda do Mouse** | Aproximar / afastar zoom |
231
+ | **ESC** | Liberar cursor do mouse (pressione novamente para fechar) |
232
+ | **F3** | Alternar informações de debug |
233
+ | **F12** | Salvar captura de tela (screenshot) |
234
+ # Para mais informações visite: https://lively-flan-80d822.netlify.app/
@@ -0,0 +1,5 @@
1
+ cosmo3d.py,sha256=JJL7p6XNAjkGmgFAXw1K7NWQ2DP0qfWCxmpcXa-vu1E,39365
2
+ cosmo3d-0.0.1.dist-info/METADATA,sha256=unu4x-Q1RdmuzgfmkHvoODc849UYHGJ6ebE_g_fxuic,8903
3
+ cosmo3d-0.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
4
+ cosmo3d-0.0.1.dist-info/top_level.txt,sha256=0NwhgHRcuiN3-IU0aeQg0s5nwdFCt3tSYWplDg2U4_M,8
5
+ cosmo3d-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ cosmo3d
cosmo3d.py ADDED
@@ -0,0 +1,895 @@
1
+ """
2
+ cosmo3d.py - engine 3D em UM único arquivo, feita para ser intuitiva.
3
+ Dependência: pygame (pip install pygame)
4
+
5
+ Exemplo mínimo (main.py):
6
+
7
+ import cosmo3d
8
+ cam = cosmo3d.Camera3 # câmera em 3ª pessoa
9
+ player = cosmo3d.MenPlayer(gravity=1, collision=1, base=cosmo3d.RigBody)
10
+ floor = cosmo3d.floor(gravity=1, collision=1)
11
+ # pronto: não precisa chamar run(), a engine inicia sozinha no fim do script
12
+
13
+ Controles: WASD/setas mover | ESPAÇO pular | MOUSE câmera | RODA zoom
14
+ ESC solta o mouse (ESC de novo fecha) | F3 debug | F12 screenshot
15
+
16
+ Mundo: X direita, Y cima, Z frente. Rotação em graus.
17
+ Renderização: rasterização por software (algoritmo do pintor) com sombreamento
18
+ plano, neblina e sombras em "blob". Ótimo para protótipos e cenas simples.
19
+ """
20
+ import atexit
21
+ import inspect
22
+ import math
23
+ import sys
24
+
25
+ try:
26
+ import pygame
27
+ except ImportError: # mensagem amigável
28
+ raise ImportError("cosmo3d precisa do pygame. Instale com: pip install pygame")
29
+
30
+ __version__ = "0.1.0"
31
+ __all__ = [
32
+ "Vec3", "color", "Mesh", "Entity", "Cube", "Sphere", "Cylinder", "Pyramid",
33
+ "Floor", "floor", "Wall", "Stairs", "Tree", "House", "MenPlayer", "Player",
34
+ "RigBody", "Text", "scene", "run", "held", "pressed", "on_update", "destroy",
35
+ ]
36
+
37
+ GRAVITY = 24.0 # aceleração base (multiplicada pelo gravity= de cada objeto)
38
+ auto_run = True # False => você chama cosmo3d.run() manualmente
39
+ _EPS = 1e-4
40
+
41
+
42
+ # ───────────────────────────── utilidades ──────────────────────────────
43
+ class Vec3:
44
+ """Vetor 3D simples: aceita Vec3(1,2,3), Vec3((1,2,3)), Vec3(2) -> (2,2,2)."""
45
+ __slots__ = ("x", "y", "z")
46
+
47
+ def __init__(self, x=0.0, y=None, z=None):
48
+ if y is None and z is None:
49
+ if isinstance(x, (int, float)):
50
+ x, y, z = x, x, x
51
+ else:
52
+ x, y, z = x
53
+ self.x, self.y, self.z = float(x), float(y), float(z)
54
+
55
+ def __iter__(self):
56
+ yield self.x; yield self.y; yield self.z
57
+ def __len__(self): return 3
58
+ def __getitem__(self, i): return (self.x, self.y, self.z)[i]
59
+ def __setitem__(self, i, v):
60
+ if i == 0: self.x = float(v)
61
+ elif i == 1: self.y = float(v)
62
+ else: self.z = float(v)
63
+ def __add__(self, o): o = Vec3(o); return Vec3(self.x + o.x, self.y + o.y, self.z + o.z)
64
+ __radd__ = __add__
65
+ def __sub__(self, o): o = Vec3(o); return Vec3(self.x - o.x, self.y - o.y, self.z - o.z)
66
+ def __rsub__(self, o): return Vec3(o) - self
67
+ def __mul__(self, k):
68
+ if isinstance(k, (int, float)): return Vec3(self.x * k, self.y * k, self.z * k)
69
+ k = Vec3(k); return Vec3(self.x * k.x, self.y * k.y, self.z * k.z)
70
+ __rmul__ = __mul__
71
+ def __truediv__(self, k): return Vec3(self.x / k, self.y / k, self.z / k)
72
+ def __neg__(self): return Vec3(-self.x, -self.y, -self.z)
73
+ def __repr__(self): return f"Vec3({self.x:.2f}, {self.y:.2f}, {self.z:.2f})"
74
+ def length(self): return math.sqrt(self.x ** 2 + self.y ** 2 + self.z ** 2)
75
+ def normalized(self):
76
+ l = self.length()
77
+ return Vec3(self.x / l, self.y / l, self.z / l) if l else Vec3(0, 0, 0)
78
+ def dot(self, o): o = Vec3(o); return self.x * o.x + self.y * o.y + self.z * o.z
79
+ def copy(self): return Vec3(self.x, self.y, self.z)
80
+
81
+
82
+ class color:
83
+ """Cores prontas: color.red, color.skyblue ... (ou use 'red', '#ff8800', (255,0,0))."""
84
+ white = (255, 255, 255); black = (20, 20, 24); gray = (140, 140, 150)
85
+ red = (220, 60, 60); green = (80, 190, 90); blue = (70, 110, 230)
86
+ yellow = (245, 215, 70); orange = (245, 150, 50); purple = (150, 90, 210)
87
+ pink = (240, 130, 190); cyan = (70, 210, 220); brown = (130, 85, 50)
88
+ lime = (150, 230, 70); azure = (60, 160, 240); skyblue = (135, 190, 235)
89
+ royalblue = (65, 105, 225); gold = (240, 190, 40); beige = (225, 205, 165)
90
+
91
+
92
+ def _rgba(c):
93
+ if c is None: return (255, 255, 255, 255)
94
+ if isinstance(c, str):
95
+ s = c.strip().lower()
96
+ if s.startswith("#"):
97
+ s = s[1:]
98
+ if len(s) == 3: s = "".join(ch * 2 for ch in s)
99
+ vals = [int(s[i:i + 2], 16) for i in range(0, len(s), 2)]
100
+ return tuple(vals) + (255,) if len(vals) == 3 else tuple(vals[:4])
101
+ v = getattr(color, s, None)
102
+ if v is None: raise ValueError(f"cor desconhecida: {c!r}")
103
+ return tuple(v) + (255,)
104
+ c = tuple(c)
105
+ if any(isinstance(v, float) for v in c) and max(c) <= 1.0:
106
+ c = tuple(v * 255 for v in c)
107
+ c = tuple(int(max(0, min(255, v))) for v in c)
108
+ return c + (255,) if len(c) == 3 else c[:4]
109
+
110
+
111
+ def _arity_adapter(fn):
112
+ """Permite update=lambda: ... ou update=lambda dt: ... (e métodos)."""
113
+ try: n = len(inspect.signature(fn).parameters)
114
+ except (TypeError, ValueError): n = 1
115
+ return lambda *a: fn(*a[:n])
116
+
117
+
118
+ # ───────────────────────────── matemática ──────────────────────────────
119
+ def _mm(A, B):
120
+ return (A[0]*B[0]+A[1]*B[3]+A[2]*B[6], A[0]*B[1]+A[1]*B[4]+A[2]*B[7], A[0]*B[2]+A[1]*B[5]+A[2]*B[8],
121
+ A[3]*B[0]+A[4]*B[3]+A[5]*B[6], A[3]*B[1]+A[4]*B[4]+A[5]*B[7], A[3]*B[2]+A[4]*B[5]+A[5]*B[8],
122
+ A[6]*B[0]+A[7]*B[3]+A[8]*B[6], A[6]*B[1]+A[7]*B[4]+A[8]*B[7], A[6]*B[2]+A[7]*B[5]+A[8]*B[8])
123
+
124
+
125
+ def _rot(rx, ry, rz): # R = Ry * Rx * Rz (yaw 0 => frente = +Z)
126
+ cx, sx, cy, sy, cz, sz = math.cos(rx), math.sin(rx), math.cos(ry), math.sin(ry), math.cos(rz), math.sin(rz)
127
+ Rz = (cz, -sz, 0, sz, cz, 0, 0, 0, 1)
128
+ Rx = (1, 0, 0, 0, cx, -sx, 0, sx, cx)
129
+ Ry = (cy, 0, sy, 0, 1, 0, -sy, 0, cy)
130
+ return _mm(Ry, _mm(Rx, Rz))
131
+
132
+
133
+ # ─────────────────────────────── malhas ────────────────────────────────
134
+ class Mesh:
135
+ """Malha de polígonos convexos. As normais são calculadas automaticamente."""
136
+
137
+ def __init__(self, verts, faces, normals=None, face_colors=None, two_sided=False):
138
+ self.verts = [tuple(float(c) for c in v) for v in verts]
139
+ self.faces = [tuple(f) for f in faces]
140
+ self.face_colors = face_colors
141
+ self.two_sided = two_sided
142
+ n = len(self.verts)
143
+ cen = tuple(sum(v[i] for v in self.verts) / n for i in range(3))
144
+ if normals is None:
145
+ normals = []
146
+ for f in self.faces:
147
+ nx = ny = nz = 0.0
148
+ for i in range(len(f)): # método de Newell
149
+ a, b = self.verts[f[i]], self.verts[f[(i + 1) % len(f)]]
150
+ nx += (a[1] - b[1]) * (a[2] + b[2])
151
+ ny += (a[2] - b[2]) * (a[0] + b[0])
152
+ nz += (a[0] - b[0]) * (a[1] + b[1])
153
+ l = math.sqrt(nx * nx + ny * ny + nz * nz) or 1.0
154
+ nx, ny, nz = nx / l, ny / l, nz / l
155
+ fc = tuple(sum(self.verts[i][k] for i in f) / len(f) for k in range(3))
156
+ if nx * (fc[0] - cen[0]) + ny * (fc[1] - cen[1]) + nz * (fc[2] - cen[2]) < 0:
157
+ nx, ny, nz = -nx, -ny, -nz # garante normal para fora
158
+ normals.append((nx, ny, nz))
159
+ self.normals = normals
160
+ self.radius = max(math.sqrt(x * x + y * y + z * z) for x, y, z in self.verts)
161
+ lo = [min(v[i] for v in self.verts) for i in range(3)]
162
+ hi = [max(v[i] for v in self.verts) for i in range(3)]
163
+ self.size = tuple(hi[i] - lo[i] for i in range(3))
164
+
165
+
166
+ def _cube_mesh(pivot_top=False):
167
+ y0, y1 = (-1.0, 0.0) if pivot_top else (-0.5, 0.5)
168
+ v = [(x, y0 if y < 0 else y1, z) for x in (-.5, .5) for y in (-1, 1) for z in (-.5, .5)]
169
+ # índice = x*4 + y*2 + z
170
+ faces = [(0, 1, 3, 2), (4, 5, 7, 6), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]
171
+ return Mesh(v, faces)
172
+
173
+
174
+ def _sphere_mesh(rings=8, seg=14):
175
+ v = [(0, .5, 0), (0, -.5, 0)]
176
+ for i in range(1, rings):
177
+ a = math.pi * i / rings
178
+ for j in range(seg):
179
+ b = 2 * math.pi * j / seg
180
+ v.append((math.cos(b) * math.sin(a) * .5, math.cos(a) * .5, math.sin(b) * math.sin(a) * .5))
181
+ idx = lambda i, j: 2 + (i - 1) * seg + (j % seg)
182
+ f = [(0, idx(1, j + 1), idx(1, j)) for j in range(seg)]
183
+ for i in range(1, rings - 1):
184
+ f += [(idx(i, j), idx(i, j + 1), idx(i + 1, j + 1), idx(i + 1, j)) for j in range(seg)]
185
+ f += [(1, idx(rings - 1, j), idx(rings - 1, j + 1)) for j in range(seg)]
186
+ return Mesh(v, f)
187
+
188
+
189
+ def _cylinder_mesh(seg=16):
190
+ v = [(math.cos(2 * math.pi * j / seg) * .5, y, math.sin(2 * math.pi * j / seg) * .5)
191
+ for y in (-.5, .5) for j in range(seg)]
192
+ f = [(j, (j + 1) % seg, seg + (j + 1) % seg, seg + j) for j in range(seg)]
193
+ f += [tuple(range(seg, 2 * seg)), tuple(range(seg))]
194
+ return Mesh(v, f)
195
+
196
+
197
+ def _pyramid_mesh():
198
+ v = [(-.5, -.5, -.5), (.5, -.5, -.5), (.5, -.5, .5), (-.5, -.5, .5), (0, .5, 0)]
199
+ return Mesh(v, [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 0, 4), (0, 1, 2, 3)])
200
+
201
+
202
+ def _grid_mesh(size, tile, c1, c2):
203
+ n = max(1, round(size / tile)); step = size / n; half = size / 2
204
+ v = [(-half + i * step, 0, -half + j * step) for j in range(n + 1) for i in range(n + 1)]
205
+ faces, cols = [], []
206
+ for j in range(n):
207
+ for i in range(n):
208
+ a = j * (n + 1) + i
209
+ faces.append((a, a + 1, a + n + 2, a + n + 1))
210
+ cols.append(c1 if (i + j) % 2 == 0 else c2)
211
+ return Mesh(v, faces, normals=[(0, 1, 0)] * len(faces), face_colors=cols)
212
+
213
+
214
+ _MESHES = {"cube": lambda: _cube_mesh(), "cube_top": lambda: _cube_mesh(True), "sphere": _sphere_mesh,
215
+ "cylinder": _cylinder_mesh, "pyramid": _pyramid_mesh}
216
+ _mesh_cache = {}
217
+
218
+
219
+ def _get_mesh(m):
220
+ if m is None or isinstance(m, Mesh): return m
221
+ if m not in _MESHES: raise ValueError(f"malha desconhecida: {m!r} (use {list(_MESHES)})")
222
+ if m not in _mesh_cache: _mesh_cache[m] = _MESHES[m]()
223
+ return _mesh_cache[m]
224
+
225
+
226
+ # ─────────────────────────────── cena ──────────────────────────────────
227
+ class Scene:
228
+ def __init__(self):
229
+ self.entities, self.ui = [], []
230
+ self.camera = None
231
+ self.player = None
232
+ self._sky = (135, 190, 235)
233
+ self.fog = (45, 120) # (início, fim) da neblina; (0,0) desliga
234
+ self.ambient = 0.5 # luz ambiente 0..1
235
+ l = Vec3(0.45, 1.0, 0.6).normalized()
236
+ self.light = (l.x, l.y, l.z) # direção PARA a luz
237
+ self._col = []
238
+
239
+ sky = property(lambda s: s._sky, lambda s, v: setattr(s, "_sky", _rgba(v)[:3]))
240
+
241
+ def add(self, e): self.entities.append(e)
242
+
243
+ def remove(self, e):
244
+ if e in self.entities: self.entities.remove(e)
245
+
246
+ def refresh(self):
247
+ self._col = [e for e in self.entities if e.collision and e.parent is None]
248
+
249
+ def clear(self):
250
+ self.entities.clear(); self.ui.clear(); self.player = None
251
+
252
+ def ground_below(self, e):
253
+ lo, hi = e.collider_box()
254
+ x, z = (lo[0] + hi[0]) / 2, (lo[2] + hi[2]) / 2
255
+ best = None
256
+ for c in self._col:
257
+ if c is e: continue
258
+ clo, chi = c.collider_box()
259
+ if clo[0] <= x <= chi[0] and clo[2] <= z <= chi[2] and chi[1] <= lo[1] + 0.35:
260
+ if best is None or chi[1] > best: best = chi[1]
261
+ return best
262
+
263
+
264
+ scene = Scene()
265
+
266
+
267
+ # ──────────────────────────── física (RigBody) ─────────────────────────
268
+ class RigBody:
269
+ """Corpo rígido: gravidade + colisão AABB contra todo objeto com collision=True.
270
+ Use como base=cosmo3d.RigBody em qualquer prefab."""
271
+
272
+ def __init__(self, owner, gravity=1, step_height=0.45, max_fall=30.0):
273
+ self.owner = owner
274
+ self.gravity = gravity
275
+ self.step_height = step_height
276
+ self.max_fall = max_fall
277
+ self.velocity = Vec3()
278
+ self.on_ground = False
279
+ self._was_grounded = False
280
+
281
+ def _hit(self, o):
282
+ lo, hi = o.collider_box()
283
+ for c in scene._col:
284
+ if c is o: continue
285
+ clo, chi = c.collider_box()
286
+ if (lo[0] < chi[0] - _EPS and hi[0] > clo[0] + _EPS and lo[1] < chi[1] - _EPS and
287
+ hi[1] > clo[1] + _EPS and lo[2] < chi[2] - _EPS and hi[2] > clo[2] + _EPS):
288
+ return c
289
+ return None
290
+
291
+ def _move(self, axis, d):
292
+ if d == 0: return
293
+ o = self.owner; p = o.position
294
+ p[axis] += d
295
+ if not o.collision: return
296
+ for _ in range(4):
297
+ c = self._hit(o)
298
+ if c is None: return
299
+ lo, hi = o.collider_box(); clo, chi = c.collider_box()
300
+ if axis != 1 and self.step_height and self._was_grounded: # sobe degraus
301
+ need = chi[1] - lo[1]
302
+ if 0 < need <= self.step_height:
303
+ y0 = p.y; p.y += need + 0.001
304
+ if self._hit(o) is None: return
305
+ p.y = y0
306
+ if d > 0: p[axis] -= hi[axis] - clo[axis]
307
+ else: p[axis] += chi[axis] - lo[axis]
308
+ self.velocity[axis] = 0
309
+ if axis == 1 and d < 0: self.on_ground = True
310
+
311
+ def step(self, dt):
312
+ o = self.owner; v = self.velocity
313
+ self._was_grounded = self.on_ground
314
+ self.on_ground = False
315
+ n = 3; h = dt / n
316
+ for _ in range(n):
317
+ v.y = max(-self.max_fall, v.y - GRAVITY * self.gravity * h)
318
+ self._move(0, v.x * h); self._move(2, v.z * h); self._move(1, v.y * h)
319
+ if o.position.y < -60: # caiu do mundo: reaparece
320
+ o.position = o.spawn; v.x = v.y = v.z = 0
321
+
322
+
323
+ # ─────────────────────────────── entidades ─────────────────────────────
324
+ class Entity:
325
+ """Objeto base. Tudo na cena é uma Entity.
326
+
327
+ Entity(mesh='cube', position=(0,1,0), scale=2, color='red', collision=True,
328
+ gravity=1, base=RigBody, shadow=True, update=lambda dt: ...)
329
+ """
330
+
331
+ def __init__(self, mesh=None, position=(0, 0, 0), rotation=(0, 0, 0), scale=1, color="white",
332
+ parent=None, collision=False, gravity=0, base=None, shadow=False, visible=True,
333
+ unlit=False, layer=2, name="", **kw):
334
+ self._position = Vec3(position)
335
+ self._rotation = Vec3(rotation)
336
+ self.scale = scale
337
+ self.mesh = _get_mesh(mesh)
338
+ self.color = color
339
+ self.parent = parent
340
+ self.children = []
341
+ if parent is not None: parent.children.append(self)
342
+ self.collision = bool(collision)
343
+ self.shadow, self.visible, self.unlit, self.layer, self.name = shadow, visible, unlit, layer, name
344
+ self.collider_size = None
345
+ self.collider_offset = Vec3()
346
+ self.spawn = Vec3(position)
347
+ self.body = None
348
+ self._owned = []
349
+ for k, v in kw.items():
350
+ if k == "update" and callable(v): v = _arity_adapter(v)
351
+ setattr(self, k, v)
352
+ if base is not None:
353
+ self.body = base(self, gravity=gravity) if isinstance(base, type) else base
354
+ elif gravity:
355
+ self.body = RigBody(self, gravity=gravity)
356
+ scene.add(self)
357
+
358
+ # propriedades convenientes
359
+ position = property(lambda s: s._position, lambda s, v: setattr(s, "_position", Vec3(v)))
360
+ rotation = property(lambda s: s._rotation, lambda s, v: setattr(s, "_rotation", Vec3(v)))
361
+ scale = property(lambda s: s._scale, lambda s, v: setattr(s, "_scale", Vec3(v)))
362
+ color = property(lambda s: s.rgba, lambda s, v: setattr(s, "rgba", _rgba(v)))
363
+ x = property(lambda s: s._position.x, lambda s, v: setattr(s._position, "x", float(v)))
364
+ y = property(lambda s: s._position.y, lambda s, v: setattr(s._position, "y", float(v)))
365
+ z = property(lambda s: s._position.z, lambda s, v: setattr(s._position, "z", float(v)))
366
+ rotation_y = property(lambda s: s._rotation.y, lambda s, v: setattr(s._rotation, "y", float(v)))
367
+
368
+ def update(self, dt): # sobrescreva em subclasses
369
+ pass
370
+
371
+ def is_visible(self):
372
+ return self.visible and (self.parent is None or self.parent.is_visible())
373
+
374
+ def world_matrix(self):
375
+ r, s, p = self._rotation, self._scale, self._position
376
+ R = _rot(math.radians(r.x), math.radians(r.y), math.radians(r.z))
377
+ R = (R[0]*s.x, R[1]*s.y, R[2]*s.z, R[3]*s.x, R[4]*s.y, R[5]*s.z, R[6]*s.x, R[7]*s.y, R[8]*s.z)
378
+ t = (p.x, p.y, p.z)
379
+ if self.parent is not None:
380
+ PR, Pt = self.parent.world_matrix()
381
+ t = (PR[0]*t[0]+PR[1]*t[1]+PR[2]*t[2]+Pt[0], PR[3]*t[0]+PR[4]*t[1]+PR[5]*t[2]+Pt[1],
382
+ PR[6]*t[0]+PR[7]*t[1]+PR[8]*t[2]+Pt[2])
383
+ R = _mm(PR, R)
384
+ return R, t
385
+
386
+ def collider_box(self):
387
+ if self.collider_size is not None: sz = tuple(self.collider_size)
388
+ else:
389
+ ms = self.mesh.size if self.mesh else (1, 1, 1)
390
+ sz = (ms[0] * abs(self._scale.x), ms[1] * abs(self._scale.y), ms[2] * abs(self._scale.z))
391
+ p, o = self._position, self.collider_offset
392
+ c = (p.x + o.x, p.y + o.y, p.z + o.z)
393
+ return (c[0]-sz[0]/2, c[1]-sz[1]/2, c[2]-sz[2]/2), (c[0]+sz[0]/2, c[1]+sz[1]/2, c[2]+sz[2]/2)
394
+
395
+ def intersects(self, other):
396
+ a, b = self.collider_box(), other.collider_box()
397
+ return all(a[0][i] < b[1][i] and a[1][i] > b[0][i] for i in range(3))
398
+
399
+ def _spawn(self, cls, *a, **kw):
400
+ e = cls(*a, **kw); self._owned.append(e); return e
401
+
402
+ def destroy(self):
403
+ for c in list(self.children) + list(self._owned): c.destroy()
404
+ if self.parent is not None and self in self.parent.children: self.parent.children.remove(self)
405
+ if scene.player is self: scene.player = None
406
+ scene.remove(self)
407
+
408
+
409
+ def destroy(e): e.destroy()
410
+
411
+
412
+ # ───────────────────────────── prefabs ─────────────────────────────────
413
+ class _Shape(Entity):
414
+ MESH = "cube"
415
+ def __init__(self, position=(0, 0, 0), **kw):
416
+ kw.setdefault("collision", True)
417
+ super().__init__(mesh=self.MESH, position=position, **kw)
418
+
419
+ class Cube(_Shape): MESH = "cube"
420
+ class Sphere(_Shape): MESH = "sphere"
421
+ class Cylinder(_Shape): MESH = "cylinder"
422
+ class Pyramid(_Shape): MESH = "pyramid"
423
+
424
+
425
+ class Floor(Entity):
426
+ """Chão xadrez sólido. position = altura da superfície. (gravity é aceito por
427
+ compatibilidade: o chão é estático e nunca cai.)"""
428
+ def __init__(self, position=(0, 0, 0), size=80, tile=4, color="#5cae5c", color2=None,
429
+ gravity=0, collision=True, **kw):
430
+ c1 = _rgba(color)[:3]
431
+ c2 = _rgba(color2)[:3] if color2 else tuple(int(v * 0.88) for v in c1)
432
+ super().__init__(mesh=_grid_mesh(size, tile, c1, c2), position=position, color=color,
433
+ collision=collision, layer=0, **kw)
434
+ self.collider_size = (size, 4, size)
435
+ self.collider_offset = Vec3(0, -2, 0)
436
+
437
+ def floor(**kw): return Floor(**kw) # estilo: cosmo3d.floor(gravity=1, collision=1)
438
+
439
+
440
+ class Wall(Cube):
441
+ """Parede: position é o centro. Padrão 6 x 3 x 0.4."""
442
+ def __init__(self, position=(0, 1.5, 0), **kw):
443
+ kw.setdefault("scale", (6, 3, 0.4)); kw.setdefault("color", "#c9b99a")
444
+ super().__init__(position, **kw)
445
+
446
+
447
+ class Stairs(Entity):
448
+ """Escada (position = pé da escada, sobe em +Z)."""
449
+ def __init__(self, position=(0, 0, 0), steps=8, width=3, rise=0.3, run_=0.8, color="#a0a0aa", **kw):
450
+ super().__init__(position=position, **kw)
451
+ p = self.position
452
+ for i in range(steps):
453
+ h = rise * (i + 1)
454
+ self._spawn(Cube, (p.x, p.y + h / 2, p.z + run_ * i + run_ / 2),
455
+ scale=(width, h, run_), color=color)
456
+
457
+
458
+ class Tree(Entity):
459
+ """Árvore (position = base do tronco)."""
460
+ def __init__(self, position=(0, 0, 0), height=3.0, **kw):
461
+ super().__init__(position=position, **kw)
462
+ p = self.position
463
+ self._spawn(Cylinder, (p.x, p.y + height / 2, p.z), scale=(0.5, height, 0.5), color="#7a5230")
464
+ self._spawn(Sphere, (p.x, p.y + height + 0.9, p.z), scale=(2.6, 2.4, 2.6), color="#2f9e44",
465
+ collision=False)
466
+
467
+
468
+ class House(Entity):
469
+ """Casa com porta na frente (-Z). position = centro da base."""
470
+ def __init__(self, position=(0, 0, 0), size=(8, 3, 8), wall="#d9c7a3", roof="#b5473a", **kw):
471
+ super().__init__(position=position, **kw)
472
+ p, (w, h, d), t, door = self.position, size, 0.4, 1.8
473
+ W = lambda pos, sc: self._spawn(Cube, pos, scale=sc, color=wall)
474
+ W((p.x, p.y + h / 2, p.z + d / 2), (w, h, t)) # fundo
475
+ W((p.x - w / 2, p.y + h / 2, p.z), (t, h, d)); W((p.x + w / 2, p.y + h / 2, p.z), (t, h, d))
476
+ side = (w - door) / 2 # frente com porta
477
+ W((p.x - (door + side) / 2, p.y + h / 2, p.z - d / 2), (side, h, t))
478
+ W((p.x + (door + side) / 2, p.y + h / 2, p.z - d / 2), (side, h, t))
479
+ W((p.x, p.y + (h + 2.3) / 2, p.z - d / 2), (door, h - 2.3, t))
480
+ self._spawn(Pyramid, (p.x, p.y + h + 1.1, p.z), scale=(w + 1, 2.2, d + 1), color=roof, collision=False)
481
+
482
+
483
+ # ───────────────────────────── câmeras ─────────────────────────────────
484
+ class _Camera:
485
+ first_person = False
486
+ def __init__(self):
487
+ self.position = Vec3(0, 3, -8)
488
+ self.yaw, self.pitch = 0.0, 0.0 # radianos
489
+ self.fov = 70.0
490
+ self.sensitivity = 0.0025
491
+ self.target = None # se None usa o MenPlayer da cena
492
+ self.pitch_limits = (-1.45, 1.45)
493
+
494
+ def __call__(self, **kw): # cosmo3d.Camera3(distance=9, fov=80)
495
+ for k, v in kw.items(): setattr(self, k, v)
496
+ return self
497
+
498
+ def look(self, dx, dy):
499
+ self.yaw += dx * self.sensitivity
500
+ self.pitch = max(self.pitch_limits[0], min(self.pitch_limits[1], self.pitch - dy * self.sensitivity))
501
+
502
+ def zoom(self, amount): pass
503
+ def update(self, dt): pass
504
+ def _target(self): return self.target or scene.player
505
+
506
+
507
+ class ThirdPersonCamera(_Camera):
508
+ def __init__(self):
509
+ super().__init__()
510
+ self.distance, self.height, self.smooth = 7.0, 1.5, 14.0
511
+ self.pitch = -0.3
512
+ self.pitch_limits = (-1.3, 0.9)
513
+ self._pivot = None
514
+
515
+ def zoom(self, a): self.distance = max(2.0, min(25.0, self.distance - a * 0.7))
516
+
517
+ def update(self, dt):
518
+ t = self._target()
519
+ goal = (t.position + (0, self.height, 0)) if t else Vec3(0, 1, 0)
520
+ if self._pivot is None: self._pivot = goal
521
+ k = 1 - math.exp(-self.smooth * dt)
522
+ self._pivot = self._pivot + (goal - self._pivot) * k
523
+ cp = math.cos(self.pitch)
524
+ d = Vec3(math.sin(self.yaw) * cp, math.sin(self.pitch), math.cos(self.yaw) * cp)
525
+ self.position = self._pivot - d * self.distance
526
+ if self.position.y < 0.25: self.position.y = 0.25
527
+
528
+
529
+ class FirstPersonCamera(_Camera):
530
+ first_person = True
531
+ def __init__(self):
532
+ super().__init__()
533
+ self.eye_height = 1.72
534
+
535
+ def update(self, dt):
536
+ t = self._target()
537
+ if t: self.position = t.position + (0, self.eye_height, 0)
538
+
539
+
540
+ class FreeCamera(_Camera):
541
+ def __init__(self):
542
+ super().__init__()
543
+ self.speed = 9.0
544
+
545
+ def update(self, dt):
546
+ f = (held("w", "up") - held("s", "down")); r = (held("d", "right") - held("a", "left"))
547
+ u = (held("e", "space") - held("q", "shift"))
548
+ cp = math.cos(self.pitch)
549
+ fw = Vec3(math.sin(self.yaw) * cp, math.sin(self.pitch), math.cos(self.yaw) * cp)
550
+ rt = Vec3(math.cos(self.yaw), 0, -math.sin(self.yaw))
551
+ self.position = self.position + (fw * f + rt * r + Vec3(0, u, 0)) * (self.speed * dt)
552
+
553
+
554
+ _CAMERAS = {"Camera1": FirstPersonCamera, "Camera3": ThirdPersonCamera, "CameraFree": FreeCamera}
555
+ _cam_cache = {}
556
+
557
+
558
+ def _camera_instance(name):
559
+ if name not in _cam_cache: _cam_cache[name] = _CAMERAS[name]()
560
+ scene.camera = _cam_cache[name] # acessar a câmera já a ativa
561
+ return scene.camera
562
+
563
+
564
+ def __getattr__(name): # cosmo3d.Camera3 / Camera1 / CameraFree (com ou sem parênteses)
565
+ if name in _CAMERAS: return _camera_instance(name)
566
+ raise AttributeError(f"module 'cosmo3d' has no attribute {name!r}")
567
+
568
+
569
+ # ───────────────────────────── entrada ─────────────────────────────────
570
+ _keys = None
571
+ _down = set()
572
+ _kc = {}
573
+ _ALIAS = {"shift": ("left shift", "right shift"), "ctrl": ("left ctrl", "right ctrl"), "esc": ("escape",),
574
+ "enter": ("return",)}
575
+
576
+
577
+ def _codes(name):
578
+ out = []
579
+ for n in _ALIAS.get(name, (name,)):
580
+ if n not in _kc:
581
+ try: _kc[n] = pygame.key.key_code(n)
582
+ except Exception: _kc[n] = getattr(pygame, "K_" + n.upper(), None)
583
+ if _kc[n] is not None: out.append(_kc[n])
584
+ return out
585
+
586
+ def held(*names):
587
+ """True se alguma das teclas está pressionada: held('w', 'up')"""
588
+ return any(_keys[c] for n in names for c in _codes(n)) if _keys is not None else False
589
+
590
+ def pressed(*names):
591
+ """True apenas no frame em que a tecla foi apertada."""
592
+ return any(c in _down for n in names for c in _codes(n))
593
+
594
+
595
+ _update_hooks = []
596
+ def on_update(fn):
597
+ """Decorador: @cosmo3d.on_update def tick(dt): ..."""
598
+ _update_hooks.append(_arity_adapter(fn)); return fn
599
+
600
+
601
+ # ─────────────────────────────── jogador ───────────────────────────────
602
+ class MenPlayer(Entity):
603
+ """Boneco jogável. position = pés. WASD move relativo à câmera, ESPAÇO pula.
604
+
605
+ MenPlayer(gravity=1, collision=1, base=RigBody, speed=6, jump=8.5,
606
+ shirt='royalblue', pants='#2b3a67', skin='#f1c27d')
607
+ """
608
+ def __init__(self, position=(0, 0, 0), speed=6.0, jump=8.5, gravity=1, collision=1, base=RigBody,
609
+ shirt="royalblue", pants="#2b3a67", skin="#f1c27d", hair="#3b2a1a",
610
+ controls=True, shadow=True, **kw):
611
+ super().__init__(position=position, gravity=gravity, collision=collision, base=base,
612
+ shadow=shadow, **kw)
613
+ self.collider_size = (0.6, 1.9, 0.6)
614
+ self.collider_offset = Vec3(0, 0.95, 0)
615
+ self.speed, self.jump, self.controls = speed, jump, controls
616
+ self._phase = 0.0
617
+ P = lambda **k: Entity(parent=self, **k)
618
+ P(mesh="cube", position=(0, 1.15, 0), scale=(0.6, 0.7, 0.3), color=shirt) # torso
619
+ P(mesh="cube", position=(0, 1.7, 0), scale=0.4, color=skin) # cabeça
620
+ P(mesh="cube", position=(0, 1.88, 0), scale=(0.43, 0.12, 0.43), color=hair)
621
+ for sx in (-1, 1):
622
+ P(mesh="cube", position=(sx * 0.1, 1.72, 0.2), scale=(0.07, 0.07, 0.03), color="#111111", unlit=True)
623
+ self.arms = [P(mesh="cube_top", position=(sx * 0.4, 1.5, 0), scale=(0.2, 0.7, 0.2), color=shirt)
624
+ for sx in (-1, 1)]
625
+ self.legs = [P(mesh="cube_top", position=(sx * 0.15, 0.8, 0), scale=(0.27, 0.8, 0.27), color=pants)
626
+ for sx in (-1, 1)]
627
+ scene.player = self
628
+
629
+ def update(self, dt):
630
+ cam, b = scene.camera, self.body
631
+ yaw = cam.yaw if cam else 0.0
632
+ fp = bool(cam and cam.first_person)
633
+ self.visible = not fp
634
+ v = b.velocity if b else Vec3()
635
+ ix = iz = 0.0
636
+ if self.controls:
637
+ iz = held("w", "up") - held("s", "down")
638
+ ix = held("d", "right") - held("a", "left")
639
+ dx = math.sin(yaw) * iz + math.cos(yaw) * ix
640
+ dz = math.cos(yaw) * iz - math.sin(yaw) * ix
641
+ l = math.hypot(dx, dz)
642
+ if l > 0: dx, dz = dx / l, dz / l
643
+ grounded = b.on_ground if b else True
644
+ k = min(1.0, (14 if grounded else 5) * dt)
645
+ v.x += (dx * self.speed - v.x) * k
646
+ v.z += (dz * self.speed - v.z) * k
647
+ if self.controls and held("space") and grounded and b: v.y = self.jump
648
+ if not b: # sem física: move direto
649
+ self._position = self._position + (v.x * dt, 0, v.z * dt)
650
+ # rotação do corpo
651
+ if fp: self.rotation.y = math.degrees(yaw)
652
+ elif l > 0:
653
+ diff = (math.degrees(math.atan2(dx, dz)) - self.rotation.y + 180) % 360 - 180
654
+ self.rotation.y += diff * min(1.0, 14 * dt)
655
+ # animação de caminhada
656
+ sp = math.hypot(v.x, v.z)
657
+ amp = min(1.0, sp / self.speed) if grounded else 0.35
658
+ self._phase += sp * dt * 1.7
659
+ sw = math.sin(self._phase) * 55 * amp
660
+ self.legs[0].rotation.x, self.legs[1].rotation.x = sw, -sw
661
+ self.arms[0].rotation.x, self.arms[1].rotation.x = -sw, sw
662
+
663
+ Player = MenPlayer
664
+
665
+
666
+ # ──────────────────────────────── HUD ──────────────────────────────────
667
+ _fonts = {}
668
+ def _font(size):
669
+ if size not in _fonts: _fonts[size] = pygame.font.Font(None, size)
670
+ return _fonts[size]
671
+
672
+
673
+ class Text:
674
+ """Texto 2D na tela: cosmo3d.Text('Olá!', position=(10, 10), size=28)"""
675
+ def __init__(self, text="", position=(10, 10), color="white", size=24):
676
+ self.text, self.position, self.color, self.size, self.visible = text, position, _rgba(color)[:3], size, True
677
+ scene.ui.append(self)
678
+
679
+ def draw(self, surf):
680
+ if not self.visible: return
681
+ f = _font(self.size)
682
+ surf.blit(f.render(str(self.text), True, (0, 0, 0)), (self.position[0] + 1, self.position[1] + 1))
683
+ surf.blit(f.render(str(self.text), True, self.color), self.position)
684
+
685
+ def destroy(self):
686
+ if self in scene.ui: scene.ui.remove(self)
687
+
688
+
689
+ # ───────────────────────────── renderizador ────────────────────────────
690
+ def _render(surf, overlay, stats):
691
+ cam = scene.camera
692
+ W, H = surf.get_size()
693
+ cx, cy = W / 2, H / 2
694
+ f = cy / math.tan(math.radians(cam.fov) / 2)
695
+ sy_, cy_ = math.sin(cam.yaw), math.cos(cam.yaw)
696
+ sp, cp = math.sin(cam.pitch), math.cos(cam.pitch)
697
+ px, py, pz = cam.position.x, cam.position.y, cam.position.z
698
+ near = 0.1
699
+ sky = scene.sky
700
+ fog0, fog1 = scene.fog
701
+ lx, ly, lz = scene.light
702
+ amb = scene.ambient
703
+ far = fog1 * 1.15 if fog1 > fog0 else 1e9
704
+ polys = []
705
+
706
+ def to_cam(x, y, z):
707
+ dx, dy, dz = x - px, y - py, z - pz
708
+ z0 = dx * sy_ + dz * cy_
709
+ return (dx * cy_ - dz * sy_, dy * cp - z0 * sp, z0 * cp + dy * sp)
710
+
711
+ def emit(pts, col, alpha, layer):
712
+ if any(p[2] < near for p in pts): # recorte no plano próximo
713
+ out = []
714
+ for i in range(len(pts)):
715
+ a, b = pts[i], pts[(i + 1) % len(pts)]
716
+ ia, ib = a[2] >= near, b[2] >= near
717
+ if ia: out.append(a)
718
+ if ia != ib:
719
+ t = (near - a[2]) / (b[2] - a[2])
720
+ out.append((a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, near))
721
+ pts = out
722
+ if len(pts) < 3: return
723
+ sp_, zs = [], 0.0
724
+ x0 = y0 = 1e9; x1 = y1 = -1e9
725
+ for x, y, z in pts:
726
+ zs += z
727
+ u = max(-8000.0, min(8000.0, cx + x / z * f)); v = max(-8000.0, min(8000.0, cy - y / z * f))
728
+ sp_.append((u, v))
729
+ if u < x0: x0 = u
730
+ if u > x1: x1 = u
731
+ if v < y0: y0 = v
732
+ if v > y1: y1 = v
733
+ if x1 < 0 or x0 > W or y1 < 0 or y0 > H: return
734
+ z = zs / len(pts)
735
+ if fog1 > fog0:
736
+ t = (z - fog0) / (fog1 - fog0)
737
+ if t > 0:
738
+ t = min(t, 1.0)
739
+ col = (int(col[0] + (sky[0] - col[0]) * t), int(col[1] + (sky[1] - col[1]) * t),
740
+ int(col[2] + (sky[2] - col[2]) * t))
741
+ polys.append((layer, -z, col, alpha, sp_))
742
+
743
+ for e in scene.entities:
744
+ m = e.mesh
745
+ if m is None or not e.is_visible(): continue
746
+ R, t = e.world_matrix()
747
+ R0, R1, R2, R3, R4, R5, R6, R7, R8 = R
748
+ smax = max(math.sqrt(R0*R0+R3*R3+R6*R6), math.sqrt(R1*R1+R4*R4+R7*R7), math.sqrt(R2*R2+R5*R5+R8*R8))
749
+ rad = m.radius * smax
750
+ ccx, ccy, ccz = to_cam(*t)
751
+ if ccz < -rad or math.sqrt(ccx*ccx + ccy*ccy + ccz*ccz) > far + rad: continue
752
+ wv = [(R0*x+R1*y+R2*z+t[0], R3*x+R4*y+R5*z+t[1], R6*x+R7*y+R8*z+t[2]) for x, y, z in m.verts]
753
+ cv = [to_cam(*v) for v in wv]
754
+ base = e.rgba; fc = m.face_colors
755
+ for i, face in enumerate(m.faces):
756
+ nx, ny, nz = m.normals[i]
757
+ wx, wy, wz = R0*nx+R1*ny+R2*nz, R3*nx+R4*ny+R5*nz, R6*nx+R7*ny+R8*nz
758
+ l = math.sqrt(wx*wx + wy*wy + wz*wz) or 1.0
759
+ wx, wy, wz = wx / l, wy / l, wz / l
760
+ v0 = wv[face[0]]
761
+ facing = wx * (v0[0] - px) + wy * (v0[1] - py) + wz * (v0[2] - pz)
762
+ if facing >= 0:
763
+ if not m.two_sided: continue
764
+ wx, wy, wz = -wx, -wy, -wz
765
+ c = fc[i] if fc else base
766
+ sh = 1.0 if e.unlit else amb + (1 - amb) * max(0.0, wx * lx + wy * ly + wz * lz)
767
+ emit([cv[j] for j in face], (min(255, int(c[0] * sh)), min(255, int(c[1] * sh)),
768
+ min(255, int(c[2] * sh))), base[3], e.layer)
769
+ # sombras em "blob"
770
+ for e in scene.entities:
771
+ if not e.shadow or not e.is_visible(): continue
772
+ g = scene.ground_below(e)
773
+ if g is None: continue
774
+ lo, hi = e.collider_box()
775
+ ex, ez = (lo[0] + hi[0]) / 2, (lo[2] + hi[2]) / 2
776
+ r = max(hi[0] - lo[0], hi[2] - lo[2]) * 0.6 * max(0.35, 1 - (lo[1] - g) * 0.12)
777
+ emit([to_cam(ex + math.cos(a) * r, g + 0.02, ez + math.sin(a) * r)
778
+ for a in [k * math.pi / 7 for k in range(14)]], (0, 0, 0), 90, 1)
779
+
780
+ polys.sort(key=lambda p: (p[0], p[1]))
781
+ surf.fill(sky)
782
+ used = False
783
+ for _, _, col, alpha, pts in polys:
784
+ if alpha < 255:
785
+ if not used: overlay.fill((0, 0, 0, 0)); used = True
786
+ pygame.draw.polygon(overlay, (col[0], col[1], col[2], alpha), pts)
787
+ else:
788
+ if used: surf.blit(overlay, (0, 0)); used = False
789
+ pygame.draw.polygon(surf, col, pts)
790
+ pygame.draw.polygon(surf, col, pts, 1) # fecha frestas entre polígonos
791
+ if used: surf.blit(overlay, (0, 0))
792
+ stats["polys"] = len(polys)
793
+
794
+
795
+ # ───────────────────────────── loop principal ──────────────────────────
796
+ _ran = False
797
+ _crashed = False
798
+
799
+
800
+ def run(title="Cosmo3D", size=(1100, 650), fps=60, sky=None, fullscreen=False, update=None,
801
+ debug=False, frames=None, screenshot=None):
802
+ """Abre a janela e roda o jogo. (Opcional: é chamado sozinho no fim do script.)"""
803
+ global _ran, _keys
804
+ _ran = True
805
+ if update: _update_hooks.append(_arity_adapter(update))
806
+ if sky is not None: scene.sky = sky
807
+ pygame.init()
808
+ pygame.display.set_caption(title)
809
+ screen = pygame.display.set_mode(size, (pygame.FULLSCREEN if fullscreen else pygame.RESIZABLE))
810
+ if scene.camera is None: _camera_instance("Camera3")
811
+ overlay = pygame.Surface(screen.get_size(), pygame.SRCALPHA)
812
+ clock = pygame.time.Clock()
813
+ grabbed = False
814
+
815
+ def grab(on):
816
+ nonlocal grabbed
817
+ grabbed = on
818
+ pygame.event.set_grab(on); pygame.mouse.set_visible(not on)
819
+ pygame.mouse.get_rel()
820
+ grab(True)
821
+ stats, n, running = {"polys": 0}, 0, True
822
+ while running:
823
+ dt = min(clock.tick(fps) / 1000.0, 1 / 20)
824
+ _down.clear()
825
+ for ev in pygame.event.get():
826
+ if ev.type == pygame.QUIT: running = False
827
+ elif ev.type == pygame.KEYDOWN:
828
+ _down.add(ev.key)
829
+ if ev.key == pygame.K_ESCAPE:
830
+ if grabbed: grab(False)
831
+ else: running = False
832
+ elif ev.key == pygame.K_F3: debug = not debug
833
+ elif ev.key == pygame.K_F12: pygame.image.save(screen, "cosmo3d_screenshot.png")
834
+ elif ev.type == pygame.MOUSEBUTTONDOWN and not grabbed: grab(True)
835
+ elif ev.type == pygame.MOUSEWHEEL: scene.camera.zoom(ev.y)
836
+ _keys = pygame.key.get_pressed()
837
+ screen = pygame.display.get_surface()
838
+ if overlay.get_size() != screen.get_size(): overlay = pygame.Surface(screen.get_size(), pygame.SRCALPHA)
839
+ if grabbed:
840
+ mx, my = pygame.mouse.get_rel(); scene.camera.look(mx, my)
841
+
842
+ scene.refresh()
843
+ for e in list(scene.entities): e.update(dt)
844
+ for h in list(_update_hooks): h(dt)
845
+ for e in list(scene.entities):
846
+ if e.body is not None: e.body.step(dt)
847
+ scene.camera.update(dt)
848
+
849
+ _render(screen, overlay, stats)
850
+ for t in list(scene.ui): t.draw(screen)
851
+ if scene.player:
852
+ screen.blit(_font(20).render("WASD mover | ESPAÇO pular | MOUSE câmera | RODA zoom | "
853
+ "ESC soltar mouse | F3 debug", True, (255, 255, 255)),
854
+ (10, screen.get_height() - 24))
855
+ if debug:
856
+ info = f"FPS {clock.get_fps():.0f} polígonos {stats['polys']} objetos {len(scene.entities)}"
857
+ if scene.player: info += f" pos {scene.player.position}"
858
+ screen.blit(_font(24).render(info, True, (255, 255, 0)), (10, 8))
859
+ pygame.display.flip()
860
+ n += 1
861
+ if frames is not None and n >= frames: running = False
862
+ if screenshot: pygame.image.save(screen, screenshot)
863
+ pygame.quit()
864
+
865
+
866
+ # executa sozinho quando o script termina (a menos que você já tenha chamado run())
867
+ _orig_hook = sys.excepthook
868
+ def _hook(*a):
869
+ global _crashed
870
+ _crashed = True
871
+ _orig_hook(*a)
872
+ sys.excepthook = _hook
873
+
874
+ @atexit.register
875
+ def _autorun():
876
+ if auto_run and not _ran and not _crashed and (scene.entities or scene.camera):
877
+ run()
878
+
879
+
880
+ # ───────────────────────────────── demo ────────────────────────────────
881
+ def _demo():
882
+ Floor()
883
+ MenPlayer(position=(0, 0.1, 0))
884
+ Stairs(position=(6, 0, 4), steps=8)
885
+ House(position=(-12, 0, 14))
886
+ for i, (x, z) in enumerate([(-6, 5), (8, -6), (14, 10), (-3, -9)]):
887
+ Tree(position=(x, 0, z), height=2.5 + i * 0.4)
888
+ Cube((3, 0.5, 6), color="orange")
889
+ Cube((3, 4, 6), color="red", base=RigBody, gravity=1) # cai e pousa sozinho
890
+ Sphere((-4, 3, 3), scale=1.4, color="purple", base=RigBody, gravity=1, shadow=True)
891
+ Text("cosmo3d demo", (10, 30), size=30)
892
+
893
+
894
+ if __name__ == "__main__":
895
+ _demo()