├── .gitattributes ├── .gitignore ├── Bistro.scn ├── CustomRenderer.cs ├── FreeLookCamera ├── LICENSE └── camera.gd ├── LICENSE ├── Main.scn ├── Materials ├── blue.tres ├── glass.tres ├── green.tres ├── light.tres ├── red.tres └── reflective.tres ├── Models ├── portal_mesh.tres ├── sphere_mesh.tres └── wall_mesh.tres ├── Portal.cs ├── README.md ├── RTX.csproj ├── RTX.csproj.old ├── RTX.sln ├── Screenshots ├── .gdignore ├── Screenshot 2023-05-16_Diffuse.png └── Screenshot 2023-08-10_Cornell.png ├── SettingsMenu.cs ├── Shader ├── compute_rays.glsl ├── compute_rays.glsl.import ├── image_slider.gdshader ├── image_slider.material ├── projected_view.gdshader └── projected_view_material.tres ├── Sphere.cs ├── cornell_box.tscn ├── export_presets.cfg ├── icon.svg ├── icon.svg.import ├── project.godot └── sphere.tscn /.gitattributes: -------------------------------------------------------------------------------- 1 | # Normalize EOL for all files that Git considers text files. 2 | * text=auto eol=lf 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Godot 4+ specific ignores 2 | .godot/ 3 | Old/ 4 | .vs/ 5 | Models/bistro/ 6 | -------------------------------------------------------------------------------- /Bistro.scn: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gvvim/Godot4-Raytracing/a697682bfe5d4ec6dda5d3147fec506fe28326a9/Bistro.scn -------------------------------------------------------------------------------- /CustomRenderer.cs: -------------------------------------------------------------------------------- 1 | using Godot; 2 | using Godot.Collections; 3 | using System; 4 | using System.Collections; 5 | using System.Collections.Generic; 6 | using System.Runtime.InteropServices; 7 | 8 | public partial class CustomRenderer : Sprite2D 9 | { 10 | [Export] public Vector2I Resolution = new Vector2I(1280, 720); 11 | [Export] Camera3D Camera; 12 | [Export] Node3D SceneRoot; 13 | 14 | private bool _projectedViewEnabled = false; 15 | public bool ProjectedViewEnabled { 16 | get { return _projectedViewEnabled; } 17 | set { 18 | _projectedViewEnabled = value; 19 | if(value) { 20 | ProjectedView.Visible = true; 21 | ProjectedView.GlobalPosition = Camera.GlobalPosition - Camera.GlobalTransform.Basis.Z * CalculateOffset(Camera.Fov); 22 | defaultDistance = ProjectedView.GlobalPosition.DistanceTo(Camera.GlobalPosition); 23 | projectedViewMaterial.SetShaderParameter("screenSize", Resolution); 24 | projectedViewMaterial.SetShaderParameter("_Texture", imageTexture); 25 | projectedViewMaterial.SetShaderParameter("dist", 0f); 26 | ProjectedView.Texture = imageTexture; 27 | } else { 28 | ProjectedView.Visible = false; 29 | } 30 | } 31 | } 32 | [Export] public float ProjectedViewOffset = 2f; 33 | [Export] Sprite3D ProjectedView; 34 | [Export] float aspectRatio = 1280f / 720f; 35 | //[Export] float focusDistance = 1f; 36 | 37 | [Export] 38 | public bool Run 39 | { 40 | get => false; 41 | set 42 | { 43 | Compute(); 44 | } 45 | } 46 | 47 | [Export] 48 | public bool InitializeShader 49 | { 50 | get => false; 51 | set 52 | { 53 | if (rd is not null) 54 | { 55 | rd.Dispose(); 56 | } 57 | Initialize(); 58 | Compute(); 59 | } 60 | } 61 | 62 | private RenderingDevice rd; 63 | private Rid shader; 64 | 65 | private ShaderMaterial projectedViewMaterial; 66 | 67 | private const int SIZE_SETTINGS = 28; 68 | private const int SIZE_LIGHT = 44; 69 | private const int SIZE_MATERIAL = 52; 70 | private const int SIZE_SURFACE = 72; 71 | private const int SIZE_SPHERE = 56; 72 | private const int SIZE_PORTAL = 36; 73 | private const int SIZE_VEC3 = 12; 74 | private const int SIZE_VEC2 = 8; 75 | private const int SIZE_NUM = 4; 76 | 77 | [StructLayout(LayoutKind.Sequential, Size = SIZE_SETTINGS)] 78 | public struct SettingsData 79 | { 80 | public uint width; 81 | public uint height; 82 | public uint numRays; 83 | public uint maxBounces; 84 | public bool temporalAccumulation; 85 | public float recentFrameBias; 86 | public bool checkerboard; 87 | } 88 | 89 | [StructLayout(LayoutKind.Sequential, Size = SIZE_LIGHT)] 90 | public struct LightData { 91 | public float positionX; 92 | public float positionY; 93 | public float positionZ; 94 | public float colorR; 95 | public float colorG; 96 | public float colorB; 97 | public float energy; 98 | public bool isDirectionalLight; 99 | public float directionX; // or range if not directional 100 | public float directionY; 101 | public float directionZ; 102 | } 103 | 104 | [StructLayout(LayoutKind.Sequential, Size = SIZE_MATERIAL)] 105 | public class MaterialData { 106 | public float albedoR = 0.95f; 107 | public float albedoG = 0.95f; 108 | public float albedoB = 0.95f; 109 | public int textureID = -1; 110 | public float specularity = 0.0f; 111 | public float emissiveR = 0f; 112 | public float emissiveG = 0f; 113 | public float emissiveB = 0f; 114 | public int emissiveTextureID = -1; 115 | public float roughness = 0.0f; 116 | public int roughnessTextureID = -1; 117 | public float alpha = 1f; 118 | public int alphaTextureID = -1; 119 | 120 | public MaterialData() {} 121 | 122 | public override string ToString() { 123 | return $"({albedoR},{albedoG},{albedoB}), {roughness}, {alpha}, ({emissiveR}, {emissiveG}, {emissiveB})"; 124 | } 125 | } 126 | 127 | class SurfaceData { 128 | public Vector3[] vertices; 129 | public Vector3[] normals; 130 | public Vector2[] uvs; 131 | public int[] indices; 132 | } 133 | 134 | class SurfaceInstance { 135 | public Vector3 position; 136 | public Vector3 rotation; 137 | public Vector3 scale; 138 | public Vector3 boxMin; 139 | public Vector3 boxMax; 140 | public MaterialData material; 141 | public SurfaceData surfaceData; 142 | } 143 | 144 | [StructLayout(LayoutKind.Sequential, Size = SIZE_SURFACE)] 145 | class SurfaceDescriptor { 146 | public float positionX; 147 | public float positionY; 148 | public float positionZ; 149 | public float rotationX; 150 | public float rotationY; 151 | public float rotationZ; 152 | public float scaleX; 153 | public float scaleY; 154 | public float scaleZ; 155 | public float boxMinX; 156 | public float boxMinY; 157 | public float boxMinZ; 158 | public float boxMaxX; 159 | public float boxMaxY; 160 | public float boxMaxZ; 161 | public int materialID; 162 | public int indexStart; 163 | public int indexEnd; 164 | } 165 | 166 | [StructLayout(LayoutKind.Sequential, Size = SIZE_SPHERE)] 167 | class SphereData { 168 | public float positionX; 169 | public float positionY; 170 | public float positionZ; 171 | // public float rotationX; 172 | // public float rotationY; 173 | // public float rotationZ; 174 | public float scaleX; 175 | public float scaleY; 176 | public float scaleZ; 177 | public float boxMinX; 178 | public float boxMinY; 179 | public float boxMinZ; 180 | public float boxMaxX; 181 | public float boxMaxY; 182 | public float boxMaxZ; 183 | public int materialID; 184 | public float radius; 185 | } 186 | 187 | [StructLayout(LayoutKind.Sequential, Size = SIZE_PORTAL)] 188 | class PortalData { 189 | public float positionX; 190 | public float positionY; 191 | public float positionZ; 192 | public float rotationX; 193 | public float rotationY; 194 | public float rotationZ; 195 | public float width; 196 | public float height; 197 | public int otherID; 198 | } 199 | 200 | private float CalculateOffset(float fovDegrees) 201 | { 202 | return -0.00139f * fovDegrees + 0.57225f; 203 | } 204 | 205 | private void UpdateProjectedView() { 206 | defaultCameraPosition = Camera.GlobalPosition; 207 | ProjectedView.GlobalPosition = Camera.GlobalPosition - Camera.GlobalTransform.Basis.Z * CalculateOffset(Camera.Fov); 208 | projectedViewMaterial.SetShaderParameter("offset", Vector2.Zero); 209 | projectedViewMaterial.SetShaderParameter("angle", Vector2.Zero); 210 | projectedViewMaterial.SetShaderParameter("dist", 0f); 211 | ProjectedView.LookAt(Camera.GlobalPosition, Camera.GlobalTransform.Basis.Y); 212 | ProjectedView.RotateObjectLocal(Vector3.Up, Mathf.Pi); 213 | } 214 | 215 | // Buffers to update 216 | public SettingsData settings; 217 | private Rid settingsBuffer; 218 | 219 | private byte[] cameraDataBytes; 220 | private float[] cameraData; 221 | private Rid cameraDataBuffer; 222 | 223 | private Rid lightDataBuffer; 224 | private Rid surfaceDataBuffer; 225 | private Rid sphereDataBuffer; 226 | private Rid vertexBuffer; 227 | private Rid normalBuffer; 228 | private Rid uvBuffer; 229 | private Rid indexBuffer; 230 | private Rid materialBuffer; 231 | 232 | private Rid portalDataBuffer; 233 | 234 | // private Rid textureBuffer; 235 | 236 | private Rid outputTexture; 237 | private Image img; 238 | private ImageTexture imageTexture; 239 | private Rid uniformSet; 240 | private Rid pipeline; 241 | 242 | private bool _initialized = false; 243 | 244 | private uint currentFrame = 0; 245 | 246 | void Initialize() 247 | { 248 | if (Camera is null || SceneRoot is null) 249 | { 250 | var root = GetParent().GetParent(); 251 | 252 | Camera = root.GetNode("Camera3D") as Camera3D; 253 | SceneRoot = root.GetNode("World") as Node3D; 254 | } 255 | 256 | rd = RenderingServer.CreateLocalRenderingDevice(); 257 | 258 | var shaderFile = GD.Load("res://Shader/compute_rays.glsl"); 259 | var shaderBytecode = shaderFile.GetSpirV(); 260 | shader = rd.ShaderCreateFromSpirV(shaderBytecode); 261 | 262 | TextureFilter = TextureFilterEnum.Nearest; 263 | 264 | // Create buffers 265 | var settingsBytes = GetBytes(settings); 266 | settingsBuffer = rd.StorageBufferCreate((uint)settingsBytes.Length, settingsBytes); 267 | 268 | // Camera 269 | cameraData = new float[16 + 3 + 3 + 1]; // mat4 Vector3 Vector3 uint 270 | cameraDataBytes = new byte[cameraData.Length * 4]; 271 | UpdateCameraData(); 272 | //cameraData = new CameraData(); 273 | 274 | //cameraDataBytes = GetBytes(cameraData); 275 | Buffer.BlockCopy(cameraData, 0, cameraDataBytes, 0, cameraData.Length * sizeof(float)); 276 | cameraDataBuffer = rd.StorageBufferCreate((uint)cameraDataBytes.Length, cameraDataBytes); 277 | 278 | UpdateScene(SceneRoot); 279 | 280 | // Light 281 | lightDataBuffer = rd.StorageBufferCreate((uint)lightDataBytes.Length, lightDataBytes); 282 | 283 | // Mesh 284 | surfaceDataBuffer = rd.StorageBufferCreate((uint)surfaceDataBytes.Length, surfaceDataBytes); 285 | sphereDataBuffer = rd.StorageBufferCreate((uint)sphereDataBytes.Length, sphereDataBytes); 286 | vertexBuffer = rd.StorageBufferCreate((uint)vertexDataBytes.Length, vertexDataBytes); 287 | normalBuffer = rd.StorageBufferCreate((uint)normalDataBytes.Length, normalDataBytes); 288 | uvBuffer = rd.StorageBufferCreate((uint)uvDataBytes.Length, uvDataBytes); 289 | indexBuffer = rd.StorageBufferCreate((uint)indexDataBytes.Length, indexDataBytes); 290 | materialBuffer = rd.StorageBufferCreate((uint)materialDataBytes.Length, materialDataBytes); 291 | 292 | portalDataBuffer = rd.StorageBufferCreate((uint)portalDataBytes.Length + 1, portalDataBytes); 293 | 294 | 295 | // textureBuffer = rd.TextureBufferCreate(textureData, RenderingDevice.DataFormat.R32G32B32A32Sfloat); 296 | 297 | // Create uniforms to assign the buffers to the rendering device 298 | 299 | var fmt = new RDTextureFormat(); 300 | fmt.Width = (uint)Resolution.X; 301 | fmt.Height = (uint)Resolution.Y; 302 | fmt.Format = RenderingDevice.DataFormat.R32G32B32A32Sfloat; 303 | fmt.UsageBits = RenderingDevice.TextureUsageBits.CanUpdateBit | RenderingDevice.TextureUsageBits.StorageBit | RenderingDevice.TextureUsageBits.CanCopyFromBit; 304 | 305 | var view = new RDTextureView(); 306 | 307 | var outputImage = Image.Create(Resolution.X, Resolution.Y, false, Image.Format.Rgbaf); 308 | var outputData = new Godot.Collections.Array { outputImage.GetData() }; 309 | outputTexture = rd.TextureCreate(fmt, view, outputData); 310 | var outputTextureUniform = new RDUniform() 311 | { 312 | UniformType = RenderingDevice.UniformType.Image, 313 | Binding = 0 314 | }; 315 | 316 | var uniformSettings = new RDUniform 317 | { 318 | UniformType = RenderingDevice.UniformType.StorageBuffer, 319 | Binding = 1 320 | }; 321 | var uniformCamera = new RDUniform 322 | { 323 | UniformType = RenderingDevice.UniformType.StorageBuffer, 324 | Binding = 2 325 | }; 326 | var uniformLights = new RDUniform 327 | { 328 | UniformType = RenderingDevice.UniformType.StorageBuffer, 329 | Binding = 3 330 | }; 331 | 332 | var uniformSurfaces = new RDUniform 333 | { 334 | UniformType = RenderingDevice.UniformType.StorageBuffer, 335 | Binding = 4 336 | }; 337 | var uniformVertices = new RDUniform 338 | { 339 | UniformType = RenderingDevice.UniformType.StorageBuffer, 340 | Binding = 5 341 | }; 342 | var uniformNormals = new RDUniform 343 | { 344 | UniformType = RenderingDevice.UniformType.StorageBuffer, 345 | Binding = 6 346 | }; 347 | var uniformUVs = new RDUniform 348 | { 349 | UniformType = RenderingDevice.UniformType.StorageBuffer, 350 | Binding = 7 351 | }; 352 | var uniformIndices = new RDUniform 353 | { 354 | UniformType = RenderingDevice.UniformType.StorageBuffer, 355 | Binding = 8 356 | }; 357 | var uniformMaterials = new RDUniform 358 | { 359 | UniformType = RenderingDevice.UniformType.StorageBuffer, 360 | Binding = 9 361 | }; 362 | var uniformSpheres = new RDUniform 363 | { 364 | UniformType = RenderingDevice.UniformType.StorageBuffer, 365 | Binding = 10 366 | }; 367 | var uniformPortals = new RDUniform 368 | { 369 | UniformType = RenderingDevice.UniformType.StorageBuffer, 370 | Binding = 11 371 | }; 372 | 373 | // var uniformTextures= new RDUniform 374 | // { 375 | // UniformType = RenderingDevice.UniformType.TextureBuffer, 376 | // Binding = 377 | // }; 378 | 379 | outputTextureUniform.AddId(outputTexture); 380 | uniformSettings.AddId(settingsBuffer); 381 | uniformCamera.AddId(cameraDataBuffer); 382 | uniformLights.AddId(lightDataBuffer); 383 | uniformSurfaces.AddId(surfaceDataBuffer); 384 | uniformSpheres.AddId(sphereDataBuffer); 385 | uniformVertices.AddId(vertexBuffer); 386 | uniformNormals.AddId(normalBuffer); 387 | uniformUVs.AddId(uvBuffer); 388 | uniformIndices.AddId(indexBuffer); 389 | uniformMaterials.AddId(materialBuffer); 390 | 391 | uniformPortals.AddId(portalDataBuffer); 392 | 393 | // uniformTextures.AddId(albedoTextureBuffer); 394 | 395 | uniformSet = rd.UniformSetCreate(new Array { 396 | outputTextureUniform, 397 | uniformSettings, 398 | uniformCamera, 399 | uniformLights, 400 | uniformSurfaces, 401 | uniformVertices, 402 | uniformNormals, 403 | uniformUVs, 404 | uniformIndices, 405 | uniformMaterials, 406 | uniformSpheres, 407 | uniformPortals, 408 | // uniformTextures 409 | }, shader, 0); 410 | 411 | // Create a compute pipeline 412 | pipeline = rd.ComputePipelineCreate(shader); 413 | 414 | currentFrame = 0; 415 | } 416 | 417 | void Compute() 418 | { 419 | // UPDATE BUFFERS 420 | 421 | // Camera 422 | if(cameraData is not null) { 423 | UpdateCameraData(); 424 | 425 | // PrintBuffer(cameraDataBytes); 426 | Buffer.BlockCopy(cameraData, 0, cameraDataBytes, 0, cameraData.Length * sizeof(float)); 427 | rd.BufferUpdate(cameraDataBuffer, 0, (uint)cameraDataBytes.Length, cameraDataBytes); 428 | } 429 | 430 | if(rd is null) { 431 | GD.Print("No render device!"); 432 | return; 433 | } 434 | 435 | // Submit to GPU and wait for sync 436 | var computeList = rd.ComputeListBegin(); 437 | rd.ComputeListBindComputePipeline(computeList, pipeline); 438 | rd.ComputeListBindUniformSet(computeList, uniformSet, 0); 439 | rd.ComputeListDispatch(computeList, xGroups: settings.width / 8, yGroups:settings.height / 8, zGroups: 1); 440 | rd.ComputeListEnd(); 441 | 442 | rd.Submit(); 443 | rd.Sync(); 444 | 445 | // Read new data from the output image buffer 446 | var byteData = rd.TextureGetData(outputTexture, 0); 447 | if (imageTexture is null) 448 | { 449 | img = Image.CreateFromData(Resolution.X, Resolution.Y, false, Image.Format.Rgbaf, byteData); 450 | img.ResourceName = "Raytraced Image"; 451 | 452 | imageTexture = ImageTexture.CreateFromImage(img); 453 | Texture = imageTexture; 454 | } else { 455 | img.SetData(Resolution.X, Resolution.Y, false, Image.Format.Rgbaf, byteData); 456 | imageTexture.Update(img); 457 | } 458 | 459 | currentFrame++; 460 | if(_projectedViewEnabled) { 461 | UpdateProjectedView(); 462 | } 463 | lastFrameComputed = true; 464 | } 465 | 466 | public void UpdateRenderResolution(Vector2I newSize) { 467 | imageTexture = null; 468 | Resolution = newSize; 469 | settings.width = (uint)newSize.X; 470 | settings.height = (uint)newSize.Y; 471 | Initialize(); 472 | ReScale(); 473 | } 474 | 475 | private Vector2I windowSize; 476 | 477 | public void UpdateWindowResolution(Vector2I newSize) { 478 | windowSize = newSize; 479 | ReScale(); 480 | GetWindow().Size = newSize; 481 | } 482 | 483 | private void ReScale() { 484 | ProjectedView.Scale = new Vector3(1280f / Resolution.X, 720f / Resolution.Y, 1); 485 | Scale = new Vector2((float)windowSize.X / Resolution.X, (float)windowSize.Y / Resolution.Y); 486 | RefreshProjectedView(); 487 | } 488 | 489 | private async void RefreshProjectedView() 490 | { 491 | bool projectedViewWasEnabled = ProjectedViewEnabled; 492 | await ToSignal(GetTree().CreateTimer(0.01f), "timeout"); 493 | ProjectedViewEnabled = projectedViewWasEnabled; 494 | await ToSignal(GetTree().CreateTimer(0.5f), "timeout"); // Hack to refresh the view if the image hasn't been recomputed by the GPU on time. 495 | ProjectedViewEnabled = projectedViewWasEnabled; 496 | } 497 | 498 | public static List BytesToVector3List(byte[] byteArray) { 499 | if (byteArray.Length % 12 != 0) { 500 | throw new ArgumentException("Byte array length must be a multiple of 12 bytes."); 501 | } 502 | 503 | List vectorList = new List(); 504 | 505 | for (int i = 0; i < byteArray.Length; i += 12) { 506 | byte[] subArray = new byte[12]; 507 | System.Array.Copy(byteArray, i, subArray, 0, 12); 508 | 509 | Vector3 vector3; 510 | GCHandle handle = GCHandle.Alloc(subArray, GCHandleType.Pinned); 511 | vector3 = (Vector3)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(Vector3)); 512 | handle.Free(); 513 | 514 | vectorList.Add(vector3); 515 | } 516 | 517 | return vectorList; 518 | } 519 | 520 | public void ProcessNode(Node3D node) { 521 | if(!node.Visible) 522 | return; 523 | 524 | if(node is Portal portal) { 525 | int id=bigPortalList.Count; 526 | 527 | Portal portalOther = portal.Other; 528 | PortalData portalDataA = new PortalData{ 529 | positionX = portal.GlobalPosition.X, 530 | positionY = portal.GlobalPosition.Y, 531 | positionZ = portal.GlobalPosition.Z, 532 | rotationX = portal.GlobalRotation.X, 533 | rotationY = portal.GlobalRotation.Y, 534 | rotationZ = portal.GlobalRotation.Z, 535 | width = portal.Width, 536 | height = portal.Height, 537 | otherID = id+1 538 | }; 539 | PortalData portalDataB = new PortalData{ 540 | positionX = portalOther.GlobalPosition.X, 541 | positionY = portalOther.GlobalPosition.Y, 542 | positionZ = portalOther.GlobalPosition.Z, 543 | rotationX = portalOther.GlobalRotation.X, 544 | rotationY = portalOther.GlobalRotation.Y, 545 | rotationZ = portalOther.GlobalRotation.Z, 546 | width = portalOther.Width, 547 | height = portalOther.Height, 548 | otherID = id 549 | }; 550 | bigPortalList.Add(portalDataA); 551 | bigPortalList.Add(portalDataB); 552 | 553 | } else if(node is Sphere sphere) { 554 | SphereData newSphereData = new SphereData 555 | { 556 | positionX = sphere.GlobalPosition.X, 557 | positionY = sphere.GlobalPosition.Y, 558 | positionZ = sphere.GlobalPosition.Z, 559 | // rotation = sphere.GlobalRotation, 560 | scaleX = sphere.Scale.X, 561 | scaleY = sphere.Scale.Y, 562 | scaleZ = sphere.Scale.Z, 563 | boxMinX = sphere.GetAabb().Position.X, 564 | boxMinY = sphere.GetAabb().Position.Y, 565 | boxMinZ = sphere.GetAabb().Position.Z, 566 | boxMaxX = sphere.GetAabb().End.X, 567 | boxMaxY = sphere.GetAabb().End.Y, 568 | boxMaxZ = sphere.GetAabb().End.Z, 569 | radius = ((SphereMesh)sphere.Mesh).Radius 570 | }; 571 | var materialData = new MaterialData(); 572 | Material material = sphere.MaterialOverride; 573 | Material materialOverlay = sphere.MaterialOverlay; 574 | if(materialOverlay is not null) { 575 | material = materialOverlay; 576 | } 577 | if(material is StandardMaterial3D standardMaterial) { 578 | materialData.albedoR = standardMaterial.AlbedoColor.R; 579 | materialData.albedoG = standardMaterial.AlbedoColor.G; 580 | materialData.albedoB = standardMaterial.AlbedoColor.B; 581 | materialData.specularity = standardMaterial.MetallicSpecular; 582 | materialData.emissiveR = standardMaterial.Emission.R; 583 | materialData.emissiveG = standardMaterial.Emission.G; 584 | materialData.emissiveB = standardMaterial.Emission.B; 585 | materialData.roughness = standardMaterial.Roughness; 586 | materialData.alpha = standardMaterial.AlbedoColor.A; 587 | materialData.textureID = 0; 588 | materialData.emissiveTextureID = 0; 589 | materialData.alphaTextureID = 0; 590 | materialData.textureID = 0; 591 | } 592 | int materialIndex = GetMaterialFromCache(materialData); 593 | newSphereData.materialID = materialIndex; 594 | bigSphereList.Add(newSphereData); 595 | } else if(node is MeshInstance3D meshInstance) { 596 | Mesh mesh = meshInstance.Mesh; 597 | if(mesh != null) { 598 | int numSurfaces = mesh.GetSurfaceCount(); 599 | for(int i=0; i bigVertexList, 680 | List bigNormalList, 681 | List bigUVList, 682 | List bigIndexList, 683 | List bigMaterialList, 684 | List bigSurfaceDescriptorList, 685 | ref int indexOffset 686 | ) 687 | { 688 | int materialIndex = GetMaterialFromCache(surfaceInstance.material); 689 | 690 | SurfaceDescriptor surfaceDescriptor = new SurfaceDescriptor { 691 | positionX = surfaceInstance.position.X, 692 | positionY = surfaceInstance.position.Y, 693 | positionZ = surfaceInstance.position.Z, 694 | rotationX = surfaceInstance.rotation.X, 695 | rotationY = surfaceInstance.rotation.Y, 696 | rotationZ = surfaceInstance.rotation.Z, 697 | scaleX = surfaceInstance.scale.X, 698 | scaleY = surfaceInstance.scale.Y, 699 | scaleZ = surfaceInstance.scale.Z, 700 | boxMinX = surfaceInstance.boxMin.X, 701 | boxMinY = surfaceInstance.boxMin.Y, 702 | boxMinZ = surfaceInstance.boxMin.Z, 703 | boxMaxX = surfaceInstance.boxMax.X, 704 | boxMaxY = surfaceInstance.boxMax.Y, 705 | boxMaxZ = surfaceInstance.boxMax.Z, 706 | materialID = materialIndex, 707 | indexStart = indexOffset, 708 | indexEnd = indexOffset + surfaceInstance.surfaceData.indices.Length 709 | }; 710 | 711 | if (!surfaceDataCache.TryGetValue(surfaceInstance.surfaceData, out int surfaceDataIndex)) { 712 | surfaceDataIndex = surfaceDataCache.Count; 713 | surfaceDataCache[surfaceInstance.surfaceData] = surfaceDataIndex; 714 | 715 | int vertexOffset = bigVertexList.Count; 716 | 717 | // Add vertices, normals, uvs, and indices to big lists 718 | bigVertexList.AddRange(surfaceInstance.surfaceData.vertices); 719 | bigNormalList.AddRange(surfaceInstance.surfaceData.normals); 720 | bigUVList.AddRange(surfaceInstance.surfaceData.uvs); 721 | 722 | foreach (int index in surfaceInstance.surfaceData.indices) { 723 | bigIndexList.Add(index + vertexOffset); 724 | } 725 | 726 | indexOffset += surfaceInstance.surfaceData.indices.Length; 727 | } 728 | 729 | bigSurfaceDescriptorList.Add(surfaceDescriptor); 730 | } 731 | 732 | List surfaceInstances; 733 | 734 | List bigVertexList; 735 | List bigNormalList; 736 | List bigUVList; 737 | List bigIndexList; 738 | List bigMaterialList; 739 | List bigSurfaceDescriptorList; 740 | List bigSphereList; 741 | List bigLightList; 742 | List bigPortalList; 743 | 744 | byte[] surfaceDataBytes, sphereDataBytes, vertexDataBytes, normalDataBytes, uvDataBytes, indexDataBytes, materialDataBytes, lightDataBytes, portalDataBytes; 745 | 746 | System.Collections.Generic.Dictionary materialCache; 747 | System.Collections.Generic.Dictionary surfaceDataCache; 748 | 749 | public void UpdateScene(Node3D root) { 750 | materialCache = new System.Collections.Generic.Dictionary(); 751 | surfaceDataCache = new System.Collections.Generic.Dictionary(); 752 | 753 | bigVertexList = new List(); 754 | bigNormalList = new List(); 755 | bigUVList = new List(); 756 | bigIndexList = new List(); 757 | bigMaterialList = new List(); 758 | bigSurfaceDescriptorList = new List(); 759 | bigSphereList = new List(); 760 | 761 | bigLightList = new List(); 762 | 763 | bigPortalList = new List(); 764 | 765 | // Process node will scan the nodes and populate the surfaceInstances and genericLights. 766 | if(surfaceInstances == null) 767 | surfaceInstances = new List(); 768 | else 769 | surfaceInstances.Clear(); 770 | 771 | ProcessNode(root); 772 | 773 | int indexOffset = 0; 774 | 775 | foreach(SurfaceInstance surfaceInstance in surfaceInstances) { 776 | RegisterSurface(surfaceInstance, bigVertexList, bigNormalList, bigUVList, bigIndexList, bigMaterialList, bigSurfaceDescriptorList, ref indexOffset); 777 | } 778 | 779 | surfaceDataBytes = GetBytes(bigSurfaceDescriptorList, SIZE_SURFACE); 780 | sphereDataBytes = GetBytes(bigSphereList, SIZE_SPHERE); 781 | vertexDataBytes = GetBytes(bigVertexList, SIZE_VEC3); 782 | normalDataBytes = GetBytes(bigNormalList, SIZE_VEC3); 783 | uvDataBytes = GetBytes(bigUVList, SIZE_VEC2); 784 | indexDataBytes = GetBytes(bigIndexList, SIZE_NUM); 785 | materialDataBytes = GetBytes(bigMaterialList, SIZE_MATERIAL); 786 | 787 | lightDataBytes = GetBytes(bigLightList, SIZE_LIGHT); 788 | portalDataBytes = GetBytes(bigPortalList, SIZE_PORTAL); 789 | 790 | // for(int i=0; i(List list, uint size) 916 | { 917 | byte[] arr = new byte[size * list.Count]; 918 | 919 | for(int i=0; i= interval) 981 | { 982 | if(lastFrameComputed) { 983 | lastFrameComputed = false; 984 | Compute(); 985 | } else { 986 | GD.Print("Failed to compute last frame on time, skipping this frame!"); 987 | } 988 | t = 0; 989 | } else { 990 | float distance = ProjectedView.GlobalPosition.DistanceTo(Camera.GlobalPosition); 991 | if(distance < defaultDistance) { 992 | ProjectedView.GlobalPosition = Camera.GlobalPosition - Camera.GlobalTransform.Basis.Z * CalculateOffset(Camera.Fov); 993 | } else { 994 | Vector3 direction = ProjectedView.GlobalPosition - Camera.GlobalPosition; 995 | Vector2 difference = new Vector2(direction.Dot(-Camera.Basis.X), direction.Dot(-Camera.Basis.Y)); 996 | direction = direction.Normalized(); 997 | 998 | Vector2 angles; 999 | angles.X = Mathf.Atan2(-direction.X, direction.Z); 1000 | angles.Y = Mathf.Asin(direction.Y); 1001 | 1002 | projectedViewMaterial.SetShaderParameter("angles", angles); 1003 | projectedViewMaterial.SetShaderParameter("offset", difference); 1004 | // GD.Print(difference); 1005 | } 1006 | projectedViewMaterial.SetShaderParameter("dist", distance - defaultDistance); 1007 | } 1008 | 1009 | t += delta; 1010 | } 1011 | } 1012 | } 1013 | -------------------------------------------------------------------------------- /FreeLookCamera/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020 Adam Viola 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /FreeLookCamera/camera.gd: -------------------------------------------------------------------------------- 1 | class_name FreeLookCamera extends Camera3D 2 | 3 | # Modifier keys' speed multiplier 4 | const SHIFT_MULTIPLIER = 2.5 5 | const ALT_MULTIPLIER = 1.0 / SHIFT_MULTIPLIER 6 | 7 | @export_range(0.0, 1.0) var sensitivity = 0.25 8 | 9 | # Mouse state 10 | var _mouse_position = Vector2(0.0, 0.0) 11 | var _total_pitch = 0.0 12 | 13 | # Movement state 14 | var _direction = Vector3(0.0, 0.0, 0.0) 15 | var _velocity = Vector3(0.0, 0.0, 0.0) 16 | var _acceleration = 30 17 | var _deceleration = -10 18 | var _vel_multiplier = 4 19 | 20 | # Keyboard state 21 | var _w = false 22 | var _s = false 23 | var _a = false 24 | var _d = false 25 | var _q = false 26 | var _e = false 27 | var _shift = false 28 | var _alt = false 29 | 30 | func _input(event): 31 | # Receives mouse motion 32 | if event is InputEventMouseMotion: 33 | _mouse_position = event.relative 34 | 35 | # Receives mouse button input 36 | if event is InputEventMouseButton: 37 | match event.button_index: 38 | MOUSE_BUTTON_RIGHT: # Only allows rotation if right click down 39 | Input.set_mouse_mode(Input.MOUSE_MODE_CAPTURED if event.pressed else Input.MOUSE_MODE_VISIBLE) 40 | MOUSE_BUTTON_WHEEL_UP: # Increases max velocity 41 | _vel_multiplier = clamp(_vel_multiplier * 1.1, 0.2, 20) 42 | MOUSE_BUTTON_WHEEL_DOWN: # Decereases max velocity 43 | _vel_multiplier = clamp(_vel_multiplier / 1.1, 0.2, 20) 44 | 45 | # Receives key input 46 | if event is InputEventKey: 47 | match event.keycode: 48 | KEY_W: 49 | _w = event.pressed 50 | KEY_S: 51 | _s = event.pressed 52 | KEY_A: 53 | _a = event.pressed 54 | KEY_D: 55 | _d = event.pressed 56 | KEY_Q: 57 | _q = event.pressed 58 | KEY_E: 59 | _e = event.pressed 60 | 61 | # Updates mouselook and movement every frame 62 | func _process(delta): 63 | _update_mouselook() 64 | _update_movement(delta) 65 | 66 | # Updates camera movement 67 | func _update_movement(delta): 68 | # Computes desired direction from key states 69 | _direction = Vector3((_d as float) - (_a as float), 70 | (_e as float) - (_q as float), 71 | (_s as float) - (_w as float)) 72 | 73 | # Computes the change in velocity due to desired direction and "drag" 74 | # The "drag" is a constant acceleration on the camera to bring it's velocity to 0 75 | var offset = _direction.normalized() * _acceleration * _vel_multiplier * delta \ 76 | + _velocity.normalized() * _deceleration * _vel_multiplier * delta 77 | 78 | # Compute modifiers' speed multiplier 79 | var speed_multi = 1 80 | if _shift: speed_multi *= SHIFT_MULTIPLIER 81 | if _alt: speed_multi *= ALT_MULTIPLIER 82 | 83 | # Checks if we should bother translating the camera 84 | if _direction == Vector3.ZERO and offset.length_squared() > _velocity.length_squared(): 85 | # Sets the velocity to 0 to prevent jittering due to imperfect deceleration 86 | _velocity = Vector3.ZERO 87 | else: 88 | # Clamps speed to stay within maximum value (_vel_multiplier) 89 | _velocity.x = clamp(_velocity.x + offset.x, -_vel_multiplier, _vel_multiplier) 90 | _velocity.y = clamp(_velocity.y + offset.y, -_vel_multiplier, _vel_multiplier) 91 | _velocity.z = clamp(_velocity.z + offset.z, -_vel_multiplier, _vel_multiplier) 92 | 93 | translate(_velocity * delta * speed_multi) 94 | 95 | # Updates mouse look 96 | func _update_mouselook(): 97 | # Only rotates mouse if the mouse is captured 98 | if Input.get_mouse_mode() == Input.MOUSE_MODE_CAPTURED: 99 | _mouse_position *= sensitivity 100 | var yaw = _mouse_position.x 101 | var pitch = _mouse_position.y 102 | _mouse_position = Vector2(0, 0) 103 | 104 | # Prevents looking up/down too far 105 | pitch = clamp(pitch, -90 - _total_pitch, 90 - _total_pitch) 106 | _total_pitch += pitch 107 | 108 | rotate_y(deg_to_rad(-yaw)) 109 | rotate_object_local(Vector3(1,0,0), deg_to_rad(-pitch)) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /Main.scn: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gvvim/Godot4-Raytracing/a697682bfe5d4ec6dda5d3147fec506fe28326a9/Main.scn -------------------------------------------------------------------------------- /Materials/blue.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="StandardMaterial3D" format=3 uid="uid://b3u3bbmo5hu6t"] 2 | 3 | [resource] 4 | albedo_color = Color(0, 0, 1, 1) 5 | metallic_specular = 1.0 6 | roughness = 0.5 7 | -------------------------------------------------------------------------------- /Materials/glass.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="StandardMaterial3D" format=3 uid="uid://dmssvjft3r7nf"] 2 | 3 | [resource] 4 | transparency = 1 5 | albedo_color = Color(1, 1, 1, 0.682353) 6 | roughness = 0.0 7 | refraction_enabled = true 8 | -------------------------------------------------------------------------------- /Materials/green.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="StandardMaterial3D" format=3 uid="uid://cufwcfdr6tia1"] 2 | 3 | [resource] 4 | albedo_color = Color(0, 1, 0, 1) 5 | metallic = 1.0 6 | metallic_specular = 0.0 7 | roughness = 0.0 8 | -------------------------------------------------------------------------------- /Materials/light.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="StandardMaterial3D" format=3 uid="uid://b3adab3ecdccm"] 2 | 3 | [resource] 4 | emission_enabled = true 5 | emission = Color(1, 1, 1, 1) 6 | emission_energy_multiplier = 4.07 7 | -------------------------------------------------------------------------------- /Materials/red.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="StandardMaterial3D" format=3 uid="uid://cctf0t024p5hx"] 2 | 3 | [resource] 4 | albedo_color = Color(1, 0, 0, 1) 5 | roughness = 0.2 6 | -------------------------------------------------------------------------------- /Materials/reflective.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="StandardMaterial3D" format=3 uid="uid://brpddgwbhesdm"] 2 | 3 | [resource] 4 | metallic = 1.0 5 | metallic_specular = 1.0 6 | roughness = 0.0 7 | -------------------------------------------------------------------------------- /Models/portal_mesh.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="QuadMesh" format=3 uid="uid://bgoo8sxoop3s4"] 2 | 3 | [resource] 4 | -------------------------------------------------------------------------------- /Models/sphere_mesh.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="SphereMesh" format=3 uid="uid://cpos174earq4s"] 2 | 3 | [resource] 4 | radius = 0.25 5 | height = 0.5 6 | -------------------------------------------------------------------------------- /Models/wall_mesh.tres: -------------------------------------------------------------------------------- 1 | [gd_resource type="BoxMesh" format=3 uid="uid://c26or4k2qjxgi"] 2 | 3 | [resource] 4 | size = Vector3(2, 0.01, 2) 5 | -------------------------------------------------------------------------------- /Portal.cs: -------------------------------------------------------------------------------- 1 | using Godot; 2 | using System; 3 | 4 | [Tool] 5 | public partial class Portal : MeshInstance3D 6 | { 7 | [Export] public float Width { 8 | get { 9 | return _width; 10 | } 11 | set { 12 | _width = value; 13 | UpdateWidthHeight(); 14 | } 15 | } 16 | 17 | [Export] public float Height { 18 | get { 19 | return _height; 20 | } 21 | set { 22 | _height = value; 23 | UpdateWidthHeight(); 24 | } 25 | } 26 | 27 | private void UpdateWidthHeight() { 28 | Scale = new Vector3(_width, _height,1f); 29 | } 30 | 31 | private float _width = 1f, _height = 1f; 32 | [Export] public Portal Other; 33 | 34 | public override void _Ready() 35 | { 36 | if (Engine.IsEditorHint()) 37 | { 38 | if(Mesh is null) { 39 | Mesh = ResourceLoader.Load("res://Models/portal_mesh.tres"); 40 | } 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Godot4-Raytracing 2 | Implementation of ray-tracing in Godot engine, via compute shaders. Focus on realtime performance and optimization. 3 | 4 | ![Example render](./Screenshots/Screenshot%202023-08-10_Cornell.png) 5 | 6 | ## Instructions: 7 | 8 | Press tab to toggle settings menu, use the slider in the bottom to compare views. 9 | 10 | -------------------------------------------------------------------------------- /RTX.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | true 5 | 6 | -------------------------------------------------------------------------------- /RTX.csproj.old: -------------------------------------------------------------------------------- 1 | 2 | 3 | net6.0 4 | true 5 | 6 | -------------------------------------------------------------------------------- /RTX.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio 2012 3 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RTX", "RTX.csproj", "{3FC5BED1-D032-405D-9862-2EBFC63BC946}" 4 | EndProject 5 | Global 6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 7 | Debug|Any CPU = Debug|Any CPU 8 | ExportDebug|Any CPU = ExportDebug|Any CPU 9 | ExportRelease|Any CPU = ExportRelease|Any CPU 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {3FC5BED1-D032-405D-9862-2EBFC63BC946}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 13 | {3FC5BED1-D032-405D-9862-2EBFC63BC946}.Debug|Any CPU.Build.0 = Debug|Any CPU 14 | {3FC5BED1-D032-405D-9862-2EBFC63BC946}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU 15 | {3FC5BED1-D032-405D-9862-2EBFC63BC946}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU 16 | {3FC5BED1-D032-405D-9862-2EBFC63BC946}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU 17 | {3FC5BED1-D032-405D-9862-2EBFC63BC946}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU 18 | EndGlobalSection 19 | EndGlobal 20 | -------------------------------------------------------------------------------- /Screenshots/.gdignore: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gvvim/Godot4-Raytracing/a697682bfe5d4ec6dda5d3147fec506fe28326a9/Screenshots/.gdignore -------------------------------------------------------------------------------- /Screenshots/Screenshot 2023-05-16_Diffuse.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gvvim/Godot4-Raytracing/a697682bfe5d4ec6dda5d3147fec506fe28326a9/Screenshots/Screenshot 2023-05-16_Diffuse.png -------------------------------------------------------------------------------- /Screenshots/Screenshot 2023-08-10_Cornell.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gvvim/Godot4-Raytracing/a697682bfe5d4ec6dda5d3147fec506fe28326a9/Screenshots/Screenshot 2023-08-10_Cornell.png -------------------------------------------------------------------------------- /SettingsMenu.cs: -------------------------------------------------------------------------------- 1 | using Godot; 2 | using System; 3 | 4 | public partial class SettingsMenu : Control 5 | { 6 | private static Control instance; 7 | private bool isMenuVisible = false; 8 | [Export] private ShaderMaterial shaderMaterial; 9 | [Export] private ShaderMaterial projectionShaderMaterial; 10 | [Export] private CanvasItem canvasItem; 11 | [Export] private Sprite3D projectedView; 12 | [Export] private Camera3D camera; 13 | [Export(PropertyHint.Layers3DRender)] private uint defaultCameraMask; 14 | [Export(PropertyHint.Layers3DRender)] private uint projectedViewCameraMask; 15 | [Export] private Slider slider; 16 | 17 | [Export] private CustomRenderer customRenderer; 18 | [Export] private Panel settingsPanel; 19 | [Export] private OptionButton renderResolutionOptions; 20 | [Export] private OptionButton windowResolutionOptions; 21 | [Export] private CheckButton fullScreenCheck; 22 | [Export] private SpinBox numRays; 23 | [Export] private SpinBox maxBounces; 24 | [Export] private SpinBox targetFPS; 25 | [Export] private Label currentFPS; 26 | [Export] private Slider recentFrameBias; 27 | [Export] private CheckButton temporalAccumulationCheck; 28 | [Export] private CheckButton checkerboardCheck; 29 | [Export] private CheckButton viewReprojectionCheck; 30 | [Export] private Slider parallaxSlider; 31 | [Export] private Slider offsetSlider; 32 | [Export] private CheckButton showDepthCheck; 33 | 34 | public Vector2I[] resolutions = {new Vector2I(1920, 1080), new Vector2I(1600, 900), new Vector2I(1280, 720), new Vector2I(640, 360)}; 35 | public float[] scales = {2, 1.5f, 1, 0.5f}; 36 | 37 | public override void _Ready() 38 | { 39 | isMenuVisible = Visible; 40 | 41 | temporalAccumulationCheck.ButtonPressed = customRenderer.settings.temporalAccumulation; 42 | checkerboardCheck.ButtonPressed = customRenderer.settings.checkerboard; 43 | 44 | numRays.Value = customRenderer.settings.numRays; 45 | maxBounces.Value = customRenderer.settings.maxBounces; 46 | 47 | slider.ValueChanged += (value) => { 48 | shaderMaterial.SetShaderParameter("t", value); 49 | }; 50 | 51 | renderResolutionOptions.ItemSelected += (index) => { 52 | if(index >= resolutions.Length || index < 0) return; 53 | 54 | customRenderer.UpdateRenderResolution(resolutions[index]); 55 | 56 | if(viewReprojectionCheck.ButtonPressed) { 57 | camera.CullMask = projectedViewCameraMask; 58 | } else { 59 | camera.CullMask = defaultCameraMask; 60 | } 61 | customRenderer.ProjectedViewEnabled = viewReprojectionCheck.ButtonPressed; 62 | }; 63 | 64 | windowResolutionOptions.ItemSelected += (index) => { 65 | if(index >= resolutions.Length || index < 0) return; 66 | 67 | int scaleIndex = (int)Mathf.Clamp(index, 2, 4); 68 | settingsPanel.Scale = new Vector2(scales[scaleIndex], scales[scaleIndex]); 69 | customRenderer.UpdateWindowResolution(resolutions[index]); 70 | }; 71 | 72 | fullScreenCheck.Toggled += (value) => { 73 | windowResolutionOptions.Disabled = value; 74 | 75 | if(value) { 76 | customRenderer.UpdateWindowResolution(DisplayServer.ScreenGetSize()); 77 | DisplayServer.WindowSetMode(DisplayServer.WindowMode.Fullscreen); 78 | } else { 79 | GD.Print(resolutions[windowResolutionOptions.Selected]); 80 | DisplayServer.WindowSetMode(DisplayServer.WindowMode.Windowed); 81 | customRenderer.UpdateWindowResolution(resolutions[windowResolutionOptions.Selected]); 82 | } 83 | }; 84 | 85 | numRays.ValueChanged += (value) => { 86 | customRenderer.settings.numRays = (uint)value; 87 | customRenderer.UpdateSettings(); 88 | }; 89 | 90 | maxBounces.ValueChanged += (value) => { 91 | customRenderer.settings.maxBounces = (uint)value; 92 | customRenderer.UpdateSettings(); 93 | }; 94 | 95 | targetFPS.ValueChanged += (value) => { 96 | customRenderer.interval = 1.0 / value; 97 | }; 98 | 99 | temporalAccumulationCheck.Toggled += (value) => { 100 | customRenderer.settings.temporalAccumulation = value; 101 | customRenderer.UpdateSettings(); 102 | }; 103 | 104 | recentFrameBias.ValueChanged += (value) => { 105 | customRenderer.settings.recentFrameBias = (float)value; 106 | if(customRenderer.settings.temporalAccumulation) { 107 | customRenderer.UpdateSettings(); 108 | } 109 | }; 110 | 111 | checkerboardCheck.Toggled += (value) => { 112 | customRenderer.settings.checkerboard = value; 113 | customRenderer.UpdateSettings(); 114 | }; 115 | 116 | viewReprojectionCheck.Toggled += (value) => { 117 | slider.Value = 1.0f; 118 | 119 | if(value) { 120 | camera.CullMask = projectedViewCameraMask; 121 | } else { 122 | camera.CullMask = defaultCameraMask; 123 | } 124 | customRenderer.ProjectedViewEnabled = value; 125 | }; 126 | 127 | parallaxSlider.ValueChanged += (value) => { 128 | projectionShaderMaterial.SetShaderParameter("depthMultiplier", value); 129 | }; 130 | 131 | offsetSlider.ValueChanged += (value) => { 132 | projectionShaderMaterial.SetShaderParameter("offsetMultiplier", value); 133 | }; 134 | 135 | showDepthCheck.Toggled += (value) => { 136 | shaderMaterial.SetShaderParameter("depth", value); 137 | projectionShaderMaterial.SetShaderParameter("depth", value); 138 | }; 139 | } 140 | 141 | public override void _Process(double delta) { 142 | currentFPS.Text = Engine.GetFramesPerSecond().ToString(); 143 | } 144 | 145 | public override void _Input(InputEvent @event) 146 | { 147 | // Toggle menu visibility with the Tab key 148 | if (@event.IsActionPressed("toggle_menu")) 149 | { 150 | isMenuVisible = !isMenuVisible; 151 | Visible = isMenuVisible; 152 | } 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /Shader/compute_rays.glsl: -------------------------------------------------------------------------------- 1 | #[compute] 2 | #version 450 3 | 4 | // #include "res://Shader/rtx_utilities.gdshaderinc" 5 | 6 | struct Light { 7 | float positionX; 8 | float positionY; 9 | float positionZ; 10 | float colorR; 11 | float colorG; 12 | float colorB; 13 | float energy; 14 | bool isDirectionalLight; 15 | float directionX; 16 | float directionY; 17 | float directionZ; 18 | }; 19 | 20 | struct Surface { 21 | float positionX; 22 | float positionY; 23 | float positionZ; 24 | float rotationX; 25 | float rotationY; 26 | float rotationZ; 27 | float scaleX; 28 | float scaleY; 29 | float scaleZ; 30 | float boxMinX; 31 | float boxMinY; 32 | float boxMinZ; 33 | float boxMaxX; 34 | float boxMaxY; 35 | float boxMaxZ; 36 | int materialID; 37 | int indexStart; 38 | int indexEnd; 39 | }; 40 | 41 | struct Sphere { 42 | float positionX; 43 | float positionY; 44 | float positionZ; 45 | // float rotationX; 46 | // float rotationY; 47 | // float rotationZ; 48 | float scaleX; 49 | float scaleY; 50 | float scaleZ; 51 | float boxMinX; 52 | float boxMinY; 53 | float boxMinZ; 54 | float boxMaxX; 55 | float boxMaxY; 56 | float boxMaxZ; 57 | int materialID; 58 | float radius; 59 | }; 60 | 61 | struct Portal { 62 | float positionX; 63 | float positionY; 64 | float positionZ; 65 | float rotationX; 66 | float rotationY; 67 | float rotationZ; 68 | float width; 69 | float height; 70 | int otherID; 71 | }; 72 | 73 | struct Material { 74 | float albedoR; 75 | float albedoG; 76 | float albedoB; 77 | int textureID; 78 | float specularity; 79 | float emissiveR; 80 | float emissiveG; 81 | float emissiveB; 82 | int emissiveTextureID; 83 | float roughness; 84 | int roughnessTextureID; 85 | float alpha; 86 | int alphaTextureID; 87 | }; 88 | 89 | // Invocations in the (x, y, z) dimension 90 | layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in; 91 | 92 | layout(binding = 0, rgba32f) uniform image2D OUTPUT_TEXTURE; 93 | 94 | layout(binding = 1, std430) restrict buffer SettingsBuffer { 95 | int width; 96 | int height; 97 | uint numRays; 98 | uint maxBounces; 99 | bool temporalAccumulation; 100 | float recentFrameBias; 101 | bool checkerboard; 102 | } settingsBuffer; 103 | 104 | layout(binding = 2, std430) restrict buffer CameraBuffer { 105 | mat4 cameraBufferToWorld; 106 | vec3 worldSpaceCameraPosition; 107 | float width; 108 | float height; 109 | float near; 110 | float frame; 111 | } cameraBuffer; 112 | 113 | layout(binding = 3, std430) restrict buffer LightBuffer { 114 | Light lights[]; 115 | } lightBuffer; 116 | 117 | // Mesh buffer 118 | layout(binding = 4, std430) readonly buffer SurfaceBuffer { 119 | Surface surfaces[]; 120 | } surfaceBuffer; 121 | 122 | // Vertex buffer 123 | layout(binding = 5, std430) readonly buffer VertexBuffer { 124 | float vertices[]; // Or your vertex type 125 | } vertexBuffer; 126 | 127 | layout(binding = 6, std430) readonly buffer NormalBuffer { 128 | float normals[]; // Or your vertex type 129 | } normalBuffer; 130 | 131 | layout(binding = 7, std430) readonly buffer UVBuffer { 132 | vec2 uvs[]; // Or your vertex type 133 | } uvBuffer; 134 | 135 | // Index buffer 136 | layout(binding = 8, std430) readonly buffer IndexBuffer { 137 | int indices[]; 138 | } indexBuffer; 139 | 140 | // Material buffer 141 | layout(binding = 9, std430) readonly buffer MaterialBuffer { 142 | Material materials[]; 143 | } materialBuffer; 144 | 145 | // Spheres buffer 146 | layout(binding = 10, std430) readonly buffer SphereBuffer { 147 | Sphere spheres[]; 148 | } sphereBuffer; 149 | 150 | layout(binding = 11, std430) readonly buffer PortalBuffer { 151 | Portal portals[]; 152 | } portalBuffer; 153 | 154 | // Texture array 155 | // layout(binding = 8) uniform texture2DArray albedoTextures; 156 | 157 | const float FAR = 4000.0f; 158 | const float MAX_DEPTH = 10.0f; 159 | const float SKY_MULT = 0.25f; 160 | const float RAY_POS_NORMAL_NUDGE = 0.01f; 161 | const float TWO_PI = 6.28318530718f; 162 | 163 | struct Ray { 164 | vec3 origin; 165 | vec3 dir; 166 | }; 167 | 168 | struct HitInfo { 169 | bool didHit; 170 | bool frontFace; 171 | float dist; 172 | vec3 point; 173 | vec3 normal; 174 | Material material; 175 | bool portalHit; 176 | int portalID; 177 | vec2 portalUV; 178 | }; 179 | 180 | vec3 GetSkyGradient(Ray ray) { 181 | float t = 0.5f * (ray.dir.y + 1.0f); 182 | vec3 a = vec3(0.239, 0.20, 0.153); 183 | vec3 b = vec3(1, 1, 1); 184 | vec3 c = vec3(0.5882, 0.7137, 0.8745); 185 | vec3 ab = mix(a, b, smoothstep(0, 0.15, t - 0.4)); 186 | vec3 bc = mix(b, c, smoothstep(0.55, 1, t + 0.2)); 187 | 188 | return mix(ab, bc, smoothstep(0.45, 0.55, t)); 189 | } 190 | 191 | Ray CreateRay(vec3 origin, vec3 dir) { 192 | Ray ray; 193 | ray.origin = origin; 194 | ray.dir = dir; 195 | 196 | return ray; 197 | } 198 | 199 | bool RaySphere(in Ray ray, in vec3 sphereCenter, in float sphereRadius, inout HitInfo hitInfo) 200 | { 201 | vec3 offsetRayOrigin = ray.origin - sphereCenter; 202 | // From the equation: sqrLength(rayOrigin + rayDir * dst) = radius^2 203 | // Solving for dst results in a quadratic equation with coefficients: 204 | float a = dot(ray.dir, ray.dir); // a = 1 (assuming unit vector) 205 | float bHalf = dot(offsetRayOrigin, ray.dir); 206 | float c = dot(offsetRayOrigin, offsetRayOrigin) - sphereRadius * sphereRadius; 207 | // Quadratic discriminant 208 | float discriminant = bHalf * bHalf - a * c; 209 | 210 | // No solution when d < 0 (ray misses sphere) 211 | if (discriminant >= 0.0f) { 212 | // Distance to nearest intersection point (from quadratic formula) 213 | float dist = (-bHalf - sqrt(discriminant)) / a; 214 | 215 | // Ignore intersections that occur behind the ray 216 | if (dist >= 0.0f && dist < hitInfo.dist) { 217 | hitInfo.didHit = true; 218 | hitInfo.dist = dist; 219 | hitInfo.point = ray.origin + ray.dir * dist; 220 | hitInfo.normal = normalize(hitInfo.point - sphereCenter); 221 | return true; 222 | } 223 | 224 | hitInfo.frontFace = dot(ray.dir, hitInfo.normal) <= 0.0f; 225 | } 226 | 227 | return false; 228 | } 229 | 230 | bool RayTriangle(in Ray ray, vec3 a, vec3 b, vec3 c, vec3 normA, vec3 normB, vec3 normC, inout HitInfo hitInfo) 231 | { 232 | vec3 edge1 = b - a; 233 | vec3 edge2 = c - a; 234 | vec3 h = cross(ray.dir, edge2); 235 | float a_dot_edge1 = dot(edge1, h); 236 | 237 | if (a_dot_edge1 > -1E-6 && a_dot_edge1 < 1E-6) { 238 | return false; // Ray and triangle are parallel 239 | } 240 | 241 | float f = 1.0 / a_dot_edge1; 242 | vec3 s = ray.origin - a; 243 | float u = f * dot(s, h); 244 | 245 | if (u < 0.0 || u > 1.0) { 246 | return false; 247 | } 248 | 249 | vec3 q = cross(s, edge1); 250 | float v = f * dot(ray.dir, q); 251 | 252 | if (v < 0.0 || u + v > 1.0) { 253 | return false; 254 | } 255 | 256 | float t = f * dot(edge2, q); 257 | 258 | if (t > 1E-6 && t < hitInfo.dist) { 259 | // Calculate the triangle normal based on the barycentric coordinates 260 | vec3 normal = normalize(normA * (1.0 - u - v) + normB * u + normC * v); 261 | 262 | // Calculate the dot product between ray direction and triangle normal 263 | float dotProduct = dot(normal, ray.dir); 264 | 265 | // Check if the hit is from the front side of the triangle 266 | if (dotProduct > 0.0) { 267 | return false; // Return false if hit is from the back side 268 | } 269 | 270 | hitInfo.didHit = true; 271 | hitInfo.dist = t; 272 | hitInfo.point = ray.origin + ray.dir * t; 273 | 274 | // Set the hitInfo normal to the calculated normal 275 | hitInfo.normal = normal; 276 | 277 | return true; 278 | } 279 | 280 | return false; 281 | } 282 | 283 | bool RayPortalRect(Ray ray, Portal portal, out float t, out vec2 uv) { 284 | vec3 rectCenter = vec3(portal.positionX, portal.positionY, portal.positionZ); 285 | vec3 dir = normalize(ray.dir); 286 | 287 | // Apply inverse rotation to the ray and rectangle 288 | vec3 rayOriginRotated = ray.origin - rectCenter; 289 | vec3 rayOriginInvRot = mat3( 290 | vec3(portal.rotationX, 0, 0), 291 | vec3(0, portal.rotationY, 0), 292 | vec3(0, 0, portal.rotationZ) 293 | ) * rayOriginRotated; 294 | 295 | vec3 rayDirInvRot = mat3( 296 | vec3(portal.rotationX, 0, 0), 297 | vec3(0, portal.rotationY, 0), 298 | vec3(0, 0, portal.rotationZ) 299 | ) * dir; 300 | 301 | // Calculate intersection with the rotated rectangle 302 | vec3 p = rayOriginInvRot / rayDirInvRot; 303 | 304 | t = p.x; 305 | uv.x = p.y; 306 | uv.y = p.z; 307 | 308 | if (t > 0.0 && uv.x >= 0.0 && uv.x <= portal.width && uv.y >= 0.0 && uv.y <= portal.height) { 309 | return true; 310 | } 311 | 312 | return false; 313 | } 314 | 315 | bool IntersectAABB(vec3 rayOrigin, vec3 rayDir, vec3 boxMin, vec3 boxMax) { 316 | vec3 tMin = (boxMin - rayOrigin) / rayDir; 317 | vec3 tMax = (boxMax - rayOrigin) / rayDir; 318 | vec3 t1 = min(tMin, tMax); 319 | vec3 t2 = max(tMin, tMax); 320 | float tNear = max(max(t1.x, t1.y), t1.z); 321 | float tFar = min(min(t2.x, t2.y), t2.z); 322 | return (tNear > tFar); 323 | } 324 | 325 | uint WangHash(inout uint seed) 326 | { 327 | seed = uint(seed ^ uint(61)) ^ uint(seed >> uint(16)); 328 | seed *= uint(9); 329 | seed = seed ^ (seed >> 4u); 330 | seed *= uint(0x27d4eb2d); 331 | seed = seed ^ (seed >> 15u); 332 | return seed; 333 | } 334 | 335 | float RandomFloat01(inout uint state) 336 | { 337 | return float(WangHash(state)) / 4294967296.0; 338 | } 339 | 340 | vec3 RandomUnitVector(inout uint state) 341 | { 342 | float z = RandomFloat01(state) * 2.0 - 1.0; 343 | float a = RandomFloat01(state) * TWO_PI; 344 | float r = sqrt(1.0 - z * z); 345 | float x = r * cos(a); 346 | float y = r * sin(a); 347 | return vec3(x, y, z); 348 | } 349 | 350 | mat3 rotationXMatrix(float angle) { 351 | float cosAngle = cos(angle); 352 | float sinAngle = sin(angle); 353 | 354 | return mat3( 355 | vec3(1.0, 0.0, 0.0), 356 | vec3(0.0, cosAngle, -sinAngle), 357 | vec3(0.0, sinAngle, cosAngle) 358 | ); 359 | } 360 | 361 | mat3 rotationYMatrix(float angle) { 362 | float cosAngle = cos(angle); 363 | float sinAngle = sin(angle); 364 | 365 | return mat3( 366 | vec3(cosAngle, 0.0, sinAngle), 367 | vec3(0.0, 1.0, 0.0), 368 | vec3(-sinAngle, 0.0, cosAngle) 369 | ); 370 | } 371 | 372 | mat3 rotationZMatrix(float angle) { 373 | float cosAngle = cos(angle); 374 | float sinAngle = sin(angle); 375 | 376 | return mat3( 377 | vec3(cosAngle, -sinAngle, 0.0), 378 | vec3(sinAngle, cosAngle, 0.0), 379 | vec3(0.0, 0.0, 1.0) 380 | ); 381 | } 382 | 383 | void TraceScene(in Ray ray, inout HitInfo hitInfo) { 384 | Surface surface; 385 | Sphere sphere; 386 | Material material; 387 | Ray offsetRay; 388 | 389 | Material defaultMaterial; 390 | defaultMaterial.albedoR = 1; 391 | defaultMaterial.albedoG = 0; 392 | defaultMaterial.albedoB = 1; 393 | defaultMaterial.emissiveR = 1; 394 | defaultMaterial.emissiveG = 0; 395 | defaultMaterial.emissiveB = 1; 396 | defaultMaterial.roughness = 0.5f; 397 | defaultMaterial.alpha = 1.0f; 398 | 399 | defaultMaterial.textureID = -1; 400 | defaultMaterial.emissiveTextureID = -1; 401 | defaultMaterial.roughnessTextureID = -1; 402 | defaultMaterial.alphaTextureID = -1; 403 | 404 | for(int i=0; i < surfaceBuffer.surfaces.length(); i++) { 405 | surface = surfaceBuffer.surfaces[i]; 406 | vec3 position = vec3(surface.positionX, surface.positionY, surface.positionZ); 407 | vec3 boxMin = vec3(surface.boxMinX, surface.boxMinY, surface.boxMinZ); 408 | vec3 boxMax = vec3(surface.boxMaxX, surface.boxMaxY, surface.boxMaxZ); 409 | 410 | mat3 rotationMatrix = rotationZMatrix(surface.rotationZ) * rotationYMatrix(surface.rotationY) * rotationXMatrix(surface.rotationX); 411 | mat3 scaleMatrix = mat3( 412 | vec3(surface.scaleX, 0.0, 0.0), 413 | vec3(0.0, surface.scaleY, 0.0), 414 | vec3(0.0, 0.0, surface.scaleZ) 415 | ); 416 | mat3 transformMatrix = rotationMatrix * scaleMatrix; 417 | 418 | if(IntersectAABB(ray.origin - position, ray.dir, transformMatrix * boxMin, transformMatrix * boxMax)) { 419 | continue; 420 | } 421 | 422 | if(surface.materialID >= 0) { 423 | material = materialBuffer.materials[surface.materialID]; 424 | } else { 425 | material = defaultMaterial; 426 | } 427 | 428 | for(int j=surface.indexStart; j= 0) { 477 | material = materialBuffer.materials[sphere.materialID]; 478 | } else { 479 | material = defaultMaterial; 480 | } 481 | 482 | if(RaySphere(ray, position, sphere.radius, hitInfo)) { 483 | hitInfo.material = material; 484 | } 485 | } 486 | 487 | for(int i=0; i < portalBuffer.portals.length(); i++) { 488 | Portal portal = portalBuffer.portals[i]; 489 | float t; 490 | vec2 uv; 491 | 492 | if (RayPortalRect(ray, portal, t, uv)) { 493 | if (!hitInfo.didHit || t < hitInfo.dist) { 494 | hitInfo.didHit = true; 495 | hitInfo.dist = t; 496 | hitInfo.point = ray.origin + t * ray.dir; 497 | hitInfo.portalHit = true; 498 | hitInfo.portalID = portal.otherID; 499 | hitInfo.portalUV = uv; 500 | } 501 | } 502 | } 503 | } 504 | 505 | bool Refract(vec3 incidentDir, vec3 normal, float refractiveIndex, out vec3 refractedDir) 506 | { 507 | float cosThetaIncident = dot(incidentDir, normal); 508 | float discriminant = 1.0 - refractiveIndex * refractiveIndex * (1.0 - cosThetaIncident * cosThetaIncident); 509 | 510 | if (discriminant > 0.0) { 511 | refractedDir = refractiveIndex * (incidentDir - normal * cosThetaIncident) - normal * sqrt(discriminant); 512 | return true; 513 | } else { 514 | refractedDir = vec3(0.0); 515 | return false; // Total internal reflection 516 | } 517 | } 518 | 519 | Ray RayPortal(Ray currentRay, HitInfo hitInfo) { 520 | Portal portal = portalBuffer.portals[hitInfo.portalID]; 521 | 522 | vec3 position = vec3(portal.positionX, portal.positionY, portal.positionZ); 523 | 524 | vec3 portalNormal = normalize(mat3( 525 | vec3(portal.rotationX, 0, 0), 526 | vec3(0, portal.rotationY, 0), 527 | vec3(0, 0, portal.rotationZ) 528 | ) * cross(vec3(0, 0, 1), vec3(0, 1, 0))); 529 | 530 | vec3 offsetPoint = position + portalNormal * 0.001; // Offset the point slightly to avoid self-intersection 531 | 532 | vec3 exitDirection = reflect(currentRay.dir, portalNormal); 533 | vec3 exitOrigin = offsetPoint + exitDirection * 0.001; // Offset the origin slightly to avoid starting inside the portal 534 | 535 | Ray newRay; 536 | newRay.origin = exitOrigin; 537 | newRay.dir = exitDirection; 538 | 539 | return newRay; 540 | } 541 | 542 | vec4 GetColorForRay(in Ray ray, inout uint rngState) 543 | { 544 | vec3 ret = vec3(0.0f, 0.0f, 0.0f); 545 | float depth = 1; 546 | vec3 throughput = vec3(1.0f, 1.0f, 1.0f); 547 | 548 | Ray nextRay; 549 | nextRay.origin = ray.origin; 550 | nextRay.dir = ray.dir; 551 | 552 | for(uint rayIndex = 0u; rayIndex <= settingsBuffer.numRays; ++rayIndex) { 553 | for (uint bounceIndex = 0u; bounceIndex <= settingsBuffer.maxBounces; ++bounceIndex) 554 | { 555 | // shoot a ray out into the world 556 | HitInfo hitInfo; 557 | hitInfo.dist = FAR; 558 | TraceScene(nextRay, hitInfo); 559 | 560 | // if the ray missed, we are done 561 | if (hitInfo.dist == FAR) { 562 | vec3 skyColor = GetSkyGradient(ray) / settingsBuffer.numRays; 563 | ret += skyColor * throughput * 0.5f; 564 | if(rayIndex == 0 && bounceIndex == 0u) depth = 1.0f; 565 | break; 566 | } else { 567 | if(rayIndex == 0 && bounceIndex == 0u) depth = hitInfo.dist / MAX_DEPTH; 568 | } 569 | 570 | if(hitInfo.portalHit) { 571 | ret = vec3(0,0,0); 572 | return vec4(ret, 0); 573 | 574 | nextRay = RayPortal(nextRay, hitInfo); 575 | } else { 576 | 577 | // update the ray position 578 | nextRay.origin = (nextRay.origin + nextRay.dir * hitInfo.dist) + hitInfo.normal * RAY_POS_NORMAL_NUDGE; 579 | 580 | Material mat = hitInfo.material; 581 | 582 | // calculate whether we are going to do a diffuse or specular reflection ray 583 | float doSpecular = (RandomFloat01(rngState) < hitInfo.material.specularity) ? 1.0f : 0.0f; 584 | 585 | // Calculate a new ray direction. 586 | // Diffuse uses a normal oriented cosine weighted hemisphere sample. 587 | // Perfectly smooth specular uses the reflection ray. 588 | // Rough (glossy) specular lerps from the smooth specular to the rough diffuse by the material roughness squared 589 | // Squaring the roughness is just a convention to make roughness feel more linear perceptually. 590 | vec3 diffuseRayDir = normalize(hitInfo.normal + RandomUnitVector(rngState)); 591 | vec3 specularRayDir = reflect(ray.dir, hitInfo.normal); 592 | specularRayDir = normalize(mix(specularRayDir, diffuseRayDir, mat.roughness)); 593 | nextRay.dir = mix(diffuseRayDir, specularRayDir, doSpecular); 594 | 595 | // add in emissive lighting 596 | ret += vec3(mat.emissiveR, mat.emissiveG, mat.emissiveB) * throughput; 597 | 598 | // Loop through all lights 599 | for (int lightIndex = 0; lightIndex < lightBuffer.lights.length(); lightIndex++) { 600 | Light light = lightBuffer.lights[lightIndex]; 601 | vec3 lightColor = vec3(light.colorR, light.colorG, light.colorB); 602 | if(!light.isDirectionalLight) { 603 | vec3 lightPosition = vec3(light.positionX, light.positionY, light.positionZ); 604 | float dist = distance(hitInfo.point, lightPosition); 605 | if(dist < light.directionX) { 606 | float t = 1.0 - dist / light.directionX; 607 | ret += (lightColor * t * light.energy * 2) / settingsBuffer.numRays; 608 | } 609 | } 610 | } 611 | 612 | // update the colorMultiplier 613 | throughput *= vec3(mat.albedoR, mat.albedoG, mat.albedoB); 614 | 615 | // Russian Roulette 616 | // As the throughput gets smaller, the ray is more likely to get terminated early. 617 | // Survivors have their value boosted to make up for fewer samples being in the average. 618 | { 619 | float p = max(throughput.r, max(throughput.g, throughput.b)); 620 | if (RandomFloat01(rngState) > p) 621 | break; 622 | } 623 | 624 | } 625 | } 626 | } 627 | 628 | // return pixel color 629 | return vec4(ret, depth); 630 | } 631 | 632 | // The code we want to execute in each invocation 633 | void main() { 634 | // gl_GlobalInvocationID.x uniquely identifies this invocation across all work groups 635 | 636 | uint rngState = uint(uint(gl_GlobalInvocationID.x) * uint(1973) + uint(gl_GlobalInvocationID.y) * uint(9277) + cameraBuffer.frame * uint(26699)) | uint(1); 637 | 638 | // calculate subpixel camera jitter for anti aliasing 639 | vec2 jitter = vec2(RandomFloat01(rngState), RandomFloat01(rngState)) - 0.5f; 640 | 641 | // calculate coordinates of the ray target on the imaginary pixel plane. 642 | // -1 to +1 on x,y axis. 1 unit away on the z axis 643 | float u = (gl_GlobalInvocationID.x + jitter.x) / float(settingsBuffer.width); 644 | float v = (gl_GlobalInvocationID.y + jitter.y) / float(settingsBuffer.height); 645 | 646 | // Skip rendering this pixel if it's odd/even compared to last frame, if checkerboard is enabled. 647 | if(settingsBuffer.checkerboard && int(gl_GlobalInvocationID.x+gl_GlobalInvocationID.y)%2 == int(cameraBuffer.frame)%2) { 648 | return; 649 | } 650 | 651 | vec2 uv = vec2(1.0f - u, v); 652 | 653 | vec3 viewLocal = vec3(uv * 2.0f - 1.0f, 1.0f) * vec3(cameraBuffer.width, cameraBuffer.height, cameraBuffer.near); 654 | vec4 view = vec4(viewLocal, 1) * cameraBuffer.cameraBufferToWorld; 655 | vec3 origin = cameraBuffer.worldSpaceCameraPosition; 656 | vec3 dir = -normalize(view.xyz - origin); 657 | Ray ray = CreateRay(origin, dir); 658 | 659 | vec4 color = GetColorForRay(ray, rngState); 660 | 661 | ivec2 texel = ivec2(gl_GlobalInvocationID.xy); 662 | 663 | if(settingsBuffer.temporalAccumulation) { 664 | vec4 lastFrameColor = imageLoad(OUTPUT_TEXTURE, texel); 665 | color = mix(lastFrameColor, color, settingsBuffer.recentFrameBias + 1.0f / float(cameraBuffer.frame + 1)); 666 | } 667 | 668 | imageStore(OUTPUT_TEXTURE, texel, color); 669 | } -------------------------------------------------------------------------------- /Shader/compute_rays.glsl.import: -------------------------------------------------------------------------------- 1 | [remap] 2 | 3 | importer="glsl" 4 | type="RDShaderFile" 5 | uid="uid://dj3uq5qn7g3nh" 6 | path="res://.godot/imported/compute_rays.glsl-f568df4e68e24bf57126c2da17914ebc.res" 7 | 8 | [deps] 9 | 10 | source_file="res://Shader/compute_rays.glsl" 11 | dest_files=["res://.godot/imported/compute_rays.glsl-f568df4e68e24bf57126c2da17914ebc.res"] 12 | 13 | [params] 14 | 15 | -------------------------------------------------------------------------------- /Shader/image_slider.gdshader: -------------------------------------------------------------------------------- 1 | shader_type canvas_item; 2 | 3 | uniform float t: hint_range(0.0, 1.0, 0.001) = 0.5; 4 | uniform bool depth = false; 5 | 6 | void fragment() { 7 | if(depth) { 8 | float depthValue = (1.0 - COLOR.a); 9 | COLOR = vec4(depthValue, depthValue, depthValue, float(UV.x > t)); 10 | } 11 | else { 12 | COLOR = vec4(COLOR.xyz, float(UV.x > t)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Shader/image_slider.material: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gvvim/Godot4-Raytracing/a697682bfe5d4ec6dda5d3147fec506fe28326a9/Shader/image_slider.material -------------------------------------------------------------------------------- /Shader/projected_view.gdshader: -------------------------------------------------------------------------------- 1 | shader_type spatial; 2 | render_mode unshaded; 3 | 4 | uniform sampler2D _Texture : hint_default_white; 5 | uniform bool depth = false; 6 | uniform vec2 angles; 7 | uniform vec2 offset; 8 | uniform vec2 screenSize; 9 | uniform float dist = 0.0f; 10 | uniform float offsetMultiplier = 0.0f; 11 | uniform float depthMultiplier = 0.005f; 12 | 13 | const float TWO_PI = 6.28318530718; 14 | 15 | vec3 LessThan(vec3 f, float value) 16 | { 17 | return vec3( 18 | (f.x < value) ? 1.0f : 0.0f, 19 | (f.y < value) ? 1.0f : 0.0f, 20 | (f.z < value) ? 1.0f : 0.0f); 21 | } 22 | 23 | vec3 SRGBToLinear(vec3 rgb) 24 | { 25 | rgb = clamp(rgb, 0.0f, 1.0f); 26 | 27 | return mix( 28 | pow(((rgb + 0.055f) / 1.055f), vec3(2.4f)), 29 | rgb / 12.92f, 30 | LessThan(rgb, 0.04045f) 31 | ); 32 | } 33 | 34 | float GaussianBlurNoise(vec2 uv, float directions, float quality, float size) 35 | { 36 | vec2 radius = size/screenSize; 37 | 38 | // Pixel colour 39 | float color = texture(_Texture, uv).a; 40 | 41 | // Blur calculations 42 | for( float d=0.0; d("res://Models/sphere_mesh.tres"); 15 | } 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /cornell_box.tscn: -------------------------------------------------------------------------------- 1 | [gd_scene load_steps=13 format=3 uid="uid://bmf463dyukiji"] 2 | 3 | [ext_resource type="Material" uid="uid://b3adab3ecdccm" path="res://Materials/light.tres" id="1_6qwuu"] 4 | [ext_resource type="BoxMesh" uid="uid://c26or4k2qjxgi" path="res://Models/wall_mesh.tres" id="1_g3anr"] 5 | [ext_resource type="Material" uid="uid://cctf0t024p5hx" path="res://Materials/red.tres" id="2_xdsjy"] 6 | [ext_resource type="Material" uid="uid://cufwcfdr6tia1" path="res://Materials/green.tres" id="3_pcesb"] 7 | [ext_resource type="Script" path="res://Sphere.cs" id="5_v5vg7"] 8 | [ext_resource type="Material" uid="uid://brpddgwbhesdm" path="res://Materials/reflective.tres" id="5_vwsrh"] 9 | [ext_resource type="SphereMesh" uid="uid://cpos174earq4s" path="res://Models/sphere_mesh.tres" id="6_y5i4f"] 10 | [ext_resource type="Material" uid="uid://b3u3bbmo5hu6t" path="res://Materials/blue.tres" id="8_ena8t"] 11 | [ext_resource type="Material" uid="uid://dmssvjft3r7nf" path="res://Materials/glass.tres" id="9_46u08"] 12 | 13 | [sub_resource type="BoxMesh" id="BoxMesh_78mds"] 14 | 15 | [sub_resource type="BoxMesh" id="BoxMesh_qeefh"] 16 | size = Vector3(2, 0.25, 2) 17 | 18 | [sub_resource type="PlaneMesh" id="PlaneMesh_pt7ih"] 19 | 20 | [node name="CornellBox" type="Node3D"] 21 | 22 | [node name="Wall" type="MeshInstance3D" parent="."] 23 | mesh = ExtResource("1_g3anr") 24 | skeleton = NodePath("../..") 25 | 26 | [node name="Cube" type="MeshInstance3D" parent="."] 27 | transform = Transform3D(0.25, 0, 0, 0, 0.25, 0, 0, 0, 0.25, -0.524779, 0.127299, -0.367543) 28 | material_override = ExtResource("3_pcesb") 29 | mesh = SubResource("BoxMesh_78mds") 30 | skeleton = NodePath("") 31 | 32 | [node name="Wall2" type="MeshInstance3D" parent="."] 33 | transform = Transform3D(1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0, 1, -0.986584) 34 | mesh = ExtResource("1_g3anr") 35 | skeleton = NodePath("../Wall") 36 | 37 | [node name="Light" type="MeshInstance3D" parent="."] 38 | transform = Transform3D(0.2, 0, 0, 0, -0.2, 1.74846e-08, 0, -1.74846e-08, -0.2, 0, 1.94844, -1.74846e-07) 39 | material_override = ExtResource("1_6qwuu") 40 | mesh = SubResource("BoxMesh_qeefh") 41 | skeleton = NodePath("../Wall2") 42 | 43 | [node name="Wall3" type="MeshInstance3D" parent="."] 44 | transform = Transform3D(1, 0, 0, 0, -1, 8.74228e-08, 0, -8.74228e-08, -1, 0, 2, 0) 45 | mesh = ExtResource("1_g3anr") 46 | skeleton = NodePath("../Wall2") 47 | 48 | [node name="Wall4" type="MeshInstance3D" parent="."] 49 | transform = Transform3D(-4.37114e-08, 1, -1.31134e-07, 0, 1.31134e-07, 1, 1, 4.37114e-08, 0, -1, 1, -5.96046e-08) 50 | material_override = ExtResource("2_xdsjy") 51 | mesh = ExtResource("1_g3anr") 52 | skeleton = NodePath("../Wall") 53 | 54 | [node name="Wall5" type="MeshInstance3D" parent="."] 55 | transform = Transform3D(-4.37114e-08, -1, 2.18557e-07, 0, -2.18557e-07, -1, 1, -4.37114e-08, 0, 1, 1, 5.96046e-08) 56 | material_override = ExtResource("3_pcesb") 57 | mesh = ExtResource("1_g3anr") 58 | skeleton = NodePath("../Wall3") 59 | 60 | [node name="Wall6" type="MeshInstance3D" parent="."] 61 | transform = Transform3D(1, 0, 0, 0, 1.31134e-07, 1, 0, -1, 1.31134e-07, 0, 1, 1) 62 | visible = false 63 | mesh = SubResource("PlaneMesh_pt7ih") 64 | skeleton = NodePath("../Wall3") 65 | 66 | [node name="Sphere" type="MeshInstance3D" parent="."] 67 | transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1.01393, 0) 68 | material_override = ExtResource("5_vwsrh") 69 | mesh = ExtResource("6_y5i4f") 70 | script = ExtResource("5_v5vg7") 71 | 72 | [node name="Sphere2" type="MeshInstance3D" parent="."] 73 | transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.724151, 0.290013, 0) 74 | material_override = ExtResource("8_ena8t") 75 | mesh = ExtResource("6_y5i4f") 76 | skeleton = NodePath("../Sphere") 77 | script = ExtResource("5_v5vg7") 78 | 79 | [node name="Sphere3" type="MeshInstance3D" parent="."] 80 | transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.199886, 0.290013, -0.578323) 81 | material_override = ExtResource("2_xdsjy") 82 | mesh = ExtResource("6_y5i4f") 83 | skeleton = NodePath("../Sphere") 84 | script = ExtResource("5_v5vg7") 85 | 86 | [node name="Sphere4" type="MeshInstance3D" parent="."] 87 | transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.711952, 0.290013, 0.482998) 88 | material_override = ExtResource("9_46u08") 89 | mesh = ExtResource("6_y5i4f") 90 | skeleton = NodePath("../Sphere") 91 | script = ExtResource("5_v5vg7") 92 | -------------------------------------------------------------------------------- /export_presets.cfg: -------------------------------------------------------------------------------- 1 | [preset.0] 2 | 3 | name="Windows Desktop" 4 | platform="Windows Desktop" 5 | runnable=true 6 | dedicated_server=false 7 | custom_features="" 8 | export_filter="all_resources" 9 | include_filter="" 10 | exclude_filter="" 11 | export_path="../raytracer_windows.zip" 12 | encryption_include_filters="" 13 | encryption_exclude_filters="" 14 | encrypt_pck=false 15 | encrypt_directory=false 16 | script_encryption_key="" 17 | 18 | [preset.0.options] 19 | 20 | custom_template/debug="" 21 | custom_template/release="" 22 | debug/export_console_script=1 23 | binary_format/embed_pck=false 24 | texture_format/bptc=true 25 | texture_format/s3tc=true 26 | texture_format/etc=false 27 | texture_format/etc2=false 28 | binary_format/architecture="x86_64" 29 | codesign/enable=false 30 | codesign/identity_type=0 31 | codesign/identity="" 32 | codesign/password="" 33 | codesign/timestamp=true 34 | codesign/timestamp_server_url="" 35 | codesign/digest_algorithm=1 36 | codesign/description="" 37 | codesign/custom_options=PackedStringArray() 38 | application/modify_resources=true 39 | application/icon="" 40 | application/console_wrapper_icon="" 41 | application/icon_interpolation=4 42 | application/file_version="" 43 | application/product_version="" 44 | application/company_name="" 45 | application/product_name="godot_rtx" 46 | application/file_description="" 47 | application/copyright="" 48 | application/trademarks="" 49 | ssh_remote_deploy/enabled=false 50 | ssh_remote_deploy/host="user@host_ip" 51 | ssh_remote_deploy/port="22" 52 | ssh_remote_deploy/extra_args_ssh="" 53 | ssh_remote_deploy/extra_args_scp="" 54 | ssh_remote_deploy/run_script="Expand-Archive -LiteralPath '{temp_dir}\\{archive_name}' -DestinationPath '{temp_dir}' 55 | $action = New-ScheduledTaskAction -Execute '{temp_dir}\\{exe_name}' -Argument '{cmd_args}' 56 | $trigger = New-ScheduledTaskTrigger -Once -At 00:00 57 | $settings = New-ScheduledTaskSettingsSet 58 | $task = New-ScheduledTask -Action $action -Trigger $trigger -Settings $settings 59 | Register-ScheduledTask godot_remote_debug -InputObject $task -Force:$true 60 | Start-ScheduledTask -TaskName godot_remote_debug 61 | while (Get-ScheduledTask -TaskName godot_remote_debug | ? State -eq running) { Start-Sleep -Milliseconds 100 } 62 | Unregister-ScheduledTask -TaskName godot_remote_debug -Confirm:$false -ErrorAction:SilentlyContinue" 63 | ssh_remote_deploy/cleanup_script="Stop-ScheduledTask -TaskName godot_remote_debug -ErrorAction:SilentlyContinue 64 | Unregister-ScheduledTask -TaskName godot_remote_debug -Confirm:$false -ErrorAction:SilentlyContinue 65 | Remove-Item -Recurse -Force '{temp_dir}'" 66 | 67 | [preset.1] 68 | 69 | name="Web" 70 | platform="Web" 71 | runnable=true 72 | dedicated_server=false 73 | custom_features="" 74 | export_filter="all_resources" 75 | include_filter="" 76 | exclude_filter="" 77 | export_path="" 78 | encryption_include_filters="" 79 | encryption_exclude_filters="" 80 | encrypt_pck=false 81 | encrypt_directory=false 82 | script_encryption_key="" 83 | 84 | [preset.1.options] 85 | 86 | custom_template/debug="" 87 | custom_template/release="" 88 | variant/extensions_support=false 89 | vram_texture_compression/for_desktop=true 90 | vram_texture_compression/for_mobile=false 91 | html/export_icon=true 92 | html/custom_html_shell="" 93 | html/head_include="" 94 | html/canvas_resize_policy=2 95 | html/focus_canvas_on_start=true 96 | html/experimental_virtual_keyboard=false 97 | progressive_web_app/enabled=false 98 | progressive_web_app/offline_page="" 99 | progressive_web_app/display=1 100 | progressive_web_app/orientation=0 101 | progressive_web_app/icon_144x144="" 102 | progressive_web_app/icon_180x180="" 103 | progressive_web_app/icon_512x512="" 104 | progressive_web_app/background_color=Color(0, 0, 0, 1) 105 | 106 | [preset.2] 107 | 108 | name="Linux/X11" 109 | platform="Linux/X11" 110 | runnable=true 111 | dedicated_server=false 112 | custom_features="" 113 | export_filter="all_resources" 114 | include_filter="" 115 | exclude_filter="" 116 | export_path="../raytracer_linux.zip" 117 | encryption_include_filters="" 118 | encryption_exclude_filters="" 119 | encrypt_pck=false 120 | encrypt_directory=false 121 | script_encryption_key="" 122 | 123 | [preset.2.options] 124 | 125 | custom_template/debug="" 126 | custom_template/release="" 127 | debug/export_console_script=1 128 | binary_format/embed_pck=false 129 | texture_format/bptc=true 130 | texture_format/s3tc=true 131 | texture_format/etc=false 132 | texture_format/etc2=false 133 | binary_format/architecture="x86_64" 134 | ssh_remote_deploy/enabled=false 135 | ssh_remote_deploy/host="user@host_ip" 136 | ssh_remote_deploy/port="22" 137 | ssh_remote_deploy/extra_args_ssh="" 138 | ssh_remote_deploy/extra_args_scp="" 139 | ssh_remote_deploy/run_script="#!/usr/bin/env bash 140 | export DISPLAY=:0 141 | unzip -o -q \"{temp_dir}/{archive_name}\" -d \"{temp_dir}\" 142 | \"{temp_dir}/{exe_name}\" {cmd_args}" 143 | ssh_remote_deploy/cleanup_script="#!/usr/bin/env bash 144 | kill $(pgrep -x -f \"{temp_dir}/{exe_name} {cmd_args}\") 145 | rm -rf \"{temp_dir}\"" 146 | -------------------------------------------------------------------------------- /icon.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /icon.svg.import: -------------------------------------------------------------------------------- 1 | [remap] 2 | 3 | importer="texture" 4 | type="CompressedTexture2D" 5 | uid="uid://db6c5mtmr36rx" 6 | path="res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex" 7 | metadata={ 8 | "vram_texture": false 9 | } 10 | 11 | [deps] 12 | 13 | source_file="res://icon.svg" 14 | dest_files=["res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"] 15 | 16 | [params] 17 | 18 | compress/mode=0 19 | compress/high_quality=false 20 | compress/lossy_quality=0.7 21 | compress/hdr_compression=1 22 | compress/normal_map=0 23 | compress/channel_pack=0 24 | mipmaps/generate=false 25 | mipmaps/limit=-1 26 | roughness/mode=0 27 | roughness/src_normal="" 28 | process/fix_alpha_border=true 29 | process/premult_alpha=false 30 | process/normal_map_invert_y=false 31 | process/hdr_as_srgb=false 32 | process/hdr_clamp_exposure=false 33 | process/size_limit=0 34 | detect_3d/compress_to=1 35 | svg/scale=1.0 36 | editor/scale_with_editor_scale=false 37 | editor/convert_colors_with_editor_theme=false 38 | -------------------------------------------------------------------------------- /project.godot: -------------------------------------------------------------------------------- 1 | ; Engine configuration file. 2 | ; It's best edited using the editor UI and not directly, 3 | ; since the parameters that go here are not all obvious. 4 | ; 5 | ; Format: 6 | ; [section] ; section goes between [] 7 | ; param=value ; assign values to parameters 8 | 9 | config_version=5 10 | 11 | [application] 12 | 13 | config/name="RTX" 14 | run/main_scene="res://Main.scn" 15 | config/features=PackedStringArray("4.0", "C#", "Forward Plus") 16 | config/icon="res://icon.svg" 17 | 18 | [display] 19 | 20 | window/size/viewport_width=1280 21 | window/size/viewport_height=720 22 | window/size/resizable=false 23 | 24 | [dotnet] 25 | 26 | project/assembly_name="RTX" 27 | 28 | [filesystem] 29 | 30 | import/fbx/enabled=false 31 | 32 | [input] 33 | 34 | toggle_menu={ 35 | "deadzone": 0.5, 36 | "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194306,"key_label":0,"unicode":0,"echo":false,"script":null) 37 | ] 38 | } 39 | -------------------------------------------------------------------------------- /sphere.tscn: -------------------------------------------------------------------------------- 1 | [gd_scene load_steps=3 format=3 uid="uid://vult6hvyjien"] 2 | 3 | [ext_resource type="Script" path="res://RTMaterial.cs" id="1_yvcjp"] 4 | 5 | [sub_resource type="SphereMesh" id="SphereMesh_g5ct1"] 6 | radius = 0.05 7 | height = 0.1 8 | 9 | [node name="Sphere" type="MeshInstance3D"] 10 | transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.535751, 0, -4.88169) 11 | mesh = SubResource("SphereMesh_g5ct1") 12 | script = ExtResource("1_yvcjp") 13 | --------------------------------------------------------------------------------