Debian Codegraph @

examples/research_special_rendering_methods/dynamic_ambient_occlusion/code/gameviewmain.pas

raw
1 {
2 Copyright 2009-2023 Michalis Kamburelis.
3
4 This file is part of "Castle Game Engine".
5
6 "Castle Game Engine" is free software; see the file COPYING.txt,
7 included in this distribution, for details about the copyright.
8
9 "Castle Game Engine" is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
12
13 ----------------------------------------------------------------------------
14 }
15
16 { Main view, where most of the application logic takes place. }
17 unit GameViewMain;
18
19 {$ifndef FPC}
20 {$pointermath on}
21 {$warn COMPARING_SIGNED_UNSIGNED off}
22 {$endif}
23
24 interface
25
26 uses Classes,
27 {$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif}
28 CastleVectors, CastleComponentSerialize, CastleViewport,
29 CastleUIControls, CastleControls, CastleKeysMouse, CastleGLUtils,
30 CastleTransform, CastleShapes, CastleUtils, CastleScene, CastleGLShaders,
31 CastleImages, CastleColors, CastleSceneCore, CastleWindow;
32
33 type
34 { Main view, where most of the application logic takes place. }
35 TViewMain = class(TCastleView)
36 published
37 { Components designed using CGE editor.
38 These fields will be automatically initialized at Start. }
39 LabelFps: TCastleLabel;
40 CheckboxPlayAnimation: TCastleCheckbox;
41 ButtonDrawDisable: TCastleButton;
42 ButtonDrawElements: TCastleButton;
43 ButtonDrawElementsIntensity: TCastleButton;
44 ButtonDrawPass1: TCastleButton;
45 ButtonDrawPass2: TCastleButton;
46 private
47 type
48 TMyViewport = class(TCastleViewport)
49 public
50 View: TViewMain;
51 RectVbo: TGLuint;
52 RectVao: TVertexArrayObject;
53 procedure RenderFromView3D(const Params: TRenderParams); override;
54 end;
55
56 TShapeInfo = record
57 Shape: TShape;
58 CoordToElement: array of Integer;
59 end;
60 PShapeInfo = ^TShapeInfo;
61
62 TAOElement = record
63 Area: Single;
64 { Position and Normal are in *world* coordinates (not local!) }
65 Position, Normal: TVector3;
66 end;
67 PAOElement = ^TAOElement;
68 TAOElementList = {$ifdef FPC}specialize{$endif} TStructList<TAOElement>;
69
70 TElementsCalculator = class
71 public
72 CoordIndex: TInt32List;
73 Coord: TVector3List;
74 ShapeElements: PAOElement;
75
76 procedure Polygon(const Indexes: array of Cardinal);
77 end;
78
79 TDrawType = (dtDisable, dtElements, dtElementsIntensity, dtPass1, dtPass2);
80
81 var
82 Scene: TCastleScene;
83 SceneElements: TCastleScene;
84 Viewport: TMyViewport;
85 GLSLProgram: array [0..1] of TGLSLProgram;
86 DrawType: TDrawType;
87 ShadowScale: Single;
88
89 Elements: TAOElementList;
90 AoShapes: array of TShapeInfo;
91
92 FullRenderShape: TShape;
93 FullRenderShapeInfo: PShapeInfo;
94 FullRenderIntensityTex: TGrayscaleImage;
95
96 ElementsPositionAreaTex: TRGBAlphaImage;
97 ElementsNormalTex: TRGBImage;
98 { All Elements*Tex are square and have the same size:
99 ElementsTexSize x ElementsTexSize. }
100 ElementsTexSize: Cardinal;
101
102 GLElementsPositionAreaTex: TGLuint;
103 GLElementsNormalTex: TGLuint;
104 GLElementsIntensityTex: TGLuint;
105
106 { We will pack position (with arbitrary 3 float) and areas (with arbitrary
107 float >= 0) and normal components (with floats in -1..1 range)
108 into the texture components, which are limited to 0..1 range.
109
110 "Scale" and "shift" are used on CPU to squeeze value into texture,
111 such that
112 tex_value := value / scale - shift;
113 Then GPU can do
114 value := (tex_value + shift) * scale;
115 (as you see, we do the more costly division on CPU, to allow GPU
116 to run with maximum speed).
117
118 For normal vector components, scale = 2, shift = -0.5.
119 For area, shift = 0, scale = calculated using max area.
120 For positions, both scale and shift are calculated, using bounding box
121 of points. }
122 PositionScale, PositionShift: TVector3;
123 AreaScale: Single;
124 Verbose: Boolean; //< always left as false now, set to true in Start if needed to debug
125
126 function VertexColor(
127 const Shape: TShape;
128 const VertexPosition: TVector3;
129 const VertexIndex: Integer): TCastleColorRGB;
130 procedure SceneGeometryChanged(AScene: TCastleSceneCore;
131 const SomeLocalGeometryChanged: boolean;
132 OnlyShapeChanged: TShape);
133
134 { Storing and calculating "elements" for dynamic ambient occlusion algorithm. }
135 procedure CalculateElements;
136 procedure CalculateElementsTex;
137
138 procedure SetDrawType(const NewDrawType: TDrawType);
139
140 procedure CheckboxPlayAnimationChange(Sender: TObject);
141 procedure ButtonDrawDisableClick(Sender: TObject);
142 procedure ButtonDrawElementsClick(Sender: TObject);
143 procedure ButtonDrawElementsIntensityClick(Sender: TObject);
144 procedure ButtonDrawPass1Click(Sender: TObject);
145 procedure ButtonDrawPass2Click(Sender: TObject);
146 public
147 constructor Create(AOwner: TComponent); override;
148 procedure Start; override;
149 procedure Stop; override;
150 procedure Update(const SecondsPassed: Single; var HandleInput: Boolean); override;
151 function Press(const Event: TInputPressRelease): Boolean; override;
152 end;
153
154 var
155 ViewMain: TViewMain;
156
157 implementation
158
159 uses SysUtils, Math,
160 CastleTriangles, CastleClassUtils, CastleParameters,
161 CastleFilesUtils, CastleStringUtils,
162 X3DFields, X3DNodes, CastleGLImages, CastleMessages, CastleLog,
163 CastleGLVersion, CastleRectangles, CastleApplicationProperties,
164 CastleRenderContext, CastleCameras,
165 SceneUtilities;
166
167 { TMyViewport ---------------------------------------------------------------- }
168
169 procedure TViewMain.TMyViewport.RenderFromView3D(const Params: TRenderParams);
170
171 function CaptureAORect(SizePower2: boolean): TGrayscaleImage;
172 var
173 TexHeight: Cardinal;
174 begin
175 if SizePower2 then
176 TexHeight := View.ElementsTexSize else
177 { If size doesn't have to be power of 2 (e.g. if this is grabbed
178 only for CPU), then height may be smaller, which is a good thing
179 --- we don't have to grab so much pixels from color buffer. }
180 TexHeight := DivRoundUp(Cardinal(View.Elements.Count), View.ElementsTexSize);
181 Result := SaveScreen_NoFlush(TGrayscaleImage,
182 Rectangle(0, 0, View.ElementsTexSize, TexHeight),
183 Application.MainWindow.SaveScreenBuffer) as
184 TGrayscaleImage;
185 end;
186
187 procedure RenderAORect;
188
189 { Use direct OpenGL(ES) calls to render rectangle with 2D projection.
190 This is a bit like DrawPrimitive2D implementation, but simplified to only
191 account for rectangle and for EnableFixedFunction = false case. }
192 procedure RenderRect(const Rect: TFloatRectangle);
193 var
194 Points: array [0..3] of TVector2;
195 UniformViewportSize: TGLSLUniform;
196 AttribVertex: TGLSLAttribute;
197 begin
198 Points[0] := Vector2(Rect.Left , Rect.Bottom);
199 Points[1] := Vector2(Rect.Right, Rect.Bottom);
200 Points[2] := Vector2(Rect.Right, Rect.Top);
201 Points[3] := Vector2(Rect.Left , Rect.Top);
202
203 if RectVao = nil then
204 RectVao := TVertexArrayObject.Create(nil);
205 RenderContext.CurrentVao := RectVao;
206
207 if RectVbo = 0 then
208 glGenBuffers(1, @RectVbo);
209 RenderContext.BindBuffer[btArray] := RectVbo;
210 glBufferData(GL_ARRAY_BUFFER, SizeOf(Points), @Points, GL_DYNAMIC_DRAW);
211
212 UniformViewportSize := RenderContext.CurrentProgram.Uniform('viewport_size');
213 AttribVertex := RenderContext.CurrentProgram.Attribute('vertex');
214
215 AttribVertex.EnableArrayVector2(RectVao, SizeOf(TVector2), 0);
216 UniformViewportSize.SetValue(Vector2(
217 RenderContext.Viewport.Width,
218 RenderContext.Viewport.Height
219 ));
220
221 glDrawArrays(GL_TRIANGLE_FAN, 0, High(Points) + 1);
222
223 AttribVertex.DisableArray;
224 RenderContext.BindBuffer[btArray] := 0;
225 RenderContext.BindBuffer[btElementArray] := 0;
226 end;
227
228 procedure DoRender(Pass: Integer);
229 var
230 Prog: TGLSLProgram;
231 begin
232 Prog := View.GLSLProgram[Pass];
233 Prog.Enable;
234
235 Assert(Assigned(glActiveTexture));
236
237 glActiveTexture(GL_TEXTURE0);
238 glBindTexture(GL_TEXTURE_2D, View.GLElementsPositionAreaTex);
239 Prog.SetUniform('tex_elements_position_area', 0);
240
241 glActiveTexture(GL_TEXTURE1);
242 glBindTexture(GL_TEXTURE_2D, View.GLElementsNormalTex);
243 Prog.SetUniform('tex_elements_normal', 1);
244
245 if Pass = 1 then
246 begin
247 { GLElementsIntensityTex is already bound to GL_TEXTURE2 }
248 Prog.SetUniform('tex_elements_intensity', 2);
249 end;
250
251 Prog.SetUniform('area_scale', View.AreaScale);
252 Prog.SetUniform('position_scale', View.PositionScale);
253 Prog.SetUniform('position_shift', View.PositionShift);
254
255 Prog.SetUniform('shadow_scale', View.ShadowScale);
256
257 { Render rectangle with each pixel corresponding to one element
258 that needs intensity calculated. }
259 RenderRect(FloatRectangle(
260 0,
261 0,
262 View.ElementsTexSize,
263 DivRoundUp(Cardinal(View.Elements.Count), View.ElementsTexSize)
264 ));
265
266 Prog.Disable;
267 end;
268
269 begin
270 DoRender(0);
271
272 if View.DrawType = dtPass2 then
273 begin
274 { Alternative way to copy texture through CPU:
275 var
276 ElementsIntensityTex: TGrayscaleImage;
277 ElementsIntensityTex := CaptureAORect(true);
278 LoadGLGeneratedTexture(GLElementsIntensityTex, ElementsIntensityTex,
279 GL_NEAREST, GL_NEAREST);}
280
281 { Capture result of 1st pass into GLElementsIntensityTex
282 using glCopyTexSubImage2D. Also, this BTW binds GLElementsIntensityTex
283 to GL_TEXTURE2 texture unit, used by DoRender(1). }
284
285 glActiveTexture(GL_TEXTURE2);
286 glBindTexture(GL_TEXTURE_2D, View.GLElementsIntensityTex);
287 glReadBuffer(GL_BACK);
288 glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0,
289 View.ElementsTexSize, View.ElementsTexSize);
290
291 DoRender(1);
292 end;
293 end;
294
295 begin
296 if View.DrawType in [dtPass1, dtPass2] then
297 begin
298 FreeAndNil(View.FullRenderIntensityTex); // free previous FullRenderIntensityTex
299
300 RenderAORect;
301 View.FullRenderIntensityTex := CaptureAORect(false);
302 View.FullRenderShape := nil;
303 SetSceneColors(View.Scene, {$ifdef FPC}@{$endif} View.VertexColor);
304 end;
305 inherited;
306 end;
307
308 { TElementsCalculator -------------------------------------------------------- }
309
310 procedure TViewMain.TElementsCalculator.Polygon(
311 const Indexes: array of Cardinal);
312 var
313 FaceNormal: TVector3;
314 { DirectIndexes is Int32, not Cardinal array, since we cannot
315 guarantee that CoordIndex items are >= 0. }
316 DirectIndexes: array of Int32;
317 I: Integer;
318 FaceArea: Single;
319 begin
320 SetLength(DirectIndexes, Length(Indexes));
321 if CoordIndex <> nil then
322 begin
323 for I := 0 to Length(Indexes) - 1 do
324 DirectIndexes[I] := CoordIndex[Indexes[I]];
325 end else
326 begin
327 for I := 0 to Length(Indexes) - 1 do
328 DirectIndexes[I] := Indexes[I];
329 end;
330
331 FaceNormal := IndexedConvexPolygonNormal(
332 PInt32Array(DirectIndexes), Length(DirectIndexes),
333 { I pass ShapeElements, not Coord.List, pointer here,
334 to calculate normals in world-coordinates (that are
335 in ShapeElements[*].Position). }
336 PVector3Array(Addr(ShapeElements[0].Position)), Coord.Count, SizeOf(TAOElement),
337 Vector3(0, 0, 0));
338
339 { We assume here that polygon is convex, while in fact it doesn't
340 have to be. But this will be a good approximation anyway, usually. }
341
342 FaceArea := IndexedConvexPolygonArea(
343 PInt32Array(DirectIndexes), Length(DirectIndexes),
344 { I pass ShapeElements, not Coord.List, pointer here,
345 to calculate area in world-coordinates (that are
346 in ShapeElements[*].Position). }
347 PVector3Array(Addr(ShapeElements[0].Position)), Coord.Count, SizeOf(TAOElement));
348
349 { Split FaceArea into the number of polygon corners. }
350 FaceArea := FaceArea / Length(Indexes);
351
352 for I := 0 to Length(Indexes) - 1 do
353 if DirectIndexes[I] >= 0 then
354 begin
355 ShapeElements[DirectIndexes[I]].Normal :=
356 ShapeElements[DirectIndexes[I]].Normal + FaceNormal;
357 { Split FaceArea into the number of polygon corners. }
358 ShapeElements[DirectIndexes[I]].Area := ShapeElements[DirectIndexes[I]].Area + FaceArea;
359 end;
360 end;
361
362 { TViewMain ----------------------------------------------------------------- }
363
364 constructor TViewMain.Create(AOwner: TComponent);
365 begin
366 inherited;
367 DesignUrl := 'castle-data:/gameviewmain.castle-user-interface';
368 end;
369
370 procedure TViewMain.Start;
371
372 procedure CreateShaders;
373 var
374 FragmentShader, VertexShader: String;
375 begin
376 if not GLFeatures.Shaders then
377 raise Exception.Create('This GPU cannot handle dynamic ambient occlusion. GLSL shaders not supported.');
378 if GLFeatures.EnableFixedFunction then
379 raise Exception.Create('This GPU cannot handle dynamic ambient occlusion. Color.mode="MODULATE" does not work in fixed-function pipeline.');
380 if not GLFeatures.VertexBufferObject then
381 raise Exception.Create('This GPU cannot handle dynamic ambient occlusion. We use direct OpenGL(ES) calls here that use VBO.');
382 if (Elements.Count = 0) or Scene.BoundingBox.IsEmpty then
383 raise Exception.Create('Scene has no elements, or empty bounding box --- we cannot do dynamic ambient occlusion.');
384 if GLVersion.Fglrx then
385 raise Exception.Create('This GPU cannot handle dynamic ambient occlusion. FGLRX implementation of GLSL had so many bugs that supporting it for this demo was very burdensome.');
386
387 CalculateElementsTex;
388
389 FragmentShader := String(FileToString('castle-data:/shaders/dynamic_ambient_occlusion.fs'));
390 VertexShader := String(FileToString('castle-data:/shaders/dynamic_ambient_occlusion.vs'));
391
392 { Integer constants are really constant for the shader.
393 This allows OpenGL to optimize them more.
394 Especially important for $elements_count, since then the "for" loop
395 inside the shader can be unrolled.
396 Required e.g. by NVidia GPU "GeForce FX 5200/AGP/SSE2/3DNOW!" }
397 StringReplaceAllVar(FragmentShader, '$tex_elements_size', IntToStr(ElementsTexSize));
398 StringReplaceAllVar(FragmentShader, '$elements_count', IntToStr(Elements.Count));
399
400 { initialize GLSL program }
401 GLSLProgram[0] := TGLSLProgram.Create;
402 GLSLProgram[0].AttachVertexShader(VertexShader);
403 GLSLProgram[0].AttachFragmentShader(FragmentShader);
404 { For this test program, we eventually allow shader to run in software.
405 We display debug info, so user should know what's going on. }
406 GLSLProgram[0].Link;
407
408 WritelnLogMultiline('Shader for 1st pass', GLSLProgram[0].DebugInfo);
409
410 StringReplaceAllVar(FragmentShader,
411 '/*$defines*/',
412 '/*$defines*/' + NL + '#define PASS_2');
413
414 GLSLProgram[1] := TGLSLProgram.Create;
415 GLSLProgram[1].AttachVertexShader(VertexShader);
416 GLSLProgram[1].AttachFragmentShader(FragmentShader);
417 GLSLProgram[1].Link;
418
419 WritelnLogMultiline('Shader for 2nd pass', GLSLProgram[1].DebugInfo);
420 end;
421
422 var
423 ModelUrl: String;
424 begin
425 inherited;
426
427 DrawType := dtPass2;
428 ButtonDrawPass2.Pressed := true;
429
430 { Math correctly, this should be 1 / (2 * Pi)
431 (= inverted hemisphere surface area).
432 In practice, larger values are useful, to make shadows look more "dramatic". }
433 ShadowScale := 1 / (1 * Pi);
434
435 Elements := TAOElementList.Create;
436
437 Parameters.CheckHighAtMost(1);
438 if Parameters.High = 1 then
439 ModelUrl := Parameters[1]
440 else
441 ModelUrl :=
442 //'castle-data:/chinchilla_awakens.x3dv';
443 //'castle-data:/simplico.wrl';
444 //'castle-data:/ultra_simplico_human.wrl';
445 'castle-data:/peach.wrl.gz';
446
447 { inititalize Viewport }
448 Viewport := TMyViewport.Create(Application);
449 Viewport.View := Self;
450 Viewport.FullSize := true;
451 Viewport.InsertBack(TCastleExamineNavigation.Create(Application));
452 InsertBack(Viewport);
453
454 { initialize Scene }
455 Scene := TCastleScene.Create(Application);
456 Scene.Load(ModelUrl);
457 Scene.PreciseCollisions := true;
458 Scene.OnGeometryChanged := {$ifdef FPC}@{$endif} SceneGeometryChanged;
459 Scene.ProcessEvents := true; { allow Scene animation }
460 CalculateElements;
461 Viewport.Items.Add(Scene);
462
463 // headlight
464 Viewport.Camera.Add(TCastleDirectionalLight.Create(Application));
465
466 // nice initial camera position
467 Viewport.AssignDefaultCamera;
468
469 { initialize SceneElements }
470 SceneElements := TCastleScene.Create(Application);
471 Viewport.Items.Add(SceneElements);
472
473 CreateShaders;
474
475 CheckboxPlayAnimation.OnChange := {$ifdef FPC}@{$endif} CheckboxPlayAnimationChange;
476 ButtonDrawDisable.OnClick := {$ifdef FPC}@{$endif} ButtonDrawDisableClick;
477 ButtonDrawElements.OnClick := {$ifdef FPC}@{$endif} ButtonDrawElementsClick;
478 ButtonDrawElementsIntensity.OnClick := {$ifdef FPC}@{$endif} ButtonDrawElementsIntensityClick;
479 ButtonDrawPass1.OnClick := {$ifdef FPC}@{$endif} ButtonDrawPass1Click;
480 ButtonDrawPass2.OnClick := {$ifdef FPC}@{$endif} ButtonDrawPass2Click;
481 end;
482
483 procedure TViewMain.Stop;
484
485 procedure DestroyShaders;
486 begin
487 FreeAndNil(GLSLProgram[0]);
488 FreeAndNil(GLSLProgram[1]);
489 end;
490
491 begin
492 FreeAndNil(Elements);
493 FreeAndNil(ElementsPositionAreaTex);
494 FreeAndNil(ElementsNormalTex);
495 FreeAndNil(FullRenderIntensityTex);
496 inherited;
497 end;
498
499 procedure TViewMain.Update(const SecondsPassed: Single; var HandleInput: Boolean);
500 begin
501 inherited;
502
503 { This virtual method is executed every frame (many times per second). }
504 Assert(LabelFps <> nil, 'If you remove LabelFps from the design, remember to remove also the assignment "LabelFps.Caption := ..." from code');
505 LabelFps.Caption := 'FPS: ' + Container.Fps.ToString;
506
507 if Container.Pressed.Characters['s'] then
508 begin
509 ShadowScale := ShadowScale * (Power(1.1, SecondsPassed * 20));
510 Container.Invalidate;
511 end;
512 if Container.Pressed.Characters['S'] then
513 begin
514 ShadowScale := ShadowScale * (Power(1/1.1, SecondsPassed * 20));
515 Container.Invalidate;
516 end;
517 end;
518
519 function TViewMain.Press(const Event: TInputPressRelease): Boolean;
520 begin
521 Result := inherited;
522 if Result then Exit; // allow the ancestor to handle keys
523
524 { This virtual method is executed when user presses
525 a key, a mouse button, or touches a touch-screen.
526
527 Note that each UI control has also events like OnPress and OnClick.
528 These events can be used to handle the "press", if it should do something
529 specific when used in that UI control.
530 The TViewMain.Press method should be used to handle keys
531 not handled in children controls.
532 }
533
534 // Use this to handle keys:
535 {
536 if Event.IsKey(keyXxx) then
537 begin
538 // DoSomething;
539 Exit(true); // key was handled
540 end;
541 }
542 end;
543
544 procedure TViewMain.CalculateElements;
545
546 procedure AddShapeElements(ShapeIndex: Integer; Shape: TShape);
547 var
548 Coord: TMFVec3f;
549 Calculator: TElementsCalculator;
550 ShapeElementIndex: Cardinal;
551 ShapeElements: PAOElement;
552 I: Integer;
553 begin
554 AoShapes[ShapeIndex].Shape := Shape;
555
556 if Shape.Geometry.InternalCoord(Shape.State, Coord) and (Coord <> nil) then
557 begin
558 { Grow Elements array }
559 ShapeElementIndex := Elements.Count;
560 Elements.Count := Elements.Count + Coord.Count;
561 ShapeElements := PAOElement(Elements.Ptr(ShapeElementIndex));
562
563 SetLength(AoShapes[ShapeIndex].CoordToElement, Coord.Count);
564
565 { This does a modified and tweaked version of normal calculation
566 from CreateSmoothNormalsCoordinateNode from CastleInternalNormals.
567 We want to additionally store Position and calculate Area for
568 each element (= just vertex). }
569
570 { Initialize: set position,
571 clear normals and area at the beginning, we will sum to them. }
572 for I := 0 to Coord.Count - 1 do
573 begin
574 ShapeElements[I].Position :=
575 Shape.State.Transformation.Transform.MultPoint(Coord.Items.L[I]);
576 ShapeElements[I].Normal := TVector3.Zero;
577 ShapeElements[I].Area := 0;
578 end;
579
580 { Iterate over polygons, adding normals and areas of new elements }
581 Calculator := TElementsCalculator.Create;
582 try
583 Calculator.Coord := Coord.Items;
584 if Shape.Geometry.CoordIndexField <> nil then
585 Calculator.CoordIndex := Shape.Geometry.CoordIndexField.Items else
586 Calculator.CoordIndex := nil;
587 Calculator.ShapeElements := ShapeElements;
588 Shape.Geometry.InternalCoordPolygons(Shape.State,
589 {$ifdef FPC}@{$endif} Calculator.Polygon);
590 finally FreeAndNil(Calculator) end;
591
592 { Normalize all new normals }
593 for I := 0 to Coord.Count - 1 do
594 ShapeElements[I].Normal := ShapeElements[I].Normal.Normalize;
595 end else
596 begin
597 SetLength(AoShapes[ShapeIndex].CoordToElement, 0);
598 end;
599 end;
600
601 var
602 ShapeList: TShapeList;
603 I, GoodElementsCount, ShapeIndex, ShapeCoord: Integer;
604 begin
605 Elements.Count := 0;
606
607 SetLength(AoShapes, Scene.Shapes.ShapesCount(true, true, false));
608
609 ShapeList := Scene.Shapes.TraverseList(true, true, false);
610 for ShapeIndex := 0 to ShapeList.Count - 1 do
611 AddShapeElements(ShapeIndex, ShapeList[ShapeIndex]);
612
613 { Remove Elements with zero normal vector.
614
615 This means that vertex isn't neighbor to any other vertex,
616 which means e.g. that IndexedFaceSet has no coordIndex (or maybe
617 just doesn't use this particular vertex), or maybe we have IndexedLineSet
618 (that has coordinates, but no polygons).
619
620 In any case, we want to remove them, as they are invalid (zero normal,
621 zero area, besides unused vertexes may be outside of Scene.BoundingBox
622 (as calculating Scene.BoundingBox may conserve bbox to not contain
623 unused vertexes) --- so unused vertexes would fail to be "squeezed"
624 inside texture component correctly.
625
626 By the way, you also have to initialize AoShapes[].CoordToElement.
627 This provides a mapping from original (per-shape, and before this removal)
628 coords back to elements. }
629
630 GoodElementsCount := 0;
631
632 { increase ShapeIndex, ShapeCoord to next coord }
633 ShapeIndex := 0;
634 ShapeCoord := 0;
635 while (ShapeIndex < Length(AoShapes)) and
636 (Length(AoShapes[ShapeIndex].CoordToElement) = 0) do
637 Inc(ShapeIndex);
638
639 for I := 0 to Elements.Count - 1 do
640 begin
641 if not Elements.L[I].Normal.IsPerfectlyZero then
642 begin
643 { Then Element I should be on position GoodElementsCount. }
644 if GoodElementsCount <> I then
645 Elements.L[GoodElementsCount] := Elements.L[I];
646 AoShapes[ShapeIndex].CoordToElement[ShapeCoord] := GoodElementsCount;
647 Inc(GoodElementsCount);
648 end else
649 begin
650 AoShapes[ShapeIndex].CoordToElement[ShapeCoord] := -1;
651 end;
652
653 { increase ShapeIndex, ShapeCoord to next coord }
654 Inc(ShapeCoord);
655 if ShapeCoord >= Length(AoShapes[ShapeIndex].CoordToElement) then
656 begin
657 Inc(ShapeIndex);
658 ShapeCoord := 0;
659 while (ShapeIndex < Length(AoShapes)) and
660 (Length(AoShapes[ShapeIndex].CoordToElement) = 0) do
661 Inc(ShapeIndex);
662 end;
663 end;
664
665 Assert(ShapeIndex = Length(AoShapes));
666
667 if Verbose then
668 WritelnLog('Bad elements (vertexes with no neighbors) removed: %d, remaining good elements: %d', [
669 Elements.Count - GoodElementsCount,
670 GoodElementsCount
671 ]);
672 Elements.Count := GoodElementsCount;
673 end;
674
675 procedure TViewMain.CalculateElementsTex;
676
677 { Trivially convert Value in 0..1 range to a byte.
678 By the way, checks is the Value really in 0..1 range (eventually,
679 slightly off due to fp errors). This way it checks if our scale/shift
680 variables are not too large. }
681 function ClampedCheck(const Value: Single): Byte;
682 var
683 ResultInt: Integer;
684 begin
685 ResultInt := Round(Value * High(Byte));
686
687 { I check ResultInt below with 25 margin, which is 25/255 ~= 0.1 error
688 tolerance. That's pretty large tolerance, values really should fit
689 within. }
690 Assert(ResultInt >= -25, 'Value squeezed into texture is < 0');
691 Assert(ResultInt <= High(Byte)+25, 'Value squeezed into texture is > 1');
692
693 if ResultInt < 0 then
694 Result := 0 else
695 if ResultInt > High(Byte) then
696 Result := High(Byte) else
697 Result := ResultInt;
698 end;
699
700 var
701 TexSizeExponent: Cardinal;
702 I: Integer;
703 PositionArea: PVector4Byte;
704 Normal: PVector3Byte;
705 Element: PAOElement;
706 begin
707 TexSizeExponent := Smallest2Exponent(Elements.Count);
708 if TexSizeExponent mod 2 = 0 then
709 TexSizeExponent := TexSizeExponent div 2 else
710 TexSizeExponent := TexSizeExponent div 2 + 1;
711 ElementsTexSize := 1 shl TexSizeExponent;
712
713 Assert(Sqr(ElementsTexSize) >= Elements.Count);
714
715 if Verbose then
716 WritelnLog('For elements %d we use texture size %d^2 = %d pixels', [
717 Elements.Count,
718 ElementsTexSize,
719 Sqr(ElementsTexSize)
720 ]);
721
722 { calculate maximum area, which is just AreaScale }
723 AreaScale := 0;
724 for I := 0 to Elements.Count - 1 do
725 MaxVar(AreaScale, Elements.L[I].Area);
726
727 { calculate PositionScale, PositionShift.
728 We have min/max in Scene.BoundingBox. }
729 PositionScale := Scene.BoundingBox.Size;
730 for I := 0 to 2 do
731 begin
732 if PositionScale.Data[I] = 0 then
733 PositionScale.Data[I] := 1;
734 PositionShift.Data[I] := Scene.BoundingBox.Data[0][I] / PositionScale[I];
735 end;
736
737 if Verbose then
738 begin
739 WritelnLog('To squeeze area into texture we use area_scale = %f', [AreaScale]);
740 WritelnLog('To squeeze positions into texture we use scale = %s and shift %s (bbox is %s)', [
741 PositionScale.ToString,
742 PositionShift.ToString,
743 Scene.BoundingBox.ToString
744 ]);
745 end;
746
747 { initialize textures }
748 FreeAndNil(ElementsPositionAreaTex);
749 FreeAndNil(ElementsNormalTex);
750
751 ElementsPositionAreaTex := TRGBAlphaImage.Create(ElementsTexSize, ElementsTexSize);
752 ElementsNormalTex := TRGBImage.Create(ElementsTexSize, ElementsTexSize);
753
754 { fill textures }
755 PositionArea := ElementsPositionAreaTex.Pixels;
756 Normal := ElementsNormalTex.Pixels;
757 Element := PAOElement(Elements.L);
758 for I := 0 to Elements.Count - 1 do
759 begin
760 PositionArea^.X := ClampedCheck(Element^.Position.X / PositionScale.X - PositionShift.X);
761 PositionArea^.Y := ClampedCheck(Element^.Position.Y / PositionScale.Y - PositionShift.Y);
762 PositionArea^.Z := ClampedCheck(Element^.Position.Z / PositionScale.Z - PositionShift.Z);
763 PositionArea^.W := ClampedCheck(Element^.Area / AreaScale);
764 Normal^.X := ClampedCheck(Element^.Normal.X / 2 + 0.5);
765 Normal^.Y := ClampedCheck(Element^.Normal.Y / 2 + 0.5);
766 Normal^.Z := ClampedCheck(Element^.Normal.Z / 2 + 0.5);
767 Inc(Element);
768 Inc(PositionArea);
769 Inc(Normal);
770 end;
771
772 { Only for testing purposes, fill the rest of the texture will special
773 value. This is only for testing, that is correct shader and other code
774 should not even touch the remaining pixels --- but in case of trouble
775 (if something will accidentally access other values),
776 it's easier when things don't jump randomly (because of memory garbage),
777 and can be easily detected by changing the special value below. }
778 for I := Elements.Count to Sqr(ElementsTexSize) - 1 do
779 begin
780 PositionArea^.X := 255;
781 PositionArea^.Y := 0;
782 PositionArea^.Z := 0;
783 PositionArea^.W := 255;
784 Normal^.X := 255;
785 Normal^.Y := 0;
786 Normal^.Z := 0;
787 // Inc(Element); // pointless, Element is not used further
788 Inc(PositionArea);
789 Inc(Normal);
790 end;
791
792 GLElementsPositionAreaTex := LoadGLTexture(ElementsPositionAreaTex,
793 TextureFilter(minNearest, magNearest), Texture2DRepeat);
794 GLElementsNormalTex := LoadGLTexture(ElementsNormalTex,
795 TextureFilter(minNearest, magNearest), Texture2DRepeat);
796
797 { Prepare OpenGL texture for shaders output (and also input to 2nd pass
798 of algorithm). }
799 glGenTextures(1, @GLElementsIntensityTex);
800 glBindTexture(GL_TEXTURE_2D, GLElementsIntensityTex);
801
802 { Texture data is not initialized at this point,
803 but we set texture width, height, format and such.
804 This will allow texture to be updated by glCopyTexSubImage,
805 which is faster than glCopyTexImage. }
806 glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE,
807 ElementsTexSize, ElementsTexSize, 0,
808 { Format and type don't matter, as far as I understand, since pixels
809 pointer is nil. }
810 GL_LUMINANCE, GL_UNSIGNED_BYTE, nil);
811 TextureMemoryProfiler.Allocate(GLElementsIntensityTex, '', 'luminance',
812 ElementsTexSize * ElementsTexSize,
813 false, ElementsTexSize, ElementsTexSize, 1);
814
815 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
816 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
817 end;
818
819 function TViewMain.VertexColor(
820 const Shape: TShape;
821 const VertexPosition: TVector3;
822 const VertexIndex: Integer): TCastleColorRGB;
823 var
824 ElemIndex, I: Integer;
825 Intensity: Single;
826 begin
827 if FullRenderShape <> Shape then
828 begin
829 FullRenderShape := Shape;
830 FullRenderShapeInfo := nil;
831 for I := 0 to Length(AoShapes) - 1 do
832 if AoShapes[I].Shape = Shape then
833 begin
834 FullRenderShapeInfo := @AoShapes[I];
835 Break;
836 end;
837 Assert(FullRenderShapeInfo <> nil, 'Shape info not found');
838 end;
839
840 ElemIndex := FullRenderShapeInfo^.CoordToElement[VertexIndex];
841 if ElemIndex = -1 then
842 Result := TVector3.Zero { element invalid, probably separate vertex } else
843 begin
844 Intensity := FullRenderIntensityTex.Pixels[ElemIndex]/255;
845 Result.X := Intensity;
846 Result.Y := Intensity;
847 Result.Z := Intensity;
848 end;
849 end;
850
851 procedure TViewMain.SceneGeometryChanged(AScene: TCastleSceneCore;
852 const SomeLocalGeometryChanged: boolean;
853 OnlyShapeChanged: TShape);
854 var
855 OldElementsTexSize, OldElementsCount: Cardinal;
856 begin
857 OldElementsTexSize := ElementsTexSize;
858 OldElementsCount := Elements.Count;
859
860 CalculateElements;
861 CalculateElementsTex;
862
863 if (OldElementsTexSize <> ElementsTexSize) or
864 (OldElementsCount <> Cardinal(Elements.Count)) then
865 begin
866 WritelnWarning('TODO: animation changed elements count / texture size. Shaders need to reinitialiazed.');
867 end;
868 end;
869
870 procedure TViewMain.ButtonDrawDisableClick(Sender: TObject);
871 begin
872 SetDrawType(dtDisable);
873 end;
874
875 procedure TViewMain.ButtonDrawElementsClick(Sender: TObject);
876 begin
877 SetDrawType(dtElements);
878 end;
879
880 procedure TViewMain.ButtonDrawElementsIntensityClick(Sender: TObject);
881 begin
882 SetDrawType(dtElementsIntensity);
883 end;
884
885 procedure TViewMain.ButtonDrawPass1Click(Sender: TObject);
886 begin
887 SetDrawType(dtPass1);
888 end;
889
890 procedure TViewMain.ButtonDrawPass2Click(Sender: TObject);
891 begin
892 SetDrawType(dtPass2);
893 end;
894
895 procedure TViewMain.CheckboxPlayAnimationChange(Sender: TObject);
896 begin
897 Scene.TimePlaying := CheckboxPlayAnimation.Checked;
898 end;
899
900 procedure TViewMain.SetDrawType(const NewDrawType: TDrawType);
901
902 { Update SceneElements contents.
903
904 If ElementsIntensityTex = nil,
905 then all element discs will have the same material.
906 Otherwise, we will assign a color for each element,
907 using values from ElementsIntensityTex. }
908 procedure UpdateElements(const ElementsIntensityTex: TGrayscaleImage);
909 var
910 RootNode: TX3DRootNode;
911 Mat: TUnlitMaterialNode;
912 Appearance: TAppearanceNode;
913 Disk: TDisk2DNode;
914 DiskShape: TShapeNode;
915 DiskTransform: TTransformNode;
916 I: Integer;
917 ElementIntensity: PByte;
918 begin
919 RootNode := TX3DRootNode.Create;
920
921 if ElementsIntensityTex <> nil then
922 ElementIntensity := ElementsIntensityTex.Pixels
923 else
924 ElementIntensity := nil; // silence Delphi warning
925
926 for I := 0 to Elements.Count - 1 do
927 begin
928 Disk := TDisk2DNode.CreateWithTransform(DiskShape, DiskTransform);
929 { Area = Pi * Radius^2, so Radius := Sqrt(Area/Pi) }
930 Disk.OuterRadius := Sqrt(Elements.L[I].Area / Pi);
931 Disk.Solid := false;
932
933 if ElementsIntensityTex <> nil then
934 begin
935 Mat := TUnlitMaterialNode.Create;
936 Mat.EmissiveColor := Vector3(
937 ElementIntensity^ / 255,
938 ElementIntensity^ / 255,
939 ElementIntensity^ / 255
940 );
941 Appearance := TAppearanceNode.Create;
942 Appearance.Material := Mat;
943 DiskShape.Appearance := Appearance;
944 Inc(ElementIntensity);
945 end;
946
947 DiskTransform.Translation := Elements.L[I].Position;
948 DiskTransform.Rotation := OrientationFromDirectionUp(
949 Elements.L[I].Normal,
950 AnyOrthogonalVector(Elements.L[I].Normal)
951 );
952 RootNode.AddChildren(DiskTransform);
953 end;
954
955 SceneElements.Load(RootNode, true);
956 end;
957
958 begin
959 if DrawType <> NewDrawType then
960 begin
961 DrawType := NewDrawType;
962 Scene.Exists := DrawType in [dtDisable, dtPass1, dtPass2];
963 SceneElements.Exists := DrawType in [dtElements, dtElementsIntensity];
964 Container.Invalidate;
965
966 case DrawType of
967 dtDisable:
968 RemoveSceneColors(Scene); // clear colors, otherwise dtPass1/2 would leave their colors
969 dtElements:
970 UpdateElements(nil);
971 dtElementsIntensity:
972 UpdateElements(FullRenderIntensityTex);
973 end;
974 end;
975
976 ButtonDrawDisable.Pressed := DrawType = dtDisable;
977 ButtonDrawElements.Pressed := DrawType = dtElements;
978 ButtonDrawElementsIntensity.Pressed := DrawType = dtElementsIntensity;
979 ButtonDrawPass1.Pressed := DrawType = dtPass1;
980 ButtonDrawPass2.Pressed := DrawType = dtPass2;
981 end;
982
983 end.