Estella 0.113.0
A fast 2D and 3D game engine powered by WebAssembly and ECS
Loading...
Searching...
No Matches
GeometryBindings.cpp
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
3
5#include "ActiveContext.hpp"
6#include "BoundarySpan.hpp"
16
17#include <glm/glm.hpp>
18#include <glm/gtc/type_ptr.hpp>
19#include <vector>
20#include <string>
21
22namespace esengine {
23
24static EstellaContext& ctx() { return activeCtx(); }
25
26#define g_device (ctx().tryGet<GfxDevice>())
27#define g_initialized (ctx().state().initialized)
28#define g_geometryManager (ctx().tryGet<GeometryManager>())
29#define g_resourceManager (ctx().tryGet<resource::ResourceManager>())
30#define g_immediateDraw (ctx().tryGet<ImmediateDraw>())
31#define g_immediateDrawActive (ctx().state().immediate_draw_active)
32#define g_currentViewProjection (ctx().state().current_view_projection)
33#define g_renderContext (ctx().tryGet<RenderContext>())
34
37 g_immediateDraw->flush();
38 }
39}
40
41// Bind + submit a custom geometry through the device (indexed or arrays).
42static void drawGeometry(GfxDevice& device, CustomGeometry& geom) {
43 geom.bind(device);
44 if (geom.hasIndices()) {
45 auto* ib = geom.indexBuffer();
46 if (ib) {
47 auto type = ib->is16Bit() ? GfxDataType::UnsignedShort : GfxDataType::UnsignedInt;
48 device.drawElements(geom.getIndexCount(), type, 0);
49 }
50 } else {
51 device.drawArrays(0, geom.getVertexCount());
52 }
53}
54
55// A mesh draw's pipeline: the requested shader + this geometry's vertex layout,
56// with blend/depth taken from the immediate-draw session state (Draw.setBlendMode /
57// setDepthTest apply to mesh draws too). The pipeline cache dedupes repeats.
58static void applyMeshPipeline(GfxDevice& device, const Shader& shader, const CustomGeometry& geom) {
59 PipelineDesc desc{};
60 desc.program = shader.handle();
61 desc.vertexLayout = geom.layoutHandle();
62 desc.blendEnabled = true;
63 desc.depthWrite = true;
64 if (auto* imm = g_immediateDraw) {
65 desc.blend = imm->blendMode();
66 desc.depthTest = imm->depthTest();
67 }
69 device.setPipeline(device.createPipeline(desc));
70}
71
73 if (!g_geometryManager) return 0;
74 return g_geometryManager->create();
75}
76
77void geometry_init(u32 handle, uintptr_t verticesPtr, u32 vertexCount,
78 uintptr_t layoutPtr, u32 layoutCount, bool dynamic) {
79 if (!g_geometryManager || verticesPtr == 0 || layoutPtr == 0) return;
80
81 auto* geom = g_geometryManager->get(handle);
82 if (!geom) return;
83
84 static constexpr u32 MAX_ATTRS = 8;
85 if (layoutCount == 0 || layoutCount > MAX_ATTRS) {
86 ES_LOG_WARN("geometry_init: invalid layoutCount {}, max {}", layoutCount, MAX_ATTRS);
87 return;
88 }
89
90 const i32* layoutData = boundarySpan<i32>(layoutPtr, layoutCount, "geometry_init.layout");
91 if (!layoutData) return;
92
93 static constexpr const char* ATTR_NAMES[] = {
94 "a_attr0", "a_attr1", "a_attr2", "a_attr3",
95 "a_attr4", "a_attr5", "a_attr6", "a_attr7"
96 };
97
98 std::vector<VertexAttribute> attrs;
99 attrs.reserve(layoutCount);
100 for (u32 i = 0; i < layoutCount; ++i) {
101 attrs.emplace_back(static_cast<ShaderDataType>(layoutData[i]), ATTR_NAMES[i]);
102 }
103
104 VertexLayout layout(std::move(attrs));
105 const f32* vertices = boundarySpan<f32>(
106 verticesPtr, static_cast<u64>(vertexCount) * (layout.getStride() / sizeof(f32)),
107 "geometry_init.vertices");
108 if (!vertices) return;
109 geom->init(ctx().require<GfxDevice>(), vertices, vertexCount, std::move(layout), dynamic);
110}
111
112void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
113 if (!g_geometryManager || indicesPtr == 0) return;
114
115 auto* geom = g_geometryManager->get(handle);
116 if (!geom) return;
117
118 const u16* indices = boundarySpan<u16>(indicesPtr, indexCount, "geometry_setIndices16");
119 if (!indices) return;
120 geom->setIndices(indices, indexCount);
121}
122
123void geometry_setIndices32(u32 handle, uintptr_t indicesPtr, u32 indexCount) {
124 if (!g_geometryManager || indicesPtr == 0) return;
125
126 auto* geom = g_geometryManager->get(handle);
127 if (!geom) return;
128
129 const u32* indices = boundarySpan<u32>(indicesPtr, indexCount, "geometry_setIndices32");
130 if (!indices) return;
131 geom->setIndices(indices, indexCount);
132}
133
134void geometry_updateVertices(u32 handle, uintptr_t verticesPtr, u32 vertexCount, u32 offset) {
135 if (!g_geometryManager || verticesPtr == 0) return;
136
137 auto* geom = g_geometryManager->get(handle);
138 if (!geom) return;
139
140 const f32* vertices = boundarySpan<f32>(
141 verticesPtr, static_cast<u64>(vertexCount) * (geom->getVertexStride() / sizeof(f32)),
142 "geometry_updateVertices");
143 if (!vertices) return;
144 geom->updateVertices(vertices, vertexCount, offset);
145}
146
147void geometry_release(u32 handle) {
148 if (!g_geometryManager) return;
149 g_geometryManager->release(handle);
150}
151
152bool geometry_isValid(u32 handle) {
153 if (!g_geometryManager) return false;
154 return g_geometryManager->isValid(handle);
155}
156
157void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {
159
160 auto* geom = g_geometryManager->get(geometryHandle);
161 if (!geom || !geom->isValid()) return;
162
163 Shader* shader = g_resourceManager->getShader(resource::ShaderHandle(shaderHandle));
164 if (!shader) return;
165
167
168 const f32* transformData = boundarySpan<f32>(transformPtr, 16, "draw_mesh.transform");
169 if (!transformData) return;
170 glm::mat4 transform = glm::make_mat4(transformData);
171
172 applyMeshPipeline(*g_device, *shader, *geom);
173 shader->setUniform("u_projection", g_currentViewProjection);
174 shader->setUniform("u_model", transform);
175 shader->commitParams();
176
177 drawGeometry(*g_device, *geom);
178}
179
180bool draw_meshWithMaterial(u32 geometryHandle, u32 materialId) {
181 if (!g_initialized || !g_geometryManager) return false;
182 auto* rc = g_renderContext;
183 if (!rc) return false;
184
185 // Route through the reflected path only when the material's shader registered a
186 // #pragma-param layout (compileEsshader). A raw-GLSL createShader program has no
187 // layout — return false so the SDK falls back to the legacy uniform-stream path.
188 const MaterialRecord* rec = rc->materials().find(materialId);
189 if (!rec || !rc->materials().layoutFor(rec->shaderRef)) return false;
190
191 auto* geom = g_geometryManager->get(geometryHandle);
192 if (!geom || !geom->isValid()) return true; // routed modern; nothing to draw
193
195
196 // The material record supplies the full pipeline state (same resolve as
197 // DrawList::execute); positioning comes from FrameConstants + params in the
198 // shader — no per-draw loose uniforms, so the draw is backend-neutral.
199 GfxDevice& device = *g_device;
200 // A program still compiling in the background draws nothing yet, as in the draw list: waiting for it here held the page.
201 if (device.skipPendingPrograms() && !device.programReady(ShaderHandle{rec->shader})) return true;
202 PipelineDesc desc{};
203 desc.program = ShaderHandle{rec->shader};
204 desc.vertexLayout = geom->layoutHandle();
205 desc.blend = rec->blend;
206 desc.blendEnabled = true;
207 desc.depthTest = rec->depthTest;
208 desc.depthWrite = rec->depthWrite;
209 desc.cullEnabled = rec->cull != CullMode::None;
210 desc.cullFront = rec->cull == CullMode::Front;
212 device.setPipeline(device.createPipeline(desc));
213
214 // Per-material constants (binding 1): upload-if-dirty + bind, plus texture params.
215 rc->materials().bindForDraw(materialId);
216
217 drawGeometry(device, *geom);
218 return true;
219}
220
221void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr,
222 uintptr_t uniformsPtr, u32 uniformCount) {
224
225 auto* geom = g_geometryManager->get(geometryHandle);
226 if (!geom || !geom->isValid()) return;
227
228 Shader* shader = g_resourceManager->getShader(resource::ShaderHandle(shaderHandle));
229 if (!shader) return;
230
232
233 const f32* transformData = boundarySpan<f32>(transformPtr, 16, "draw_meshWithUniforms.transform");
234 if (!transformData) return;
235 glm::mat4 transform = glm::make_mat4(transformData);
236
237 applyMeshPipeline(*g_device, *shader, *geom);
238 shader->setUniform("u_projection", g_currentViewProjection);
239 shader->setUniform("u_model", transform);
240
241 static constexpr const char* UNIFORM_NAMES[] = {
242 "u_time", "u_color", "u_intensity", "u_scale", "u_offset",
243 "u_param0", "u_param1", "u_param2", "u_param3", "u_param4",
244 "u_vec0", "u_vec1", "u_vec2", "u_vec3",
245 "u_texture0", "u_texture1", "u_texture2", "u_texture3"
246 };
247 static constexpr u32 UNIFORM_NAME_COUNT = sizeof(UNIFORM_NAMES) / sizeof(UNIFORM_NAMES[0]);
248
249 const f32* uniforms = boundarySpan<f32>(uniformsPtr, uniformCount, "draw_meshWithUniforms.uniforms");
250 if (uniformCount != 0 && !uniforms) return;
251 u32 idx = 0;
252
253 // Each record is [type, nameId, payload...]; a truncated record must stop the
254 // walk instead of reading past uniformCount.
255 while (idx + 2 <= uniformCount) {
256 auto type = static_cast<i32>(uniforms[idx++]);
257 auto nameId = static_cast<i32>(uniforms[idx++]);
258 const u32 arity = (type == 10) ? 2u : (type >= 1 && type <= 4 ? static_cast<u32>(type) : 0u);
259 if (uniformCount - idx < arity) break;
260
261 const char* name = (nameId >= 0 && static_cast<u32>(nameId) < UNIFORM_NAME_COUNT)
262 ? UNIFORM_NAMES[nameId] : "u_unknown";
263
264 switch (type) {
265 case 1: {
266 f32 value = uniforms[idx++];
267 shader->setUniform(name, value);
268 break;
269 }
270 case 2: {
271 glm::vec2 value(uniforms[idx], uniforms[idx + 1]);
272 idx += 2;
273 shader->setUniform(name, value);
274 break;
275 }
276 case 3: {
277 glm::vec3 value(uniforms[idx], uniforms[idx + 1], uniforms[idx + 2]);
278 idx += 3;
279 shader->setUniform(name, value);
280 break;
281 }
282 case 4: {
283 glm::vec4 value(uniforms[idx], uniforms[idx + 1],
284 uniforms[idx + 2], uniforms[idx + 3]);
285 idx += 4;
286 shader->setUniform(name, value);
287 break;
288 }
289 case 10: {
290 i32 slot = static_cast<i32>(uniforms[idx++]);
291 u32 textureId = static_cast<u32>(uniforms[idx++]);
292 // Material.tex carries a resource identity, just like the reflected
293 // material store. Resolve at draw time so device re-uploads behind
294 // the same resource handle do not leave cached streams stale.
295 const Texture* texture = g_resourceManager->getTexture(resource::TextureHandle{textureId});
296 g_device->bindTexture(static_cast<u32>(slot), texture ? texture->handle() : TextureHandle::Invalid);
297 shader->setUniform(name, slot);
298 break;
299 }
300 default:
301 break;
302 }
303 }
304
305 // Lifted uniforms (everything above except the sampler slots) live in the
306 // shader's DrawParams block; flush + bind them for this draw.
307 shader->commitParams();
308
309 drawGeometry(*g_device, *geom);
310}
311
312} // namespace esengine
313
Always-on validation for JS-supplied pointer+length pairs at the WASM boundary.
GPU buffer abstractions for vertex and index data.
Custom geometry for user-defined mesh rendering.
#define g_renderContext
#define g_geometryManager
#define g_immediateDrawActive
#define g_resourceManager
#define g_initialized
#define g_immediateDraw
#define g_currentViewProjection
#define g_device
Abstract graphics device interface.
Immediate mode 2D drawing API.
#define ES_LOG_WARN(...)
Logs a warning message.
Definition Log.hpp:294
Engine-side material registry — the resolved "how to draw" for a material handle.
Rendering context containing all renderer state.
Frame resources and the shared scene rendering contract.
Central resource management system.
System for computing hierarchical world transforms.
Custom geometry for user-defined mesh rendering.
const IndexBuffer * indexBuffer() const
Gets the index buffer (null when non-indexed).
bool hasIndices() const
Checks if geometry uses indices.
u32 getVertexCount() const
Gets the vertex count.
void bind(GfxDevice &device) const
Binds the geometry's buffers for the next draw.
u32 getIndexCount() const
Gets the index count.
VertexLayoutHandle layoutHandle() const
The device vertex layout a pipeline drawing this geometry must reference.
Abstract graphics device interface.
Definition GfxDevice.hpp:75
bool programReady(ShaderHandle program)
Whether program can be drawn with now, without waiting: linked, or finished linking in the background...
void invalidatePipelineCache()
Forces the next setPipeline to re-apply, dropping the cached current pipeline.
bool skipPendingPrograms() const
virtual void drawElements(u32 indexCount, GfxDataType indexType, u32 byteOffset)=0
Draws indexed triangles.
void setPipeline(PipelineHandle handle)
Binds a pipeline: applies its program, blend, depth, stencil compare/op and culling.
virtual void drawArrays(u32 first, u32 vertexCount)=0
Draws non-indexed triangles.
PipelineHandle createPipeline(const PipelineDesc &desc)
Resolves a pipeline description to a cached handle (creating it on first use).
GPU shader program for rendering.
Definition Shader.hpp:86
void commitParams()
Uploads the shadow (when dirty) and binds this shader's params UBO at DRAW_PARAMS_BINDING.
Definition Shader.cpp:382
void setUniform(const std::string &name, i32 value) const
Sets an integer uniform.
Definition Shader.cpp:422
ShaderHandle handle() const
Gets the device program handle.
Definition Shader.hpp:254
2D texture for GPU rendering
Definition Texture.hpp:116
TextureHandle handle() const
Gets the device texture handle.
Definition Texture.hpp:233
Describes the layout of vertex data in a buffer.
Definition Buffer.hpp:126
u32 getStride() const
Gets the stride (total size) of one vertex.
Definition Buffer.hpp:155
Handle< esengine::Shader > ShaderHandle
Handle to a shader resource.
Definition Handle.hpp:214
Handle< esengine::Texture > TextureHandle
Handle to a texture resource.
Definition Handle.hpp:217
void geometry_updateVertices(u32 handle, uintptr_t verticesPtr, u32 vertexCount, u32 offset)
const T * boundarySpan(uintptr_t ptr, u64 count, const char *what)
Validates a JS-supplied pointer to count elements of T and returns it typed.
std::int32_t i32
Signed 32-bit integer.
Definition Types.hpp:54
bool geometry_isValid(u32 handle)
void geometry_release(u32 handle)
static void applyMeshPipeline(GfxDevice &device, const Shader &shader, const CustomGeometry &geom)
std::uint64_t u64
Unsigned 64-bit integer.
Definition Types.hpp:47
bool draw_meshWithMaterial(u32 geometryHandle, u32 materialId)
ShaderDataType
Vertex attribute data types.
Definition Buffer.hpp:45
static void flushImmediateDrawIfActive()
u32 geometry_create()
void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr)
void geometry_setIndices32(u32 handle, uintptr_t indicesPtr, u32 indexCount)
std::uint32_t u32
Unsigned 32-bit integer.
Definition Types.hpp:45
static void drawGeometry(GfxDevice &device, CustomGeometry &geom)
std::uint16_t u16
Unsigned 16-bit integer.
Definition Types.hpp:43
void geometry_init(u32 handle, uintptr_t verticesPtr, u32 vertexCount, uintptr_t layoutPtr, u32 layoutCount, bool dynamic)
void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount)
void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr, uintptr_t uniformsPtr, u32 uniformCount)
static EstellaContext & ctx()
EstellaContext & activeCtx()
The engine context every binding routes through — single source of truth.
float f32
32-bit floating point
Definition Types.hpp:59
A material's resolved render state (P0) plus its packed std140 constants (P1).
resource::ShaderHandle shaderRef
u32 shader
Program id; 0 means "use the path's default batch shader".
Immutable description of a draw pipeline. Equality keys the pipeline cache, so two draws with the sam...
VertexLayoutHandle vertexLayout