Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Minimal Example of Updating Sky Reflection and Ambient SH

Discussion in 'Global Illumination' started by ferretnt, May 24, 2019.

  1. ferretnt

    ferretnt

    Joined:
    Apr 10, 2012
    Posts:
    412
    Is there a minimal example, anywhere, that shows how to update a procedural skybox such that objects in the scene are updating their sky environment reflection and ambient (SH) light per-frame as the sunlight rotates.

    Consider a scene containing only a camera, a directional light, and a sphere. Suppose that the only directional light (the sun) is set to an intensity of 0.01 so it is almost negligible, and we make the atmosphere on the skybox really thick to exaggerate it 2019-05-23 (5).png 2019-05-23 (6).png . Suppose that in edit mode the scene looks like [screenshot 1] this when the sun is low to the horizon, and [screenshot 2] when it's overhead, and assume that all lighting in the scene is coming from environment lighting and environment reflections (which is easy to prove by turning their lighting settings to zero.) We're not in PlayMode, "auto generate lighting is checked", and the only difference between the screenshots is that light.Transform.x is changed from 0.0 to 90.0.

    Now, what exactly do we have to do to make that lighting update identically at runtime, in playmode, on an arbitrary device (possibly ios, etc.) and have the environment lighting (presumbaly internally an SH), and environment reflections update identically to edit mode? Googling reveals a massive number of hits for people trying LightProbes, ReflectionProbes, changing bits of qualitysettings, calling ReflectionProbe.RenderProbes(), etc.

    We cannot replicate the behavior identically between the simple case in the editor when auto-update is enabled, and runtime with any combination of things. Half the posts read like people trying things at random then suggesting things work

    Things that are clearly not suffient:
    Enabling DynamicGI.SynchronousMode.
    Calling DynamicGI.UpdateEnvironment

    Enabling Dynamic Reflection Probes in PlayerSettings and creating a reflection probe which we set to "realtime".

    It feels like a simple example of placing a sphere in the scene and updating environment as the sun moves should be available in a minimally correct form somewhere.

    Unity 2018.4.x.
     
  2. ferretnt

    ferretnt

    Joined:
    Apr 10, 2012
    Posts:
    412
    Nobody?

    I still can't get a minimal example of a reflective metallic sphere to update the sky reflection texture at runtime. The diffuse case seems to work OK provided you call DynamicGI.UpdateEnvironment().

    What am I missing?
     
  3. fguinier

    fguinier

    Unity Technologies

    Joined:
    Sep 14, 2015
    Posts:
    146
    I guess you are missing the specular part, ie from an up to date reflection probe :)
     
  4. ferretnt

    ferretnt

    Joined:
    Apr 10, 2012
    Posts:
    412
    Thanks for the reply. I have made a working version of this since posting, but I'm not happy about the fact that I can't explain why it's correct, or enough about the interaction of the standard shader with sky/reflection (note we're on mobile so not actually using GI) to satisfy myself it works in all cases. And I'd like to leave this thread in a state such that future graphics programmers who stumble across it can derive all the details (I'm less concerned about lighting artists, and more with programmers trying to understand Unity's lighting and which terms of it are affected by what algorithmically.)

    Yes, I have now made a version that seems to work correctly, but I still feel the docs, or at least the ones I've seen, don't do a great job of explaining how the algorithmic-level terms of the lighting are handled or updated. The docs for, e.g. DynamicGI.UpdateEnvironment() say "Schedules an update of the environment texture", which is super-vague. Which textures? Does is also recompute ambient SH? When does it schedule it for?

    Here's a screenshot of nine spheres (with values of 0, 0.5, 1.0 for metallic and specular.) I've verified that I can make them look the same under various rotations of a single light (which the procedural skybox uses as its sun) both in editor with "Auto Update" enabled and in play mode. I'm assuming device will behave identically to play mode with auto-update disabled, but it's harder to diff screenshots then...

    Through experimentation, I conclude that:

    (1) We must create a Reflection Probe. The sky itself does not update as a reflection probe (?? - what does that mean - update a convolved specular texture, or ???) when you move the light. Note that I can see the sun moving in the metallic objects even if I don't use a reflection probe, so I assume that there are multiple levels of texture here - ? the skybox itself which always gets updated and a convolved version created for the sky by baking but only updated at runtime when using a reflection probe?
    (2) Calling DynamicGI.UpdateEnvironment is also necessary after moving the light even when using a reflection probe otherwise some term isn't updated ??ambient SH?? (see screenshot 2, composed by moving the light after the build has started, and clearly some term of the lighting is different.)

    I don't really understand (a) why there isn't an algorithmic-level description of which function calls update the SH component, which things update convolved map foo and which things update convolved map bar, and which maps the standard shader samples.

    I don't really understand why the sky doesn't behave like a reflection probe, given that we have moved the light and called DynamicGI.UpdateEnvironment().

    As a similar example, in this case I'm assuming DynamicGI.UpdateEnvironment update the SH coefficients used for irradiance, but I'm not using a LightProbe Group to do this, so why do I need a reflection probe to duplicate the sky functionality but not a light probe?

    I don't really understand why the only way to derive all of this stuff is to read the standard shader source code, call functions, and see which maps and coefficients change when you fiddle with stuff? Is there a page of the docs that I'm missing? The more I read shaders, everything for the sky/envmap seems to be passed in the 9-component SH evaluated as ambient, unity_SpecCube0 (is this ultimately a single envmap, and if so why is the sky/refl probe independent as it seems to be), and unity_SpecCube1 (used only with probe interpolation, and not used in my case.) Assuming I'm correct and in the general (mobile) case all lighting is reduced to ambient SH and unity_SpecCube0, there seems to be almost no docs about how/what objects in the scene updates those values at runtime.


    Correct.png NoUpdateEnvironment.png
     
    Last edited: Jun 11, 2019
    hippocoder, Cery_ and Romaleks360 like this.
  5. Romaleks360

    Romaleks360

    Joined:
    Sep 9, 2017
    Posts:
    72
    This must be in the docs for sure
    It would be great to have some API to control this internal reflection probe, at least trigger an async bake as it is done automatically in the editor
     
    stonstad and hippocoder like this.
  6. paradoxical-jay

    paradoxical-jay

    Joined:
    Jan 28, 2020
    Posts:
    8
    We're seeing this problem in our game (on 2019.3.0f3, currently - PC platform/HDRP). We see it with both Procedural Sky and Physical Sky.
    The specular reflection from sky appears fine and up-to-date at all times, but diffuse catches up only at unpredictable times, triggered by unknown events, or never.
    I've thrown everything I could find at it, but had no luck. It sure feels like a bug.
    Would be nice to have some clarity on this, as it's a significant problem for us.
    Edit: standalone build does not seem to exhibit the issue, so maybe this problem is in editor only.
     
    Last edited: Jan 28, 2020
  7. JenniferNordwall

    JenniferNordwall

    Unity Technologies

    Joined:
    Sep 19, 2016
    Posts:
    160
    Hi

    Could you maybe make a small repo project and file this as a bug and we can have a look? Thanks :)
     
  8. sirleto

    sirleto

    Joined:
    Sep 9, 2019
    Posts:
    141
    i may have the same or a similar issue. please tell me if i misunderstood the current test case discussed here.

    my situation:
    simple space game, very empty scene, on load of scene i change 1 skybox face.
    (important hint: as it is a shared material, leaving the PLAY mode and returning to editor it stays the way i changed it until i enter PLAY mode next time).

    after changing 1 skybox face, calling DynamicGI.UpdateEnvironment seem NOT to update the (diffuse spherical harmonics) light probes.

    (i am on unity 2019.3.4f1, building for android, testing with play mode on windows, this behaviour is consistent between play mode and android buil)

    what i am doing in detail:
    -empty space scene (black skybox textures )
    -one face of the skybox material gets exchanged against colorful texture (purple, green, etc.)
    -the exchange happens in a script on MonoBehaviour.Start()
    -when the game is running (MS Windows or Android build) the spherical harmonics still show what was PREVIOUSLY visible (in the editor / before the build)
    -it is NOT updating the spherical harmonics, neither when calling DynamicGI.UpdateEnvironment () nor at any time later (waited for minutes).
    -i also changed all other DynamicGI settings according to documentation, to ensure that it definitely gets updated
    -the scene is very empty, it shouldnt be a performance issue
    -nothing happens while running

    excerpt from my code
    Code (CSharp):
    1. RenderSettings.skybox.SetTexture(active_face, stars[Random.Range(1, stars.Length)]);
    2.  
    3. DynamicGI.materialUpdateTimeSlice = 5000; //5 seconds
    4. DynamicGI.synchronousMode = true;
    5. DynamicGI.UpdateEnvironment();
    6.  
    7. while(DynamicGI.isConverged == false)
    8.     Debug.Log("waiting for GI to converge");
    the Debug.Log message is never shown, so i believe it is not a performance / waiting problem.


    thus it seems the documentation is wrong and the call to DynamicGI.UpdateEnvironment does not update the ambient probes?
     
  9. sirleto

    sirleto

    Joined:
    Sep 9, 2019
    Posts:
    141
    addendum:
    - all my objects are only lit by 1 direction light in scene + 1 very range limited point light + 1 light probe group with 32 light probe spheres inside (spread evenly as a grid of 4x4x2 around <0,0,0>)

    - i have a custom shader that works well but allows to make the SH term to be even more clearly visible.

    -i have static and dynamic meshes

    -i have zero lightmapped objects

    -if i light map one of my static meshes, the load time of the scene goes definitely up by a second or two, and the object propery shows the current skybox face GI (e.g. pink or green light is visible on correct side of otherwhise dark-shadowwed part of the static mesh)

    -even if i add such a lightmap, the spherical harmonics still seem unlit / unchanged / unupdated
     
  10. sirleto

    sirleto

    Joined:
    Sep 9, 2019
    Posts:
    141
    and more information:
    - i am using progressive cpu lightmapper
    - the scene has no fog
    - mixed lighting has baked GI with shadowmask
    - i have checked that the probes are properly used by my meshes, using the Lighting > Scene > Debug Settings > Light Probe Visualization
     
  11. sirleto

    sirleto

    Joined:
    Sep 9, 2019
    Posts:
    141
    and more:
    - i am NOT using Lighting > Scene > Realtime Lighting > Realtime GI (Deprecated)
    - i am using Mixed Lighting > Baked Global Illumination

    .... is this perhaps the problem? it doesnt make any sense to turn it of to only have realtime lights and not mixed anymore (which i believe i want and need), but it seems to solve at least the issue that the probes are not getting updated anymore. is that possible?
     
  12. sirleto

    sirleto

    Joined:
    Sep 9, 2019
    Posts:
    141
    and:

    it feels totall silly and wrong:
    - if i turn OFF Lighting > Scene > Mixed ighting > Baked GI then the spherical harmonics are updated as expected (but all lightmapping is gone, is that correct? or my interpretation?)
    - if i turn it OFF also the preview of spherical harmonics: Light > Scene > Debug > Light Probe Visualization doesnt show any probes anymore connected to my test mesh, in fact for no mesh at all. as if the feature of light probes via SHs is now disabled (which i believe visually i can tell it is not)
    - if i turn it ON the preview of SH is showing me reasonable ones and the light looks good (while in editor) and in PLAY mode it doesnt update the probes anymore. in fact once i return to editor i can see for a few frames how it looked while in PLAY mode (just from different editor camera perspective) and then the lighting updates to how the scene was randomized (in PLAY mode)

    i have the feeling that
    1. documentation is lacking a lot here to clarify things
    2. editor visualization can have a bug
    3. baked GI setting in editor can have a bug
    4. DynamicGI.Update either has a bug or needs more debug information so its clear what is happening

    please help me to solve what i am doing wrong (or misunderstood) and verify what seem to be bugs in unity
     
  13. KEngelstoft

    KEngelstoft

    Unity Technologies

    Joined:
    Aug 13, 2013
    Posts:
    1,366
    Hi, I have brought this up with the documentation team. I agree that the current state of the ambient docs leave a lot to be desired and we will improve this so your questions can be answered.
     
  14. ferretnt

    ferretnt

    Joined:
    Apr 10, 2012
    Posts:
    412
    Thank you for checking the forum and following up.
     
  15. Arycama

    Arycama

    Joined:
    May 25, 2014
    Posts:
    183
    I've run into this issue too. A solution I've come up with is to
    • Set the RenderSettings Reflection to Custom
    • Create a new Cubemap() via script, assign it to RenderSettings.customReflection
    • Create a RenderTexture matching the Cubemap format
    • Use a command buffer to render each face into the RenderTexture using the skybox shader, using a Sphere
    • Copy each Face into the final Cubemap

    A basic example is below. A few notes:
    • It uses the built-in sphere mesh. Unity's default skybox renders with a smoother mesh which gives better results
    • Mipmaps only use bilinear-downsampling which does not match built-in reflection probes, as they use a special shader.
    • This will generate an uncompressed texture, unlike the built-in probe. However it's possible to use BC6 format and a ComputeShader to compress the Cubemap, which will help with rendering.
    • Realtime reflection probes render and convolve the cubemap faces over several frames which my example doesn't do. You will want to do this for performance reasons.
    A couple of advantages however:
    • You have control over some built-in parameters such as camera position, light color/direction etc.
    • You can enable/disable keywords, for example, you might not want to render the sun, as it will be rendered as a light source during regular rendering.
      • I haven't yet tested, but I'm hoping this will also stop it being included in ambient lighting after calling DynamicGI.UpdateEnvironment too
    • As mentioned above, you can compress the texture at runtime for faster rendering.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3. using UnityEngine.Rendering;
    4.  
    5. [ExecuteAlways]
    6. public class EnvironmentUpdater : MonoBehaviour
    7. {
    8.     private CommandBuffer commandBuffer;
    9.     private Cubemap cubemap;
    10.     private RenderTexture renderTexture;
    11.  
    12.     private void OnEnable()
    13.     {
    14.         // Initialize cubemap/render texture
    15.         RenderSettings.defaultReflectionMode = DefaultReflectionMode.Custom;
    16.         var resolution = RenderSettings.defaultReflectionResolution;
    17.         renderTexture = new RenderTexture(resolution, resolution, 0, RenderTextureFormat.ARGBHalf) { autoGenerateMips = false, useMipMap = true };
    18.         renderTexture.Create();
    19.  
    20.         var skyboxMaterial = RenderSettings.skybox;
    21.         cubemap = new Cubemap(resolution, TextureFormat.RGBAHalf, true) { filterMode = FilterMode.Trilinear };
    22.         cubemap.Apply(false, true);
    23.  
    24.         RenderSettings.customReflection = cubemap;
    25.  
    26.         // Initialize command buffer
    27.         var mesh = Resources.GetBuiltinResource<Mesh>("Sphere.fbx");
    28.         commandBuffer = new CommandBuffer();
    29.  
    30.         var projectionMatrix = GL.GetGPUProjectionMatrix(Matrix4x4.Perspective(90, 1, 0.1f, 1), true);
    31.         commandBuffer.SetProjectionMatrix(projectionMatrix);
    32.  
    33.         // Matrices for rendering the six cubemap faces
    34.         var matrices = new[] { Matrix4x4.TRS(Vector3.zero, Quaternion.LookRotation(Vector3.right, Vector3.down), -Vector3.one).inverse,
    35.         Matrix4x4.TRS(Vector3.zero, Quaternion.LookRotation(Vector3.left, Vector3.down), -Vector3.one).inverse,
    36.         Matrix4x4.TRS(Vector3.zero, Quaternion.LookRotation(Vector3.up, Vector3.forward), -Vector3.one).inverse,
    37.         Matrix4x4.TRS(Vector3.zero, Quaternion.LookRotation(Vector3.down, Vector3.back), -Vector3.one).inverse,
    38.         Matrix4x4.TRS(Vector3.zero, Quaternion.LookRotation(Vector3.forward, Vector3.down), -Vector3.one).inverse,
    39.         Matrix4x4.TRS(Vector3.zero, Quaternion.LookRotation(Vector3.back, Vector3.down), -Vector3.one).inverse };
    40.  
    41.         // Set the camera to render each face into a temporary texture, and then copy that texture into the final cubemap
    42.         for (var face = CubemapFace.PositiveX; (int)face < 6; face++)
    43.         {
    44.             commandBuffer.SetViewMatrix(matrices[(int)face]);
    45.             commandBuffer.SetRenderTarget(renderTexture, 0);
    46.             commandBuffer.ClearRenderTarget(true, true, Color.clear);
    47.             commandBuffer.DrawMesh(mesh, Matrix4x4.identity, skyboxMaterial);
    48.             commandBuffer.GenerateMips(renderTexture);
    49.             commandBuffer.CopyTexture(renderTexture, 0,cubemap, (int)face);
    50.         }
    51.     }
    52.  
    53.     private void Update()
    54.     {
    55.         Graphics.ExecuteCommandBuffer(commandBuffer);
    56.     }
    57. }
    58.  
     
    Last edited: May 31, 2020
    d11javierv likes this.
  16. Arycama

    Arycama

    Joined:
    May 25, 2014
    Posts:
    183
    I just remembered you can access the global ReflectionProbe with ReflectionProbe.defaultTexture, assuming you have it already baked in-Editor. So you could use this to avoid having to manually create a cubemap. Keep in mind that it may be compressed depending on your settings, so you'll have to set it to uncompressed first.
     
  17. ferretnt

    ferretnt

    Joined:
    Apr 10, 2012
    Posts:
    412
    Did any documentation ever get updated here? We're testing an XR app that instantiates a lot of content, with variable orientations (depending on where the user was looking) and a lot of very finely tuned lighting, and it would be great to say to our client "yes, we're 100% sure everything is right on device."
     
  18. KEngelstoft

    KEngelstoft

    Unity Technologies

    Joined:
    Aug 13, 2013
    Posts:
    1,366
    The ticket's still open with the documentation team. Sorry for the delay.
     
  19. ferretnt

    ferretnt

    Joined:
    Apr 10, 2012
    Posts:
    412
    Hey Kasper, is there any updated info on this? I believe I've reverse-engineered everything I need to know at this point, but it would be great if there were an official explanation.

    Thanks,
    Alex
     
  20. KEngelstoft

    KEngelstoft

    Unity Technologies

    Joined:
    Aug 13, 2013
    Posts:
    1,366
    Hi, the ticket is still with the docs team. It is not forgotten, they are just swamped with requests. I am sorry that it is taking so long.
     
  21. timsoret

    timsoret

    Joined:
    Apr 9, 2015
    Posts:
    16
    Would love an update. Right now, simply changing the sky in real-time in Unity is really challenging, and documentation is completely lacking regarding how it affects all the subsystems (fog, ambient lighting, ambient reflection, light probes, reflection probes, fog, etc). Having to manually trigger all these subsystems is really obscure & painful.
     
  22. Cathei

    Cathei

    Joined:
    Dec 18, 2012
    Posts:
    7
    I'd say it's forgotten if it's not updated for more than 2 years from original post.
     
    TorbenDK likes this.
  23. sirleto

    sirleto

    Joined:
    Sep 9, 2019
    Posts:
    141
    i have still the same problem in a new project. a bit sad that there is still no proposal how to do it right.

    adding to my points above:
    - manually (in edit mode) only baking the reflection probe does NOT work.
    - creating a custom reflection probe in scene, configuring it correctly, as in this thread: https://forum.unity.com/threads/reflections-dont-update-when-changing-skybox-at-runtime.529442/ even making sure that special unity shaders are included, does not solve it.
    - @Arycama FYI the ReflectionProbe.defaultTexture is read only, so you cant acess it in a meaning full way (e.g. overwriting it with your own custom probe).
    - obviously only calling DynamicGI.UpdateEnvironment() sounds quite what would help here, but of course is unrelated and doesnt solve the problem.

    i would really like someone to explain to me what the documentation team is supposed to write into the docs, so i can use what i described above ... i dont care when they write it, just for it to be in this thread as soon as possible.

    thanks for any reply,
    Daniel from switzerland
     
    Ghat-Smith and Cery_ like this.
  24. Cery_

    Cery_

    Joined:
    Aug 17, 2012
    Posts:
    48
    I would also really appreciate an update on this!

    My experience so far is very similar. For my case i can use some workarounds.
    Based on @Arycama i can just switch between different preset skybox cubemaps when set to custom.

    One thing to note with this approach is to make sure to include Mipmaps and cubemap convolution in the Texture/Import settings of the chosen cubemap. Otherwise the roughness/smoothness property of materials doesn't really work.
     
  25. sirleto

    sirleto

    Joined:
    Sep 9, 2019
    Posts:
    141
    i want to tell what i am currently doing. maybe it is helpful to others:

    for now i have finished my 200+ of hours trying to make practical approaches to GI with skyboxes and light probes and reflection probes, and have decided that its to slow (cpu cost is horrible as nearly nothing which is needed for realtime processing of light probes can be moved to other threads, from https://docs.unity3d.com/ScriptReference/Rendering.SphericalHarmonicsL2.html to Texture2D). so even if you raycast quickly on cpu with https://docs.unity3d.com/ScriptReference/RaycastCommand.html these days, you will not benefit from it as it requires you to build strange architectures (to get the raycasting async) while the most work will still with SphericalHarmonicsL2.Evaluate() and SphericalHarmonicsL2.AddDirectionalLight() and those cant be moved away from mainthread. atleast AFAIK, if someone has better proposals, i am happy to hear.


    so these GI steps remain as realistic paths in summer 2022:


    either use unity free lightamp based gi (i dont want to, as the bake steps are terribly annoying slow for me in my projects, even i have a very good cpu and gpu).

    ENGLIGHTEN https://assetstore.unity.com/packages/essentials/tutorial-projects/the-courtyard-49377


    or go with a full scenery GI solution: i am using voxelization

    LUMINA https://assetstore.unity.com/packag...gi-real-time-voxel-global-illumination-226660



    or use a SSGI solution: maybe you are contempt with a screen spaced gi effect, there are enough available on github and the asset store for built-in + urp + hdrp plus also unity offers free solutions on newest LTS(es).

    H-TRACE https://forum.unity.com/threads/h-trace-global-illumination-and-occlusion.1251273/ SSGI with nice reflection probe fallback

    RADIANT https://assetstore.unity.com/packag...ra-effects/radiant-global-illumination-225934

    SUNFALL https://assetstore.unity.com/packag...fects/sunfall-global-illumination-ssgi-197714



    or go with gi "tricks"

    UPGEN https://assetstore.unity.com/packag...camera-effects/upgen-lighting-standard-173313

    FREE https://assetstore.unity.com/packages/vfx/shaders/gi-light-system-151941
     
    Last edited: Sep 1, 2022