Debian Codegraph @

src/base_rendering/castlerenderprimitives_render_unlit_mesh.inc

raw
1 {%MainUnit castlerenderprimitives.pas}
2 {
3 Copyright 2023-2023 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 { TCastleRenderUnlitMesh class. }
18
19 {$ifdef read_interface}
20
21 type
22 { Render a set of vertexes, with optional indexes.
23 Can be used multiple times, to render the same vertexes many times.
24
25 This is a deliberately simple and @italic(thin) wrapper over creating
26 and drawing a bunch of vertexes on modern GPUs.
27 E.g. on OpenGL(ES) it creates 1 VBO (vertex buffer object) for position data
28 and optional 1 VBO for indexes (if SetIndexes is ever called).
29
30 Make sure all usage is within the same rendering context.
31 This has to be created and destroyed while the OpenGL(ES) context is active.
32
33 This is suitable to render only trivial unlit (or invisible) meshes.
34 @italic(This is not a full-featured mesh renderer.)
35 Some deliberate limitations / hardcoded assumptions to keep this class simple:
36
37 @unorderedList(
38 @item(It doesn't define any per-vertex attributes other than vertex positions.)
39
40 @item(If it uses indexes, it always uses 16-bit indexes, not 32-bit.
41 So it works even with OpenGLES 2.0 (not 3.0) or WebGL 1.0.)
42
43 @item(Always passes vectors as 4D (in homogeneous coordinates).
44 4D coordinates are useful e.g. for shadow volume quads.)
45
46 @item(It follows various current @link(RenderContext) state,
47 like @link(TRenderContext.DepthTest),
48 @link(TRenderContext.LineWidth) -- it doesn't control this state.)
49 )
50
51 For a full-featured mesh rendering, just use TCastleScene, and construct your
52 mesh as TIndexedTriangleSetNode or TIndexedFaceSetNode, see
53 https://castle-engine.io/viewport_and_scenes_from_code#_building_a_mesh_using_code .
54
55 The things you really have to set before rendering are:
56
57 @unorderedList(
58 @item(Vertexes, using @link(SetVertexes).)
59 @item(Matrix (combined projection * camera * model transformation) @link(ModelViewProjection).)
60 @item(That's it, the rest has sensible defaults. You can just call @link(Render).)
61 )
62
63 For shading this uses a simple shader:
64
65 @unorderedList(
66 @item(If @link(UseColor) (default @true) then the shader writes @link(Color)
67 to the color buffer. Effectively this makes unlit rendering.
68
69 Note: This class does not set up blending if @link(Color) alpha is less than 1.
70 If you want blending, set it yourself using @link(TRenderContext.BlendingEnable)
71 and disable using @link(TRenderContext.BlendingDisable).
72 )
73
74 @item(If @link(UseColor) is @false then the shader writes undefined
75 value to the color buffer.
76
77 But it still writes proper values to depth and stencil.
78
79 This is esp. useful when you render things with color buffer disabled
80 (using @code(RenderContext.ColorChannels := [])).
81 The rendering may still be useful, e.g. to fill depth buffer (for shadow maps),
82 stencil buffer, or define shape for GPU occlusion query.
83
84 Note: This class does not configure @code(RenderContext.ColorChannels).
85 It is up to you to decide how to hide from user the undefined effect
86 this has on the color buffer.
87 )
88 )
89
90 Example usage:
91
92 @longCode(#
93 SavedDepthTest := RenderContext.DepthTest;
94 RenderContext.DepthTest := true;
95
96 Mesh := TCastleRenderUnlitMesh.Create(true);
97 try
98 Mesh.Color := Yellow;
99 Mesh.ModelViewProjection := RenderContext.ProjectionMatrix * RenderingCamera.CurrentMatrix;
100 Mesh.SetVertexes([
101 Vector3(0, 0, 0, 1),
102 Vector3(10, 0, 0, 1),
103 Vector3(0, 10, 0, 1)
104 ], false);
105 Mesh.Render(pmTriangles);
106 finally FreeAndNil(Mesh) end;
107
108 RenderContext.DepthTest := SavedDepthTest;
109 #)
110 }
111 TCastleRenderUnlitMesh = class
112 strict private
113 type
114 TProgram = record
115 Shader: TGLSLProgram;
116 UniformModelViewProjectionMatrix, UniformColor: TGLSLUniform;
117 AttributeVertex: TGLSLAttribute;
118 end;
119
120 class var
121 Programs: array [ { UseColor? } Boolean ] of TProgram;
122
123 var
124 FUseColor: Boolean;
125 FColor: TCastleColor;
126 VboVertex, VboIndex: TGLuint;
127 VertexAllocatedBytes, IndexAllocatedBytes,
128 VertexAllocatedItems, IndexAllocatedItems: Cardinal;
129 FixedFunctionVertexes: TVector4List;
130 FixedFunctionIndexes: TUInt16List;
131 Vao: TVertexArrayObject;
132
133 class procedure PrepareShader(const AUseColor: Boolean);
134 procedure SetUseColor(const Value: Boolean);
135 private
136 class procedure StaticGLContextClose;
137 public
138 { By default all zeros, you must set this before any rendering. }
139 ModelViewProjection: TMatrix4;
140
141 constructor Create(const AUseColor: Boolean = true);
142 destructor Destroy; override;
143
144 { Define indexes for all future rendering.
145 Note: Passing indexes that do not exist in vertexes you define in SetVertexes
146 may result in crashes, neither CGE nor rendering API necessarily check it. }
147 procedure SetIndexes(const Indexes: array of UInt16); overload;
148 procedure SetIndexes(const Indexes: PUInt16; const IndexesCount: Cardinal); overload;
149
150 { Set vertexes (points) to render.
151
152 UsageDynamic is an optimization hint, pass @true if you plan to change this VBO often,
153 e.g. always or almost-always before each @link(Render) you will send new vertexes
154 with @link(SetVertexes). Pass @false if this VBO stays constant for a long time,
155 and will be drawn many times (so you call @link(SetVertexes) once,
156 then many times @link(Render)). }
157 procedure SetVertexes(const Vertexes: array of TVector4;
158 const UsageDynamic: Boolean); overload;
159 procedure SetVertexes(const Vertexes: TVector4List;
160 const UsageDynamic: Boolean); overload;
161 procedure SetVertexes(const Vertexes: PVector4; const VertexesCount: Cardinal;
162 const UsageDynamic: Boolean); overload;
163
164 { Should we render with @link(Color) (if @false, output color is undefined). }
165 property UseColor: Boolean read FUseColor write SetUseColor;
166
167 { Color used for unlit rendering, if only UseColor is @true. Opaque white by default. }
168 property Color: TCastleColor read FColor write FColor;
169
170 procedure Render(const Mode: TPrimitiveMode);
171 end;
172
173 {$endif read_interface}
174
175 {$ifdef read_implementation}
176
177 { TODO: Constants duplicated from castleglutils_draw_primitive_2d.inc,
178 maybe one day we'll join DrawPrimitive2D and TCastleRenderUnlitMesh into one unit
179 (CastleRenderPrimitives?) which would make it natural to define this in one place. }
180
181 const
182 PrimitiveModeToGL: array [TPrimitiveMode] of TGLEnum = (
183 GL_POINTS,
184 GL_LINE_STRIP,
185 GL_LINE_LOOP,
186 GL_LINES,
187 GL_TRIANGLE_STRIP,
188 GL_TRIANGLE_FAN,
189 GL_TRIANGLES
190 );
191
192 constructor TCastleRenderUnlitMesh.Create(const AUseColor: Boolean);
193 begin
194 inherited Create;
195 FUseColor := AUseColor;
196 FColor := White;
197 PrepareShader(AUseColor);
198 Vao := TVertexArrayObject.Create(nil);
199 end;
200
201 destructor TCastleRenderUnlitMesh.Destroy;
202 begin
203 FreeAndNil(Vao);
204 glFreeBuffer(VboIndex);
205 glFreeBuffer(VboVertex);
206 inherited;
207 end;
208
209 class procedure TCastleRenderUnlitMesh.PrepareShader(const AUseColor: Boolean);
210 const
211 SimplestVS = {$I simplest.vs.inc};
212 SimplestFS = {$I simplest.fs.inc};
213 SimplestUnlitFS = {$I simplest_unlit.fs.inc};
214 var
215 Shader: TGLSLProgram;
216 begin
217 if GLFeatures.EnableFixedFunction then
218 Exit;
219 Assert(GLFeatures.Shaders); // EnableFixedFunction and Shaders are now synchronized
220
221 // already prepared
222 if Programs[AUseColor].Shader <> nil then
223 Exit;
224
225 Shader := TGLSLProgram.Create;
226 Shader.Name := 'TCastleRenderUnlitMesh:UseColor=' + BoolToStr(AUseColor, true);
227 Shader.AttachShader(stVertex, SimplestVS);
228
229 if AUseColor then
230 begin
231 Shader.AttachShader(stFragment, SimplestUnlitFS);
232 end else
233 begin
234 { On desktop OpenGL, fragment shader doesn't need to exist now.
235 https://www.khronos.org/opengl/wiki/Fragment_Shader#Optional
236 It still has to exist with OpenGLES.
237 Also macOS requires it always (in "core" profile), otherwise rendering shadow volumes
238 makes GL error at glDrawArrays in this unit. }
239 {$if defined(OpenGLES) or defined(DARWIN)}
240 Shader.AttachShader(stFragment, SimplestFS);
241 {$endif}
242 end;
243
244 Shader.Link;
245
246 Programs[AUseColor].Shader := Shader;
247 Programs[AUseColor].AttributeVertex := Shader.Attribute('castle_Vertex');
248 Programs[AUseColor].UniformModelViewProjectionMatrix := Shader.Uniform('castle_ModelViewProjectionMatrix');
249 if AUseColor then
250 Programs[AUseColor].UniformColor := Shader.Uniform('color');
251 end;
252
253 class procedure TCastleRenderUnlitMesh.StaticGLContextClose;
254 begin
255 FreeAndNil(Programs[false].Shader);
256 FreeAndNil(Programs[true].Shader);
257 end;
258
259 procedure TCastleRenderUnlitMesh.Render(const Mode: TPrimitiveMode);
260
261 { Call glDrawElements or glDrawArrays.
262 IndexPtr is used only when using indexes, and should be
263 relative to VBO memory (if VBO is used). }
264 procedure RenderDrawCall(const IndexPtr: Pointer);
265 begin
266 if IndexAllocatedItems <> 0 then
267 begin
268 glDrawElements(PrimitiveModeToGL[Mode], IndexAllocatedItems, GL_UNSIGNED_SHORT, IndexPtr);
269 end else
270 glDrawArrays(PrimitiveModeToGL[Mode], 0, VertexAllocatedItems);
271 end;
272
273 { Render using modern pipeline. }
274 procedure RenderShaders;
275 begin
276 if VboVertex = 0 then
277 raise EInternalError.Create('TCastleRenderUnlitMesh has no vertexes defined to render');
278
279 RenderContext.CurrentProgram := Programs[UseColor].Shader;
280 RenderContext.CurrentVao := Vao;
281
282 RenderContext.BindBuffer[btArray] := VboVertex;
283 // do this even if VboIndex = 0, to set this to 0
284 RenderContext.BindBuffer[btElementArray] := VboIndex;
285
286 if FUseColor then
287 Programs[UseColor].UniformColor.SetValue(Color);
288 Programs[UseColor].UniformModelViewProjectionMatrix.SetValue(ModelViewProjection);
289 Programs[UseColor].AttributeVertex.EnableArrayVector4(Vao, SizeOf(TVector4), 0);
290
291 RenderDrawCall(nil);
292
293 Programs[UseColor].AttributeVertex.DisableArray;
294
295 RenderContext.BindBuffer[btArray] := 0;
296 RenderContext.BindBuffer[btElementArray] := 0;
297 end;
298
299 {$ifndef OpenGLES}
300 { Render using ancient fixed-function pipeline. }
301 procedure RenderFixedFunction;
302 var
303 SavedFixedFunctionLighting: Boolean;
304 IndexPtr: Pointer;
305 begin
306 if FUseColor then
307 glColorv(Color);
308
309 { We load as GL_MODELVIEW the complete matrix projection * modelview.
310 This keeps our API simple (we just need 1 matrix, ModelViewProjection, already multiplied)
311 and is good enough for rendering unlit stuff.
312 So for GL_PROJECTION, we make sure to load identity. }
313
314 glMatrixMode(GL_PROJECTION);
315 glPushMatrix;
316 glLoadIdentity;
317 glMatrixMode(GL_MODELVIEW);
318 glLoadMatrix(ModelViewProjection);
319
320 glEnableClientState(GL_VERTEX_ARRAY);
321 glVertexPointer(4, GL_FLOAT, SizeOf(TVector4), FixedFunctionVertexes.L);
322
323 SavedFixedFunctionLighting := RenderContext.FixedFunctionLighting;
324 RenderContext.FixedFunctionLighting := false;
325
326 if FixedFunctionIndexes = nil then
327 IndexPtr := nil
328 else
329 IndexPtr := FixedFunctionIndexes.L;
330
331 RenderDrawCall(IndexPtr);
332
333 { Restore GL_PROJECTION matrix value, other drawing code may depend on it.
334 Don't restore GL_MODELVIEW, no need, other drawing code has to be prepared
335 to always initialize GL_MODELVIEW. }
336 glMatrixMode(GL_PROJECTION);
337 glPopMatrix;
338 glMatrixMode(GL_MODELVIEW);
339
340 glDisableClientState(GL_VERTEX_ARRAY);
341
342 RenderContext.FixedFunctionLighting := SavedFixedFunctionLighting;
343 end;
344 {$endif}
345
346 begin
347 {$ifndef OpenGLES}
348 if GLFeatures.EnableFixedFunction then
349 RenderFixedFunction
350 else
351 {$endif}
352 RenderShaders;
353 end;
354
355 procedure TCastleRenderUnlitMesh.SetIndexes(const Indexes: array of UInt16);
356 begin
357 { Note: This assumes that Indexes is actually a "packed array of UInt16",
358 but it cannot be declared as such in Delphi.
359 We verify it by test TTestCompiler.TestPackedOpenArray in CGE tests/ projects. }
360 SetIndexes(@Indexes[0], High(Indexes) + 1);
361 end;
362
363 procedure TCastleRenderUnlitMesh.SetIndexes(const Indexes: PUInt16; const IndexesCount: Cardinal);
364 var
365 NewVbo: Boolean;
366 NewSize: Cardinal;
367 begin
368 if not GLFeatures.EnableFixedFunction then
369 begin
370 NewVbo := VboIndex = 0;
371 if NewVbo then
372 glGenBuffers(1, @VboIndex);
373
374 RenderContext.BindBuffer[btElementArray] := VboIndex;
375
376 NewSize := IndexesCount * SizeOf(UInt16);
377 if NewVbo or (NewSize <> IndexAllocatedBytes) then
378 begin
379 // always GL_STATIC_DRAW for indexes, we assume we will not modify indexes very often
380 glBufferData(GL_ELEMENT_ARRAY_BUFFER, NewSize, Indexes, GL_STATIC_DRAW);
381 IndexAllocatedBytes := NewSize;
382 IndexAllocatedItems := IndexesCount;
383 end else
384 glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, NewSize, Indexes);
385 end else
386 begin
387 IndexAllocatedItems := IndexesCount;
388 IndexAllocatedBytes := SizeOf(UInt16) * IndexesCount;
389 if FixedFunctionIndexes = nil then
390 FixedFunctionIndexes := TUInt16List.Create;
391 FixedFunctionIndexes.Count := IndexesCount;
392 Move(Indexes^, FixedFunctionIndexes.L^, IndexAllocatedBytes);
393 end;
394 end;
395
396 procedure TCastleRenderUnlitMesh.SetVertexes(const Vertexes: PVector4; const VertexesCount: Cardinal;
397 const UsageDynamic: Boolean);
398 var
399 NewVbo: Boolean;
400 NewSize: Cardinal;
401 DataUsage: TGLEnum;
402 begin
403 if not GLFeatures.EnableFixedFunction then
404 begin
405 NewVbo := VboVertex = 0;
406 if NewVbo then
407 glGenBuffers(1, @VboVertex);
408
409 RenderContext.BindBuffer[btArray] := VboVertex;
410
411 NewSize := VertexesCount * SizeOf(TVector4);
412 if NewVbo or (NewSize <> VertexAllocatedBytes) then
413 begin
414 if UsageDynamic then
415 { GL_STREAM_DRAW is most suitable if we will modify this every frame,
416 according to
417 https://www.khronos.org/opengl/wiki/Buffer_Object
418 https://computergraphics.stackexchange.com/questions/5712/gl-static-draw-vs-gl-dynamic-draw-vs-gl-stream-draw-does-it-matter
419 }
420 DataUsage := GL_STREAM_DRAW
421 else
422 DataUsage := GL_STATIC_DRAW;
423 glBufferData(GL_ARRAY_BUFFER, NewSize, Vertexes, DataUsage);
424 VertexAllocatedBytes := NewSize;
425 VertexAllocatedItems := VertexesCount;
426 end else
427 glBufferSubData(GL_ARRAY_BUFFER, 0, NewSize, Vertexes);
428 end else
429 begin
430 VertexAllocatedItems := VertexesCount;
431 VertexAllocatedBytes := SizeOf(TVector4) * VertexesCount;
432 if FixedFunctionVertexes = nil then
433 FixedFunctionVertexes := TVector4List.Create;
434 FixedFunctionVertexes.Count := VertexesCount;
435 Move(Vertexes^, FixedFunctionVertexes.L^, VertexAllocatedBytes);
436 end;
437 end;
438
439 procedure TCastleRenderUnlitMesh.SetVertexes(const Vertexes: array of TVector4;
440 const UsageDynamic: Boolean);
441 begin
442 { Note: This assumes that Vertexes is actually a "packed array of TVector4",
443 but it cannot be declared as such in Delphi.
444 We verify it by test TTestCompiler.TestPackedOpenArray in CGE tests/ projects. }
445 SetVertexes(@Vertexes[0], High(Vertexes) + 1, UsageDynamic);
446 end;
447
448 procedure TCastleRenderUnlitMesh.SetVertexes(const Vertexes: TVector4List;
449 const UsageDynamic: Boolean);
450 begin
451 SetVertexes(PVector4(Vertexes.L), Vertexes.Count, UsageDynamic);
452 end;
453
454 procedure TCastleRenderUnlitMesh.SetUseColor(const Value: Boolean);
455 begin
456 if FUseColor <> Value then
457 begin
458 FUseColor := Value;
459 PrepareShader(Value);
460 end;
461 end;
462
463 {$endif read_implementation}