| 1 |
{ |
| 2 |
Copyright 2003-2022 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 3D models by ray-tracing (TClassicRayTracer, TPathTracer). } |
| 17 |
unit CastleRayTracer; |
| 18 |
|
| 19 |
{$I castleconf.inc} |
| 20 |
{$I octreeconf.inc} |
| 21 |
|
| 22 |
{$ifndef FPC} |
| 23 |
{$message fatal 'This unit is only for FPC, not Delphi.'} |
| 24 |
{$endif} |
| 25 |
|
| 26 |
{ TODO: |
| 27 |
- for classic raytracer do shadow cache |
| 28 |
- for classic raytracer use various space filling curves |
| 29 |
- now that FPC inline is stable and cross-unit, use it to inline |
| 30 |
various things from CastleVectors. Check speed. |
| 31 |
} |
| 32 |
|
| 33 |
{ Define PATHTR_USES_SHADOW_CACHE to make path tracing use shadow cache. |
| 34 |
Speed gain is small (sometimes it's even a little worse with |
| 35 |
shadow cache (see ~/ownCloud/3dmodels/rayhunter-demos/raporty/shadow-cache)), |
| 36 |
but in general it's a good idea. For appropriate scenes, speed gain |
| 37 |
is more than 110%. } |
| 38 |
{$define PATHTR_USES_SHADOW_CACHE} |
| 39 |
|
| 40 |
interface |
| 41 |
|
| 42 |
uses Classes, |
| 43 |
CastleVectors, CastleImages, CastleInternalRays, CastleProjection, CastleUtils, |
| 44 |
CastleInternalBaseTriangleOctree, CastleShapes, X3DNodes, |
| 45 |
CastleInternalSpaceFillingCurves, CastleTriangles; |
| 46 |
|
| 47 |
type |
| 48 |
{ } |
| 49 |
TPixelsMadeNotifierFunc = procedure(PixelsMadeCount: Cardinal; Data: Pointer); |
| 50 |
|
| 51 |
TRayTracerKind = (rtkClassic, rtkPathTracer); |
| 52 |
|
| 53 |
TRayTracer = class |
| 54 |
strict protected |
| 55 |
procedure AppendStats(const Stats: TStrings; const RenderingTime: Single); virtual; |
| 56 |
public |
| 57 |
{ Scene to render. |
| 58 |
Must be set before calling @link(Execute). } |
| 59 |
Octree: TBaseTrianglesOctree; |
| 60 |
|
| 61 |
{ Image where the ray-tracer result will be stored. |
| 62 |
Must be set before calling @link(Execute). |
| 63 |
|
| 64 |
We will not resize given here Image. Instead we will use it's |
| 65 |
current size --- so you just have to set Image size as appropriate |
| 66 |
before calling this method. |
| 67 |
|
| 68 |
For every pixel, we calculate it's color and store it by |
| 69 |
@code(TCastleImage.Color[X, Y, 0] := xxx) method. |
| 70 |
We don't modify alpha channel of the image. |
| 71 |
|
| 72 |
Using TRGBFloatImage class is advised if you want the full color |
| 73 |
information. Otherwise color precision is lost beyond 8 bits, and values |
| 74 |
above 1.0 are clamped. } |
| 75 |
Image: TCastleImage; |
| 76 |
|
| 77 |
{ Camera view. |
| 78 |
CamDirection and CamUp do not have to be normalized --- we will correct |
| 79 |
them here if needed. |
| 80 |
CamUp will be automatically corrected to be orthogonal to |
| 81 |
CamDirection if necessary, you only make sure it's not parallel |
| 82 |
to CamDirection. } |
| 83 |
CamPosition, CamDirection, CamUp: TVector3; |
| 84 |
|
| 85 |
{ Camera projection properties. } |
| 86 |
Projection: TProjection; |
| 87 |
|
| 88 |
{ Default background color, if scene doesn't have Background node with skyColor. } |
| 89 |
SceneBGColor: TVector3; |
| 90 |
|
| 91 |
{ Scene Background node. } |
| 92 |
Background: TAbstractBackgroundNode; |
| 93 |
|
| 94 |
{ Callback notified (if assigned) about writing each image pixel. |
| 95 |
This way you can display somewhere, or store to file, partially |
| 96 |
generated image. This callback gets information (in PixelsMadeCount) |
| 97 |
about how many pixels were generated (this includes also pixels skipped |
| 98 |
in case FirstPixel > 0). |
| 99 |
|
| 100 |
The pixels are written in the order of TSwapScanCurve for |
| 101 |
TClassicRayTracer, and in order dependent on TPathTracer.SFCurveClass |
| 102 |
for TPathTracer. When shadow cache will be implemented to TClassicRayTracer, |
| 103 |
then configurable SFCurveClass may be done also for TClassicRayTracer. |
| 104 |
|
| 105 |
Remember that pixels not done yet have the same content as they |
| 106 |
had when you @link(Execute) method started. In other words, |
| 107 |
if you set PixelsMadeNotifier <> nil, then often it's |
| 108 |
desirable to initialize Image content with some color (e.g. black) |
| 109 |
before calling @link(Execute). Otherwise at the time of @link(Execute) |
| 110 |
call, the pixels not done yet will have undefined colors. } |
| 111 |
PixelsMadeNotifier: TPixelsMadeNotifierFunc; |
| 112 |
PixelsMadeNotifierData: Pointer; |
| 113 |
|
| 114 |
{ Initial pixel to start rendering from. By setting this to something > 0, |
| 115 |
you can (re-)start rendering from the middle. Useful to finish |
| 116 |
the job of a previous terminated ray-tracer process. |
| 117 |
|
| 118 |
Must be in [0 .. Image.Width * Image.Height] range. |
| 119 |
Setting to @code(Image.Width * Image.Height) makes the ray-tracer |
| 120 |
do nothing. } |
| 121 |
FirstPixel: Cardinal; |
| 122 |
|
| 123 |
{ Do ray-tracing, writing a ray-traced image into the @link(Image). } |
| 124 |
procedure Execute; virtual; abstract; |
| 125 |
|
| 126 |
{ Do ray-tracing, like @link(Execute), |
| 127 |
additionally gathering some statistics. |
| 128 |
The statistics will be added to the given string list. } |
| 129 |
procedure ExecuteStats(const Stats: TStrings); |
| 130 |
end; |
| 131 |
|
| 132 |
{ Classic Whitted-style ray-tracer. |
| 133 |
See [https://castle-engine.io/vrml_engine_doc/output/xsl/html/section.classic_ray_tracer.html] |
| 134 |
for documentation. |
| 135 |
|
| 136 |
Make sure that VRML2Lights in states are properly initialized if you |
| 137 |
plan to render VRML 2.0 nodes. TCastleSceneCore and descendants do |
| 138 |
this for you automatically. } |
| 139 |
TClassicRayTracer = class(TRayTracer) |
| 140 |
protected |
| 141 |
procedure AppendStats(const Stats: TStrings; const RenderingTime: Single); override; |
| 142 |
public |
| 143 |
{ Limit for recursion depth. 0 means that only primary rays will be cast, |
| 144 |
1 means that primary rays and 1 ray into mirror / transmitted / shadow, |
| 145 |
and so on. } |
| 146 |
InitialDepth: Cardinal; |
| 147 |
|
| 148 |
{ Fog to render. Set FogNode <> @nil to render a fog, |
| 149 |
following VRML 2.0/X3D lighting equations. |
| 150 |
FogNode.TransformScale is used. } |
| 151 |
FogNode: TFogNode; |
| 152 |
|
| 153 |
{ Lights shining on everything, like a headlight. } |
| 154 |
GlobalLights: TLightInstancesList; |
| 155 |
OwnsGlobalLights: boolean; |
| 156 |
|
| 157 |
property BaseLights: TLightInstancesList read GlobalLights write GlobalLights; |
| 158 |
{$ifdef FPC}deprecated 'use GlobalLights';{$endif} |
| 159 |
property OwnsBaseLights: Boolean read OwnsGlobalLights write OwnsGlobalLights; |
| 160 |
{$ifdef FPC}deprecated 'use OwnsGlobalLights';{$endif} |
| 161 |
|
| 162 |
procedure Execute; override; |
| 163 |
destructor Destroy; override; |
| 164 |
end; |
| 165 |
|
| 166 |
{ Path tracer. See |
| 167 |
[https://castle-engine.io/vrml_engine_doc/output/xsl/html/section.path_tracer.html] |
| 168 |
for documentation. } |
| 169 |
TPathTracer = class(TRayTracer) |
| 170 |
private |
| 171 |
CollectedLightItems: TFPList; |
| 172 |
procedure CollectLightItems(const Triangle: PTriangle); |
| 173 |
protected |
| 174 |
procedure AppendStats(const Stats: TStrings; const RenderingTime: Single); override; |
| 175 |
public |
| 176 |
constructor Create; |
| 177 |
procedure Execute; override; |
| 178 |
public |
| 179 |
{ MinDepth and RRoulContinue together determine the path length. |
| 180 |
The path has at least MinDepth length, and then Russian roulette |
| 181 |
is used. |
| 182 |
|
| 183 |
See [https://castle-engine.io/rayhunter.php] |
| 184 |
documentation about "<recursion-depth>" and @--r-roul-continue |
| 185 |
for suggestions about how to use these parameters. |
| 186 |
See also [https://castle-engine.io/raytr_gallery.php] |
| 187 |
for some experiments with these values. |
| 188 |
|
| 189 |
RRoulContinue must be in 0..1 range. |
| 190 |
|
| 191 |
You can give RRoulContinue = 0 if you don't want to use |
| 192 |
Russian roulette at all (works OK because our comparison |
| 193 |
@code(Random < RRoulContinue) uses "<", not "<="). |
| 194 |
Note that this causes bias (result is darker than it should be). |
| 195 |
Only RRoulContinue > 0 removes bias (the expected result is the correct |
| 196 |
one). |
| 197 |
|
| 198 |
Small RRoulContinue values cause a lot of noise. |
| 199 |
Large RRoulContinue values cause long rendering. |
| 200 |
|
| 201 |
MinDepth must be >= 0. You can use MinDepth = 0 to |
| 202 |
disable "minimal path length", and use Russian roulette always (noisy). |
| 203 |
@groupBegin } |
| 204 |
MinDepth: Integer; |
| 205 |
RRoulContinue: Single; |
| 206 |
{ @groupEnd } |
| 207 |
|
| 208 |
{ How many paths to use. Both must be > 0. |
| 209 |
|
| 210 |
PrimarySamplesCount tells how many paths are used for primary ray, |
| 211 |
and is really useful only for anti-aliasing. You can set this to |
| 212 |
a few. Values above ~10 are useless, they cause much longer rendering |
| 213 |
without really improving the result. You can set this to 1 if you |
| 214 |
don't need anti-aliasing. |
| 215 |
|
| 216 |
NonPrimarySamplesCount is the number of paths caused by each hit |
| 217 |
of a primary ray. This is the main quality control for the path-tracer, |
| 218 |
more paths mean that colors are gathered from more random samples, |
| 219 |
which means that final color is more accurate. In total you have |
| 220 |
pixels count * PrimarySamplesCount * NonPrimarySamplesCount, |
| 221 |
so beware when increasing this: you really have a lot paths. } |
| 222 |
PrimarySamplesCount, NonPrimarySamplesCount: Cardinal; |
| 223 |
|
| 224 |
{ How many samples are used to calculate @italic(direct) |
| 225 |
illumination at every path point. These are rays sent into |
| 226 |
random points of random light sources, to test if given light |
| 227 |
shines here. |
| 228 |
|
| 229 |
Set this to 0 to have a really naive path-tracing, that wanders |
| 230 |
randomly hoping to hit light source by chance. This will usually |
| 231 |
need an enormous amount of PrimarySamplesCount * NonPrimarySamplesCount |
| 232 |
to given any sensible results. |
| 233 |
|
| 234 |
Set this to 1 or more for a normal path-tracer. } |
| 235 |
DirectIllumSamplesCount: Cardinal; |
| 236 |
|
| 237 |
{ Order of pixels filled. In theory, something like THilbertCurve |
| 238 |
or TPeanoCurve could speed up rendering (because shadow cache is more |
| 239 |
utilized) compared to TSwapScanCurve. But in practice, right now |
| 240 |
this doesn't give any noticeable benefit. } |
| 241 |
SFCurveClass: TSpaceFillingCurveClass; |
| 242 |
end; |
| 243 |
|
| 244 |
implementation |
| 245 |
|
| 246 |
uses SysUtils, Math, |
| 247 |
CastleInternalSphereSampling, CastleTimeUtils, CastleColors, CastleRenderOptions; |
| 248 |
|
| 249 |
{ TOctreeIgnoreForShadowRaysAndOneItem -------------------------------------- } |
| 250 |
|
| 251 |
type |
| 252 |
{ Simple utility class to easily ignore all transparent, non-shadow-casting |
| 253 |
triangles, and, additionally, one chosen triangle. |
| 254 |
Useful for TrianglesToIgnoreFunc parameters of various |
| 255 |
TBaseTrianglesOctree methods. } |
| 256 |
TOctreeIgnoreForShadowRaysAndOneItem = class |
| 257 |
public |
| 258 |
OneItem: PTriangle; |
| 259 |
function IgnoreItem(const Sender: TObject; const Triangle: PTriangle): boolean; |
| 260 |
constructor Create(AOneItem: PTriangle); |
| 261 |
end; |
| 262 |
|
| 263 |
function TOctreeIgnoreForShadowRaysAndOneItem.IgnoreItem( |
| 264 |
const Sender: TObject; const Triangle: PTriangle): boolean; |
| 265 |
begin |
| 266 |
Result := (Triangle = OneItem) or Triangle^.IgnoreForShadowRays; |
| 267 |
end; |
| 268 |
|
| 269 |
constructor TOctreeIgnoreForShadowRaysAndOneItem.Create( |
| 270 |
AOneItem: PTriangle); |
| 271 |
begin |
| 272 |
inherited Create; |
| 273 |
OneItem := AOneItem; |
| 274 |
end; |
| 275 |
|
| 276 |
type |
| 277 |
TOctreeIgnoreForShadowRays = class |
| 278 |
{ Ignore (return @true) transparent triangles |
| 279 |
(with Material.Transparency > 0) and non-shadow-casting triangles |
| 280 |
(with Appearance.shadowCaster = FALSE). |
| 281 |
|
| 282 |
This is suitable for TTriangleIgnoreFunc function, you can pass |
| 283 |
this to RayCollision and such. } |
| 284 |
class function IgnoreForShadowRays( |
| 285 |
const Sender: TObject; const Triangle: PTriangle): boolean; |
| 286 |
end; |
| 287 |
|
| 288 |
class function TOctreeIgnoreForShadowRays.IgnoreForShadowRays( |
| 289 |
const Sender: TObject; const Triangle: PTriangle): boolean; |
| 290 |
begin |
| 291 |
Result := Triangle^.IgnoreForShadowRays; |
| 292 |
end; |
| 293 |
|
| 294 |
{ Checks whether Light (point or directional) shines at scene point |
| 295 |
LightedPoint. |
| 296 |
|
| 297 |
"Lights at scene" means that the light is turned on |
| 298 |
(field "on" is @true) and between light source and a LightedPoint |
| 299 |
nothing blocks the light (we check it by querying collisions using |
| 300 |
the octree, ignoring transparent and non-shadow-casting triangles), |
| 301 |
and the light source is on the same side of LightedPointPlane as |
| 302 |
RenderDir. |
| 303 |
|
| 304 |
TriangleToIgnore and IgnoreMarginAtStart work just like for |
| 305 |
SegmentCollision. You should usually set TriangleToIgnore to the |
| 306 |
triangle containing your LightedPoint and IgnoreMarginAtStart to @true, |
| 307 |
to avoid detecting point as shadowing itself. } |
| 308 |
function OctreeLightNotBlocked(const Octree: TBaseTrianglesOctree; |
| 309 |
const Light: TLightInstance; |
| 310 |
const LightedPoint, LightedPointPlane, RenderDir: TVector3; |
| 311 |
const TriangleToIgnore: PTriangle; |
| 312 |
const IgnoreMarginAtStart: boolean): boolean; |
| 313 |
var |
| 314 |
LightPos: TVector3; |
| 315 |
begin |
| 316 |
if not Light.Node.FdOn.Value then |
| 317 |
Exit(false); |
| 318 |
|
| 319 |
if Light.Node is TAbstractDirectionalLightNode then |
| 320 |
{ Swiatlo directional oznacza ze swiatlo polozone jest tak bardzo |
| 321 |
daleko ze wszystkie promienie od swiatla sa rownolegle. |
| 322 |
|
| 323 |
Od pozycji LightedPoint odejmujemy wydluzone Direction swiatla. |
| 324 |
|
| 325 |
3 * Box3DMaxSize(Octree.TreeRoot.Box) na pewno jest odlegloscia |
| 326 |
ktora sprawi ze LightPos bedzie poza Octree.TreeRoot.Box |
| 327 |
(bo gdyby nawet Octree.TreeRoot.Box byl szescianem to jego przekatna |
| 328 |
ma dlugosc tylko Sqrt(2) * Sqrt(2) * Box3DMaxSize(Octree.TreeRoot.Box) |
| 329 |
(= 2 * Box3DMaxSize(Octree.TreeRoot.Box)) |
| 330 |
W ten sposob otrzymujemy punkt ktory na pewno lezy POZA TreeRoot.Box |
| 331 |
i jezeli nic nie zaslania drogi od Point do tego punktu to |
| 332 |
znaczy ze swiatlo oswietla Intersection. } |
| 333 |
LightPos := LightedPoint - |
| 334 |
Light.Direction.AdjustToLength(3 * Octree.InternalTreeRoot.Box.MaxSize) |
| 335 |
else |
| 336 |
LightPos := Light.Location; |
| 337 |
|
| 338 |
Result := |
| 339 |
VectorsSamePlaneDirections( |
| 340 |
LightPos - LightedPoint, |
| 341 |
RenderDir, |
| 342 |
LightedPointPlane) and |
| 343 |
(Octree.SegmentCollision(LightedPoint, LightPos, false, TriangleToIgnore, IgnoreMarginAtStart, |
| 344 |
{$ifdef FPC}@{$endif} TOctreeIgnoreForShadowRays {$ifdef FPC}(nil){$endif}.IgnoreForShadowRays) = nil); |
| 345 |
end; |
| 346 |
|
| 347 |
{ RayDirection calculations ----------------------------------------------------- } |
| 348 |
|
| 349 |
{ Calculate the transmitted ray created by hitting a ray |
| 350 |
- with direction NormRayDirection (normalized ray direction is expected here) |
| 351 |
- from material with angle of refraction EtaFrom |
| 352 |
- transmitted into the material with angle of refraction EtaTo |
| 353 |
- hit occurs on the plane with normal vector (i.e. normalized) PlaneNormal } |
| 354 |
function TryTransmittedRayDirection( |
| 355 |
out TransmittedRayDirection: TVector3; |
| 356 |
const NormRayDirection: TVector3; |
| 357 |
const PlaneNormal: TVector3; |
| 358 |
const EtaFrom, EtaTo: Single): boolean; |
| 359 |
{ Written based on Foley, page 627 } |
| 360 |
var |
| 361 |
EtaTransmission, RayIDotNormal, ToBeSqrRooted: Single; |
| 362 |
RayI: TVector3; |
| 363 |
{ This is the Normal pointing in the direction from where the RayDirection came |
| 364 |
(i.e. in the opposite of RayDirection, |
| 365 |
i.e. -RayDirection (note the "-") and Normal must point to the same side |
| 366 |
of plane with PlaneNormal) } |
| 367 |
Normal: TVector3; |
| 368 |
begin |
| 369 |
Normal := PlaneDirNotInDirection(PlaneNormal, NormRayDirection); |
| 370 |
RayI := -NormRayDirection; |
| 371 |
|
| 372 |
RayIDotNormal := TVector3.DotProduct(RayI, Normal); |
| 373 |
|
| 374 |
{ EtaTransmission is the ratio between angles of refraction of materials |
| 375 |
that change when the transmitted ray enters to the other side |
| 376 |
of the plane. } |
| 377 |
EtaTransmission := EtaFrom / EtaTo; |
| 378 |
|
| 379 |
ToBeSqrRooted := 1 - Sqr(EtaTransmission) * (1 - Sqr(RayIDotNormal)); |
| 380 |
|
| 381 |
Result := ToBeSqrRooted >= 0; |
| 382 |
if Result then |
| 383 |
TransmittedRayDirection := |
| 384 |
(Normal * (EtaTransmission * RayIDotNormal - Sqrt(ToBeSqrRooted))) |
| 385 |
- (RayI * EtaTransmission); |
| 386 |
end; |
| 387 |
|
| 388 |
{ Calculate the perfect reflected vector. |
| 389 |
Arguments NormRayDirection and PlaneNormal like for TryTransmittedRayDirection. } |
| 390 |
function ReflectedRayDirection( |
| 391 |
const NormRayDirection: TVector3; |
| 392 |
const PlaneNormal: TVector3): TVector3; |
| 393 |
var |
| 394 |
Normal, NormNegatedRayDirection: TVector3; |
| 395 |
begin |
| 396 |
{ Calculate Normal like in TryTransmittedRayDirection. } |
| 397 |
Normal := PlaneDirNotInDirection(PlaneNormal, NormRayDirection); |
| 398 |
NormNegatedRayDirection := -NormRayDirection; |
| 399 |
|
| 400 |
{ We calculate ray as mirror ray to NormNegatedRayDirection. |
| 401 |
Calculation is just like in Foley (page 601, section (14.16)). } |
| 402 |
Result := (Normal * 2 * TVector3.DotProduct(Normal, NormNegatedRayDirection)) |
| 403 |
- NormNegatedRayDirection; |
| 404 |
end; |
| 405 |
|
| 406 |
function GetSceneBackgroundColor(const Background: TAbstractBackgroundNode; |
| 407 |
const Default: TCastleColorRGB): TCastleColorRGB; |
| 408 |
begin |
| 409 |
if (Background is TAbstract3DBackgroundNode) and |
| 410 |
(TAbstract3DBackgroundNode(Background).FdSkyColor.Count <> 0) then |
| 411 |
Result := TAbstract3DBackgroundNode(Background).FdSkyColor.Items[0] |
| 412 |
else |
| 413 |
Result := Default; |
| 414 |
end; |
| 415 |
|
| 416 |
function GetDiffuseTexture(const Texture: TAbstractTextureNode; |
| 417 |
const TexCoord: TVector4): TCastleColorRGB; |
| 418 |
|
| 419 |
function DivUnsignedModulo(const Dividend: Integer; const Divisor: Integer): Integer; |
| 420 |
var |
| 421 |
DivResult: Smallint; |
| 422 |
DivRemainder: Word; |
| 423 |
begin |
| 424 |
DivUnsignedMod(Dividend, Divisor, DivResult, DivRemainder); |
| 425 |
Result := DivRemainder; |
| 426 |
end; |
| 427 |
|
| 428 |
var |
| 429 |
RepeatCoord: array [0..2] of boolean; |
| 430 |
|
| 431 |
function SampleNearest(const Image: TCastleImage; const Pixel: TVector3): TCastleColor; |
| 432 |
var |
| 433 |
I: Integer; |
| 434 |
Dimensions: TVector3Cardinal; |
| 435 |
PixelInt: TVector3Integer; |
| 436 |
begin |
| 437 |
Dimensions := Image.Dimensions; |
| 438 |
for I := 0 to 2 do |
| 439 |
begin |
| 440 |
PixelInt.Data[I] := Round(Pixel[I] - 0.5); |
| 441 |
if RepeatCoord[I] then |
| 442 |
PixelInt.Data[I] := DivUnsignedModulo(PixelInt[I], Dimensions[I]) |
| 443 |
else |
| 444 |
PixelInt.Data[I] := Clamped(PixelInt[I], 0, Dimensions[I] - 1); |
| 445 |
end; |
| 446 |
Result := Image.Colors[PixelInt[0], PixelInt[1], PixelInt[2]]; |
| 447 |
end; |
| 448 |
|
| 449 |
// This works OK, but is not needed now (as it ~2 times slower than SampleLinear2D). |
| 450 |
{ |
| 451 |
function SampleLinear(const Image: TCastleImage; Pixel: TVector3): TCastleColor; |
| 452 |
var |
| 453 |
I: Integer; |
| 454 |
Dimensions: TVector3Cardinal; |
| 455 |
PixelInt: array [boolean, 0..2] of Integer; |
| 456 |
PixelFrac: TVector3; |
| 457 |
begin |
| 458 |
Dimensions := Image.Dimensions; |
| 459 |
for I := 0 to 2 do |
| 460 |
begin |
| 461 |
if RepeatCoord[I] then |
| 462 |
Pixel[I] := FloatModulo(Pixel[I], Dimensions[I]) |
| 463 |
else |
| 464 |
Pixel[I] := Clamped(Pixel[I], 0, Dimensions[I]); |
| 465 |
end; |
| 466 |
|
| 467 |
for I := 0 to 2 do |
| 468 |
begin |
| 469 |
PixelInt[false][I] := Clamped(Floor(Pixel[I]), 0, Dimensions[I] - 1); |
| 470 |
PixelInt[true ][I] := Min(PixelInt[false][I] + 1, Dimensions[I] - 1); |
| 471 |
PixelFrac[I] := Clamped(Pixel[I] - PixelInt[false][I], 0.0, 1.0); |
| 472 |
end; |
| 473 |
|
| 474 |
Result := |
| 475 |
Image.Colors[PixelInt[false][0], PixelInt[false][1], PixelInt[false][2]] * (1 - PixelFrac[0]) * (1 - PixelFrac[1]) * (1 - PixelFrac[2]) + |
| 476 |
Image.Colors[PixelInt[false][0], PixelInt[false][1], PixelInt[ true][2]] * (1 - PixelFrac[0]) * (1 - PixelFrac[1]) * ( PixelFrac[2]) + |
| 477 |
Image.Colors[PixelInt[false][0], PixelInt[ true][1], PixelInt[false][2]] * (1 - PixelFrac[0]) * ( PixelFrac[1]) * (1 - PixelFrac[2]) + |
| 478 |
Image.Colors[PixelInt[false][0], PixelInt[ true][1], PixelInt[ true][2]] * (1 - PixelFrac[0]) * ( PixelFrac[1]) * ( PixelFrac[2]) + |
| 479 |
Image.Colors[PixelInt[ true][0], PixelInt[false][1], PixelInt[false][2]] * ( PixelFrac[0]) * (1 - PixelFrac[1]) * (1 - PixelFrac[2]) + |
| 480 |
Image.Colors[PixelInt[ true][0], PixelInt[false][1], PixelInt[ true][2]] * ( PixelFrac[0]) * (1 - PixelFrac[1]) * ( PixelFrac[2]) + |
| 481 |
Image.Colors[PixelInt[ true][0], PixelInt[ true][1], PixelInt[false][2]] * ( PixelFrac[0]) * ( PixelFrac[1]) * (1 - PixelFrac[2]) + |
| 482 |
Image.Colors[PixelInt[ true][0], PixelInt[ true][1], PixelInt[ true][2]] * ( PixelFrac[0]) * ( PixelFrac[1]) * ( PixelFrac[2]); |
| 483 |
end; |
| 484 |
} |
| 485 |
|
| 486 |
function SampleLinear2D(const Image: TCastleImage; Pixel: TVector3): TCastleColor; |
| 487 |
var |
| 488 |
I: Integer; |
| 489 |
Dimensions: TVector3Cardinal; |
| 490 |
PixelInt: array [boolean, 0..1] of Integer; |
| 491 |
PixelFrac: TVector2; |
| 492 |
begin |
| 493 |
Dimensions := Image.Dimensions; |
| 494 |
for I := 0 to 1 do |
| 495 |
begin |
| 496 |
if RepeatCoord[I] then |
| 497 |
Pixel.Data[I] := FloatModulo(Pixel[I], Dimensions[I]) |
| 498 |
else |
| 499 |
Pixel.Data[I] := Clamped(Pixel[I], 0, Dimensions[I]); |
| 500 |
end; |
| 501 |
|
| 502 |
for I := 0 to 1 do |
| 503 |
begin |
| 504 |
// TODO: this is not correct in case RepeatCoord[I], |
| 505 |
// it will not filter 100% nicely on the border pixels |
| 506 |
PixelInt[false][I] := Clamped(Floor(Pixel[I]), 0, Dimensions[I] - 1); |
| 507 |
PixelInt[true ][I] := Min(PixelInt[false][I] + 1, Dimensions[I] - 1); |
| 508 |
PixelFrac.Data[I] := Clamped(Pixel[I] - PixelInt[false][I], 0.0, 1.0); |
| 509 |
end; |
| 510 |
|
| 511 |
Result := |
| 512 |
Image.Colors[PixelInt[false][0], PixelInt[false][1], 0] * (1 - PixelFrac[0]) * (1 - PixelFrac[1]) + |
| 513 |
Image.Colors[PixelInt[ true][0], PixelInt[false][1], 0] * ( PixelFrac[0]) * (1 - PixelFrac[1]) + |
| 514 |
Image.Colors[PixelInt[false][0], PixelInt[ true][1], 0] * (1 - PixelFrac[0]) * ( PixelFrac[1]) + |
| 515 |
Image.Colors[PixelInt[ true][0], PixelInt[ true][1], 0] * ( PixelFrac[0]) * ( PixelFrac[1]); |
| 516 |
end; |
| 517 |
|
| 518 |
var |
| 519 |
SingleTexture: TX3DNode; |
| 520 |
Texture2D: TAbstractTexture2DNode; |
| 521 |
EncodedImage: TEncodedImage; |
| 522 |
Image: TCastleImage; |
| 523 |
TexCoord3D: TVector3; |
| 524 |
Pixel: TVector3; |
| 525 |
Color: TCastleColor; |
| 526 |
Bilinear: boolean; |
| 527 |
begin |
| 528 |
Result := WhiteRGB; |
| 529 |
|
| 530 |
SingleTexture := nil; |
| 531 |
if Texture is TMultiTextureNode { also makes sure Texture <> nil } then |
| 532 |
begin |
| 533 |
if TMultiTextureNode(Texture).FdTexture.Count > 0 then |
| 534 |
SingleTexture := TMultiTextureNode(Texture).FdTexture[0]; |
| 535 |
end else |
| 536 |
SingleTexture := Texture; |
| 537 |
|
| 538 |
if SingleTexture is TAbstractTexture2DNode { also makes sure SingleTexture <> nil } then |
| 539 |
begin |
| 540 |
// TODO: 3D textures could be handled easily too! |
| 541 |
Texture2D := TAbstractTexture2DNode(SingleTexture); |
| 542 |
if Texture2D.IsTextureImage then |
| 543 |
begin |
| 544 |
EncodedImage := Texture2D.TextureImage; |
| 545 |
if (EncodedImage is TCastleImage) and |
| 546 |
(not EncodedImage.IsEmpty) and |
| 547 |
(not IsZero(TexCoord[3])) then |
| 548 |
begin |
| 549 |
Image := TCastleImage(EncodedImage); |
| 550 |
TexCoord3D := TexCoord.ToPosition; |
| 551 |
Pixel := Vector3( |
| 552 |
TexCoord3D[0] * Image.Width, |
| 553 |
TexCoord3D[1] * Image.Height, |
| 554 |
TexCoord3D[2] * Image.Depth |
| 555 |
); |
| 556 |
if IsNan(TexCoord[0]) then |
| 557 |
begin |
| 558 |
// TODO: bug on demo-models/bump_mapping/bump_mapping_leaf_test.wrl |
| 559 |
{ |
| 560 |
Writeln(Pixel.ToRawString); |
| 561 |
Writeln(TexCoord3D.ToRawString); |
| 562 |
Writeln(TexCoord.ToRawString); |
| 563 |
Writeln(Image.Width, ' ', Image.Height, ' ', Image.Depth); |
| 564 |
} |
| 565 |
Exit; |
| 566 |
end; |
| 567 |
|
| 568 |
RepeatCoord[0] := Texture2D.RepeatS; |
| 569 |
RepeatCoord[1] := Texture2D.RepeatT; |
| 570 |
RepeatCoord[2] := false { Texture2D.RepeatR }; |
| 571 |
|
| 572 |
Bilinear := not ( |
| 573 |
(Texture2D.TextureProperties <> nil) and |
| 574 |
// TODO: we should look either at MagnificationFilter or MinificationFilter |
| 575 |
(Texture2D.TextureProperties.MagnificationFilter = magNearest) |
| 576 |
); |
| 577 |
if Bilinear then |
| 578 |
Color := SampleLinear2D(Image, Pixel) |
| 579 |
else |
| 580 |
Color := SampleNearest(Image, Pixel); |
| 581 |
|
| 582 |
Result := Color.XYZ; |
| 583 |
end; |
| 584 |
end; |
| 585 |
end; |
| 586 |
end; |
| 587 |
|
| 588 |
{ TRayTracer ----------------------------------------------------------------- } |
| 589 |
|
| 590 |
procedure TRayTracer.AppendStats(const Stats: TStrings; const RenderingTime: Single); |
| 591 |
begin |
| 592 |
Stats.Append(Format('Rendering done in %f seconds.', [RenderingTime])); |
| 593 |
Stats.Append(Format('%d simple collision tests done (one ray tested with one triangle).', |
| 594 |
[TriangleCollisionTestsCounter])); |
| 595 |
end; |
| 596 |
|
| 597 |
procedure TRayTracer.ExecuteStats(const Stats: TStrings); |
| 598 |
var |
| 599 |
TimerBegin: TProcessTimerResult; |
| 600 |
RenderingTime: Single; |
| 601 |
begin |
| 602 |
TimerBegin := ProcessTimer; |
| 603 |
TriangleCollisionTestsCounter := 0; |
| 604 |
|
| 605 |
Execute; |
| 606 |
|
| 607 |
RenderingTime := ProcessTimerSeconds(ProcessTimer, TimerBegin); |
| 608 |
AppendStats(Stats, RenderingTime); |
| 609 |
end; |
| 610 |
|
| 611 |
{ TClassicRayTracer ---------------------------------------------------------- } |
| 612 |
|
| 613 |
procedure TClassicRayTracer.Execute; |
| 614 |
var |
| 615 |
FogType: TFogTypeOrNone; |
| 616 |
SceneBackgroundColor: TCastleColorRGB; |
| 617 |
|
| 618 |
{ Traces the ray with given Depth. |
| 619 |
Returns @false if the ray didn't hit anything, otherwise |
| 620 |
returns @true and sets Color. } |
| 621 |
function Trace(const RayOrigin, RayDirection: TVector3; const Depth: Cardinal; |
| 622 |
const TriangleToIgnore: PTriangle; IgnoreMarginAtStart: boolean): TCastleColorRGB; |
| 623 |
var |
| 624 |
Intersection: TVector3; |
| 625 |
IntersectNormal: TVector3; |
| 626 |
IntersectNode: PTriangle; |
| 627 |
MaterialTransparency: Single; |
| 628 |
MaterialReflectionColor: TVector3; |
| 629 |
|
| 630 |
procedure ModifyColorByTransmittedRay; |
| 631 |
var |
| 632 |
TransmittedColor, TransmittedRayVec: TVector3; |
| 633 |
EtaFrom, EtaTo: Single; |
| 634 |
const |
| 635 |
EtaConst = 1.3; |
| 636 |
begin |
| 637 |
{ Make transmitted ray if Transparency > 0 and there |
| 638 |
is no total internal reflection |
| 639 |
[http://en.wikipedia.org/wiki/Total_internal_reflection]. } |
| 640 |
if MaterialTransparency > 0 then |
| 641 |
begin |
| 642 |
{ TODO: we should get an information from our model here |
| 643 |
(from Octree IntersectNode item). But we don't have it for now. |
| 644 |
So for now we just always assume that the first transmission |
| 645 |
has Eta = EtaConst and the next one has 1/EtaConst |
| 646 |
and the next one has again EtaConst etc. } |
| 647 |
if Odd(InitialDepth - Depth) then |
| 648 |
begin EtaFrom := 1; EtaTo := EtaConst end else |
| 649 |
begin EtaFrom := EtaConst; EtaTo := 1 end; |
| 650 |
|
| 651 |
if TryTransmittedRayDirection( |
| 652 |
TransmittedRayVec, RayDirection.Normalize, |
| 653 |
IntersectNormal, EtaFrom, EtaTo) then |
| 654 |
begin |
| 655 |
TransmittedColor := Trace(Intersection, TransmittedRayVec, |
| 656 |
Depth - 1, IntersectNode, true); |
| 657 |
Result := Result * (1 - MaterialTransparency) + |
| 658 |
TransmittedColor * MaterialTransparency; |
| 659 |
end; |
| 660 |
end; |
| 661 |
end; |
| 662 |
|
| 663 |
procedure ModifyColorByReflectedRay; |
| 664 |
var |
| 665 |
ReflRayDirection, ReflColor: TVector3; |
| 666 |
MaterialReflection: Single; |
| 667 |
begin |
| 668 |
MaterialReflection := MaterialReflectionColor.Max; |
| 669 |
if MaterialReflection > 0 then |
| 670 |
begin |
| 671 |
ReflRayDirection := ReflectedRayDirection(RayDirection.Normalize, |
| 672 |
IntersectNormal); |
| 673 |
ReflColor := Trace(Intersection, ReflRayDirection, Depth - 1, |
| 674 |
IntersectNode, true); |
| 675 |
Result := |
| 676 |
{ Scale down original result, by "1 - MaterialReflection". |
| 677 |
Note: scaling down by "1 - MaterialReflectionColor" would be bad, |
| 678 |
makes the material look like the inversion of MaterialReflectionColor. |
| 679 |
E.g. for MaterialReflectionColor = blue, it will make the surface |
| 680 |
somewhat yellowish. } |
| 681 |
Result * (1 - MaterialReflection) + |
| 682 |
(ReflColor * MaterialReflectionColor); |
| 683 |
end; |
| 684 |
end; |
| 685 |
|
| 686 |
function LightNotBlocked(const Light: TLightInstance): boolean; |
| 687 |
begin |
| 688 |
{ Does the light get to the current surface ? |
| 689 |
|
| 690 |
Note that we treat partially transparent objects here |
| 691 |
as not casting a shadow. |
| 692 |
This is better that not doing anything (partially transparent objects |
| 693 |
making normal "blocking" shadows looks bad), but it's not really correct, |
| 694 |
since in reality partially transparent objects just bend |
| 695 |
(or rather translate, if you consider a thin partially transparent object |
| 696 |
like a glass that doesn't intersect any other objects) |
| 697 |
the ray so it can get to the light. |
| 698 |
|
| 699 |
We also take into account here that things with |
| 700 |
Appearance.shadowCaster = FALSE do not block light. |
| 701 |
|
| 702 |
We also take into account that the light may be on the opposide |
| 703 |
side of the plane than from where RayDirection came. |
| 704 |
In such case the light shines on IntersectNode, but from the opposite |
| 705 |
side, so we will not add it here. } |
| 706 |
Result := OctreeLightNotBlocked(Octree, Light, |
| 707 |
Intersection, IntersectNormal, |
| 708 |
-RayDirection, IntersectNode, true); |
| 709 |
end; |
| 710 |
|
| 711 |
{ Calculate emission color of given shape. |
| 712 |
|
| 713 |
This can be used by software renderers (ray-tracers etc.) |
| 714 |
to calculate pixel color following VRML/X3D specifications. |
| 715 |
Emission should be added to |
| 716 |
TLightInstance.Contribution (for each light), |
| 717 |
and resulting color should be processed by TFogNode.ApplyFog. |
| 718 |
|
| 719 |
When LightingCalculationOn = @false we actually take diffuseColor |
| 720 |
instead of emissiveColor. This is useful if you want to force |
| 721 |
the scene completely unlit, usually diffuseColor is more useful for this |
| 722 |
(since emissiveColor is often black on everything). } |
| 723 |
function Emission(const M: TMaterialInfo; |
| 724 |
const LightingCalculationOn: boolean): TVector3; |
| 725 |
begin |
| 726 |
if M <> nil then |
| 727 |
begin |
| 728 |
if LightingCalculationOn then |
| 729 |
Result := M.EmissiveColor |
| 730 |
else |
| 731 |
Result := M.MainColor; |
| 732 |
end else |
| 733 |
begin |
| 734 |
if LightingCalculationOn then |
| 735 |
{ Default VRML 2.0 Material.emissiveColor } |
| 736 |
Result := TVector3.Zero |
| 737 |
else |
| 738 |
{ Default VRML 2.0 Material.diffuseColor } |
| 739 |
Result := Vector3(0.8, 0.8, 0.8); |
| 740 |
end; |
| 741 |
end; |
| 742 |
|
| 743 |
var |
| 744 |
i: integer; |
| 745 |
Lights: TLightInstancesList; |
| 746 |
MaterialInfo: TMaterialInfo; |
| 747 |
DiffuseTextureColor: TCastleColorRGB; |
| 748 |
begin |
| 749 |
IntersectNode := Octree.RayCollision(Intersection, RayOrigin, RayDirection, true, |
| 750 |
TriangleToIgnore, IgnoreMarginAtStart, nil); |
| 751 |
if IntersectNode = nil then Exit(SceneBackgroundColor); |
| 752 |
|
| 753 |
IntersectNormal := |
| 754 |
{$ifdef CONSERVE_TRIANGLE_MEMORY} |
| 755 |
IntersectNode^.World.Plane.XYZ |
| 756 |
{$else} |
| 757 |
IntersectNode^.INormalWorldSpace(Intersection) |
| 758 |
{$endif}; |
| 759 |
|
| 760 |
MaterialInfo := IntersectNode^.MaterialInfo; |
| 761 |
if MaterialInfo is TPhongMaterialInfo then // also checks MaterialInfo <> nil |
| 762 |
begin |
| 763 |
MaterialReflectionColor := TPhongMaterialInfo(MaterialInfo).ReflectionColor; |
| 764 |
MaterialTransparency := TPhongMaterialInfo(MaterialInfo).Transparency; |
| 765 |
end else |
| 766 |
begin |
| 767 |
MaterialReflectionColor := TPhongMaterialInfo.DefaultReflectionColor; |
| 768 |
MaterialTransparency := TPhongMaterialInfo.DefaultTransparency; |
| 769 |
end; |
| 770 |
|
| 771 |
DiffuseTextureColor := |
| 772 |
{$ifdef CONSERVE_TRIANGLE_MEMORY} |
| 773 |
WhiteRGB |
| 774 |
{$else} |
| 775 |
GetDiffuseTexture( |
| 776 |
IntersectNode^.State.MainTexture, |
| 777 |
IntersectNode^.ITexCoord(Intersection)) |
| 778 |
{$endif}; |
| 779 |
|
| 780 |
Result := Emission(IntersectNode^.State.MaterialInfo, InitialDepth <> 0); |
| 781 |
with IntersectNode^ do |
| 782 |
begin |
| 783 |
if Depth > 0 then |
| 784 |
begin |
| 785 |
Lights := State.Lights; |
| 786 |
if Lights <> nil then |
| 787 |
for i := 0 to Lights.Count - 1 do |
| 788 |
if LightNotBlocked(Lights.L[i]) then |
| 789 |
Result := Result + Lights.L[i].Contribution(Intersection, |
| 790 |
IntersectNormal, IntersectNode^.State, CamPosition, DiffuseTextureColor); |
| 791 |
|
| 792 |
{ Add GlobalLights contribution, just like other lights. |
| 793 |
|
| 794 |
Note for LightNotBlocked testing: theoretically, just using |
| 795 |
LightNotBlocked always (no matter Depth/InitialDepth) should |
| 796 |
be fully correct. But: |
| 797 |
|
| 798 |
1. For Depth = InitialDepth, we know that headlight is not blocked |
| 799 |
(since a camera sees a point, so headlight on camera also sees it). |
| 800 |
Avoiding shadow ray test in this case is an optimization. |
| 801 |
|
| 802 |
2. For directional headlights, this somewhat workarounds a problem |
| 803 |
with our shadow rays. LightNotBlocked treats directional |
| 804 |
lights as coming from infinity. While directional headlight |
| 805 |
doesn't come from infinity: it comes from camera position. |
| 806 |
For example, imagine a player with directional headlight standing |
| 807 |
inside a closed cube (or any closed labirynth). LightNotBlocked |
| 808 |
would make the headlight not visible (as it's blocked from all |
| 809 |
sides by the cube), since LightNotBlocked doesn't know |
| 810 |
that light source is standing inside the cube... |
| 811 |
|
| 812 |
To fix this fully correctly, we should invent new light type, |
| 813 |
like "directional, but not from infinity, but from given plane", |
| 814 |
and modify LightNotBlocked accordingly. |
| 815 |
|
| 816 |
For now, treating Depth = InitialDepth as special case, fixes |
| 817 |
the problem at least for primary rays: directional light always |
| 818 |
reaches them. |
| 819 |
|
| 820 |
The above reasoning is nice as long as GlobalLights only contain |
| 821 |
the headlight. Which is true in the current uses. } |
| 822 |
for I := 0 to GlobalLights.Count - 1 do |
| 823 |
if (Depth = InitialDepth) or |
| 824 |
LightNotBlocked(GlobalLights.L[I]) then |
| 825 |
Result := Result + GlobalLights.L[I].Contribution(Intersection, |
| 826 |
IntersectNormal, IntersectNode^.State, CamPosition, DiffuseTextureColor); |
| 827 |
|
| 828 |
{ Calculate recursively reflected and transmitted rays. |
| 829 |
Note that the order of calls (first reflected or first transmitted ?) |
| 830 |
is important --- as they may scale our Result (not only add |
| 831 |
to it). } |
| 832 |
ModifyColorByReflectedRay; |
| 833 |
ModifyColorByTransmittedRay; |
| 834 |
end; |
| 835 |
end; |
| 836 |
|
| 837 |
{ Fog calculation should be done on every |
| 838 |
depth of ray-tracing, not only once (i.e. for primary rays). |
| 839 |
Reasoning: imagine that you look through a glass window |
| 840 |
(and you're really close to this window, so that fog doesn't |
| 841 |
affect the window glass noticeably) and through this window |
| 842 |
you see something distant, like a forest. The forest is distant |
| 843 |
so fog setting should affect it. Obviously even though the window |
| 844 |
glass wasn't affected much by the fog, you will see a forest |
| 845 |
covered by the fog. So each recursive call of Trace should bring |
| 846 |
a color affected by the fog. } |
| 847 |
FogNode.ApplyFog(Result, CamPosition, Intersection, FogType); |
| 848 |
end; |
| 849 |
|
| 850 |
var |
| 851 |
RaysWindow: TRaysWindow; |
| 852 |
|
| 853 |
procedure DoPixel(const x, y: Cardinal); |
| 854 |
var |
| 855 |
RayOrigin, RayDirection: TVector3; |
| 856 |
C: TCastleColor; |
| 857 |
ColRGB: TCastleColorRGB absolute C; |
| 858 |
begin |
| 859 |
RaysWindow.PrimaryRay(x, y, Image.Width, Image.Height, RayOrigin, RayDirection); |
| 860 |
C := Image.Colors[X, Y, 0]; |
| 861 |
ColRGB := Trace(RayOrigin, RayDirection, InitialDepth, nil, false); |
| 862 |
Image.Colors[X, Y, 0] := C; |
| 863 |
end; |
| 864 |
|
| 865 |
var |
| 866 |
PixCoord: TVector2Cardinal; |
| 867 |
SFCurve: TSpaceFillingCurve; |
| 868 |
begin |
| 869 |
FogType := FogNode.FogTypeOrNone; |
| 870 |
|
| 871 |
SceneBackgroundColor := GetSceneBackgroundColor(Background, SceneBGColor); |
| 872 |
|
| 873 |
RaysWindow := nil; |
| 874 |
SFCurve := nil; |
| 875 |
try |
| 876 |
RaysWindow := TRaysWindow.CreateDescendant(CamPosition, |
| 877 |
CamDirection.Normalize, CamUp.Normalize, Projection); |
| 878 |
|
| 879 |
{ Using any other kind of space filling curve doesn't have any |
| 880 |
noticeable impact right now for classic ray tracer, since |
| 881 |
classic ray tracer doesn't use shadow cache or any other similar technique |
| 882 |
that benefits from processing similar cases in one block. |
| 883 |
In the future this make come to use. |
| 884 |
Right now, using SFCurve just makes implementing FirstPixel |
| 885 |
and PixelsMadeNotifier easier. } |
| 886 |
SFCurve := TSwapScanCurve.Create(Image.Width, Image.Height); |
| 887 |
SFCurve.SkipPixels(FirstPixel); |
| 888 |
|
| 889 |
{ generate image pixels } |
| 890 |
if Assigned(PixelsMadeNotifier) then |
| 891 |
begin |
| 892 |
while not SFCurve.EndOfPixels do |
| 893 |
begin |
| 894 |
PixCoord := SFCurve.NextPixel; |
| 895 |
DoPixel(PixCoord[0], PixCoord[1]); |
| 896 |
PixelsMadeNotifier(SFCurve.PixelsDone, PixelsMadeNotifierData); |
| 897 |
end; |
| 898 |
end else |
| 899 |
begin |
| 900 |
while not SFCurve.EndOfPixels do |
| 901 |
begin |
| 902 |
PixCoord := SFCurve.NextPixel; |
| 903 |
DoPixel(PixCoord[0], PixCoord[1]); |
| 904 |
end; |
| 905 |
end; |
| 906 |
|
| 907 |
finally |
| 908 |
RaysWindow.Free; |
| 909 |
SFCurve.Free; |
| 910 |
end; |
| 911 |
end; |
| 912 |
|
| 913 |
procedure TClassicRayTracer.AppendStats(const Stats: TStrings; const RenderingTime: Single); |
| 914 |
var |
| 915 |
PrimaryRaysCount: Cardinal; |
| 916 |
begin |
| 917 |
inherited; |
| 918 |
PrimaryRaysCount := Image.Width * Image.Height - FirstPixel; |
| 919 |
Stats.Append(Format('Image size is %d x %d pixels (first %d pixels skipped) which gives %d primary rays.', |
| 920 |
[Image.Width, Image.Height, FirstPixel, PrimaryRaysCount])); |
| 921 |
Stats.Append(Format('%f primary rays done per second.', |
| 922 |
[PrimaryRaysCount / RenderingTime])); |
| 923 |
Stats.Append(Format('%f simple collision tests done per one primary ray.', |
| 924 |
[TriangleCollisionTestsCounter / PrimaryRaysCount ])); |
| 925 |
end; |
| 926 |
|
| 927 |
destructor TClassicRayTracer.Destroy; |
| 928 |
begin |
| 929 |
if OwnsGlobalLights then |
| 930 |
FreeAndNil(GlobalLights); |
| 931 |
inherited; |
| 932 |
end; |
| 933 |
|
| 934 |
{ TPathTracer -------------------------------------------------------------- } |
| 935 |
|
| 936 |
constructor TPathTracer.Create; |
| 937 |
begin |
| 938 |
inherited; |
| 939 |
SFCurveClass := TSwapScanCurve; |
| 940 |
end; |
| 941 |
|
| 942 |
function EmissiveColor(const Item: TTriangle): TVector3; |
| 943 |
var |
| 944 |
M: TMaterialInfo; |
| 945 |
begin |
| 946 |
M := Item.MaterialInfo; |
| 947 |
if M <> nil then |
| 948 |
Result := M.EmissiveColor |
| 949 |
else |
| 950 |
Result := TPhongMaterialInfo.DefaultEmissiveColor; |
| 951 |
end; |
| 952 |
|
| 953 |
function IsLightSource(const Item: TTriangle): boolean; |
| 954 |
begin |
| 955 |
Result := EmissiveColor(Item).LengthSqr > Sqr(SingleEpsilon); |
| 956 |
end; |
| 957 |
|
| 958 |
procedure TPathTracer.CollectLightItems(const Triangle: PTriangle); |
| 959 |
begin |
| 960 |
if IsLightSource(Triangle^) then |
| 961 |
CollectedLightItems.Add(Triangle); |
| 962 |
end; |
| 963 |
|
| 964 |
{ Some notes about path tracer implementation : |
| 965 |
|
| 966 |
- Meaning of TraceOnlyIndirect parameter for Trace(): |
| 967 |
|
| 968 |
When (DirectIllumSamplesCount <> 0) then rendering equation at each point |
| 969 |
is splitted into |
| 970 |
L_out = L_emission + IntegralOverHemisphere( L_direct + L_indirect ), |
| 971 |
where |
| 972 |
L_indirect = L_emission + IntegralOverHemisphere( L_direct + L_indirect ), |
| 973 |
and L_indirect must hit something that is *not* a light source. |
| 974 |
Which means that L_emission is always here = (0, 0, 0) so we have |
| 975 |
L_indirect = IntegralOverHemisphere( L_direct + L_indirect ), |
| 976 |
|
| 977 |
Which means that when we do recursive calls to Trace to calculate |
| 978 |
L_indirect we *do not want to hit light source* since then |
| 979 |
L_direct would be calculated twice. |
| 980 |
|
| 981 |
In other words, |
| 982 |
- for primary rays we pass TraceOnIndirect = false |
| 983 |
since we calculate L_out and we want L_emission (which makes sense anyway, |
| 984 |
since when you look directly at the light source you obviously see it's |
| 985 |
light). |
| 986 |
|
| 987 |
- for non-primary rays, i.e. in Trace recursive call from Trace itself, |
| 988 |
we pass TraceOnIndirect = true. (Well, unless DirectIllumSamplesCount = 0, |
| 989 |
in which case we just always make normal rendering equation |
| 990 |
and we want to always calculate L_emission; |
| 991 |
So TraceOnlyIndirect is actually DirectIllumSamplesCount <> 0). |
| 992 |
|
| 993 |
Tests confirm that this is right. Without this (if we would remove |
| 994 |
the check |
| 995 |
"if TraceOnlyIndirect and IsLightSource(IntersectNode) then ...") |
| 996 |
we get a lot more noise on our image. |
| 997 |
|
| 998 |
Trace call with TraceOnlyIndirect = true that hits into a light source |
| 999 |
returns just black color. |
| 1000 |
|
| 1001 |
- Note that MinDepth and Depth (Trace parameters) are *signed* integers. |
| 1002 |
Depth can be negative, for each recursive call we pass Depth = Depth - 1. |
| 1003 |
When Depth <= 0 then roussian roulette will be used. |
| 1004 |
MinDepth is also signed becasue of that, since it's a starting Depth value. |
| 1005 |
} |
| 1006 |
|
| 1007 |
procedure TPathTracer.Execute; |
| 1008 |
var |
| 1009 |
{ In LightItems we have pointers to Octree.Triangles[] pointing |
| 1010 |
to the items with emission color > 0. In other words, light sources. } |
| 1011 |
LightItems: TFPList; |
| 1012 |
|
| 1013 |
{$ifdef PATHTR_USES_SHADOW_CACHE} |
| 1014 |
{ For each light in LightItems[I], ShadowCache[I] gives the pointer |
| 1015 |
(somewhere into Octree.Triangles[]) of the last object that blocked this |
| 1016 |
light source (or nil if no such object was yet found during |
| 1017 |
this path tracer execution). |
| 1018 |
|
| 1019 |
This index is updated and used in IsLightShadowed. |
| 1020 |
The idea of "shadow cache" comes from RGK, crystalized in "Graphic Gems II". } |
| 1021 |
ShadowCache: TFPList; |
| 1022 |
{$endif} |
| 1023 |
|
| 1024 |
SceneBackgroundColor: TCastleColorRGB; |
| 1025 |
|
| 1026 |
{ TODO: comments below are in Polish. } |
| 1027 |
|
| 1028 |
const |
| 1029 |
{ LightEmissionArea definiuje co znacza wlasciwosci .Emission zrodel swiatla. |
| 1030 |
Kolor emission swiatla bedzie oczywiscie skalowany przez kat brylowy jaki |
| 1031 |
ma zrodlo swiatla dla oswietlanego punktu. Skalowanie to bedzie robione tak |
| 1032 |
ze jezeli swiatlo bedzie zajmowalo kat brylowy LightEmissionArea |
| 1033 |
(w steradianach) to kolor swiatla dodany do DirectIllumination bedzie wynosil |
| 1034 |
doklanie Emission swiatla. Jesli kat brylowy bedzie a razy wiekszy (mniejszy) |
| 1035 |
niz LightEmissionArea to kolor jaki bedzie mial byc dodany do Direct Illumination |
| 1036 |
bedzie wynosil a*LightEmissionArea. |
| 1037 |
|
| 1038 |
Oczywiscie ten kolor bedzie dalej skalowany, przez BRDFa i inne rzeczy, |
| 1039 |
wiec to nie oznacza ze dokladnie taki kolor a*Emission zostanie zwrocony |
| 1040 |
przez DirectIllumination. Ale taka bedzie "podstawa" tego koloru. |
| 1041 |
|
| 1042 |
Mowiac nieco formalnie, LightEmissionArea okresla w jakich jednostkach |
| 1043 |
mamy zapisane Emission swiatla w modelu. |
| 1044 |
|
| 1045 |
Wartosc ponizej dobralem eksperymentalnie chcac zeby cornell-box renderowane |
| 1046 |
z path wygladalo tak samo jak rendering na stronie www.cornell-box'a. |
| 1047 |
Dopasowywalem ten parametr tak dlugo az rysunki path (z rosyjska ruletka, |
| 1048 |
bo ona nie wprowadza biasu) mialy "na oko" podobna jasnosc co tamtejszy |
| 1049 |
box.jpg. } |
| 1050 |
LightEmissionArea = 1/30; |
| 1051 |
|
| 1052 |
function IsLightShadowed(const Item: PTriangle; |
| 1053 |
const ItemPoint: TVector3; |
| 1054 |
const LightSourceIndiceIndex: Integer; |
| 1055 |
LightSourcePoint: TVector3): boolean; |
| 1056 |
{ ta funkcja liczy shadow ray (a w zasadzie segment). Zwraca true jezeli |
| 1057 |
pomiedzy punktem ItemPoint a LightSourcePoint jest jakis element |
| 1058 |
o transparency = 1. Wpp. zwraca false. |
| 1059 |
LightSourceIndiceIndex to indeks to tablicy LightItems[]. |
| 1060 |
Item to pointer to given item (somewhere in Octree.Triangles[]). } |
| 1061 |
{ TODO: transparent objects should scale light color instead of just |
| 1062 |
letting it pass } |
| 1063 |
var |
| 1064 |
OctreeIgnorer: TOctreeIgnoreForShadowRaysAndOneItem; |
| 1065 |
Shadower: PTriangle; |
| 1066 |
{$ifdef PATHTR_USES_SHADOW_CACHE} |
| 1067 |
CachedShadower: PTriangle; |
| 1068 |
{$endif} |
| 1069 |
begin |
| 1070 |
{$ifdef PATHTR_USES_SHADOW_CACHE} |
| 1071 |
{ sprobuj wziac wynik z ShadowCache } |
| 1072 |
CachedShadower := ShadowCache.Items[LightSourceIndiceIndex]; |
| 1073 |
if (CachedShadower <> nil) and |
| 1074 |
(CachedShadower <> Item) then |
| 1075 |
begin |
| 1076 |
Inc(TriangleCollisionTestsCounter); |
| 1077 |
if IsTriangleSegmentCollision(CachedShadower^.World.Triangle, |
| 1078 |
CachedShadower^.World.Plane, ItemPoint, LightSourcePoint) then |
| 1079 |
Exit(true); |
| 1080 |
|
| 1081 |
{ powyzej zapominamy o marginesie epsilonowym wokol ItemPoint i |
| 1082 |
LightSourcePoint (jezeli tam jest przeciecie to powinno byc uznawane |
| 1083 |
za niewazne). Zreszta ponizej zapominamy o marginesie wokol |
| 1084 |
LightSourcePoint. W moim kodzie te marginesy epsilonowe nie sa tak |
| 1085 |
wazne (tylko dla nieprawidlowych modeli, dla prawidlowych modeli |
| 1086 |
wystarcza ItemIndexToIgnore i OctreeIgnorer) wiec olewam tutaj te |
| 1087 |
niedorobki. } |
| 1088 |
end; |
| 1089 |
{$endif} |
| 1090 |
|
| 1091 |
{ oblicz przeciecie uzywajac Octree } |
| 1092 |
OctreeIgnorer := TOctreeIgnoreForShadowRaysAndOneItem.Create( |
| 1093 |
LightItems.Items[LightSourceIndiceIndex]); |
| 1094 |
try |
| 1095 |
Shadower := Octree.SegmentCollision(ItemPoint, LightSourcePoint, false, |
| 1096 |
Item, true, @OctreeIgnorer.IgnoreItem); |
| 1097 |
Result := Shadower <> nil; |
| 1098 |
{$ifdef PATHTR_USES_SHADOW_CACHE} |
| 1099 |
ShadowCache.Items[LightSourceIndiceIndex] := Shadower; |
| 1100 |
{$endif} |
| 1101 |
finally OctreeIgnorer.Free end; |
| 1102 |
end; |
| 1103 |
|
| 1104 |
function Trace(const RayOrigin, RayDirection: TVector3; |
| 1105 |
const Depth: Integer; const TriangleToIgnore: PTriangle; |
| 1106 |
const IgnoreMarginAtStart: boolean; const TraceOnlyIndirect: boolean) |
| 1107 |
: TVector3; |
| 1108 |
{ sledzi promien z zadana glebokoscia. Zwraca Black (0, 0, 0) jesli |
| 1109 |
promien w nic nie trafia, wpp. zwraca wyliczony kolor. } |
| 1110 |
var |
| 1111 |
Intersection: TVector3; |
| 1112 |
IntersectNode: PTriangle; |
| 1113 |
Material: TPhongMaterialInfo; { = IntersectNode.MaterialInfo } |
| 1114 |
IntersectNormal: TVector3; |
| 1115 |
|
| 1116 |
function TraceNonEmissivePart: TVector3; |
| 1117 |
|
| 1118 |
function TryCalculateTransmittedSpecularRayDirection( |
| 1119 |
var TracedDir: TVector3; |
| 1120 |
var PdfValue: Single): boolean; |
| 1121 |
var |
| 1122 |
TransmittedRayDirection: TVector3; |
| 1123 |
EtaFrom, EtaTo: Single; |
| 1124 |
const |
| 1125 |
EtaConst = 1.3; { TODO: tu tez uzywam EtaConst, jak w Classic } |
| 1126 |
begin |
| 1127 |
if Odd(MinDepth-Depth) then |
| 1128 |
begin EtaFrom := 1; EtaTo := EtaConst end else |
| 1129 |
begin EtaFrom := EtaConst; EtaTo := 1 end; |
| 1130 |
|
| 1131 |
Result := TryTransmittedRayDirection(TransmittedRayDirection, |
| 1132 |
RayDirection.Normalize, |
| 1133 |
IntersectNormal, EtaFrom, EtaTo); |
| 1134 |
if Result then |
| 1135 |
TracedDir := PhiThetaToXYZ( |
| 1136 |
RandomHemispherePointCosThetaExp( |
| 1137 |
Round(Material.TransSpecularExp), |
| 1138 |
PdfValue), |
| 1139 |
TransmittedRayDirection); |
| 1140 |
end; |
| 1141 |
|
| 1142 |
function DirectIllumination: TVector3; |
| 1143 |
{ ta funkcja liczy DirectIllumination dla naszego Intersection. |
| 1144 |
Implementacja : uzywamy sformulowania (101) z GlobalIllumCompendium : |
| 1145 |
|
| 1146 |
for i = 0..DirectIllumSamplesCount-1 do |
| 1147 |
uniformly losuj LightItemIndex sposrod 0..LightIndices.Count-1. |
| 1148 |
uniformly (wzgledem pola powierzchni trojkata wylosowanego swiatla) |
| 1149 |
losuj punkt na swietle jako SampleLightPoint. |
| 1150 |
if (SampleLightPoint widoczny z Intersection) then |
| 1151 |
result += PolePowierzchni(LightItem) * LightEmission * BRDF * |
| 1152 |
GeometryFunction |
| 1153 |
Na koncu result *= LightIndices.Count / DirectIllumSamplesCount. |
| 1154 |
|
| 1155 |
Mozna powiedziec ze instrukcja |
| 1156 |
result += PolePowierzchni(LightItem) * LightEmission * BRDF * |
| 1157 |
GeometryFunction |
| 1158 |
jest mniej wiecej rownowazne |
| 1159 |
result += LightEmission * BRDF * cos(LightDirNorm, IntersectNormal) |
| 1160 |
* solid-angle-swiatla |
| 1161 |
(taka jest rola PolePowierzchni(LightItem) i czesci GeometryFunction - |
| 1162 |
one po prostu licza solid angle; no, de facto pewne bardzo dobre przyblizenie |
| 1163 |
solid angle) |
| 1164 |
|
| 1165 |
W rezultacie result = sredni kolor ze swiatla razy srednia powierzchnia |
| 1166 |
swiatla * ilosc swiatel = wlasnie direct illumination, uwzgledniajace |
| 1167 |
ze rozne swiatla maja rozna powierzchnie i swieca z rozna intensywnoscia. |
| 1168 |
} |
| 1169 |
{ TODO: better approach : (102), czyli losuj punkt na zrodle swiatla |
| 1170 |
ze wzgledu na jego solid angle. |
| 1171 |
TODO: jeszcze lepiej : (103), czyli losuj swiatlo w taki sposob ze |
| 1172 |
swiatla o wiekszej powierzchni (a wlasciwie, o wiekszym kacie |
| 1173 |
brylowym) i/lub o wiekszej intensywnosci beda wybierane czesciej. } |
| 1174 |
var |
| 1175 |
LightSource: PTriangle; |
| 1176 |
LightSourceIndiceIndex: Integer; { indeks do LightIndices[] } |
| 1177 |
SampleLightPoint: TVector3; |
| 1178 |
DirectColor, LightDirNorm, NegatedLightDirNorm: TVector3; |
| 1179 |
i: integer; |
| 1180 |
begin |
| 1181 |
Result := TVector3.Zero; |
| 1182 |
|
| 1183 |
{ trzeba ustrzec sie tu przed LightsItems.Count = 0 (zeby moc pozniej |
| 1184 |
spokojnie robic Random(LightsItems.Count) i przed |
| 1185 |
DirectIllumSamplesCount = 0 (zeby moc pozniej spokojnie podzielic przez |
| 1186 |
DirectIllumSamplesCount). } |
| 1187 |
if (LightItems.Count = 0) or (DirectIllumSamplesCount = 0) then Exit; |
| 1188 |
|
| 1189 |
for i := 0 to DirectIllumSamplesCount - 1 do |
| 1190 |
begin |
| 1191 |
{ calculate LightSourceIndiceIndex, LightSourceIndex, LightSource } |
| 1192 |
LightSourceIndiceIndex := Random(LightItems.Count); |
| 1193 |
LightSource := LightItems.Items[LightSourceIndiceIndex]; |
| 1194 |
if LightSource = IntersectNode then Continue; |
| 1195 |
|
| 1196 |
{ calculate SampleLightPoint. |
| 1197 |
Lepiej pozniej sprawdz ze SampleLightPoint jest |
| 1198 |
rozny od Intersection (poniewaz SampleLightPoint jest losowy to na |
| 1199 |
nieprawidlowo skonstruowanym modelu wszystko moze sie zdarzyc...) } |
| 1200 |
SampleLightPoint := LightSource^.World.Triangle.RandomPoint; |
| 1201 |
if TVector3.Equals(SampleLightPoint, Intersection) then Continue; |
| 1202 |
|
| 1203 |
{ calculate LigtDirNorm (nieznormalizowane). |
| 1204 |
Jezeli LigtDirNorm wychodzi z innej strony |
| 1205 |
IntersectionNode.TriangleNormPlane niz IntersectNormal |
| 1206 |
to znaczy ze swiatlo jest po przeciwnej stronie plane - wiec |
| 1207 |
swiatlo nie oswietla naszego pixela. } |
| 1208 |
LightDirNorm := SampleLightPoint - Intersection; |
| 1209 |
if not VectorsSamePlaneDirections(LightDirNorm, IntersectNormal, |
| 1210 |
IntersectNormal) then Continue; |
| 1211 |
|
| 1212 |
{ sprawdz IsLightShadowed, czyli zrob shadow ray } |
| 1213 |
if IsLightShadowed(IntersectNode, Intersection, |
| 1214 |
LightSourceIndiceIndex, SampleLightPoint) then Continue; |
| 1215 |
|
| 1216 |
{ calculate DirectColor = kolor emission swiatla } |
| 1217 |
DirectColor := EmissiveColor(LightSource^); |
| 1218 |
|
| 1219 |
{ wymnoz przez naszego "niby-BRDFa" czyli po prostu przez kolor Diffuse |
| 1220 |
materialu } |
| 1221 |
DirectColor := DirectColor * Material.DiffuseColor; |
| 1222 |
|
| 1223 |
{ calculate LightDirNorm (znormalizowane), NegatedLightDirNorm } |
| 1224 |
LightDirNorm := LightDirNorm.Normalize; |
| 1225 |
NegatedLightDirNorm := -LightDirNorm; |
| 1226 |
|
| 1227 |
{ Wymnoz DirectColor |
| 1228 |
1) przez GeometryFunction czyli |
| 1229 |
cos(LightDirNorm, IntersectNormal) |
| 1230 |
* cos(-LightDirNorm, LightSource.World.Normal) / |
| 1231 |
PointsDistanceSqr(SampleLightPoint, Intersection). |
| 1232 |
Cosinusy naturalnie licz uzywajac dot product. |
| 1233 |
2) przez TriangleArea |
| 1234 |
|
| 1235 |
Mozna zauwazyc ze czlon |
| 1236 |
TriangleArea * |
| 1237 |
cos(-LightDirNorm, LightSource.World.Normal) / |
| 1238 |
PointsDistanceSqr(SampleLightPoint, Intersection) |
| 1239 |
liczy po prostu solid angle swiatla with respect to Intersection |
| 1240 |
(no, mowiac scisle pewne bardzo dobre przyblizenie tego solid angle). |
| 1241 |
|
| 1242 |
Moze byc tutaj pouczajace zobaczyc jak to dziala gdy usuniemy mnozenie |
| 1243 |
przez cos(-LightDirNorm, LightSource.World.Normal) |
| 1244 |
(swiatlo bedzie wtedy jasniej swiecilo jakby "w bok"), |
| 1245 |
pouczajace moze tez byc usuniecie dzielenia przez |
| 1246 |
PointsDistanceSqr(SampleLightPoint, Intersection) i jednoczesnie |
| 1247 |
mnozenia przez TriangleArea (te dwie rzeczy "wspolpracuja ze soba", |
| 1248 |
tzn. wazny jest tu wlasnie ich iloraz, dlatego usuwanie tylko |
| 1249 |
jednej z tych wartosci nie ma sensu). |
| 1250 |
|
| 1251 |
Elegancko byloby tutaj pomnozyc jeszcze przez |
| 1252 |
1/LightEmissionArea. Ale poniewaz LightEmissionArea = const wiec |
| 1253 |
przenioslem mnozenie przez LightEmissionArea na sam koniec tej |
| 1254 |
funkcji.} |
| 1255 |
DirectColor *= |
| 1256 |
TVector3.DotProduct(LightDirNorm, IntersectNormal) * |
| 1257 |
TVector3.DotProduct(NegatedLightDirNorm, |
| 1258 |
PlaneDirInDirection(LightSource^.World.Plane, |
| 1259 |
NegatedLightDirNorm)) * |
| 1260 |
LightSource^.World.Area / |
| 1261 |
PointsDistanceSqr(SampleLightPoint, Intersection); |
| 1262 |
|
| 1263 |
Result := Result + DirectColor; |
| 1264 |
end; |
| 1265 |
|
| 1266 |
{ dopiero tu przemnoz przez 1/LightEmissionArea. |
| 1267 |
Podziel tez przez ilosc probek i pomnoz przez ilosc swiatel - |
| 1268 |
- w rezultacie spraw zeby wynik przyblizal sume wkladu direct illumination |
| 1269 |
wszystkich swiatel. } |
| 1270 |
Result := Result * (LightItems.Count / |
| 1271 |
(LightEmissionArea * DirectIllumSamplesCount)); |
| 1272 |
end; |
| 1273 |
|
| 1274 |
type |
| 1275 |
{ kolory Transmittive/Reflective Diffuse/Specular } |
| 1276 |
TColorKind = (ckRS, ckRD, ckTS, ckTD); |
| 1277 |
var |
| 1278 |
Colors: array[TColorKind]of TVector3; |
| 1279 |
Weights: array[TColorKind]of Single; |
| 1280 |
WeightsSum: Single; |
| 1281 |
RandomCK: Single; |
| 1282 |
PdfValue: Single; |
| 1283 |
TracedCol, TracedDir: TVector3; |
| 1284 |
ck: TColorKind; |
| 1285 |
begin |
| 1286 |
Result := TVector3.Zero; |
| 1287 |
{ caly result jaki tu wyliczymy dostaniemy dzieki wygranej w rosyjskiej |
| 1288 |
ruletce jezeli Depth <= 0. (Trzeba o tym pamietac i pozniej podzielic |
| 1289 |
przez RROulContinue.) } |
| 1290 |
|
| 1291 |
if (Depth > 0) or (Random < RRoulContinue) then |
| 1292 |
begin |
| 1293 |
{ krok sciezki to importance sampling zgodnie z Modified Phong BRDF, |
| 1294 |
patrz GlobalIllumComp (66), diffuse samplujemy z gestoscia cos(), |
| 1295 |
specular z gestoscia cos()^N_EXP. |
| 1296 |
|
| 1297 |
W rezultacie po otrzymaniu wyniku Trace diffuse nie dziele juz wyniku |
| 1298 |
przez cosinus() (a powinienem, bo to jest importance sampling) ani |
| 1299 |
nie mnoze go przez cosinus() (a powinienem, bo w calce BRDF'a jest |
| 1300 |
ten cosinus - diffuse oznacza zbieranie ze wszystkich kierunkow swiatla |
| 1301 |
rownomiernie ale pod mniejszym katem na powierzchnie pada mniej promieni, |
| 1302 |
dlatego w diffuse mamy cosinus). Wszystko dlatego ze te cosinusy sie |
| 1303 |
skracaja. |
| 1304 |
|
| 1305 |
Podobnie dla specular - mam nadzieje ! TODO: Specular jeszcze |
| 1306 |
nie jest zbyt dobrze przetestowane... |
| 1307 |
|
| 1308 |
W rezultacie kompletnie ignoruje PdfValue (otrzymywane w wyniku |
| 1309 |
RandomUnitHemispeherePoint) i BRDF'a - po prostu akurat taki rozklad PDF'ow |
| 1310 |
odpowiada DOKLADNIE temu jak wpada swiatlo. } |
| 1311 |
|
| 1312 |
{ calculate Colors[] } |
| 1313 |
Colors[ckRS] := Material.ReflSpecular; |
| 1314 |
Colors[ckRD] := Material.ReflDiffuse; |
| 1315 |
Colors[ckTS] := Material.TransSpecular; |
| 1316 |
Colors[ckTD] := Material.TransDiffuse; |
| 1317 |
|
| 1318 |
{ calculate Weights[] and WeightSum } |
| 1319 |
WeightsSum := 0; |
| 1320 |
for ck := Low(ck) to High(ck) do |
| 1321 |
begin |
| 1322 |
Weights[ck] := Colors[ck][0] + |
| 1323 |
Colors[ck][1] + |
| 1324 |
Colors[ck][2]; |
| 1325 |
WeightsSum := WeightsSum + Weights[ck]; |
| 1326 |
end; |
| 1327 |
|
| 1328 |
{ wylosuj jedno z ck : wylosuj zmienna RandomCK z przedzialu 0..WeightsSum |
| 1329 |
a potem zbadaj do ktorego z przedzialow Weights[] wpada. Calculate ck. } |
| 1330 |
RandomCK := Random * WeightsSum; |
| 1331 |
ck := Low(ck); |
| 1332 |
while ck < High(ck) do |
| 1333 |
begin |
| 1334 |
if RandomCK < Weights[ck] then break; |
| 1335 |
RandomCK := RandomCK - Weights[ck]; |
| 1336 |
Inc(ck); |
| 1337 |
end; |
| 1338 |
|
| 1339 |
{ notka : nie, ponizej nie mozna zamienic na test WeightsSum > |
| 1340 |
SingleEpsilon. Nawet gdy to zachodzi ciagle moze sie okazac |
| 1341 |
ze WeightsSum jest wprawdzie duzo wieksze od zera ale samo |
| 1342 |
Weights[ck] jest mikroskopijnie male (i po prostu mielismy duzo |
| 1343 |
szczescia w losowaniu; path tracer robi tyle sciezek, tyle pixeli |
| 1344 |
itd. ze nietrudno tutaj "przez przypadek" wylosowac mikroskopijnie |
| 1345 |
mala wartosc). } |
| 1346 |
if Weights[ck] > SingleEpsilon then |
| 1347 |
begin |
| 1348 |
IntersectNormal := |
| 1349 |
{$ifdef CONSERVE_TRIANGLE_MEMORY} |
| 1350 |
IntersectNode^.World.Plane.XYZ |
| 1351 |
{$else} |
| 1352 |
IntersectNode^.INormalWorldSpace(Intersection) |
| 1353 |
{$endif}; |
| 1354 |
{ choose normal at Intersection pointing in the direction of RayOrigin } |
| 1355 |
IntersectNormal := PlaneDirNotInDirection(IntersectNormal, RayDirection); |
| 1356 |
|
| 1357 |
{ calculate TracedDir i PdfValue samplujac odpowiednio polsfere |
| 1358 |
(na podstawie ck). W przypadku TS moze wystapic calk. odbicie wewn. |
| 1359 |
i wtedy konczymy sciezke. } |
| 1360 |
case ck of |
| 1361 |
ckTD: TracedDir := PhiThetaToXYZ( |
| 1362 |
RandomHemispherePointCosTheta(PdfValue), |
| 1363 |
-IntersectNormal); |
| 1364 |
ckTS: if not TryCalculateTransmittedSpecularRayDirection( |
| 1365 |
TracedDir, PdfValue) then Exit; |
| 1366 |
ckRD: TracedDir := PhiThetaToXYZ( |
| 1367 |
RandomHemispherePointCosTheta(PdfValue), |
| 1368 |
IntersectNormal); |
| 1369 |
ckRS: TracedDir := PhiThetaToXYZ( |
| 1370 |
RandomHemispherePointCosThetaExp( |
| 1371 |
Round(Material.ReflSpecularExp), |
| 1372 |
PdfValue), |
| 1373 |
ReflectedRayDirection(RayDirection.Normalize, |
| 1374 |
IntersectNormal)); |
| 1375 |
end; |
| 1376 |
|
| 1377 |
{ wywolaj rekurencyjnie Trace(), a wiec idz sciezka dalej } |
| 1378 |
TracedCol := Trace(Intersection, TracedDir, Depth - 1, |
| 1379 |
IntersectNode, true, DirectIllumSamplesCount <> 0); |
| 1380 |
|
| 1381 |
{ przetworz TracedCol : wymnoz przez Colors[ck], podziel przez szanse |
| 1382 |
jego wyboru sposrod czterech Colors[], czyli przez |
| 1383 |
Weights[ck]/WeightsSum (bo to w koncu jest importance sampling) |
| 1384 |
(czyli pomnoz przez WeightsSum/Weights[ck], wiemy ze mianownik jest |
| 1385 |
> SingleEpsilon, sprawdzilismy to juz wczesniej). } |
| 1386 |
TracedCol := TracedCol * Colors[ck]; |
| 1387 |
TracedCol := TracedCol * (WeightsSum / Weights[ck]); |
| 1388 |
|
| 1389 |
Result := Result + TracedCol; |
| 1390 |
end; |
| 1391 |
|
| 1392 |
{ dodaj DirectIllumination } |
| 1393 |
Result := Result + DirectIllumination; |
| 1394 |
|
| 1395 |
{ Jezeli weszlismy tu dzieki rosyjskiej ruletce (a wiec jezeli Depth <= 0) |
| 1396 |
to skaluj Result zeby zapisany tu estymator byl unbiased. } |
| 1397 |
if Depth <= 0 then Result := Result * (1/RRoulContinue); |
| 1398 |
end; |
| 1399 |
end; |
| 1400 |
|
| 1401 |
var |
| 1402 |
i: Integer; |
| 1403 |
NonEmissiveColor: TVector3; |
| 1404 |
AnyMaterial: TMaterialInfo; |
| 1405 |
begin |
| 1406 |
IntersectNode := Octree.RayCollision(Intersection, RayOrigin, RayDirection, true, |
| 1407 |
TriangleToIgnore, IgnoreMarginAtStart, nil); |
| 1408 |
if IntersectNode = nil then Exit(SceneBackgroundColor); |
| 1409 |
|
| 1410 |
if TraceOnlyIndirect and IsLightSource(IntersectNode^) then |
| 1411 |
begin |
| 1412 |
Result := TVector3.Zero; |
| 1413 |
Exit; |
| 1414 |
end; |
| 1415 |
|
| 1416 |
AnyMaterial := IntersectNode^.MaterialInfo; |
| 1417 |
if AnyMaterial is TPhongMaterialInfo then |
| 1418 |
Material := TPhongMaterialInfo(AnyMaterial) |
| 1419 |
else |
| 1420 |
Material := nil; // TODO: path tracer treats all non-Phong materials (like Physical) as unlit |
| 1421 |
|
| 1422 |
{ de facto jezeli TraceOnlyIndirect to ponizsza linijka na pewno dodaje |
| 1423 |
do result (0, 0, 0). Ale nie widze w tej chwili jak z tego wyciagnac |
| 1424 |
jakas specjalna optymalizacje. |
| 1425 |
|
| 1426 |
We use below EmissiveColor(), not MaterialInfo.EmissiveColor, |
| 1427 |
because this is done even when MaterialInfo is nil. } |
| 1428 |
Result := EmissiveColor(IntersectNode^); |
| 1429 |
|
| 1430 |
if Material <> nil then |
| 1431 |
begin |
| 1432 |
{ jezeli MinDepth = Depth to znaczy ze nasz Trace zwraca kolor dla primary ray. |
| 1433 |
Wiec rozgaleziamy sie tutaj na NonPrimarySamplesCount, czyli dzialamy |
| 1434 |
jakbysmy byly stochastycznym ray tracerem ktory rozgalezia sie |
| 1435 |
na wiele promieni w punkcie rekursji. |
| 1436 |
Wpp. idziemy sciezka czyli dzialamy jakbysmy byly path tracerem czyli |
| 1437 |
nie rozgaleziamy sie na wiele promieni. } |
| 1438 |
if MinDepth = Depth then |
| 1439 |
begin |
| 1440 |
NonEmissiveColor := TVector3.Zero; |
| 1441 |
for i := 0 to NonPrimarySamplesCount-1 do |
| 1442 |
NonEmissiveColor := NonEmissiveColor + TraceNonEmissivePart; |
| 1443 |
NonEmissiveColor := NonEmissiveColor * (1 / NonPrimarySamplesCount); |
| 1444 |
Result := Result + NonEmissiveColor; |
| 1445 |
end else |
| 1446 |
Result := Result + TraceNonEmissivePart; |
| 1447 |
end; |
| 1448 |
end; |
| 1449 |
|
| 1450 |
var |
| 1451 |
RaysWindow: TRaysWindow; |
| 1452 |
|
| 1453 |
procedure DoPixel(const x, y: Cardinal); |
| 1454 |
var |
| 1455 |
PixColor, PrimaryRayOrigin, PrimaryRayDirection: TVector3; |
| 1456 |
SampleNum: Integer; |
| 1457 |
C: TCastleColor; |
| 1458 |
ColRGB: TCastleColorRGB absolute C; |
| 1459 |
begin |
| 1460 |
{ generuj pixel x, y. calculate PixColor } |
| 1461 |
if PrimarySamplesCount = 1 then |
| 1462 |
begin |
| 1463 |
{ gdy PrimarySamplesCount = 1 to wysylamy jeden promien pierwotny |
| 1464 |
i ten promien NIE jest losowany na rzutni w zakresie pixela |
| 1465 |
x, y ale przechodzi dokladnie przez srodek pixela x, y. } |
| 1466 |
RaysWindow.PrimaryRay(x, y, Image.Width, Image.Height, PrimaryRayOrigin, PrimaryRayDirection); |
| 1467 |
PixColor := Trace(PrimaryRayOrigin, PrimaryRayDirection, MinDepth, nil, false, false); |
| 1468 |
end else |
| 1469 |
begin |
| 1470 |
PixColor := TVector3.Zero; |
| 1471 |
for SampleNum := 0 to PrimarySamplesCount - 1 do |
| 1472 |
begin |
| 1473 |
RaysWindow.PrimaryRay( |
| 1474 |
x + Random - 0.5, y + Random - 0.5, |
| 1475 |
Image.Width, Image.Height, PrimaryRayOrigin, PrimaryRayDirection); |
| 1476 |
PixColor := PixColor + Trace(PrimaryRayOrigin, PrimaryRayDirection, MinDepth, nil, false, false); |
| 1477 |
end; |
| 1478 |
PixColor := PixColor * (1 / PrimarySamplesCount); |
| 1479 |
end; |
| 1480 |
|
| 1481 |
{ zapisz PixColor do Image } |
| 1482 |
C := Image.Colors[X, Y, 0]; |
| 1483 |
ColRGB := PixColor; |
| 1484 |
Image.Colors[X, Y, 0] := C; |
| 1485 |
end; |
| 1486 |
|
| 1487 |
var |
| 1488 |
PixCoord: TVector2Cardinal; |
| 1489 |
SFCurve: TSpaceFillingCurve; |
| 1490 |
begin |
| 1491 |
SceneBackgroundColor := GetSceneBackgroundColor(Background, SceneBGColor); |
| 1492 |
|
| 1493 |
{ check parameters (path tracing i tak trwa bardzo dlugo wiec mozemy sobie |
| 1494 |
pozwolic zeby na poczatku tej procedury wykonac kilka testow, nawet gdy |
| 1495 |
kompilujemy sie w wersji RELEASE) } |
| 1496 |
Check(PrimarySamplesCount > 0, 'PrimarySamplesCount for PathTracer must be greater than 0'); |
| 1497 |
Check(NonPrimarySamplesCount > 0, 'NonPrimarySamplesCount for PathTracer must be greater than 0'); |
| 1498 |
ClampVar(RRoulContinue, Single(0.0), Single(1.0)); |
| 1499 |
|
| 1500 |
{ initialize all to nil, to easily free them all in one try..finally } |
| 1501 |
LightItems := nil; |
| 1502 |
{$ifdef PATHTR_USES_SHADOW_CACHE} ShadowCache := nil; {$endif} |
| 1503 |
RaysWindow := nil; |
| 1504 |
SFCurve := nil; |
| 1505 |
try |
| 1506 |
{ calculate LightItems } |
| 1507 |
LightItems := TFPList.Create; |
| 1508 |
LightItems.Capacity := Octree.TrianglesCount div 4; |
| 1509 |
CollectedLightItems := LightItems; |
| 1510 |
Octree.EnumerateTriangles(@CollectLightItems); |
| 1511 |
|
| 1512 |
{$ifdef PATHTR_USES_SHADOW_CACHE} |
| 1513 |
{ calculate ShadowCache } |
| 1514 |
ShadowCache := TFPList.Create; |
| 1515 |
ShadowCache.Count := LightItems.Count; |
| 1516 |
{ Setting TFPList.Count already makes sure that new pointers are nil } |
| 1517 |
{$endif} |
| 1518 |
|
| 1519 |
{ calculate RaysWindow } |
| 1520 |
RaysWindow := TRaysWindow.CreateDescendant(CamPosition, |
| 1521 |
CamDirection.Normalize, CamUp.Normalize, Projection); |
| 1522 |
|
| 1523 |
{ calculate SFCurve } |
| 1524 |
SFCurve := SFCurveClass.Create(Image.Width, Image.Height); |
| 1525 |
SFCurve.SkipPixels(FirstPixel); |
| 1526 |
|
| 1527 |
{ generuj pixle obrazka } |
| 1528 |
if Assigned(PixelsMadeNotifier) then |
| 1529 |
begin |
| 1530 |
while not SFCurve.EndOfPixels do |
| 1531 |
begin |
| 1532 |
PixCoord := SFCurve.NextPixel; |
| 1533 |
DoPixel(PixCoord[0], PixCoord[1]); |
| 1534 |
PixelsMadeNotifier(SFCurve.PixelsDone, PixelsMadeNotifierData); |
| 1535 |
end; |
| 1536 |
end else |
| 1537 |
begin |
| 1538 |
while not SFCurve.EndOfPixels do |
| 1539 |
begin |
| 1540 |
PixCoord := SFCurve.NextPixel; |
| 1541 |
DoPixel(PixCoord[0], PixCoord[1]); |
| 1542 |
end; |
| 1543 |
end; |
| 1544 |
|
| 1545 |
finally |
| 1546 |
SFCurve.Free; |
| 1547 |
RaysWindow.Free; |
| 1548 |
{$ifdef PATHTR_USES_SHADOW_CACHE} ShadowCache.Free; {$endif} |
| 1549 |
LightItems.Free; |
| 1550 |
end; |
| 1551 |
end; |
| 1552 |
|
| 1553 |
procedure TPathTracer.AppendStats(const Stats: TStrings; const RenderingTime: Single); |
| 1554 |
var |
| 1555 |
PathsCount: Cardinal; |
| 1556 |
begin |
| 1557 |
inherited; |
| 1558 |
PathsCount := (Image.Width * Image.Height - FirstPixel) * |
| 1559 |
PrimarySamplesCount * NonPrimarySamplesCount; |
| 1560 |
Stats.Append(Format('Image size is %d x %d pixels (first %d pixels skipped) and we use %d (primary) x %d (non-primary) samples per pixel which gives %d paths.', |
| 1561 |
[Image.Width, Image.Height, FirstPixel, |
| 1562 |
PrimarySamplesCount, NonPrimarySamplesCount, PathsCount])); |
| 1563 |
Stats.Append(Format('%f paths done per second.', |
| 1564 |
[PathsCount / RenderingTime])); |
| 1565 |
Stats.Append(Format('%f simple collision tests done per one path.', |
| 1566 |
[TriangleCollisionTestsCounter / PathsCount ])); |
| 1567 |
end; |
| 1568 |
|
| 1569 |
end. |