| 1 |
{ |
| 2 |
Copyright 2003-2024 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 |
{ Rendering of scenes (TCastleScene). } |
| 17 |
unit CastleScene; |
| 18 |
|
| 19 |
{$I castleconf.inc} |
| 20 |
|
| 21 |
{ TComponent.Height is being hidden by TCastleCone.Height, TCastleCylinder.Height. |
| 22 |
This is OK. } |
| 23 |
{$ifndef FPC}{$warn HIDING_MEMBER off}{$endif} |
| 24 |
|
| 25 |
{ By default, we don't define TCastleEnvironmentLight -- implementation is not finished yet |
| 26 |
(neither of TCastleEnvironmentLight, nor of underlying TEnvironmentLightNode). } |
| 27 |
{.$define CASTLE_EXPERIMENTAL_ENVIRONMENT_LIGHT} |
| 28 |
|
| 29 |
interface |
| 30 |
|
| 31 |
uses SysUtils, Classes, Generics.Collections, |
| 32 |
{$ifdef OpenGLES} CastleGLES, {$else} CastleGL, {$endif} |
| 33 |
CastleVectors, CastleBoxes, X3DNodes, CastleClassUtils, CastleFonts, |
| 34 |
CastleUtils, CastleSceneCore, CastleInternalBackgroundRenderer, |
| 35 |
CastleGLUtils, CastleInternalShapeOctree, CastleInternalGLShadowVolumes, X3DFields, |
| 36 |
CastleTriangles, CastleShapes, CastleFrustum, CastleTransform, CastleGLShaders, |
| 37 |
CastleRectangles, CastleCameras, CastleRendererInternalShader, CastleColors, |
| 38 |
CastleSceneInternalShape, CastleInternalFileMonitor, |
| 39 |
CastleRenderOptions, CastleTimeUtils, CastleImages, |
| 40 |
CastleBehaviors, CastleInternalShapesRenderer, CastleSceneInternalBlending; |
| 41 |
|
| 42 |
{$define read_interface} |
| 43 |
|
| 44 |
const |
| 45 |
prRenderSelf = CastleTransform.prRenderSelf; |
| 46 |
prRenderClones = CastleTransform.prRenderClones; |
| 47 |
prBackground = CastleTransform.prBackground; |
| 48 |
prBoundingBox = CastleTransform.prBoundingBox; |
| 49 |
prShadowVolume = CastleTransform.prShadowVolume; |
| 50 |
|
| 51 |
type |
| 52 |
TCastleSceneList = class; |
| 53 |
|
| 54 |
TBeforeShapeRenderProc = procedure (Shape: TShape) of object; |
| 55 |
|
| 56 |
TRenderingAttributesEvent = TCastleRenderOptionsEvent deprecated 'use TCastleRenderOptionsEvent'; |
| 57 |
TSceneRenderingAttributes = TCastleRenderOptions deprecated 'use TCastleRenderOptions'; |
| 58 |
|
| 59 |
TPrepareResourcesOption = CastleTransform.TPrepareResourcesOption; |
| 60 |
TPrepareResourcesOptions = CastleTransform.TPrepareResourcesOptions; |
| 61 |
|
| 62 |
{ Complete loading, processing and rendering of a scene. |
| 63 |
This is a descendant of @link(TCastleSceneCore) that adds efficient rendering. } |
| 64 |
TCastleScene = class(TCastleSceneCore) |
| 65 |
strict private |
| 66 |
type |
| 67 |
TSceneRenderOptions = class(TCastleRenderOptions) |
| 68 |
private |
| 69 |
OwnerScene: TCastleScene; |
| 70 |
protected |
| 71 |
procedure ReleaseCachedResources; override; |
| 72 |
end; |
| 73 |
|
| 74 |
var |
| 75 |
{ Used by UpdateGeneratedTextures, to prevent rendering the shape |
| 76 |
for which reflection texture is generated. (This wouldn't cause |
| 77 |
recursive loop in our engine, but still it's bad --- rendering |
| 78 |
from the inside of the object usually obscures the world around...). } |
| 79 |
AvoidShapeRendering: TGLShape; |
| 80 |
|
| 81 |
{ Used by UpdateGeneratedTextures, to prevent rendering non-shadow casters |
| 82 |
for shadow maps. } |
| 83 |
AvoidNonShadowCasterRendering: boolean; |
| 84 |
|
| 85 |
{ Used by UpdateGeneratedTextures, to avoid updating twice during the same render. } |
| 86 |
UpdateGeneratedTexturesFrameId: TFrameId; |
| 87 |
|
| 88 |
FDistanceCulling: Single; |
| 89 |
|
| 90 |
FReceiveShadowVolumes: Boolean; |
| 91 |
FTempPrepareParams: TPrepareParams; |
| 92 |
{ Camera position, in local scene coordinates, known during |
| 93 |
the LocalRender or LocalRenderShadowVolume calls. } |
| 94 |
RenderCameraPosition: TVector3; |
| 95 |
FCastGlobalLights: Boolean; |
| 96 |
FWasVisibleFrameId: TFrameId; |
| 97 |
|
| 98 |
{ Used by LocalRenderInside } |
| 99 |
FilteredShapes: TShapeList; |
| 100 |
|
| 101 |
{ Valid only during TCastleScene.LocalRender. |
| 102 |
Callbacks assigned to ShapeCullingFunc and ShapeCullingOctreeFunc may use it. } |
| 103 |
FrustumForShapeCulling: PFrustum; |
| 104 |
|
| 105 |
FShapeFrustumCulling, FSceneFrustumCulling: Boolean; |
| 106 |
FRenderOptions: TCastleRenderOptions; |
| 107 |
|
| 108 |
{ These fields are valid only during LocalRenderInside and CollectShape_ methods. } |
| 109 |
Render_Params: TRenderParams; |
| 110 |
Render_TestShapeVisibility: TTestShapeVisibility; |
| 111 |
Render_Collector: TShapesCollector; |
| 112 |
|
| 113 |
{ Collect Shape, adding it to Render_Collector. } |
| 114 |
procedure CollectShape_NoTests(const Shape: TGLShape); |
| 115 |
{ Render Shape if all tests pass. |
| 116 |
Checks everything except TestShapeVisibility callback, |
| 117 |
so it assumes that filtering by TestShapeVisibility is already done. } |
| 118 |
procedure CollectShape_SomeTests(const Shape: TGLShape); |
| 119 |
{ Render Shape if all tests (including TestShapeVisibility) pass. } |
| 120 |
procedure CollectShape_AllTests(const Shape: TShape); |
| 121 |
{ Render Shape if all tests (including TestShapeVisibility) pass, and it is opaque. } |
| 122 |
procedure CollectShape_AllTests_Opaque(const Shape: TShape); |
| 123 |
|
| 124 |
procedure ResetShapeVisible(const Shape: TShape); |
| 125 |
|
| 126 |
{ Collect all shapes for rendering, into Params.Collector. |
| 127 |
The actual rendering will be done using TCastleViewport and TShapesRenderer. |
| 128 |
|
| 129 |
Adds all potentially visible shapes to Params.Collector. |
| 130 |
"Potentially visible" is decided by TestShapeVisibility |
| 131 |
(shape is visible if TestShapeVisibility is @nil or returns |
| 132 |
@true for this shape) and Params.Transparent value must include |
| 133 |
given shape. |
| 134 |
|
| 135 |
Updates Params.Statistics. } |
| 136 |
procedure LocalRenderInside(const TestShapeVisibility: TTestShapeVisibility; |
| 137 |
const Params: TRenderParams); |
| 138 |
|
| 139 |
{ Render everything using LocalRenderInside. |
| 140 |
The rendering parameters are configurable by @link(RenderOptions). |
| 141 |
|
| 142 |
The shapes are only filtered here: |
| 143 |
|
| 144 |
- frustum culling, |
| 145 |
- distance culling, |
| 146 |
- filtering by transparency (only shapes matching Params.Transparent are returned) |
| 147 |
- filtering using TestShapeVisibility. |
| 148 |
|
| 149 |
Shapes that pass send to Params.Collector. |
| 150 |
|
| 151 |
The actual rendering will be done using TCastleViewport and TShapesRenderer. } |
| 152 |
procedure LocalRenderOutside( |
| 153 |
const TestShapeVisibility: TTestShapeVisibility; |
| 154 |
const Params: TRenderParams); |
| 155 |
|
| 156 |
{ Fog for this shape. @nil if none. } |
| 157 |
function ShapeFog(const Shape: TShape; const GlobalFog: TFogNode): TFogFunctionality; |
| 158 |
|
| 159 |
{ Check frustum and distance culling. } |
| 160 |
function ShapePossiblyVisible(Shape: TShape): boolean; |
| 161 |
|
| 162 |
{ Should given shape be rendered, according to distance culling. |
| 163 |
Call only when DistanceCulling > 0. } |
| 164 |
function DistanceCullingCheckShape(const Shape: TShape): Boolean; |
| 165 |
|
| 166 |
{ Should given scene be rendered, according to distance culling. |
| 167 |
Call only when DistanceCulling > 0. } |
| 168 |
function DistanceCullingCheckScene: Boolean; |
| 169 |
|
| 170 |
procedure SetShapeFrustumCulling(const Value: Boolean); |
| 171 |
procedure SetDistanceCulling(const Value: Single); |
| 172 |
|
| 173 |
function RenderFrustumOctree_TestShape(Shape: TShape): boolean; |
| 174 |
procedure RenderWithOctree_CheckShapeCulling( |
| 175 |
ShapeIndex: Integer; CollidesForSure: boolean); |
| 176 |
procedure SetCastGlobalLights(const Value: Boolean); |
| 177 |
private |
| 178 |
PreparedShapesResources, PreparedRender: Boolean; |
| 179 |
protected |
| 180 |
function CreateShape(const AGeometry: TAbstractGeometryNode; |
| 181 |
const AState: TX3DGraphTraverseState; |
| 182 |
const ParentInfo: PTraversingInfo): TShape; override; |
| 183 |
procedure InternalInvalidateBackgroundRenderer; override; |
| 184 |
|
| 185 |
procedure LocalRender(const Params: TRenderParams); override; |
| 186 |
|
| 187 |
{ Render shadow volume (sides and caps) of this scene, for shadow volume |
| 188 |
algorithm. |
| 189 |
|
| 190 |
Uses ShadowVolumeRenderer for rendering, and to detect if rendering |
| 191 |
is necessary at all. |
| 192 |
|
| 193 |
It always uses silhouette optimization. This is the usual, |
| 194 |
fast method of rendering shadow volumes. |
| 195 |
|
| 196 |
All shadow quads are generated from scene triangles transformed |
| 197 |
by ParentTransform. We must be able to correctly detect front and |
| 198 |
back facing triangles with respect to light position, |
| 199 |
so ShadowVolumeRenderer.LightPosition and |
| 200 |
"this scene transformed by ParentTransform" must be in the same coordinate system. |
| 201 |
If ParentTransformIsIdentity then ParentTransform value is ignored and |
| 202 |
everything works like ParentTransform = identity matrix (and is a little |
| 203 |
faster in this special case). |
| 204 |
|
| 205 |
Uses TrianglesListShadowCasters and ManifoldEdges and BorderEdges |
| 206 |
(so you may prefer to prepare it before, e.g. by calling PrepareResources |
| 207 |
with prShadowVolume included). |
| 208 |
|
| 209 |
We look at some RenderOptions, like RenderOptions.Blending, because transparent |
| 210 |
triangles have to be handled a little differently, and when |
| 211 |
RenderOptions.Blending = false then all triangles are forced to be opaque. |
| 212 |
In other words, this takes RenderOptions into account, to cooperate with |
| 213 |
our Render method. |
| 214 |
|
| 215 |
ShadowVolumeRenderer.LightPosition is the light position. |
| 216 |
ShadowVolumeRenderer.LightPosition[3] must be 1 |
| 217 |
(to indicate positional light) or 0 (a directional light). |
| 218 |
It's expected that ShadowVolumeRenderer is already initialized by |
| 219 |
ShadowVolumeRenderer.InitFrustumAndLight. |
| 220 |
|
| 221 |
Faces (both shadow quads and caps) are rendered such that |
| 222 |
CCW <=> you're looking at it from outside |
| 223 |
(i.e. it's considered front face of this shadow volume). } |
| 224 |
procedure LocalRenderShadowVolume(const Params: TRenderParams; |
| 225 |
const ShadowVolumeRenderer: TBaseShadowVolumeRenderer); override; |
| 226 |
|
| 227 |
procedure ChangeWorld(const Value: TCastleAbstractRootTransform); override; |
| 228 |
public |
| 229 |
constructor Create(AOwner: TComponent); override; |
| 230 |
destructor Destroy; override; |
| 231 |
procedure Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); override; |
| 232 |
function PropertySections(const PropertyName: String): TPropertySections; override; |
| 233 |
|
| 234 |
{ Destroy any associations of this object with current OpenGL context. |
| 235 |
For example, release any allocated texture names. |
| 236 |
|
| 237 |
Generally speaking, destroys everything that is allocated by |
| 238 |
PrepareResources call. It's harmless to call this |
| 239 |
method when there are already no associations with current OpenGL context. |
| 240 |
This is called automatically from the destructor. } |
| 241 |
procedure GLContextClose; override; |
| 242 |
|
| 243 |
procedure PrepareResources(const Options: TPrepareResourcesOptions; |
| 244 |
const Params: TPrepareParams); override; |
| 245 |
deprecated 'this is internal; use TCastleViewport.PrepareResources to prepare transformations'; |
| 246 |
|
| 247 |
procedure BeforeNodesFree(const InternalChangedAll: boolean = false); override; |
| 248 |
|
| 249 |
{ Does this transform have a collision mesh that TCastleMeshCollider can use. } |
| 250 |
function HasColliderMesh: Boolean; override; |
| 251 |
{ Enumerate triangles for a collision mesh that TCastleMeshCollider can use. } |
| 252 |
procedure ColliderMesh(const TriangleEvent: TTriangleEvent); override; |
| 253 |
private |
| 254 |
{ Node for which FBackground is currently prepared. } |
| 255 |
FBackgroundNode: TAbstractBindableNode; |
| 256 |
{ Cached BackgroundRenderer value } |
| 257 |
FBackgroundRenderer: TBackgroundRenderer; |
| 258 |
{ Is FBackgroundRenderer valid? |
| 259 |
|
| 260 |
We can't use "FBackgroundRenderer = nil" to detect this, |
| 261 |
bacause nil is valid value for FBackgroundRenderer in case there's no |
| 262 |
(supported) FBackgroundNode. |
| 263 |
|
| 264 |
If not FBackgroundRendererValid then FBackgroundRenderer must always be nil. |
| 265 |
Never set FBackgroundRendererValid to false directly - use InternalInvalidateBackgroundRenderer, |
| 266 |
this will automatically call FreeAndNil(FBackgroundRenderer) before setting |
| 267 |
FBackgroundRendererValid to false. } |
| 268 |
FBackgroundRendererValid: boolean; |
| 269 |
procedure PrepareBackground; |
| 270 |
public |
| 271 |
{ Internal override test visibility. } |
| 272 |
InternalVisibilityTest: TTestShapeVisibility; |
| 273 |
|
| 274 |
procedure FreeResources(Resources: TSceneFreeResources); override; |
| 275 |
|
| 276 |
{ TBackgroundRenderer instance to render the background defined in this scene. |
| 277 |
Current background is the top node on the BackgroundStack of this scene, |
| 278 |
following X3D specifications, and can be animated. |
| 279 |
The TCastleViewport should use this to render background. |
| 280 |
|
| 281 |
You should not access the background this way in your own code. |
| 282 |
This is public only because our own TCastleViewport needs to access it. |
| 283 |
|
| 284 |
If you want to change the background, |
| 285 |
instead of using this internal reference, |
| 286 |
access X3D background nodes in @code(BackgroundStack). |
| 287 |
You can modify existing background node by @code(BackgroundStack.Top), |
| 288 |
or you can push a different background node by adding @link(TBackgroundNode) |
| 289 |
to @link(RootNode) and setting @link(TAbstractBindableNode.Bound Background.Bound) to @true. |
| 290 |
|
| 291 |
Returns @nil if there is no currently bound (and supported) background node |
| 292 |
in this scene. |
| 293 |
|
| 294 |
This instance is managed (automatically created/freed |
| 295 |
and so on) by this TCastleScene instance. It is cached |
| 296 |
(so that it's recreated only when relevant things change, |
| 297 |
like X3D nodes affecting this background). |
| 298 |
|
| 299 |
@exclude } |
| 300 |
function InternalBackgroundRenderer: TBackgroundRenderer; |
| 301 |
|
| 302 |
function Attributes: TCastleRenderOptions; deprecated 'use RenderOptions'; |
| 303 |
|
| 304 |
procedure InternalCameraChanged; override; |
| 305 |
|
| 306 |
{ Screen effects information, used by TCastleViewport.ScreenEffects. |
| 307 |
ScreenEffectsCount may actually prepare screen effects. |
| 308 |
@exclude |
| 309 |
@groupBegin } |
| 310 |
function InternalScreenEffects(Index: Integer): TGLSLProgram; |
| 311 |
function InternalScreenEffectsCount: Integer; |
| 312 |
function InternalScreenEffectsNeedDepth: boolean; |
| 313 |
{ @groupEnd } |
| 314 |
|
| 315 |
{ Make TGLShape.PrepareResources call on all shapes before next render. |
| 316 |
@exclude } |
| 317 |
procedure InternalSchedulePrepareResources; |
| 318 |
|
| 319 |
{ Create a scene with the same contents (X3D scene graph) as this one. |
| 320 |
The created scene has exactly the same class as this one |
| 321 |
(we use ClassType.Create to call a virtual constructor). |
| 322 |
|
| 323 |
Note that this @bold(does not copy other scene properties), |
| 324 |
like @link(ProcessEvents) or @link(Spatial) or @link(RenderOptions) contents. } |
| 325 |
function Clone(const AOwner: TComponent): TCastleScene; |
| 326 |
|
| 327 |
{ Whether the scene was (potentially, at least partially) visible |
| 328 |
in the last rendering event. |
| 329 |
|
| 330 |
The "was visible" means that "some shape was visible", that is: |
| 331 |
some shape passed frustum culling, distance culling |
| 332 |
and occlusion culling (see https://castle-engine.io/occlusion_culling ) |
| 333 |
tests. |
| 334 |
|
| 335 |
The result of this method is not affected by: |
| 336 |
|
| 337 |
@unorderedList( |
| 338 |
@item(Lights. |
| 339 |
|
| 340 |
That is, it doesn't matter whether this scene contains some lights |
| 341 |
(X3D light nodes in @link(RootNode)) |
| 342 |
that possibly make some other scenes brighter. |
| 343 |
) |
| 344 |
|
| 345 |
@item(Background. |
| 346 |
|
| 347 |
It doesn't matter whether the scene contains some background |
| 348 |
that affects TCastleViewport skybox.) |
| 349 |
|
| 350 |
@item(Children scenes. |
| 351 |
|
| 352 |
It doesn't matter if you have any children scenes |
| 353 |
(TCastleScene instances that are children of this) |
| 354 |
and whether they are visible. |
| 355 |
This follows the general rule that TCastleScene-specific features |
| 356 |
do not look/affect children scenes, including children TCastleScene. |
| 357 |
Only TCastleTransform features, like @link(TCastleTransform.Exists), |
| 358 |
are applied recursively, i.e. they generally affect the children |
| 359 |
transformations. |
| 360 |
) |
| 361 |
) |
| 362 |
|
| 363 |
To summarize and emphasize: for this method, |
| 364 |
@bold(only the visibility of shapes within this scene matters). |
| 365 |
|
| 366 |
If this scene instance is used multiple times within some viewport, |
| 367 |
or when multiple viewports render the same scene, |
| 368 |
then it is enough that at least one shape in one of the scene instances |
| 369 |
was visible last frame. |
| 370 |
|
| 371 |
TODO: For now, occlusion culling doesn't affect this, i.e. if the scene |
| 372 |
is not visible because occlusion culling. } |
| 373 |
function WasVisible: Boolean; |
| 374 |
published |
| 375 |
{ Improve performance of rendering by checking for each shape whether |
| 376 |
it is inside frustum (camera pyramid of view) before rendering. |
| 377 |
|
| 378 |
This is almost always a good idea. |
| 379 |
Exception may be when, in the most common scene position, |
| 380 |
all the shapes are inside the frustum, |
| 381 |
or all the shapes are outside the frustum. |
| 382 |
In this case this check is wasting time, |
| 383 |
and it matters if you have a @italic(lot of shapes). |
| 384 |
In such case, @link(SceneFrustumCulling) will be enough. } |
| 385 |
property ShapeFrustumCulling: Boolean |
| 386 |
read FShapeFrustumCulling write SetShapeFrustumCulling default true; |
| 387 |
|
| 388 |
{ Improve performance of rendering by checking for the whole scene |
| 389 |
whether it is inside frustum (camera pyramid of view) before rendering. |
| 390 |
|
| 391 |
This is almost always a good idea. |
| 392 |
Exception may be when the scene is almost always within the frustum, |
| 393 |
and you have a @italic(lot of scenes). In such case, this check may be |
| 394 |
a waste of time. } |
| 395 |
property SceneFrustumCulling: Boolean |
| 396 |
read FSceneFrustumCulling write FSceneFrustumCulling default true; |
| 397 |
|
| 398 |
{ Does this scene receive shadows by shadow volumes. } |
| 399 |
property ReceiveShadowVolumes: boolean |
| 400 |
read FReceiveShadowVolumes write FReceiveShadowVolumes default true; |
| 401 |
|
| 402 |
{ Cull shapes farther than this distance. Ignored if <= 0. } |
| 403 |
property DistanceCulling: Single |
| 404 |
read FDistanceCulling write SetDistanceCulling {$ifdef FPC}default 0{$endif}; |
| 405 |
|
| 406 |
{ Rendering options. |
| 407 |
You are free to change them at any time. } |
| 408 |
property RenderOptions: TCastleRenderOptions read FRenderOptions; |
| 409 |
|
| 410 |
{ Lights defines by given scene shine on everything in the viewport, including all other TCastleScene. } |
| 411 |
property CastGlobalLights: Boolean |
| 412 |
read FCastGlobalLights write SetCastGlobalLights default false; |
| 413 |
end; |
| 414 |
|
| 415 |
TCastleSceneClass = class of TCastleScene; |
| 416 |
|
| 417 |
TCastleSceneList = class({$ifdef FPC}specialize{$endif} TObjectList<TCastleScene>) |
| 418 |
end; |
| 419 |
|
| 420 |
TTriangle4List = {$ifdef FPC}specialize{$endif} TStructList<TTriangle4>; |
| 421 |
|
| 422 |
{ @exclude Internal. |
| 423 |
|
| 424 |
Basic non-abstract implementation of render params for calling |
| 425 |
TCastleTransform.LocalRender. |
| 426 |
|
| 427 |
@bold(This is exposed here only to support some experiments with non-standard |
| 428 |
rendering in engine example programs. Do not use this in your own code.) |
| 429 |
|
| 430 |
This can be used when you have to call TCastleTransform.LocalRender, |
| 431 |
but you don't use TCastleViewport. |
| 432 |
Usually this should not be needed. |
| 433 |
This class may be removed at some point! |
| 434 |
You should always try to use TCastleViewport to manage and render |
| 435 |
3D stuff in new programs, and then TCastleViewport will take care of creating |
| 436 |
proper render params instance for you. } |
| 437 |
TBasicRenderParams = class(TRenderParams) |
| 438 |
public |
| 439 |
FGlobalLights: TLightInstancesList; |
| 440 |
constructor Create; |
| 441 |
destructor Destroy; override; |
| 442 |
function GlobalLights: TAbstractLightInstancesList; override; |
| 443 |
end; |
| 444 |
|
| 445 |
var |
| 446 |
InternalEnableRendering: Boolean = true; |
| 447 |
|
| 448 |
DynamicBatching: Boolean = false |
| 449 |
deprecated 'use TCastleViewport.DynamicBatching'; |
| 450 |
|
| 451 |
const |
| 452 |
{ We recommend using CastleRenderOptions unit to get these types. |
| 453 |
But for backward compatibility, they are also available here. } |
| 454 |
|
| 455 |
{ } |
| 456 |
weNormal = CastleRenderOptions.weNormal; |
| 457 |
weWireframeOnly = CastleRenderOptions.weWireframeOnly; |
| 458 |
weSolidWireframe = CastleRenderOptions.weSolidWireframe; |
| 459 |
weSilhouette = CastleRenderOptions.weSilhouette; |
| 460 |
|
| 461 |
ssRendering = CastleSceneCore.ssRendering; |
| 462 |
ssDynamicCollisions = CastleSceneCore.ssDynamicCollisions; |
| 463 |
ssVisibleTriangles = CastleSceneCore.ssVisibleTriangles; |
| 464 |
ssStaticCollisions = CastleSceneCore.ssStaticCollisions; |
| 465 |
|
| 466 |
{$define read_interface} |
| 467 |
{$I castlescene_roottransform.inc} |
| 468 |
{$I castlescene_abstractprimitive.inc} |
| 469 |
{$I castlescene_text.inc} |
| 470 |
{$I castlescene_box.inc} |
| 471 |
{$I castlescene_sphere.inc} |
| 472 |
{$I castlescene_plane.inc} |
| 473 |
{$I castlescene_cone.inc} |
| 474 |
{$I castlescene_cylinder.inc} |
| 475 |
{$I castlescene_imagetransform.inc} |
| 476 |
{$I castlescene_background.inc} |
| 477 |
{$I castlescene_fog.inc} |
| 478 |
{$I castlescene_editorgizmo.inc} |
| 479 |
{$I castlescene_abstractlight.inc} |
| 480 |
{$I castlescene_punctuallight.inc} |
| 481 |
{$I castlescene_pointlight.inc} |
| 482 |
{$I castlescene_directionallight.inc} |
| 483 |
{$I castlescene_spotlight.inc} |
| 484 |
{$ifdef CASTLE_EXPERIMENTAL_ENVIRONMENT_LIGHT} |
| 485 |
{$I castlescene_environmentlight.inc} |
| 486 |
{$endif} |
| 487 |
{$undef read_interface} |
| 488 |
|
| 489 |
implementation |
| 490 |
|
| 491 |
uses Math, |
| 492 |
CastleGLVersion, CastleLog, CastleStringUtils, CastleApplicationProperties, |
| 493 |
CastleShapeInternalRenderShadowVolumes, CastleUriUtils, CastleProjection, |
| 494 |
CastleComponentSerialize, CastleRenderContext, CastleFilesUtils, |
| 495 |
CastleInternalGLUtils, CastleInternalRenderer, X3DCameraUtils; |
| 496 |
|
| 497 |
{$define read_implementation} |
| 498 |
{$I castlescene_roottransform.inc} |
| 499 |
{$I castlescene_abstractprimitive.inc} |
| 500 |
{$I castlescene_text.inc} |
| 501 |
{$I castlescene_box.inc} |
| 502 |
{$I castlescene_sphere.inc} |
| 503 |
{$I castlescene_plane.inc} |
| 504 |
{$I castlescene_cone.inc} |
| 505 |
{$I castlescene_cylinder.inc} |
| 506 |
{$I castlescene_imagetransform.inc} |
| 507 |
{$I castlescene_background.inc} |
| 508 |
{$I castlescene_fog.inc} |
| 509 |
{$I castlescene_editorgizmo.inc} |
| 510 |
{$I castlescene_abstractlight.inc} |
| 511 |
{$I castlescene_punctuallight.inc} |
| 512 |
{$I castlescene_pointlight.inc} |
| 513 |
{$I castlescene_directionallight.inc} |
| 514 |
{$I castlescene_spotlight.inc} |
| 515 |
{$ifdef CASTLE_EXPERIMENTAL_ENVIRONMENT_LIGHT} |
| 516 |
{$I castlescene_environmentlight.inc} |
| 517 |
{$endif} |
| 518 |
{$undef read_implementation} |
| 519 |
|
| 520 |
{ TCastleScene.TSceneRenderOptions ------------------------------------------- } |
| 521 |
|
| 522 |
procedure TCastleScene.TSceneRenderOptions.ReleaseCachedResources; |
| 523 |
begin |
| 524 |
inherited; |
| 525 |
|
| 526 |
{ Secure, in case this is called from TCastleRenderOptions constructor -- |
| 527 |
possible if you assign TCastleRenderOptions.OnCreate there that e.g. changes |
| 528 |
PhongShading. |
| 529 |
Testcase: castle-game. } |
| 530 |
if OwnerScene = nil then |
| 531 |
Exit; |
| 532 |
|
| 533 |
{ TCastleScene must be disconnected from OpenGL, to release |
| 534 |
- resources from shapes (shaders, textures, VBOs) |
| 535 |
- screen effects (referencing renderer shaders, maybe also textures if used) |
| 536 |
So full GLContextClose is needed. } |
| 537 |
OwnerScene.GLContextClose; |
| 538 |
end; |
| 539 |
|
| 540 |
{ TCastleScene ------------------------------------------------------------ } |
| 541 |
|
| 542 |
constructor TCastleScene.Create(AOwner: TComponent); |
| 543 |
begin |
| 544 |
{ inherited Create *may* call some virtual things overriden here |
| 545 |
(although right now it doesn't): it may bind new viewpoint which |
| 546 |
may call ViewChangedSuddenly which is overridden here and uses RenderOptions. |
| 547 |
That's why I have to initialize them *before* "inherited Create" } |
| 548 |
|
| 549 |
{ Setup RenderOptions as proper sub-component. } |
| 550 |
FRenderOptions := TSceneRenderOptions.Create(Self); |
| 551 |
(FRenderOptions as TSceneRenderOptions).OwnerScene := Self; |
| 552 |
FRenderOptions.SetSubComponent(true); |
| 553 |
FRenderOptions.Name := 'RenderOptions'; |
| 554 |
|
| 555 |
inherited Create(AOwner); |
| 556 |
|
| 557 |
FBackgroundRendererValid := false; |
| 558 |
FBackgroundNode := nil; |
| 559 |
FBackgroundRenderer := nil; |
| 560 |
|
| 561 |
FSceneFrustumCulling := true; |
| 562 |
FShapeFrustumCulling := true; |
| 563 |
|
| 564 |
FReceiveShadowVolumes := true; |
| 565 |
|
| 566 |
FilteredShapes := TShapeList.Create; |
| 567 |
FTempPrepareParams := TPrepareParams.Create; |
| 568 |
end; |
| 569 |
|
| 570 |
destructor TCastleScene.Destroy; |
| 571 |
begin |
| 572 |
FreeAndNil(FilteredShapes); |
| 573 |
FreeAndNil(FTempPrepareParams); |
| 574 |
|
| 575 |
{ Make sure to free TCastleScene resources now, even though TCastleTransform.Destroy |
| 576 |
will also call it later -- but then we are in more "uninitialized" state. } |
| 577 |
GLContextClose; |
| 578 |
|
| 579 |
{ Release now all connections between RootNode and Renderer. |
| 580 |
|
| 581 |
Old reason: when freeing RootNode in "inherited" |
| 582 |
(if OwnsRootNode = false), image references (from texture nodes) |
| 583 |
are decremented. So cache used when loading these images must be |
| 584 |
available. |
| 585 |
|
| 586 |
This old reason is no longer relevant: cache is now global RendererCache, |
| 587 |
it doesn't go away when we free Renderer. |
| 588 |
And X3D nodes should have no other links to renderer. |
| 589 |
|
| 590 |
And since TShapesRenderer took over, we don't even have Renderer |
| 591 |
instance here. |
| 592 |
|
| 593 |
Maybe we can remove this call one day, after testing. } |
| 594 |
FreeResources([frTextureDataInNodes, frBackgroundImageInNodes]); |
| 595 |
|
| 596 |
FreeAndNil(FRenderOptions); |
| 597 |
|
| 598 |
inherited; |
| 599 |
end; |
| 600 |
|
| 601 |
function TCastleScene.CreateShape(const AGeometry: TAbstractGeometryNode; |
| 602 |
const AState: TX3DGraphTraverseState; const ParentInfo: PTraversingInfo): TShape; |
| 603 |
begin |
| 604 |
Result := TGLShape.Create(Self, AGeometry, AState, ParentInfo); |
| 605 |
end; |
| 606 |
|
| 607 |
procedure TCastleScene.GLContextClose; |
| 608 |
|
| 609 |
{ This must be coded carefully, because |
| 610 |
- it's called by ChangedAll, and so may be called when our constructor |
| 611 |
didn't do it's work yet. |
| 612 |
- moreover it's called from destructor, so may be called if our |
| 613 |
constructor terminated with exception. |
| 614 |
So e.g. we have to check Renderer <> nil, Shapes <> nil here. } |
| 615 |
|
| 616 |
{ Call TGLShape.GLContextClose. } |
| 617 |
procedure ShapesGLContextClose; |
| 618 |
var |
| 619 |
ShapeList: TShapeList; |
| 620 |
Shape: TShape; |
| 621 |
begin |
| 622 |
if Shapes <> nil then |
| 623 |
begin |
| 624 |
{ Iterate even over non-visible shapes too, for safety: |
| 625 |
since this GLContextClose may happen after some |
| 626 |
"visibility" changed, that is you changed proxy |
| 627 |
or such by event. } |
| 628 |
ShapeList := Shapes.TraverseList(false, false); |
| 629 |
for Shape in ShapeList do |
| 630 |
TGLShape(Shape).GLContextClose; |
| 631 |
end; |
| 632 |
end; |
| 633 |
|
| 634 |
{ Release screen effects OpenGL stuff. } |
| 635 |
procedure ScreenEffectsGLContextClose; |
| 636 |
var |
| 637 |
I: Integer; |
| 638 |
begin |
| 639 |
if ScreenEffectNodes <> nil then |
| 640 |
for I := 0 to ScreenEffectNodes.Count - 1 do |
| 641 |
TScreenEffectNode(ScreenEffectNodes[I]).InternalRendererResourceFree; |
| 642 |
end; |
| 643 |
|
| 644 |
{ When the OpenGL(ES) context is lost, generated textures contents are lost. |
| 645 |
Make sure to regenerate them when entering context again. |
| 646 |
Testcase: Silhouette on Android, switch from application and back. } |
| 647 |
procedure ScheduleUpdateGeneratedTextures; |
| 648 |
var |
| 649 |
I: Integer; |
| 650 |
begin |
| 651 |
if GeneratedTextures <> nil then |
| 652 |
for I := 0 to GeneratedTextures.Count - 1 do |
| 653 |
GeneratedTextures.L[I].Functionality.InternalUpdateNeeded := true; |
| 654 |
end; |
| 655 |
|
| 656 |
begin |
| 657 |
inherited; |
| 658 |
|
| 659 |
PreparedRender := false; |
| 660 |
PreparedShapesResources := false; |
| 661 |
|
| 662 |
ScreenEffectsGLContextClose; |
| 663 |
|
| 664 |
ShapesGLContextClose; |
| 665 |
|
| 666 |
ScheduleUpdateGeneratedTextures; |
| 667 |
|
| 668 |
InternalInvalidateBackgroundRenderer; |
| 669 |
end; |
| 670 |
|
| 671 |
function TCastleScene.ShapeFog(const Shape: TShape; const GlobalFog: TFogNode): TFogFunctionality; |
| 672 |
begin |
| 673 |
Result := nil; |
| 674 |
|
| 675 |
if {(Result = nil) and} (Shape.State.LocalFog <> nil) then |
| 676 |
Result := Shape.State.LocalFog.Functionality(TFogFunctionality) as TFogFunctionality; |
| 677 |
if (Result = nil) and (FogStack.Top <> nil) then |
| 678 |
Result := FogStack.Top.Functionality(TFogFunctionality) as TFogFunctionality; |
| 679 |
if (Result = nil) and (GlobalFog <> nil) then |
| 680 |
Result := GlobalFog.Functionality(TFogFunctionality) as TFogFunctionality; |
| 681 |
end; |
| 682 |
|
| 683 |
procedure TCastleScene.CollectShape_NoTests(const Shape: TGLShape); |
| 684 |
begin |
| 685 |
{ Whether the Shape is rendered directly or through batching, |
| 686 |
mark it "was visible this frame". |
| 687 |
Shape passed the frustum culling, distance culling |
| 688 |
and (TODO) occlusion culling tests at this point. } |
| 689 |
FWasVisibleFrameId := TFramesPerSecond.RenderFrameId; |
| 690 |
if Shape.Node <> nil then |
| 691 |
Shape.Node.InternalWasVisibleFrameId := TFramesPerSecond.RenderFrameId; |
| 692 |
|
| 693 |
Shape.Fog := ShapeFog(Shape, Render_Params.GlobalFog as TFogNode); |
| 694 |
|
| 695 |
Render_Collector.Add(Shape, RenderOptions, |
| 696 |
Render_Params.Transformation^.Transform, Render_Params.DepthRange); |
| 697 |
IsVisibleNow := true; |
| 698 |
end; |
| 699 |
|
| 700 |
procedure TCastleScene.CollectShape_SomeTests(const Shape: TGLShape); |
| 701 |
begin |
| 702 |
if (Shape <> AvoidShapeRendering) and |
| 703 |
( (not AvoidNonShadowCasterRendering) or Shape.ShadowCaster) and |
| 704 |
( { implement TAbstractShapeNode.Visible here, by a trivial check } |
| 705 |
(Shape.Node = nil) or Shape.Node.Visible |
| 706 |
) then |
| 707 |
begin |
| 708 |
CollectShape_NoTests(Shape); |
| 709 |
end; |
| 710 |
end; |
| 711 |
|
| 712 |
procedure TCastleScene.CollectShape_AllTests(const Shape: TShape); |
| 713 |
begin |
| 714 |
if ( (not Assigned(Render_TestShapeVisibility)) or |
| 715 |
Render_TestShapeVisibility(TGLShape(Shape))) then |
| 716 |
CollectShape_SomeTests(TGLShape(Shape)); |
| 717 |
end; |
| 718 |
|
| 719 |
procedure TCastleScene.CollectShape_AllTests_Opaque(const Shape: TShape); |
| 720 |
begin |
| 721 |
if not TGLShape(Shape).UseBlending then |
| 722 |
begin |
| 723 |
CollectShape_AllTests(Shape); |
| 724 |
end; |
| 725 |
end; |
| 726 |
|
| 727 |
procedure TCastleScene.LocalRenderInside( |
| 728 |
const TestShapeVisibility: TTestShapeVisibility; |
| 729 |
const Params: TRenderParams); |
| 730 |
|
| 731 |
{ If we're now collecting opaque shapes (Params.Transparent=false) then add: |
| 732 |
- all opaque shapes |
| 733 |
when IgnoreShapesWithBlending = true |
| 734 |
- all shapes (opaque and the ones supposed to use blending) |
| 735 |
when IgnoreShapesWithBlending = false, default. |
| 736 |
This is good e.g. when RenderOptions.Blending=false, |
| 737 |
so that all shapes are treated as opaque. |
| 738 |
} |
| 739 |
procedure CollectAllAsOpaque( |
| 740 |
const IgnoreShapesWithBlending: Boolean = false); |
| 741 |
begin |
| 742 |
if not Params.Transparent then |
| 743 |
begin |
| 744 |
if IgnoreShapesWithBlending then |
| 745 |
Shapes.Traverse({$ifdef FPC}@{$endif}CollectShape_AllTests_Opaque, true, true) |
| 746 |
else |
| 747 |
Shapes.Traverse({$ifdef FPC}@{$endif}CollectShape_AllTests, true, true); |
| 748 |
end; |
| 749 |
end; |
| 750 |
|
| 751 |
procedure UpdateVisibilitySensors; |
| 752 |
var |
| 753 |
J: Integer; |
| 754 |
Instances: TVisibilitySensorInstanceList; |
| 755 |
NewActive: boolean; |
| 756 |
VisibilitySensorsPair: {$ifdef FPC}TVisibilitySensors.TDictionaryPair{$else}TPair<TVisibilitySensorNode, TVisibilitySensorInstanceList>{$endif}; |
| 757 |
begin |
| 758 |
{ optimize for common case: exit early if nothing to do } |
| 759 |
if (VisibilitySensors.Count = 0) or |
| 760 |
(Params.Frustum = nil) then |
| 761 |
Exit; |
| 762 |
|
| 763 |
if ProcessEvents then |
| 764 |
begin |
| 765 |
BeginChangesSchedule; |
| 766 |
try |
| 767 |
for VisibilitySensorsPair in VisibilitySensors do |
| 768 |
if VisibilitySensorsPair.Key.Enabled then |
| 769 |
begin |
| 770 |
{ calculate NewActive } |
| 771 |
NewActive := false; |
| 772 |
Instances := VisibilitySensorsPair.Value; |
| 773 |
for J := 0 to Instances.Count - 1 do |
| 774 |
if Params.Frustum^.Box3DCollisionPossibleSimple(Instances[J].Box) then |
| 775 |
begin |
| 776 |
NewActive := true; |
| 777 |
Break; |
| 778 |
end; |
| 779 |
{ Note that NextEventTime below increases time tick for every |
| 780 |
VisibilitySensor, which is good, |
| 781 |
otherwise sensors_environmental/visibility_sensor.x3dv |
| 782 |
has a problem at initialization, when multiple sensors |
| 783 |
send isActive = TRUE, and X3D mechanism to avoid loops |
| 784 |
kicks in. } |
| 785 |
VisibilitySensorsPair.Key.SetIsActive(NewActive, NextEventTime); |
| 786 |
end; |
| 787 |
finally EndChangesSchedule; end; |
| 788 |
end; |
| 789 |
end; |
| 790 |
|
| 791 |
{ Render for RenderOptions.Mode = rmFull } |
| 792 |
procedure RenderModeFull; |
| 793 |
var |
| 794 |
I: Integer; |
| 795 |
begin |
| 796 |
if RenderOptions.Blending then |
| 797 |
begin |
| 798 |
if not Params.Transparent then |
| 799 |
begin |
| 800 |
{ Opaque objects, for Params.Transparent = false } |
| 801 |
ShapesFilterBlending(Shapes, true, true, false, |
| 802 |
TestShapeVisibility, FilteredShapes, false); |
| 803 |
for I := 0 to FilteredShapes.Count - 1 do |
| 804 |
CollectShape_SomeTests(TGLShape(FilteredShapes[I])); |
| 805 |
end else |
| 806 |
begin |
| 807 |
{ Partially transparent (blending) objects, for Params.Transparent = true } |
| 808 |
ShapesFilterBlending(Shapes, true, true, false, |
| 809 |
TestShapeVisibility, FilteredShapes, true); |
| 810 |
for I := 0 to FilteredShapes.Count - 1 do |
| 811 |
CollectShape_SomeTests(TGLShape(FilteredShapes[I])); |
| 812 |
end; |
| 813 |
end else |
| 814 |
CollectAllAsOpaque; |
| 815 |
end; |
| 816 |
|
| 817 |
begin |
| 818 |
{ We update XxxVisible only for one value of Params.Transparent. |
| 819 |
Otherwise, we would increase it twice. |
| 820 |
This method is always called first with Params.Transparent = false, |
| 821 |
then Params.Transparent = true during a single frame. } |
| 822 |
if (not Params.Transparent) and (Params.InternalPass = 0) then |
| 823 |
begin |
| 824 |
Params.Statistics.ShapesVisible := Params.Statistics.ShapesVisible + |
| 825 |
ShapesActiveVisibleCount; |
| 826 |
{ also do this only once per frame } |
| 827 |
UpdateVisibilitySensors; |
| 828 |
end; |
| 829 |
|
| 830 |
Render_Params := Params; |
| 831 |
Render_TestShapeVisibility := TestShapeVisibility; |
| 832 |
Render_Collector := Params.Collector as TShapesCollector; |
| 833 |
|
| 834 |
case RenderOptions.Mode of |
| 835 |
rmDepth: |
| 836 |
{ When not rmFull, we don't want to do anything with |
| 837 |
glDepthMask (RenderContext.DepthBufferUpdate) |
| 838 |
or GL_BLEND enable state. Just render everything |
| 839 |
(except: don't render partially transparent stuff for shadow maps). } |
| 840 |
CollectAllAsOpaque(true); |
| 841 |
rmSolidColor: |
| 842 |
CollectAllAsOpaque(false); |
| 843 |
rmFull: |
| 844 |
RenderModeFull; |
| 845 |
{$ifndef COMPILER_CASE_ANALYSIS} |
| 846 |
else raise EInternalError.Create('RenderOptions.Mode?'); |
| 847 |
{$endif} |
| 848 |
end; |
| 849 |
end; |
| 850 |
|
| 851 |
procedure TCastleScene.PrepareResources( |
| 852 |
const Options: TPrepareResourcesOptions; |
| 853 |
const Params: TPrepareParams); |
| 854 |
var |
| 855 |
Renderer: TRenderer; |
| 856 |
|
| 857 |
procedure PrepareShapesResources; |
| 858 |
var |
| 859 |
ShapeList: TShapeList; |
| 860 |
Shape: TShape; |
| 861 |
begin |
| 862 |
ShapeList := Shapes.TraverseList(false, false); |
| 863 |
for Shape in ShapeList do |
| 864 |
TGLShape(Shape).PrepareResources; |
| 865 |
end; |
| 866 |
|
| 867 |
procedure PrepareRenderShapes; |
| 868 |
var |
| 869 |
ShapeList: TShapeList; |
| 870 |
Shape: TShape; |
| 871 |
ReceivedGlobalLights: TLightInstancesList; |
| 872 |
DummyCamera: TRenderingCamera; |
| 873 |
DummyStatistics: TRenderStatistics; |
| 874 |
begin |
| 875 |
if LogRenderer then |
| 876 |
WritelnLog('Renderer', 'Preparing rendering of all shapes'); |
| 877 |
|
| 878 |
FillChar(DummyStatistics, SizeOf(DummyStatistics), #0); |
| 879 |
|
| 880 |
{ Note: we prepare also not visible shapes, in case they become visible. } |
| 881 |
ShapeList := Shapes.TraverseList(false, false); |
| 882 |
|
| 883 |
{ Prepare resources by doing rendering. |
| 884 |
But with Renderer.RenderMode set to rmPrepareRenderXxx so nothing will be actually drawn. } |
| 885 |
|
| 886 |
if prRenderSelf in Options then |
| 887 |
Renderer.RenderMode := rmPrepareRenderSelf |
| 888 |
else |
| 889 |
begin |
| 890 |
Assert(prRenderClones in Options); |
| 891 |
Renderer.RenderMode := rmPrepareRenderClones; |
| 892 |
end; |
| 893 |
|
| 894 |
ReceivedGlobalLights := Params.GlobalLights as TLightInstancesList; |
| 895 |
|
| 896 |
{ We need some non-nil TRenderingCamera instance to be able |
| 897 |
to render with lights. } |
| 898 |
DummyCamera := TRenderingCamera.Create; |
| 899 |
try |
| 900 |
{ Set camera vectors to be anything sensible. |
| 901 |
Otherwise (if we pass zero matrix) opening a scene with shadow maps makes a warning |
| 902 |
that camera matrix is all 0, |
| 903 |
and cannot be inverted, since |
| 904 |
TTextureCoordinateRenderer.RenderCoordinateBegin does |
| 905 |
RenderingCamera.InverseMatrixNeeded. |
| 906 |
Testcase: silhouette. } |
| 907 |
DummyCamera.FromViewVectors(DefaultX3DCameraView, TMatrix4.Identity); |
| 908 |
|
| 909 |
Renderer.RenderBegin(ReceivedGlobalLights, DummyCamera, nil, 0, 0, 0, |
| 910 |
@DummyStatistics); |
| 911 |
|
| 912 |
for Shape in ShapeList do |
| 913 |
begin |
| 914 |
TGLShape(Shape).Fog := ShapeFog(Shape, Params.GlobalFog as TFogNode); |
| 915 |
Renderer.RenderShape(TGLShape(Shape), RenderOptions, |
| 916 |
{ Pass sensible SceneTransform parameter below, |
| 917 |
so that TShader.EnableClipPlane will not raise an exception. |
| 918 |
PlaneTransform(Plane, SceneModelView) should not fail, |
| 919 |
so matrix should be sensible for homegeneous coordinate transformation |
| 920 |
(so identity is OK, zero is not OK). } |
| 921 |
TMatrix4.Identity, |
| 922 |
drFull); |
| 923 |
end; |
| 924 |
|
| 925 |
Renderer.RenderEnd; |
| 926 |
finally FreeAndNil(DummyCamera) end; |
| 927 |
|
| 928 |
Renderer.RenderMode := rmRender; // restore Renderer.RenderMode |
| 929 |
end; |
| 930 |
|
| 931 |
var |
| 932 |
I: Integer; |
| 933 |
PossiblyTimeConsuming: Boolean; |
| 934 |
TimeStart: TCastleProfilerTime; |
| 935 |
begin |
| 936 |
inherited; |
| 937 |
|
| 938 |
if InternalDirty <> 0 then Exit; |
| 939 |
|
| 940 |
if not ApplicationProperties.IsGLContextOpen then |
| 941 |
begin |
| 942 |
WritelnLog('PrepareResources', 'Rendering context not available, skipping preparing TCastleScene rendering resources for "%s"', [ |
| 943 |
UriDisplay(URL) |
| 944 |
]); |
| 945 |
Exit; |
| 946 |
end; |
| 947 |
|
| 948 |
{ When preparing resources, files (like textures) may get loaded, |
| 949 |
causing progress bar (for example from CastleDownload). |
| 950 |
Right now we're not ready to display the (partially loaded) scene |
| 951 |
during this time, so we use InternalDirty to prevent it. |
| 952 |
|
| 953 |
Test http://svn.code.sf.net/p/castle-engine/code/trunk/demo_models/navigation/transition_multiple_viewpoints.x3dv |
| 954 |
Most probably problems are caused because shapes are initially |
| 955 |
without a texture, so their arrays (including VBOs) are generated |
| 956 |
without texture coordinates, and we do not mark them to be prepared |
| 957 |
correctly later. Correct fix is unsure: |
| 958 |
- Marking relevant shapes to be prepared again seems easiest, |
| 959 |
but this means that potentially everything is prepared 2 times |
| 960 |
--- once before resources (like textures) are ready, 2nd time with. |
| 961 |
- It would be best to pas texture coordinates even when no texture is loaded? |
| 962 |
Ideally, the renderer operations should be the same regardless if texture |
| 963 |
is loaded or not. |
| 964 |
It remains to carefully see whether it's possible in all cases. |
| 965 |
} |
| 966 |
|
| 967 |
Inc(InternalDirty); |
| 968 |
try |
| 969 |
PossiblyTimeConsuming := (not PreparedShapesResources) or (not PreparedRender); |
| 970 |
|
| 971 |
if PossiblyTimeConsuming then |
| 972 |
TimeStart := Profiler.Start('Prepare Scene Resources ' + URL); |
| 973 |
|
| 974 |
Assert(Params <> nil); |
| 975 |
Renderer := Params.RendererToPrepareShapes as TRenderer; |
| 976 |
Assert(Renderer <> nil); |
| 977 |
|
| 978 |
if not PreparedShapesResources then |
| 979 |
begin |
| 980 |
{ Use PreparedShapesResources to avoid expensive (for large scenes) |
| 981 |
iteration over all shapes in every TCastleScene.PrepareResources call. } |
| 982 |
PreparedShapesResources := true; |
| 983 |
PrepareShapesResources; |
| 984 |
end; |
| 985 |
|
| 986 |
if ([prRenderSelf, prRenderClones] * Options <> []) and not PreparedRender then |
| 987 |
begin |
| 988 |
{ We use PreparedRender to avoid potentially expensive iteration |
| 989 |
over shapes and expensive Renderer.RenderBegin/End. } |
| 990 |
PreparedRender := true; |
| 991 |
PrepareRenderShapes; |
| 992 |
end; |
| 993 |
|
| 994 |
if prBackground in Options then |
| 995 |
PrepareBackground; |
| 996 |
|
| 997 |
if prScreenEffects in Options then |
| 998 |
begin |
| 999 |
for I := 0 to ScreenEffectNodes.Count - 1 do |
| 1000 |
TScreenEffectResources.Prepare(RenderOptions, |
| 1001 |
ScreenEffectNodes[I] as TScreenEffectNode); |
| 1002 |
end; |
| 1003 |
|
| 1004 |
if PossiblyTimeConsuming then |
| 1005 |
Profiler.Stop(TimeStart); |
| 1006 |
finally Dec(InternalDirty) end; |
| 1007 |
end; |
| 1008 |
|
| 1009 |
procedure TCastleScene.LocalRenderOutside( |
| 1010 |
const TestShapeVisibility: TTestShapeVisibility; |
| 1011 |
const Params: TRenderParams); |
| 1012 |
|
| 1013 |
procedure RenderNormal; |
| 1014 |
begin |
| 1015 |
LocalRenderInside(TestShapeVisibility, Params); |
| 1016 |
end; |
| 1017 |
|
| 1018 |
{ Render, doing some special tricks when rendering to shadow maps. } |
| 1019 |
procedure RenderWithShadowMaps; |
| 1020 |
var |
| 1021 |
SavedMode: TRenderingMode; |
| 1022 |
begin |
| 1023 |
{ For shadow maps, speed up rendering by using only features that affect |
| 1024 |
depth output. } |
| 1025 |
if Params.RenderingCamera.Target in [rtVarianceShadowMap, rtShadowMap] then |
| 1026 |
begin |
| 1027 |
{ This save/restore of RenderOptions around RenderWithWireframeEffect |
| 1028 |
works, because rmDepth is actually applied at "collection time" |
| 1029 |
(not at real rendering time, that happens in TShapesRenderer later). } |
| 1030 |
SavedMode := RenderOptions.Mode; |
| 1031 |
RenderOptions.Mode := rmDepth; |
| 1032 |
|
| 1033 |
RenderNormal; |
| 1034 |
|
| 1035 |
RenderOptions.Mode := SavedMode; |
| 1036 |
end else |
| 1037 |
begin |
| 1038 |
RenderNormal; |
| 1039 |
end; |
| 1040 |
end; |
| 1041 |
|
| 1042 |
begin |
| 1043 |
{ This is usually called by LocalRender(Params) that probably |
| 1044 |
already did tests below. But it may also be called directly, |
| 1045 |
so do the checks below anyway. (The checks are trivial, so no speed harm.) } |
| 1046 |
if CheckVisible and |
| 1047 |
(InternalDirty = 0) and |
| 1048 |
(ReceiveShadowVolumes in Params.ShadowVolumesReceivers) then |
| 1049 |
begin |
| 1050 |
{ I used to make here more complex "prepare" mechanism, that was trying |
| 1051 |
to prepare for particular shapes only right before they are rendered |
| 1052 |
(so instead of calling PrepareResources below, I was calling PrepareShape |
| 1053 |
at the beginning of each RenderShape and such). |
| 1054 |
|
| 1055 |
After a while, it turns out this was a useless complication of code |
| 1056 |
logic. There are many things that *have* to be prepared before whole |
| 1057 |
rendering, for example |
| 1058 |
- Occlusion query id must be generated (as we may start occlusion query |
| 1059 |
before actually rendering the shape). |
| 1060 |
|
| 1061 |
It's much simpler to just call PrepareResources at the beginning. |
| 1062 |
The PrepareResources is already optimized to do nothing, |
| 1063 |
if everything is ready. } |
| 1064 |
FTempPrepareParams.GlobalLights := Params.GlobalLights; |
| 1065 |
FTempPrepareParams.GlobalFog := Params.GlobalFog; |
| 1066 |
Assert(Params.RendererToPrepareShapes <> nil); |
| 1067 |
FTempPrepareParams.RendererToPrepareShapes := Params.RendererToPrepareShapes; |
| 1068 |
{$warnings off} // calling deprecated, but for internal purpose -- do not warn |
| 1069 |
PrepareResources([prRenderSelf], FTempPrepareParams); |
| 1070 |
{$warnings on} |
| 1071 |
|
| 1072 |
RenderWithShadowMaps; |
| 1073 |
end; |
| 1074 |
end; |
| 1075 |
|
| 1076 |
procedure TCastleScene.BeforeNodesFree(const InternalChangedAll: boolean); |
| 1077 |
begin |
| 1078 |
{ Release all associations with OpenGL context before freeing the nodes. |
| 1079 |
This means vrml nodes are still valid during GLRenderer unprepare |
| 1080 |
calls. |
| 1081 |
|
| 1082 |
Although we don't really want to lose our connection with OpenGL |
| 1083 |
context, in fact that's the only sensible thing to do now: since |
| 1084 |
everything possibly changed, we have to unprepare all now. |
| 1085 |
|
| 1086 |
This is done before inherited, as inherited may clear Shapes tree |
| 1087 |
(clearing per-shape information about referenced vbos etc.). } |
| 1088 |
GLContextClose; |
| 1089 |
|
| 1090 |
inherited; |
| 1091 |
end; |
| 1092 |
|
| 1093 |
function TCastleScene.HasColliderMesh: Boolean; |
| 1094 |
begin |
| 1095 |
Result := true; |
| 1096 |
end; |
| 1097 |
|
| 1098 |
procedure TCastleScene.ColliderMesh(const TriangleEvent: TTriangleEvent); |
| 1099 |
var |
| 1100 |
ShapesList: TShapeList; |
| 1101 |
I: Integer; |
| 1102 |
begin |
| 1103 |
inherited ColliderMesh(TriangleEvent); |
| 1104 |
|
| 1105 |
ShapesList := Shapes.TraverseList(true); |
| 1106 |
for I := 0 to ShapesList.Count - 1 do |
| 1107 |
if ShapesList[I].Collidable then |
| 1108 |
ShapesList[I].Triangulate(TriangleEvent); |
| 1109 |
end; |
| 1110 |
|
| 1111 |
{ Shadow volumes ------------------------------------------------------------- } |
| 1112 |
|
| 1113 |
procedure TCastleScene.LocalRenderShadowVolume(const Params: TRenderParams; |
| 1114 |
const ShadowVolumeRenderer: TBaseShadowVolumeRenderer); |
| 1115 |
|
| 1116 |
function NiceName: String; |
| 1117 |
begin |
| 1118 |
Result := Name; |
| 1119 |
if (Name = '') and |
| 1120 |
(csTransient in ComponentStyle) and |
| 1121 |
(Parent <> nil) then |
| 1122 |
Result := 'child(' + Parent.Name + ')'; |
| 1123 |
end; |
| 1124 |
|
| 1125 |
var |
| 1126 |
SceneBox, ShapeBox: TBox3D; |
| 1127 |
SVRenderer: TGLShadowVolumeRenderer; |
| 1128 |
ShapeList: TShapeList; |
| 1129 |
Shape: TShape; |
| 1130 |
ShapeWorldTransform: TMatrix4; |
| 1131 |
ForceOpaque: boolean; |
| 1132 |
begin |
| 1133 |
{ Call inherited to render shadow quads of children, |
| 1134 |
in case one TCastleScene is a child of another. |
| 1135 |
See https://forum.castle-engine.io/t/shadow-ignors-distanceculling/670/14 for testcase. |
| 1136 |
Note that inherited also checks "CheckVisible and CastShadows", |
| 1137 |
so they work recursively. } |
| 1138 |
inherited; |
| 1139 |
|
| 1140 |
if CheckVisible and |
| 1141 |
CastShadows and |
| 1142 |
{ Do not render shadow volumes when rendering wireframe. |
| 1143 |
Shadow volumes assume that object is closed (2-manifold), |
| 1144 |
otherwise weird artifacts are visible. } |
| 1145 |
(RenderOptions.WireframeEffect <> weWireframeOnly) then |
| 1146 |
begin |
| 1147 |
SVRenderer := ShadowVolumeRenderer as TGLShadowVolumeRenderer; |
| 1148 |
|
| 1149 |
ForceOpaque := not (RenderOptions.Blending and (RenderOptions.Mode = rmFull)); |
| 1150 |
|
| 1151 |
// DistanceCullingCheck* uses this value, and it may be called here |
| 1152 |
RenderCameraPosition := Params.Transformation^.InverseTransform.MultPoint( |
| 1153 |
Params.RenderingCamera.View.Translation); |
| 1154 |
|
| 1155 |
{ calculate and check SceneBox } |
| 1156 |
SceneBox := LocalBoundingBox.Transform(Params.Transformation^.Transform); |
| 1157 |
if SVRenderer.GetCasterShadowPossiblyVisible(SceneBox) then |
| 1158 |
begin |
| 1159 |
{ Do not render shadows for objects eliminated by DistanceCulling. |
| 1160 |
This checks per-scene. } |
| 1161 |
if (DistanceCulling > 0) and (not DistanceCullingCheckScene) then |
| 1162 |
Exit; |
| 1163 |
|
| 1164 |
{ Using below OnlyVisible=true, |
| 1165 |
because shadows are cast only by visible scene parts. } |
| 1166 |
ShapeList := Shapes.TraverseList({ OnlyActive } true, { OnlyVisible } true); |
| 1167 |
for Shape in ShapeList do |
| 1168 |
begin |
| 1169 |
{ Do not render shadows for shapes eliminated by DistanceCulling. |
| 1170 |
|
| 1171 |
Otherwise: Not only shadows for invisible objects would look weird, |
| 1172 |
but they would actually show errors. |
| 1173 |
Shadow volumes *assume* that shadow caster is also rendered (shadow quads |
| 1174 |
are closed) if that shadow caster is visible in frustum. |
| 1175 |
|
| 1176 |
This is done per-shape when WholeSceneManifold=false. |
| 1177 |
When WholeSceneManifold=true, we cannot do per-shape check: |
| 1178 |
the whole scene should be rendered. } |
| 1179 |
if not RenderOptions.WholeSceneManifold then |
| 1180 |
begin |
| 1181 |
if (DistanceCulling > 0) and (not DistanceCullingCheckShape(Shape)) then |
| 1182 |
Continue; |
| 1183 |
end; |
| 1184 |
|
| 1185 |
{ Do not render shadows when frustum+light check says it is definitely |
| 1186 |
not visible. |
| 1187 |
|
| 1188 |
This is done per-shape when WholeSceneManifold=false. |
| 1189 |
|
| 1190 |
When WholeSceneManifold=true, we render all shapes here. |
| 1191 |
The per-scene check already passed above. } |
| 1192 |
ShapeBox := Shape.BoundingBox.Transform(Params.Transformation^.Transform); |
| 1193 |
SVRenderer.InitCaster(ShapeBox); |
| 1194 |
if RenderOptions.WholeSceneManifold or |
| 1195 |
SVRenderer.CasterShadowPossiblyVisible then |
| 1196 |
begin |
| 1197 |
ShapeWorldTransform := Params.Transformation^.Transform * |
| 1198 |
Shape.State.Transformation.Transform; |
| 1199 |
Shape.InternalShadowVolumes.RenderSilhouetteShadowVolume( |
| 1200 |
Params, |
| 1201 |
SVRenderer.Mesh, |
| 1202 |
SVRenderer.LightPosition, |
| 1203 |
ShapeWorldTransform, |
| 1204 |
SVRenderer.ZFailAndLightCap, |
| 1205 |
SVRenderer.ZFail, |
| 1206 |
ForceOpaque, |
| 1207 |
RenderOptions.WholeSceneManifold); |
| 1208 |
end; |
| 1209 |
end; |
| 1210 |
end; |
| 1211 |
end; |
| 1212 |
end; |
| 1213 |
|
| 1214 |
function TCastleScene.ShapePossiblyVisible(Shape: TShape): boolean; |
| 1215 |
|
| 1216 |
function FrustumCullingCheck(Shape: TShape): Boolean; |
| 1217 |
begin |
| 1218 |
Result := FrustumForShapeCulling^.Box3DCollisionPossibleSimple(Shape.BoundingBox); |
| 1219 |
|
| 1220 |
// Alternative: sphere |
| 1221 |
// Result := Shape.FrustumBoundingSphereCollisionPossibleSimple(FrustumForShapeCulling^); |
| 1222 |
|
| 1223 |
// Alternative: sphere and box |
| 1224 |
// Result := Shape.FrustumBoundingSphereCollisionPossibleSimple(FrustumForShapeCulling^) and |
| 1225 |
// FrustumForShapeCulling^.Box3DCollisionPossibleSimple(Shape.BoundingBox); |
| 1226 |
|
| 1227 |
{ We used to allow users to configure the check using FrustumCulling |
| 1228 |
and OctreeFrustumCulling, but in the end this was a lot of effort |
| 1229 |
and actually not useful. } |
| 1230 |
end; |
| 1231 |
|
| 1232 |
begin |
| 1233 |
Result := |
| 1234 |
// frustum culling |
| 1235 |
( (not FShapeFrustumCulling) or FrustumCullingCheck(Shape) ) and |
| 1236 |
// distance culling |
| 1237 |
( (DistanceCulling <= 0 ) or DistanceCullingCheckShape(Shape) ); |
| 1238 |
end; |
| 1239 |
|
| 1240 |
function TCastleScene.DistanceCullingCheckScene: Boolean; |
| 1241 |
var |
| 1242 |
Box: TBox3D; |
| 1243 |
begin |
| 1244 |
// This should be only called when DistanceCulling indicates this check is necessary |
| 1245 |
Assert(DistanceCulling > 0); |
| 1246 |
Box := LocalBoundingBoxNoChildren; |
| 1247 |
Result := |
| 1248 |
(not Box.IsEmpty) and |
| 1249 |
(Box.PointDistanceSqr(RenderCameraPosition) <= |
| 1250 |
Sqr(DistanceCulling)); |
| 1251 |
end; |
| 1252 |
|
| 1253 |
function TCastleScene.DistanceCullingCheckShape(const Shape: TShape): boolean; |
| 1254 |
begin |
| 1255 |
{ When WholeSceneManifold, we have to render whole scene, or nothing. |
| 1256 |
|
| 1257 |
Shadow volumes work correctly only if shadow caster (at least the part of it |
| 1258 |
in frustum, that affects the screen) is also rendered. |
| 1259 |
|
| 1260 |
So distance culling cannot eliminate particular shapes. } |
| 1261 |
if RenderOptions.WholeSceneManifold then |
| 1262 |
Exit(true); |
| 1263 |
|
| 1264 |
// This should be only called when DistanceCulling indicates this check is necessary |
| 1265 |
Assert(DistanceCulling > 0); |
| 1266 |
Result := |
| 1267 |
(PointsDistanceSqr(Shape.BoundingSphereCenter, RenderCameraPosition) <= |
| 1268 |
Sqr(DistanceCulling + Shape.BoundingSphereRadius)) |
| 1269 |
end; |
| 1270 |
|
| 1271 |
procedure TCastleScene.SetShapeFrustumCulling(const Value: Boolean); |
| 1272 |
begin |
| 1273 |
if FShapeFrustumCulling <> Value then |
| 1274 |
FShapeFrustumCulling := Value; |
| 1275 |
end; |
| 1276 |
|
| 1277 |
procedure TCastleScene.SetDistanceCulling(const Value: Single); |
| 1278 |
begin |
| 1279 |
if FDistanceCulling <> Value then |
| 1280 |
FDistanceCulling := Value; |
| 1281 |
end; |
| 1282 |
|
| 1283 |
{ Render --------------------------------------------------------------------- } |
| 1284 |
|
| 1285 |
function TCastleScene.RenderFrustumOctree_TestShape( |
| 1286 |
Shape: TShape): boolean; |
| 1287 |
begin |
| 1288 |
{ We know that all shapes passed here are TGLShape, so we can cast } |
| 1289 |
Result := TGLShape(Shape).PassedFrustumAndDistanceCulling; |
| 1290 |
end; |
| 1291 |
|
| 1292 |
procedure TCastleScene.RenderWithOctree_CheckShapeCulling( |
| 1293 |
ShapeIndex: Integer; CollidesForSure: boolean); |
| 1294 |
var |
| 1295 |
Shape: TGLShape; |
| 1296 |
begin |
| 1297 |
Shape := TGLShape(InternalOctreeRendering.ShapesList[ShapeIndex]); |
| 1298 |
|
| 1299 |
if not Shape.PassedFrustumAndDistanceCulling then |
| 1300 |
begin |
| 1301 |
if CollidesForSure then |
| 1302 |
// frustum culling already passed, but still check distance culling |
| 1303 |
Shape.PassedFrustumAndDistanceCulling := (DistanceCulling <= 0) or DistanceCullingCheckShape(Shape) |
| 1304 |
else |
| 1305 |
// this function performs frustum culling and distance culling too |
| 1306 |
Shape.PassedFrustumAndDistanceCulling := ShapePossiblyVisible(Shape); |
| 1307 |
end; |
| 1308 |
end; |
| 1309 |
|
| 1310 |
procedure TCastleScene.Update(const SecondsPassed: Single; var RemoveMe: TRemoveType); |
| 1311 |
|
| 1312 |
{ Update generated texture for this shape. |
| 1313 |
|
| 1314 |
The given camera position, direction, up should be in world space |
| 1315 |
(that is, in TCastleRootTransform space, |
| 1316 |
not in space local to this TCastleScene). |
| 1317 |
These camera vectors are used to update TRenderedTextureNode, if any. |
| 1318 |
|
| 1319 |
This does not change current viewport or projection matrix. } |
| 1320 |
procedure UpdateOneGeneratedTexture(const Shape: TX3DRendererShape; |
| 1321 |
const TextureNode: TAbstractTextureNode; |
| 1322 |
const Render: TRenderFromViewFunction; |
| 1323 |
const ProjectionNear, ProjectionFar: Single; |
| 1324 |
const CurrentViewpoint: TAbstractViewpointNode; |
| 1325 |
const CameraViewKnown: boolean; |
| 1326 |
const CameraView: TViewVectors); |
| 1327 |
|
| 1328 |
procedure UpdateGeneratedCubeMap(const TexNode: TGeneratedCubeMapTextureNode); |
| 1329 |
var |
| 1330 |
TextureRes: TGeneratedCubeMapTextureResource; |
| 1331 |
begin |
| 1332 |
if TexNode.GenTexFunctionality.NeedsUpdate then |
| 1333 |
begin |
| 1334 |
{ Shape.BoundingBox must be non-empty, otherwise we don't know from what |
| 1335 |
3D point to capture environment. |
| 1336 |
|
| 1337 |
Note: check Shape.BoundingBox only after CheckUpdate passed. |
| 1338 |
This is more optimal, as Shape.BoundingBox may need to iterate over mesh. |
| 1339 |
Testcase: examples/mobile/simple_3d_demo/gameinitialize.pas with "toggle cubemap updates" = "off", |
| 1340 |
look at how much UpdateOneGeneratedTexture is eating. Should be 0% if off. } |
| 1341 |
if Shape.BoundingBox.IsEmpty then Exit; |
| 1342 |
|
| 1343 |
TextureRes := TGeneratedCubeMapTextureResource(TTextureResources.Get(TexNode)); |
| 1344 |
if TextureRes <> nil then |
| 1345 |
begin |
| 1346 |
TextureRes.Update(Render, ProjectionNear, ProjectionFar, |
| 1347 |
Shape.BoundingBox.Center + TexNode.FdBias.Value); |
| 1348 |
|
| 1349 |
TexNode.GenTexFunctionality.PostUpdate; |
| 1350 |
|
| 1351 |
if LogRenderer then |
| 1352 |
WritelnLog('CubeMap', TexNode.NiceName + ' texture regenerated'); |
| 1353 |
end; |
| 1354 |
end; |
| 1355 |
end; |
| 1356 |
|
| 1357 |
procedure UpdateGeneratedShadowMap(TexNode: TGeneratedShadowMapNode); |
| 1358 |
var |
| 1359 |
TextureRes: TGeneratedShadowMapResource; |
| 1360 |
begin |
| 1361 |
if TexNode.GenTexFunctionality.NeedsUpdate then |
| 1362 |
begin |
| 1363 |
if TexNode.FdLight.Value is TAbstractPunctualLightNode then |
| 1364 |
begin |
| 1365 |
TextureRes := TGeneratedShadowMapResource(TTextureResources.Get(TexNode)); |
| 1366 |
if TextureRes <> nil then |
| 1367 |
begin |
| 1368 |
TextureRes.Update(Render, ProjectionNear, ProjectionFar, |
| 1369 |
TAbstractPunctualLightNode(TexNode.FdLight.Value)); |
| 1370 |
|
| 1371 |
TexNode.GenTexFunctionality.PostUpdate; |
| 1372 |
|
| 1373 |
if LogRenderer then |
| 1374 |
WritelnLog('GeneratedShadowMap', TexNode.NiceName + ' texture regenerated'); |
| 1375 |
end; |
| 1376 |
end else |
| 1377 |
WritelnWarning('VRML/X3D', TexNode.NiceName + ' needs updating, but light = NULL or incorrect'); |
| 1378 |
end; |
| 1379 |
end; |
| 1380 |
|
| 1381 |
procedure UpdateRenderedTexture(TexNode: TRenderedTextureNode); |
| 1382 |
var |
| 1383 |
TextureRes: TRenderedTextureResource; |
| 1384 |
begin |
| 1385 |
if TexNode.GenTexFunctionality.NeedsUpdate then |
| 1386 |
begin |
| 1387 |
TextureRes := TRenderedTextureResource(TTextureResources.Get(TexNode)); |
| 1388 |
if TextureRes <> nil then |
| 1389 |
begin |
| 1390 |
TextureRes.Update(Render, ProjectionNear, ProjectionFar, CurrentViewpoint, |
| 1391 |
CameraViewKnown, CameraView, Shape); |
| 1392 |
|
| 1393 |
TexNode.GenTexFunctionality.PostUpdate; |
| 1394 |
|
| 1395 |
if LogRenderer then |
| 1396 |
WritelnLog('RenderedTexture', TexNode.NiceName + ' texture regenerated'); |
| 1397 |
end; |
| 1398 |
end; |
| 1399 |
end; |
| 1400 |
|
| 1401 |
begin |
| 1402 |
if TextureNode is TGeneratedCubeMapTextureNode then |
| 1403 |
UpdateGeneratedCubeMap(TGeneratedCubeMapTextureNode(TextureNode)) |
| 1404 |
else |
| 1405 |
if TextureNode is TGeneratedShadowMapNode then |
| 1406 |
UpdateGeneratedShadowMap(TGeneratedShadowMapNode(TextureNode)) |
| 1407 |
else |
| 1408 |
if TextureNode is TRenderedTextureNode then |
| 1409 |
UpdateRenderedTexture(TRenderedTextureNode(TextureNode)); |
| 1410 |
end; |
| 1411 |
|
| 1412 |
{ Update generated textures, like generated cubemaps/shadow maps. } |
| 1413 |
procedure UpdateGeneratedTextures( |
| 1414 |
const RenderFunc: TRenderFromViewFunction; |
| 1415 |
const ProjectionNear, ProjectionFar: Single); |
| 1416 |
var |
| 1417 |
I: Integer; |
| 1418 |
Shape: TGLShape; |
| 1419 |
TextureNode: TAbstractTextureNode; |
| 1420 |
GenTexFunctionality: TGeneratedTextureFunctionality; |
| 1421 |
CamView: TViewVectors; |
| 1422 |
begin |
| 1423 |
if GeneratedTextures.Count = 0 then |
| 1424 |
Exit; // optimize away common case |
| 1425 |
|
| 1426 |
FrameProfiler.Start(fmUpdateGeneratedTextures); |
| 1427 |
|
| 1428 |
{ Avoid doing this two times within the same FrameId. |
| 1429 |
Important if |
| 1430 |
- the same scene is present multiple times in one viewport, |
| 1431 |
- or when Viewport.Items are shared across multiple viewports |
| 1432 |
(thus scene is present in multiple viewports). } |
| 1433 |
if UpdateGeneratedTexturesFrameId = TFramesPerSecond.FrameId then |
| 1434 |
Exit; |
| 1435 |
UpdateGeneratedTexturesFrameId := TFramesPerSecond.FrameId; |
| 1436 |
|
| 1437 |
if World.MainCamera <> nil then |
| 1438 |
begin |
| 1439 |
CamView := World.MainCamera.WorldView; |
| 1440 |
end else |
| 1441 |
begin |
| 1442 |
CamView := DefaultX3DCameraView; |
| 1443 |
end; |
| 1444 |
|
| 1445 |
for I := 0 to GeneratedTextures.Count - 1 do |
| 1446 |
begin |
| 1447 |
Shape := TGLShape(GeneratedTextures.L[I].Shape); |
| 1448 |
TextureNode := GeneratedTextures.L[I].TextureNode; |
| 1449 |
GenTexFunctionality := GeneratedTextures.L[I].Functionality; |
| 1450 |
|
| 1451 |
{ update GenTexFunctionality.InternalUpdateNeeded } |
| 1452 |
if TextureNode is TGeneratedShadowMapNode then |
| 1453 |
begin |
| 1454 |
{ For TGeneratedShadowMapNode, only geometry change requires to regenerate it. } |
| 1455 |
if GenTexFunctionality.InternalLastStateId < World.InternalVisibleGeometryStateId then |
| 1456 |
begin |
| 1457 |
GenTexFunctionality.InternalLastStateId := World.InternalVisibleGeometryStateId; |
| 1458 |
GenTexFunctionality.InternalUpdateNeeded := true; |
| 1459 |
end; |
| 1460 |
end else |
| 1461 |
begin |
| 1462 |
{ For TRenderedTextureNode, TGeneratedCubeMapTextureNode etc. |
| 1463 |
any visible change indicates to regenerate it. } |
| 1464 |
if GenTexFunctionality.InternalLastStateId < World.InternalVisibleStateId then |
| 1465 |
begin |
| 1466 |
GenTexFunctionality.InternalLastStateId := World.InternalVisibleStateId; |
| 1467 |
GenTexFunctionality.InternalUpdateNeeded := true; |
| 1468 |
end; |
| 1469 |
end; |
| 1470 |
|
| 1471 |
if TextureNode is TGeneratedCubeMapTextureNode then |
| 1472 |
AvoidShapeRendering := Shape else |
| 1473 |
if TextureNode is TGeneratedShadowMapNode then |
| 1474 |
AvoidNonShadowCasterRendering := true; |
| 1475 |
|
| 1476 |
UpdateOneGeneratedTexture(Shape, TextureNode, |
| 1477 |
RenderFunc, ProjectionNear, ProjectionFar, |
| 1478 |
ViewpointStack.Top, |
| 1479 |
World.MainCamera <> nil, CamView); |
| 1480 |
|
| 1481 |
AvoidShapeRendering := nil; |
| 1482 |
AvoidNonShadowCasterRendering := false; |
| 1483 |
end; |
| 1484 |
|
| 1485 |
FrameProfiler.Stop(fmUpdateGeneratedTextures); |
| 1486 |
end; |
| 1487 |
|
| 1488 |
begin |
| 1489 |
inherited; |
| 1490 |
|
| 1491 |
{ This will do FrameProfiler.Start/Stop with fmUpdateGeneratedTextures } |
| 1492 |
if World <> nil then |
| 1493 |
UpdateGeneratedTextures( |
| 1494 |
World.InternalRenderEverythingEvent, |
| 1495 |
World.InternalProjectionNear, |
| 1496 |
World.InternalProjectionFar); |
| 1497 |
end; |
| 1498 |
|
| 1499 |
procedure TCastleScene.ResetShapeVisible(const Shape: TShape); |
| 1500 |
begin |
| 1501 |
TGLShape(Shape).PassedFrustumAndDistanceCulling := false; |
| 1502 |
end; |
| 1503 |
|
| 1504 |
procedure TCastleScene.LocalRender(const Params: TRenderParams); |
| 1505 |
|
| 1506 |
{ Call LocalRenderOutside, choosing TTestShapeVisibility function |
| 1507 |
suitable for our Params.Frustum, octrees and some settings. |
| 1508 |
|
| 1509 |
If InternalOctreeRendering is initialized (so be sure to include |
| 1510 |
ssRendering in @link(Spatial)), this octree will be used to quickly |
| 1511 |
find visible Shapes. Otherwise, we will just enumerate all |
| 1512 |
Shapes (which may be slower if you really have a lot of Shapes). } |
| 1513 |
|
| 1514 |
procedure TestOctreeWithFrustum(Octree: TShapeOctree); |
| 1515 |
begin |
| 1516 |
Shapes.Traverse({$ifdef FPC}@{$endif}ResetShapeVisible, false, true); |
| 1517 |
Octree.EnumerateCollidingOctreeItems(Params.Frustum^, |
| 1518 |
{$ifdef FPC}@{$endif}RenderWithOctree_CheckShapeCulling); |
| 1519 |
end; |
| 1520 |
|
| 1521 |
begin |
| 1522 |
inherited; |
| 1523 |
|
| 1524 |
if InternalEnableRendering and |
| 1525 |
CheckVisible and |
| 1526 |
(InternalDirty = 0) and |
| 1527 |
(ReceiveShadowVolumes in Params.ShadowVolumesReceivers) then |
| 1528 |
begin |
| 1529 |
FrameProfiler.Start(fmRenderScene); |
| 1530 |
|
| 1531 |
if (not Params.Transparent) and |
| 1532 |
(Params.InternalPass = 0) then |
| 1533 |
Inc(Params.Statistics.ScenesVisible); |
| 1534 |
|
| 1535 |
if FSceneFrustumCulling and |
| 1536 |
(Params.Frustum <> nil) and |
| 1537 |
(not Params.Frustum^.Box3DCollisionPossibleSimple(LocalBoundingBox)) then |
| 1538 |
begin |
| 1539 |
FrameProfiler.Stop(fmRenderScene); |
| 1540 |
Exit; |
| 1541 |
end; |
| 1542 |
|
| 1543 |
// RenderCameraPosition is used by DistanceCullingCheck* below |
| 1544 |
RenderCameraPosition := Params.Transformation^.InverseTransform.MultPoint( |
| 1545 |
Params.RenderingCamera.View.Translation); |
| 1546 |
|
| 1547 |
{ Do distance culling for whole scene. |
| 1548 |
When WholeSceneManifold=true, this is the only place where |
| 1549 |
we check distance culling, we cannot do per-shape distance culling then. } |
| 1550 |
if (DistanceCulling > 0) and (not DistanceCullingCheckScene) then |
| 1551 |
begin |
| 1552 |
FrameProfiler.Stop(fmRenderScene); |
| 1553 |
Exit; |
| 1554 |
end; |
| 1555 |
|
| 1556 |
if (not Params.Transparent) and |
| 1557 |
(Params.InternalPass = 0) then |
| 1558 |
Inc(Params.Statistics.ScenesRendered); |
| 1559 |
|
| 1560 |
FrustumForShapeCulling := Params.Frustum; |
| 1561 |
|
| 1562 |
if Assigned(InternalVisibilityTest) then |
| 1563 |
LocalRenderOutside(InternalVisibilityTest, Params) |
| 1564 |
else |
| 1565 |
if Params.Frustum = nil then |
| 1566 |
LocalRenderOutside(nil, Params) |
| 1567 |
else |
| 1568 |
if (InternalOctreeRendering <> nil) and |
| 1569 |
ShapeFrustumCulling then |
| 1570 |
begin |
| 1571 |
{ Check above ShapeFrustumCulling, since the InternalOctreeRendering |
| 1572 |
does per-shape frustum culling automatically, even before |
| 1573 |
ShapeCullingOctreeFunc test. Thanks to octree, many shapes |
| 1574 |
don't even reach the stage when ShapeCullingOctreeFunc could be called. } |
| 1575 |
TestOctreeWithFrustum(InternalOctreeRendering); |
| 1576 |
LocalRenderOutside({$ifdef FPC}@{$endif} RenderFrustumOctree_TestShape, Params); |
| 1577 |
end else |
| 1578 |
LocalRenderOutside({$ifdef FPC}@{$endif} ShapePossiblyVisible, Params); |
| 1579 |
|
| 1580 |
FrameProfiler.Stop(fmRenderScene); |
| 1581 |
end; |
| 1582 |
end; |
| 1583 |
|
| 1584 |
{ Background-related things -------------------------------------------------- } |
| 1585 |
|
| 1586 |
procedure TCastleScene.InternalInvalidateBackgroundRenderer; |
| 1587 |
begin |
| 1588 |
FreeAndNil(FBackgroundRenderer); |
| 1589 |
FBackgroundNode := nil; |
| 1590 |
FBackgroundRendererValid := false; |
| 1591 |
end; |
| 1592 |
|
| 1593 |
procedure TCastleScene.PrepareBackground; |
| 1594 |
{ Always after PrepareBackground => FBackgroundRendererValid = true } |
| 1595 |
begin |
| 1596 |
if FBackgroundRendererValid and (BackgroundStack.Top = FBackgroundNode) then |
| 1597 |
Exit; |
| 1598 |
|
| 1599 |
{ Background is created, but not suitable for current |
| 1600 |
BackgroundStack.Top. So destroy it. } |
| 1601 |
if FBackgroundRendererValid then |
| 1602 |
InternalInvalidateBackgroundRenderer; |
| 1603 |
|
| 1604 |
if BackgroundStack.Top <> nil then |
| 1605 |
FBackgroundRenderer := CreateBackgroundRenderer(BackgroundStack.Top) |
| 1606 |
else |
| 1607 |
FBackgroundRenderer := nil; |
| 1608 |
|
| 1609 |
FBackgroundNode := BackgroundStack.Top; |
| 1610 |
FBackgroundRendererValid := true; |
| 1611 |
end; |
| 1612 |
|
| 1613 |
function TCastleScene.InternalBackgroundRenderer: TBackgroundRenderer; |
| 1614 |
var |
| 1615 |
BackgroundNode: TAbstractBackgroundNode; |
| 1616 |
begin |
| 1617 |
PrepareBackground; |
| 1618 |
Result := FBackgroundRenderer; |
| 1619 |
|
| 1620 |
{ If background transform changed, we have to update the FBackgroundRenderer |
| 1621 |
scene. Note that we check Result <> nil always, since not every |
| 1622 |
TAbstractBackgroundNode may be supported. } |
| 1623 |
BackgroundNode := BackgroundStack.Top; |
| 1624 |
if (BackgroundNode <> nil) and (Result <> nil) then |
| 1625 |
Result.UpdateRotation(BackgroundNode.TransformRotation); |
| 1626 |
end; |
| 1627 |
|
| 1628 |
function TCastleScene.Attributes: TCastleRenderOptions; |
| 1629 |
begin |
| 1630 |
Result := RenderOptions; |
| 1631 |
end; |
| 1632 |
|
| 1633 |
procedure TCastleScene.InternalCameraChanged; |
| 1634 |
var |
| 1635 |
I: Integer; |
| 1636 |
begin |
| 1637 |
inherited; |
| 1638 |
for I := 0 to GeneratedTextures.Count - 1 do |
| 1639 |
if GeneratedTextures.L[I].TextureNode is TRenderedTextureNode then |
| 1640 |
{ Camera change causes regenerate of RenderedTexture, |
| 1641 |
as RenderedTexture with viewpoint = NULL uses current camera. |
| 1642 |
See demo_models/rendered_texture/rendered_texture_no_headlight.x3dv |
| 1643 |
testcase. } |
| 1644 |
GeneratedTextures.L[I].Functionality.InternalUpdateNeeded := true; |
| 1645 |
end; |
| 1646 |
|
| 1647 |
function TCastleScene.InternalScreenEffectsCount: Integer; |
| 1648 |
var |
| 1649 |
I: Integer; |
| 1650 |
SE: TScreenEffectNode; |
| 1651 |
begin |
| 1652 |
Result := 0; |
| 1653 |
|
| 1654 |
{ This ties our scene to OpenGL, |
| 1655 |
so we must be notified when OpenGL is closed. |
| 1656 |
Testcase: otherwise the noise1 texture of the screen effect in |
| 1657 |
"The Unholy Society" is not released from OpenGL, we get warning from |
| 1658 |
TextureMemoryProfiler. } |
| 1659 |
RegisterGLContextClose; |
| 1660 |
|
| 1661 |
for I := 0 to ScreenEffectNodes.Count - 1 do |
| 1662 |
begin |
| 1663 |
SE := TScreenEffectNode(ScreenEffectNodes[I]); |
| 1664 |
// Note: TScreenEffectResources.Prepare exits fast if already was done on this shape |
| 1665 |
TScreenEffectResources.Prepare(RenderOptions, SE); |
| 1666 |
if TScreenEffectResources.Get(SE).ShaderProgram <> nil then |
| 1667 |
Inc(Result); |
| 1668 |
end; |
| 1669 |
end; |
| 1670 |
|
| 1671 |
function TCastleScene.InternalScreenEffects(Index: Integer): TGLSLProgram; |
| 1672 |
var |
| 1673 |
I: Integer; |
| 1674 |
SeNode: TScreenEffectNode; |
| 1675 |
SeNodeRes: TScreenEffectResource; |
| 1676 |
begin |
| 1677 |
{ No need for TScreenEffectResources.Prepare here, ScreenEffectsCount (that does |
| 1678 |
TScreenEffectResources.Prepare) is always called first, otherwise the caller |
| 1679 |
would not know that this Index is valid. } |
| 1680 |
|
| 1681 |
for I := 0 to ScreenEffectNodes.Count - 1 do |
| 1682 |
begin |
| 1683 |
SeNode := TScreenEffectNode(ScreenEffectNodes[I]); |
| 1684 |
SeNodeRes := TScreenEffectResources.Get(SeNode); |
| 1685 |
if SeNodeRes.ShaderProgram <> nil then |
| 1686 |
if Index = 0 then |
| 1687 |
Exit(TGLSLProgram(SeNodeRes.ShaderProgram)) |
| 1688 |
else |
| 1689 |
Dec(Index); |
| 1690 |
end; |
| 1691 |
|
| 1692 |
raise EInternalError.Create('TCastleScene.ScreenEffects: Invalid index'); |
| 1693 |
end; |
| 1694 |
|
| 1695 |
function TCastleScene.InternalScreenEffectsNeedDepth: boolean; |
| 1696 |
var |
| 1697 |
I: Integer; |
| 1698 |
SeNode: TScreenEffectNode; |
| 1699 |
SeNodeRes: TScreenEffectResource; |
| 1700 |
begin |
| 1701 |
{ For now: No need for TScreenEffectResources.Prepare here, ScreenEffectsCount |
| 1702 |
is always called first. But actually for some scenarios we should do |
| 1703 |
here TScreenEffectResources.Prepare? } |
| 1704 |
|
| 1705 |
for I := 0 to ScreenEffectNodes.Count - 1 do |
| 1706 |
begin |
| 1707 |
SeNode := TScreenEffectNode(ScreenEffectNodes[I]); |
| 1708 |
SeNodeRes := TScreenEffectResources.Get(SeNode); |
| 1709 |
if (SeNodeRes.ShaderProgram <> nil) and |
| 1710 |
SeNode.NeedsDepth then |
| 1711 |
Exit(true); |
| 1712 |
end; |
| 1713 |
Exit(false); |
| 1714 |
end; |
| 1715 |
|
| 1716 |
procedure TCastleScene.FreeResources(Resources: TSceneFreeResources); |
| 1717 |
begin |
| 1718 |
inherited; |
| 1719 |
|
| 1720 |
if (frBackgroundImageInNodes in Resources) and |
| 1721 |
(FBackgroundRenderer <> nil) then |
| 1722 |
FBackgroundRenderer.FreeResources; |
| 1723 |
end; |
| 1724 |
|
| 1725 |
function TCastleScene.Clone(const AOwner: TComponent): TCastleScene; |
| 1726 |
begin |
| 1727 |
Result := (inherited Clone(AOwner)) as TCastleScene; |
| 1728 |
end; |
| 1729 |
|
| 1730 |
procedure TCastleScene.ChangeWorld(const Value: TCastleAbstractRootTransform); |
| 1731 |
begin |
| 1732 |
if World <> Value then |
| 1733 |
begin |
| 1734 |
if World <> nil then |
| 1735 |
begin |
| 1736 |
if CastGlobalLights then |
| 1737 |
(World as TCastleRootTransform).UnregisterCastGlobalLights(Self); |
| 1738 |
end; |
| 1739 |
|
| 1740 |
inherited; |
| 1741 |
|
| 1742 |
if World <> nil then |
| 1743 |
begin |
| 1744 |
if CastGlobalLights then |
| 1745 |
(World as TCastleRootTransform).RegisterCastGlobalLights(Self); |
| 1746 |
end; |
| 1747 |
end else |
| 1748 |
begin |
| 1749 |
inherited; |
| 1750 |
end; |
| 1751 |
end; |
| 1752 |
|
| 1753 |
procedure TCastleScene.SetCastGlobalLights(const Value: Boolean); |
| 1754 |
begin |
| 1755 |
if FCastGlobalLights <> Value then |
| 1756 |
begin |
| 1757 |
FCastGlobalLights := Value; |
| 1758 |
if World <> nil then |
| 1759 |
begin |
| 1760 |
if Value then |
| 1761 |
(World as TCastleRootTransform).RegisterCastGlobalLights(Self) |
| 1762 |
else |
| 1763 |
(World as TCastleRootTransform).UnregisterCastGlobalLights(Self); |
| 1764 |
end; |
| 1765 |
end; |
| 1766 |
end; |
| 1767 |
|
| 1768 |
function TCastleScene.PropertySections( |
| 1769 |
const PropertyName: String): TPropertySections; |
| 1770 |
begin |
| 1771 |
if (PropertyName = 'RenderOptions') or |
| 1772 |
(PropertyName = 'CastGlobalLights') then |
| 1773 |
Result := [psBasic] |
| 1774 |
else |
| 1775 |
Result := inherited PropertySections(PropertyName); |
| 1776 |
end; |
| 1777 |
|
| 1778 |
function TCastleScene.WasVisible: Boolean; |
| 1779 |
begin |
| 1780 |
{ Note: FWasVisibleFrameId is 0 by default, |
| 1781 |
and TFramesPerSecond.RenderFrameId is always >= 1, |
| 1782 |
which means that this will return (correctly) false at the beginning before any rendering run. } |
| 1783 |
Result := TFramesPerSecond.RenderFrameId = FWasVisibleFrameId; |
| 1784 |
end; |
| 1785 |
|
| 1786 |
procedure TCastleScene.InternalSchedulePrepareResources; |
| 1787 |
begin |
| 1788 |
PreparedShapesResources := false; |
| 1789 |
end; |
| 1790 |
|
| 1791 |
{ TBasicRenderParams --------------------------------------------------------- } |
| 1792 |
|
| 1793 |
constructor TBasicRenderParams.Create; |
| 1794 |
begin |
| 1795 |
inherited; |
| 1796 |
FGlobalLights := TLightInstancesList.Create; |
| 1797 |
InShadow := false; |
| 1798 |
ShadowVolumesReceivers := [false, true]; |
| 1799 |
{ Transparent does not have good default value. |
| 1800 |
User of TBasicRenderParams should call Render method with both Transparent values, |
| 1801 |
to really render everything correctly. |
| 1802 |
We just set them here to capture most 3D objects |
| 1803 |
(as using TBasicRenderParams for anything is a discouraged hack anyway). } |
| 1804 |
Transparent := false; |
| 1805 |
end; |
| 1806 |
|
| 1807 |
destructor TBasicRenderParams.Destroy; |
| 1808 |
begin |
| 1809 |
FreeAndNil(FGlobalLights); |
| 1810 |
inherited; |
| 1811 |
end; |
| 1812 |
|
| 1813 |
function TBasicRenderParams.GlobalLights: TAbstractLightInstancesList; |
| 1814 |
begin |
| 1815 |
Result := FGlobalLights; |
| 1816 |
end; |
| 1817 |
|
| 1818 |
initialization |
| 1819 |
RegisterSerializableComponent(TCastleScene, 'Scene'); |
| 1820 |
RegisterSerializableComponent(TCastleBox, 'Box'); |
| 1821 |
RegisterSerializableComponent(TCastleSphere, 'Sphere'); |
| 1822 |
RegisterSerializableComponent(TCastlePlane, 'Plane'); |
| 1823 |
RegisterSerializableComponent(TCastleText, 'Text'); |
| 1824 |
RegisterSerializableComponent(TCastleCone, 'Cone'); |
| 1825 |
RegisterSerializableComponent(TCastleCylinder, 'Cylinder'); |
| 1826 |
RegisterSerializableComponent(TCastleImageTransform, 'Image'); |
| 1827 |
RegisterSerializableComponent(TCastleBackground, 'Background'); |
| 1828 |
RegisterSerializableComponent(TCastleFog, 'Fog'); |
| 1829 |
RegisterSerializableComponent(TCastlePointLight, ['Light', 'Point']); |
| 1830 |
RegisterSerializableComponent(TCastleDirectionalLight, ['Light', 'Directional']); |
| 1831 |
RegisterSerializableComponent(TCastleSpotLight, ['Light', 'Spot']); |
| 1832 |
{$ifdef CASTLE_EXPERIMENTAL_ENVIRONMENT_LIGHT} |
| 1833 |
RegisterSerializableComponent(TCastleEnvironmentLight, ['Light', 'Environment']); |
| 1834 |
{$endif} |
| 1835 |
end. |