Debian Codegraph @

src/scene/x3d/x3dnodes_standard_lighting.inc

raw
1 {%MainUnit x3dnodes.pas}
2 {
3 Copyright 2002-2023 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18 TGeneratedShadowMapNode = class;
19
20 TLightScope = (
21 { Light shines everywhere. VRML/X3D >= 2 calls these lights global. }
22 lsGlobal,
23 { Light shines only within it's VRML/X3D grouping node.
24 VRML/X3D >= 2 calls these lights not global. }
25 lsLocal,
26 { Light shines only on the following shapes within
27 it's VRML/X3D grouping node.
28 This is used by VRML 1.0 (and Inventor) light sources. }
29 lsLocalVRML1);
30
31 { Base class for all the light nodes. }
32 TAbstractLightNode = class(TAbstractChildNode)
33 strict private
34 FTransformation: TTransformation;
35 WarningWorldTransformDone: Boolean;
36 procedure DoWarningWorldTransform;
37 protected
38 procedure BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); override;
39 procedure MiddleTraverse(StateStack: TX3DGraphTraverseStateStack); override;
40 procedure GroupBeforeTraverse(const State: TX3DGraphTraverseState; var WasPointingDeviceSensor: Boolean); override;
41 public
42 { Does this node act as a headlight.
43 Set and used internally in CGE.
44 @exclude }
45 InternalHeadlight: Boolean;
46
47 constructor Create(const AX3DName: string = ''; const ABaseUrl: String = ''); override;
48
49 { Create TLightInstance record describing this light node under given
50 State. }
51 function CreateLightInstance(State: TX3DGraphTraverseState): TLightInstance;
52
53 { Update TLightInstance record when lighting State changes.
54 Assumes that LightInstance.Node = Self.
55
56 This will set LightInstance.Transform properties, and recalculate
57 all LightInstance properties based on Transform. }
58 procedure UpdateLightInstanceState(
59 var LightInstance: TLightInstance;
60 State: TX3DGraphTraverseState);
61
62 { Update TLightInstance record when lighting location/direction (and other
63 properties precalculated on TLightInstance) change.
64 Assumes that LightInstance.Node = Self. }
65 procedure UpdateLightInstance(
66 var LightInstance: TLightInstance); virtual;
67
68 { Light scope. Default implementation returns lsGlobal or lsLocal,
69 depending on "global" field value (this follows VRML/X3D >= 2.0 rules). }
70 function Scope: TLightScope; virtual;
71
72 { Transformation of this light node, to world space.
73 This accounts for transformation to scene space (TCastleScene)
74 and then to viewport root (TCastleViewport.Items) space.
75
76 Beware: In X3D, light nodes can be instantiated many times within the scene,
77 with different transformations, so @italic(this transformation property
78 should not be used in general).
79
80 Use this only if you you know that light node occurs only once within the scene.
81 For example shadow maps assume this,
82 see [https://castle-engine.io/x3d_extensions.php#section_ext_shadow_maps .
83
84 For this to work, we multiply transformation from last traverse
85 (@link(BeforeTraverse) collects transformation to space)
86 and then use TCastleTransform.WorldTransform.
87
88 @groupBegin }
89 function Transform: TMatrix4;
90 function InverseTransform: TMatrix4;
91 { @groupEnd }
92
93 function TransformationChange: TNodeTransformationChange; override;
94
95 {$I auto_generated_node_helpers/x3dnodes_x3dlightnode.inc}
96 end;
97
98 { Base class for all "punctual" light nodes (that have a position and/or direction). }
99 TAbstractPunctualLightNode = class(TAbstractLightNode)
100 strict private
101 function GetProjectionWorldLocation: TVector3;
102 procedure SetProjectionWorldLocation(const Value: TVector3);
103 function GetProjectionWorldDirection: TVector3;
104 procedure SetProjectionWorldDirection(const Value: TVector3);
105 protected
106 function GetProjectionLocationLocal: TVector3; virtual;
107 procedure SetProjectionLocationLocal(const Value: TVector3); virtual;
108 function GetProjectionDirectionLocal: TVector3; virtual;
109 procedure SetProjectionDirectionLocal(const Value: TVector3); virtual;
110 public
111 { Matrices for rendering shadow map from this light.
112 Identity in this class, override for subclasses able to do shadow mapping.
113 @groupBegin }
114 function ProjectionMatrix: TMatrix4; virtual;
115 function ModelviewMatrix: TMatrix4; virtual;
116 function ModelviewRotationMatrix: TMatrix4; virtual;
117 function GetProjectorMatrix: TMatrix4;
118 { @groupEnd }
119
120 { Light location, direction and up vectors, for projection.
121 Useful when you think of lights as cameras (for shadow maps).
122
123 ProjectionDirectionLocal will always be exactly zero
124 for a PointLight (that doesn't have a direction).
125
126 The GetView returns vectors in global (scene) space.
127 It guarantees that Direction, Side and Up are normalized
128 and orthogonal to each other.
129
130 @groupBegin }
131 property ProjectionLocationLocal: TVector3
132 read GetProjectionLocationLocal
133 write SetProjectionLocationLocal;
134
135 property ProjectionDirectionLocal: TVector3
136 read GetProjectionDirectionLocal
137 write SetProjectionDirectionLocal;
138
139 property ProjectionWorldLocation: TVector3
140 read GetProjectionWorldLocation
141 write SetProjectionWorldLocation;
142
143 property ProjectionWorldDirection: TVector3
144 read GetProjectionWorldDirection
145 write SetProjectionWorldDirection;
146
147 procedure GetView(out Pos, Dir, Side, Up: TVector3); overload;
148 procedure GetView(out View: TViewVectors); overload;
149 { @groupEnd }
150
151 { Calculate distances between the given Box and this light source.
152 This is intended to capture the depth distances where the box
153 resides, useful for calculating e.g. depth ranges to capture in
154 the shadow maps.
155 Depending on light source type, various distance measures may be used,
156 appropriate to light sources projection.
157
158 Always MinDistance <= MaxDistance. They may be negative when
159 we measure along the light's direction.
160
161 @raises EBox3DEmpty When used with an empty box. }
162 procedure Box3DDistances(const Box: TBox3D;
163 out MinDistance, MaxDistance: Single); virtual; abstract;
164
165 { Position and direction expressed in homogeneous coordinates.
166 For positional lights, the last component is always 1.
167 For directional lights, the last component is always 0.
168
169 Note that this is expressed in the local light node coordinate system. }
170 function PositionAndDirection: TVector4; virtual; abstract;
171
172 {$I auto_generated_node_helpers/x3dnodes_x3dpunctuallightnode.inc}
173 end;
174
175 { Base class for all directional lights. }
176 TAbstractDirectionalLightNode = class(TAbstractPunctualLightNode)
177 protected
178 function GetProjectionLocationLocal: TVector3; override;
179 procedure SetProjectionLocationLocal(const Value: TVector3); override;
180 function GetProjectionDirectionLocal: TVector3; override;
181 procedure SetProjectionDirectionLocal(const Value: TVector3); override;
182 public
183 constructor Create(const AX3DName: string = ''; const ABaseUrl: String = ''); override;
184 procedure UpdateLightInstance(var LightInstance: TLightInstance); override;
185 function ProjectionMatrix: TMatrix4; override;
186 function ModelviewMatrix: TMatrix4; override;
187 function ModelviewRotationMatrix: TMatrix4; override;
188 procedure Box3DDistances(const Box: TBox3D;
189 out MinDistance, MaxDistance: Single); override;
190 function PositionAndDirection: TVector4; override;
191 {$I auto_generated_node_helpers/x3dnodes_x3ddirectionallightnode.inc}
192 end;
193
194 { Base class for all positional lights. }
195 TAbstractPositionalLightNode = class(TAbstractPunctualLightNode)
196 public
197 constructor Create(const AX3DName: string = ''; const ABaseUrl: String = ''); override;
198
199 { Calculate light intensity drop because of the distance to the light.
200 This follows the equation @code(1/max( attenuation[0] + ... ))
201 from the VRML/X3D specification, it is the same as OpenGL attenuation.
202
203 Since calculating the DistanceToLight for the @link(Attenuation)
204 method may be time-consuming in some situations,
205 you can check DistanceNeededForAttenuation first.
206 When the DistanceNeededForAttenuation returns @false,
207 then the value of DistanceToLight parameter is ignored (you can
208 pass anything).
209
210 The DistanceToLight should be a distance in the light source
211 local coordinate system. TODO: although our renderers currently
212 ignore this: ray-tracer uses global coord system,
213 OpenGL (fixed-function and shader) renderer uses eye coord system
214 (should be equal to global coord system for normal cameras).
215
216 @groupBegin }
217 function DistanceNeededForAttenuation: boolean;
218 function CalculateAttenuation(const DistanceToLight: Single): Single; overload;
219 { @groupEnd }
220
221 { Is attenuation relevant. When @false, you know that @link(Attenuation)
222 function always returns 1, so there's no point in using it at all. }
223 function HasAttenuation: boolean;
224
225 { Should the "radius" field be taken into account. }
226 function HasRadius: boolean; virtual;
227
228 procedure UpdateLightInstance(var LightInstance: TLightInstance); override;
229 function PositionAndDirection: TVector4; override;
230 {$I auto_generated_node_helpers/x3dnodes_x3dpositionallightnode.inc}
231 end;
232
233 { Point light source, that shines from a given point in all directions around,
234 for all VRML and X3D versions. }
235 TAbstractPointLightNode = class(TAbstractPositionalLightNode)
236 protected
237 function GetProjectionLocationLocal: TVector3; override;
238 procedure SetProjectionLocationLocal(const Value: TVector3); override;
239 public
240 procedure Box3DDistances(const Box: TBox3D;
241 out MinDistance, MaxDistance: Single); override;
242 {$I auto_generated_node_helpers/x3dnodes_x3dpointlightnode.inc}
243 end;
244
245 { Light source that shines along a given direction, like a sun. }
246 TDirectionalLightNode = class(TAbstractDirectionalLightNode)
247 public
248 class function ForVRMLVersion(const Version: TX3DVersion): boolean; override;
249 {$I auto_generated_node_helpers/x3dnodes_directionallight.inc}
250 end;
251 TDirectionalLightNode_2 = TDirectionalLightNode;
252
253 { Point light source, that shines from a given point in all directions around,
254 for X3D. }
255 TPointLightNode = class(TAbstractPointLightNode)
256 public
257 class function ForVRMLVersion(const Version: TX3DVersion): boolean; override;
258 {$I auto_generated_node_helpers/x3dnodes_pointlight.inc}
259 end;
260 TPointLightNode_2 = TPointLightNode;
261
262 { Light source that emits light from a specific point along a specific direction
263 constrained within a cone. }
264 TSpotLightNode = class(TAbstractPositionalLightNode)
265 protected
266 function GetProjectionLocationLocal: TVector3; override;
267 procedure SetProjectionLocationLocal(const Value: TVector3); override;
268 function GetProjectionDirectionLocal: TVector3; override;
269 procedure SetProjectionDirectionLocal(const Value: TVector3); override;
270 public
271 class function ForVRMLVersion(const Version: TX3DVersion): boolean;
272 override;
273 procedure UpdateLightInstance(var LightInstance: TLightInstance); override;
274 function ProjectionMatrix: TMatrix4; override;
275 function ModelviewMatrix: TMatrix4; override;
276 function ModelviewRotationMatrix: TMatrix4; override;
277 procedure Box3DDistances(const Box: TBox3D;
278 out MinDistance, MaxDistance: Single); override;
279
280 { Spot cutoff angle (based on cutOffAngle).
281
282 Expressed in degrees, clamped to correct range
283 (since user can input any value in VRML, and also conversion
284 radians -> degrees could accidentally raise value slightly > 90,
285 so cutOffAngle = 1.5708 is in degrees 90.0002104591,
286 which would cause OpenGL fixed-function error). }
287 function SpotCutoffDeg: Single;
288
289 function SpotCosCutoff: Single;
290
291 { Approximate spot exponent that could be used to render this spot light.
292 Do not use this, unless you really have to.
293 X3D spot light should have a linear fallback, from beamWidth to cutOffAngle,
294 and there is no sensible way to approximate it by an exponent.
295 Use this only if you have to render spot light with exponent,
296 e.g. for OpenGL fixed-function pipeline. }
297 function SpotExponentApproximate: Single;
298
299 { Projection angle, from @link(ProjectionAngle) or 2 * @link(CutOffAngle).
300 See https://castle-engine.io/x3d_extensions_shadow_maps.php . }
301 function EffectiveProjectionAngle: Single;
302
303 {$I auto_generated_node_helpers/x3dnodes_spotlight.inc}
304 end;
305 TSpotLightNode_2 = TSpotLightNode;
306
307 TEnvironmentLightNode = class(TAbstractLightNode)
308 {$I auto_generated_node_helpers/x3dnodes_environmentlight.inc}
309 end;
310
311 {$endif read_interface}
312
313 {$ifdef read_implementation}
314 const
315 FallbackProjectionNear = 1;
316 FallbackProjectionFar = 100;
317 FallbackProjectionRectangle: TVector4 = (X: -10; Y: -10; Z: 10; W: 10);
318
319 { TAbstractLightNode --------------------------------------------------------- }
320
321 constructor TAbstractLightNode.Create(const AX3DName, ABaseUrl: String);
322 begin
323 inherited;
324 FTransformation.Init;
325 end;
326
327 procedure TAbstractLightNode.BeforeTraverse(StateStack: TX3DGraphTraverseStateStack);
328 begin
329 inherited;
330 FTransformation := StateStack.Top.Transformation;
331 end;
332
333 procedure TAbstractLightNode.MiddleTraverse(StateStack: TX3DGraphTraverseStateStack);
334 begin
335 inherited;
336 if Scope = lsLocalVRML1 then
337 StateStack.Top.AddLight(CreateLightInstance(StateStack.Top));
338 end;
339
340 function TAbstractLightNode.Scope: TLightScope;
341 begin
342 if FdGlobal.Value then
343 Result := lsGlobal
344 else
345 Result := lsLocal;
346 end;
347
348 procedure TAbstractLightNode.GroupBeforeTraverse(const State: TX3DGraphTraverseState; var WasPointingDeviceSensor: Boolean);
349 begin
350 inherited;
351 if Scope = lsLocal then
352 begin
353 (*We append lights with lsLocal scope (global=FALSE and VRML/X3D >= 2.0)
354 to the current State.
355
356 It may seem wasteful to enumerate children twice
357 (first we enumerate in TAbstractInternalGroupingNode.BeforeTraverse,
358 then actual TX3DNode.Traverse enumerates again,
359 this time recursively time). But it turned out to
360 be the fastest and simplest method of propagating lsLocal lights
361 correctly...
362
363 Other (rejected) approach was to add ParentGroup to TLightInstance
364 and do it as post-processing step, i.e. in TCastleSceneCore in
365 AddGlobalLights take this ParentGroup and add light everywhere.
366 But that was
367
368 1. even slower, since it must traverse ParentGroup once again
369 for each directional light, and for each shape within this ParentGroup,
370 it must find all it's occurrences inside Shapes, and add light there
371
372 2. it fails ugly in case of DEF / USE of shapes.
373
374 See demo_models/lights_materials/directional_light_scope.wrl test. Imagine
375 (simplified VRML below) :
376
377 Group {
378 DEF S Shape { .... some sphere .... }
379 Group {
380 USE S
381 DirectionalLight { }
382 USE S
383 }
384 USE S
385 }
386
387 What would happen here? ParentGroup.Enumerate would find S *two* times.
388 For each of these occurrences, it would find *four* shapes with
389 matching node value. So 1. all four spheres would be lighted (incorrect,
390 only two spheres in the middle should be lighted) 2. all of them would
391 be lighted two times by the same light... Fix for 1st problem would
392 require us to record some list of parents within State (which would
393 awfully slow down Traverse work, that already is too crowded). Fix for 2nd
394 problem would require some intelligent avoiding of duplicates
395 (set light only for first node, that is both matching and has the light
396 not set yet).
397
398 So fixing the above solution would be quite more convoluted and slower
399 than simple, correct solution below.
400
401 *)
402
403 { Note: We do CreateLightInstance with State from TAbstractInternalGroupingNode node,
404 while precisely we should rather use State from TAbstractLightNode
405 traverse. But, fortunately, State of TAbstractLightNode doesn't
406 change inside (TAbstractLightNode doesn't do anything inside
407 BeforeTraverse), so this is the same thing. }
408
409 { TODO: we ignore here light radius, which may be relevant
410 for TAbstractPositionalLightNode with HasRadius = true.
411 E.g. PointLight with global = false should be limited by *both*
412 scope (in graph hierarchy) and radius, as far as I understand. }
413
414 State.AddLight(CreateLightInstance(State));
415 end;
416 end;
417
418 function TAbstractLightNode.CreateLightInstance(
419 State: TX3DGraphTraverseState): TLightInstance;
420 begin
421 Result.Node := Self;
422 Result.WorldCoordinates := false;
423 UpdateLightInstanceState(Result, State);
424 end;
425
426 procedure TAbstractLightNode.UpdateLightInstanceState(
427 var LightInstance: TLightInstance;
428 State: TX3DGraphTraverseState);
429 begin
430 LightInstance.Transform := State.Transformation.Transform;
431 LightInstance.TransformScale := State.Transformation.Scale;
432 UpdateLightInstance(LightInstance);
433 end;
434
435 procedure TAbstractLightNode.UpdateLightInstance(
436 var LightInstance: TLightInstance);
437 begin
438 { Nothing to do in this class. }
439 Assert(LightInstance.Node = Self);
440 end;
441
442 function TAbstractLightNode.Transform: TMatrix4;
443 begin
444 Result := FTransformation.Transform;
445 if (Scene <> nil) and Scene.HasWorldTransform then
446 Result := Scene.WorldTransform * Result
447 else
448 DoWarningWorldTransform;
449 end;
450
451 function TAbstractLightNode.InverseTransform: TMatrix4;
452 begin
453 Result := FTransformation.InverseTransform;
454 if (Scene <> nil) and Scene.HasWorldTransform then
455 Result := Result * Scene.WorldInverseTransform
456 else
457 DoWarningWorldTransform;
458 end;
459
460 procedure TAbstractLightNode.DoWarningWorldTransform;
461 begin
462 if not WarningWorldTransformDone then
463 begin
464 WarningWorldTransformDone := true;
465 WritelnWarning(NiceName + ' does not know the world transformation, results (like shadow maps) may be incorrect');
466 end;
467 end;
468
469 function TAbstractLightNode.TransformationChange: TNodeTransformationChange;
470 begin
471 Result := ntcLight;
472 end;
473
474 { TAbstractPunctualLightNode --------------------------------------------------------- }
475
476 function TAbstractPunctualLightNode.ProjectionMatrix: TMatrix4;
477 begin
478 Result := TMatrix4.Identity;
479 end;
480
481 function TAbstractPunctualLightNode.ModelviewMatrix: TMatrix4;
482 begin
483 Result := TMatrix4.Identity;
484 end;
485
486 function TAbstractPunctualLightNode.ModelviewRotationMatrix: TMatrix4;
487 begin
488 Result := TMatrix4.Identity;
489 end;
490
491 function TAbstractPunctualLightNode.GetProjectorMatrix: TMatrix4;
492 begin
493 Result := ProjectionMatrix * ModelviewMatrix;
494 end;
495
496 function TAbstractPunctualLightNode.GetProjectionLocationLocal: TVector3;
497 begin
498 Result := TVector3.Zero;
499 end;
500
501 procedure TAbstractPunctualLightNode.SetProjectionLocationLocal(const Value: TVector3);
502 begin
503 { ignored }
504 end;
505
506 function TAbstractPunctualLightNode.GetProjectionDirectionLocal: TVector3;
507 begin
508 Result := TVector3.Zero;
509 end;
510
511 procedure TAbstractPunctualLightNode.SetProjectionDirectionLocal(const Value: TVector3);
512 begin
513 { ignored }
514 end;
515
516 function TAbstractPunctualLightNode.GetProjectionWorldLocation: TVector3;
517 begin
518 Result := Transform.MultPoint(ProjectionLocationLocal);
519 end;
520
521 procedure TAbstractPunctualLightNode.SetProjectionWorldLocation(const Value: TVector3);
522 begin
523 ProjectionLocationLocal := InverseTransform.MultPoint(Value);
524 end;
525
526 function TAbstractPunctualLightNode.GetProjectionWorldDirection: TVector3;
527 begin
528 Result := Transform.MultDirection(ProjectionDirectionLocal);
529 end;
530
531 procedure TAbstractPunctualLightNode.SetProjectionWorldDirection(const Value: TVector3);
532 begin
533 ProjectionDirectionLocal := InverseTransform.MultDirection(Value);
534 end;
535
536 procedure TAbstractPunctualLightNode.GetView(out View: TViewVectors);
537 var
538 IgnoredSide: TVector3;
539 begin
540 GetView(View.Translation, View.Direction, IgnoredSide, View.Up);
541 end;
542
543 procedure TAbstractPunctualLightNode.GetView(out Pos, Dir, Side, Up: TVector3);
544 begin
545 Pos := ProjectionWorldLocation;
546 Dir := ProjectionWorldDirection;
547
548 Up := FdUp.Value;
549 { Up = zero means "calculate anything suitable".
550 We could let AnyOrthogonalVector do this job, but when +Y is sensible
551 (when it results in something non-parallel to Dir), let's use it.
552 This makes calculated "up" more deterministic. }
553 if Up.IsPerfectlyZero then
554 Up := Vector3(0, 1, 0);
555 Up := Transform.MultDirection(Up);
556 { When the "up" vector is parallel to the dir then fix it. }
557 if VectorsParallel(Up, Dir) then
558 Up := AnyOrthogonalVector(Dir);
559
560 { now normalize all vectors,
561 calculate Side,
562 and make Up orthogonal to Dir }
563 Side := TVector3.CrossProduct(Dir, Up).Normalize;
564 Dir := Dir.Normalize;
565 Up := TVector3.CrossProduct(Side, Dir);
566 end;
567
568 { TAbstractDirectionalLightNode ---------------------------------------------- }
569
570 constructor TAbstractDirectionalLightNode.Create(const AX3DName, ABaseUrl: String);
571 begin
572 inherited;
573 FdGlobal.Value := false;
574 end;
575
576 procedure TAbstractDirectionalLightNode.UpdateLightInstance(
577 var LightInstance: TLightInstance);
578 begin
579 inherited;
580 LightInstance.Direction :=
581 LightInstance.Transform.MultDirection(FdDirection.Value).Normalize;
582 end;
583
584 function TAbstractDirectionalLightNode.ProjectionMatrix: TMatrix4;
585 var
586 N, F: Single;
587 R: TVector4;
588 Dimensions: TFloatRectangle;
589 begin
590 { If author didn't provide and CastleInternalShadowMaps unit didn't calculate
591 values for some fields, then use FallbackProjection* defaults here. }
592
593 N := FdProjectionNear.Value;
594 if N = 0 then N := FallbackProjectionNear;
595
596 F := FdProjectionFar.Value;
597 if F = 0 then F := FallbackProjectionFar;
598
599 R := FdProjectionRectangle.Value;
600 if R.IsPerfectlyZero then R := FallbackProjectionRectangle;
601
602 Dimensions.Left := R[0];
603 Dimensions.Bottom := R[1];
604 Dimensions.Width := R[2] - Dimensions.Left;
605 Dimensions.Height := R[3] - Dimensions.Bottom;
606
607 Result := OrthoProjectionMatrix(Dimensions, N, F);
608 end;
609
610 function TAbstractDirectionalLightNode.ModelviewMatrix: TMatrix4;
611 var
612 Pos, Dir, Side, AUp: TVector3;
613 begin
614 GetView(Pos, Dir, Side, AUp);
615 Result := LookDirMatrix(Pos, Dir, Side, AUp);
616 end;
617
618 function TAbstractDirectionalLightNode.ModelviewRotationMatrix: TMatrix4;
619 var
620 Pos, Dir, Side, AUp: TVector3;
621 begin
622 GetView(Pos, Dir, Side, AUp);
623 Result := FastLookDirMatrix(Dir, AUp);
624 end;
625
626 function TAbstractDirectionalLightNode.GetProjectionLocationLocal: TVector3;
627 begin
628 Result := FdProjectionLocation.Value;
629 end;
630
631 procedure TAbstractDirectionalLightNode.SetProjectionLocationLocal(const Value: TVector3);
632 begin
633 FdProjectionLocation.Send(Value);
634 end;
635
636 function TAbstractDirectionalLightNode.GetProjectionDirectionLocal: TVector3;
637 begin
638 Result := FdDirection.Value;
639 end;
640
641 procedure TAbstractDirectionalLightNode.SetProjectionDirectionLocal(const Value: TVector3);
642 begin
643 FdDirection.Send(Value);
644 end;
645
646 procedure TAbstractDirectionalLightNode.Box3DDistances(const Box: TBox3D;
647 out MinDistance, MaxDistance: Single);
648 begin
649 Box.DirectionDistances(ProjectionWorldLocation, ProjectionWorldDirection, MinDistance, MaxDistance);
650 end;
651
652 function TAbstractDirectionalLightNode.PositionAndDirection: TVector4;
653 begin
654 Result := Vector4(-FdDirection.Value, 0);
655 end;
656
657 constructor TAbstractPositionalLightNode.Create(const AX3DName, ABaseUrl: String);
658 begin
659 inherited;
660 FdGlobal.Value := true;
661 end;
662
663 function TAbstractPositionalLightNode.DistanceNeededForAttenuation: boolean;
664 begin
665 Result := (FdAttenuation.Value[1] <> 0) or
666 (FdAttenuation.Value[2] <> 0);
667 end;
668
669 function TAbstractPositionalLightNode.HasAttenuation: boolean;
670 begin
671 Result := ((FdAttenuation.Value[0] <> 1) and
672 (FdAttenuation.Value[0] <> 0)) or
673 (FdAttenuation.Value[1] <> 0) or
674 (FdAttenuation.Value[2] <> 0);
675 end;
676
677 function TAbstractPositionalLightNode.HasRadius: boolean;
678 begin
679 { When radius < 0, behave like radius is infinite.
680 Useful for implementing glTF punctual lights. }
681 Result := Radius >= 0;
682 end;
683
684 procedure TAbstractPositionalLightNode.UpdateLightInstance(
685 var LightInstance: TLightInstance);
686 begin
687 inherited;
688
689 LightInstance.Location := LightInstance.Transform.MultPoint(
690 FdLocation.Value);
691
692 { TODO: For non-uniform scale, this will simply use average scale.
693 This is not fully correct, VRML spec doesn't clarify this
694 but I guess that the intention was that the non-uniform scale will
695 make radius non-uniform, i.e. light volume will not be a regular sphere
696 but some 3d ellipsoid. Unfortunately this would require quite more
697 work, AddGlobalLights (in TCastleSceneCore) would then have to check for collision
698 between
699 sphere transformed by matrix Transform
700 and
701 bounding box
702 which I don't know how to do *easily*... }
703 LightInstance.Radius := FdRadius.Value * LightInstance.TransformScale;
704 end;
705
706 function TAbstractPositionalLightNode.CalculateAttenuation(const DistanceToLight: Single): Single;
707 begin
708 { We don't really need to check DistanceNeededForAttenuation here.
709 But it may be more optimal, since it's often false,
710 and then we don't need to do 2x multiplications and 1x addition. }
711 if DistanceNeededForAttenuation then
712 Result := 1 / Max(
713 FdAttenuation.Value[0] +
714 FdAttenuation.Value[1] * DistanceToLight +
715 FdAttenuation.Value[2] * Sqr(DistanceToLight), 1.0) else
716 Result := 1 / Max(
717 FdAttenuation.Value[0], 1.0);
718 end;
719
720 function TAbstractPositionalLightNode.PositionAndDirection: TVector4;
721 begin
722 Result := Vector4(FdLocation.Value, 1);
723 end;
724
725 function TAbstractPointLightNode.GetProjectionLocationLocal: TVector3;
726 begin
727 Result := FdLocation.Value;
728 end;
729
730 procedure TAbstractPointLightNode.SetProjectionLocationLocal(const Value: TVector3);
731 begin
732 FdLocation.Send(Value);
733 end;
734
735 procedure TAbstractPointLightNode.Box3DDistances(const Box: TBox3D;
736 out MinDistance, MaxDistance: Single);
737 begin
738 Box.PointDistances(ProjectionWorldLocation, MinDistance, MaxDistance);
739 end;
740
741 class function TDirectionalLightNode.ForVRMLVersion(const Version: TX3DVersion): boolean;
742 begin
743 Result := Version.Major >= 2;
744 end;
745
746 class function TPointLightNode.ForVRMLVersion(const Version: TX3DVersion): boolean;
747 begin
748 Result := Version.Major >= 2;
749 end;
750
751 class function TSpotLightNode.ForVRMLVersion(const Version: TX3DVersion): boolean;
752 begin
753 Result := Version.Major >= 2;
754 end;
755
756 procedure TSpotLightNode.UpdateLightInstance(
757 var LightInstance: TLightInstance);
758 begin
759 inherited;
760 LightInstance.Direction :=
761 LightInstance.Transform.MultDirection(FdDirection.Value).Normalize;
762 end;
763
764 function TSpotLightNode.EffectiveProjectionAngle: Single;
765 begin
766 if ProjectionAngle <= 0 then
767 Result := 2 * CutOffAngle
768 else
769 Result := ProjectionAngle;
770 end;
771
772 function TSpotLightNode.ProjectionMatrix: TMatrix4;
773 var
774 Angle, N, F: Single;
775 begin
776 Angle := EffectiveProjectionAngle;
777
778 { If author didn't provide and CastleInternalShadowMaps unit didn't calculate
779 values for some fields, then use FallbackProjection* defaults here. }
780
781 N := FdProjectionNear.Value;
782 if N = 0 then N := FallbackProjectionNear;
783
784 F := FdProjectionFar.Value;
785 if F = 0 then F := FallbackProjectionFar;
786
787 Result := PerspectiveProjectionMatrixRad(Angle, 1, N, F);
788 end;
789
790 function TSpotLightNode.ModelviewMatrix: TMatrix4;
791 var
792 Pos, Dir, Side, AUp: TVector3;
793 begin
794 GetView(Pos, Dir, Side, AUp);
795 Result := LookDirMatrix(Pos, Dir, Side, AUp);
796 end;
797
798 function TSpotLightNode.ModelviewRotationMatrix: TMatrix4;
799 var
800 Pos, Dir, Side, AUp: TVector3;
801 begin
802 GetView(Pos, Dir, Side, AUp);
803 Result := FastLookDirMatrix(Dir, AUp);
804 end;
805
806 function TSpotLightNode.GetProjectionLocationLocal: TVector3;
807 begin
808 Result := FdLocation.Value;
809 end;
810
811 procedure TSpotLightNode.SetProjectionLocationLocal(const Value: TVector3);
812 begin
813 FdLocation.Send(Value);
814 end;
815
816 function TSpotLightNode.GetProjectionDirectionLocal: TVector3;
817 begin
818 Result := FdDirection.Value;
819 end;
820
821 procedure TSpotLightNode.SetProjectionDirectionLocal(const Value: TVector3);
822 begin
823 FdDirection.Send(Value);
824 end;
825
826 procedure TSpotLightNode.Box3DDistances(const Box: TBox3D;
827 out MinDistance, MaxDistance: Single);
828 begin
829 { TODO: MaxDistance should be a little larger, as spot light rays
830 are not parallel. }
831 Box.DirectionDistances(ProjectionWorldLocation, ProjectionWorldDirection, MinDistance, MaxDistance);
832 end;
833
834 function TSpotLightNode.SpotCutoffDeg: Single;
835 begin
836 Result := Min(90, RadToDeg(FdCutOffAngle.Value));
837 end;
838
839 function TSpotLightNode.SpotCosCutoff: Single;
840 begin
841 Result := Cos(FdCutOffAngle.Value);
842 end;
843
844 function TSpotLightNode.SpotExponentApproximate: Single;
845 begin
846 { There is no way to exactly translate beamWidth to OpenGL GL_SPOT_EXPONENT.
847 GL_SPOT_EXPONENT is an exponent for cosinus.
848 beamWidth says to use constant intensity within beamWidth angle,
849 and linear drop off to cutOffAngle.
850 See [https://castle-engine.io/vrml_engine_doc/output/xsl/html/chapter.opengl_rendering.html#section.vrml_lights]
851 for more discussion. }
852
853 if FdBeamWidth.Value >= FdCutOffAngle.Value then
854 Result := 0 else
855 Result := Clamped(0.5 / Max(FdBeamWidth.Value, 0.0001), 0.0, 128.0);
856 end;
857
858 procedure RegisterLightingNodes;
859 begin
860 NodesManager.RegisterNodeClasses([
861 TDirectionalLightNode,
862 TPointLightNode,
863 TSpotLightNode,
864 TEnvironmentLightNode
865 ]);
866 end;
867
868 {$endif read_implementation}