Sign in to follow this  

DX11 [SlimDX][DX11] Device object not being released?

This topic is 2247 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok, so I'm encountering some weirdness with SlimDX + D3D11/DXGI.

I load up my app, switch to full screen mode (I'm doing this manually in code because I think there was an issue with WinForms and DXGI not handling the ALT+ENTER properly, no idea if it's been corrected), click on on textpad (or any other application) outside of the full screen app (the extra application is on another monitor), and I do this a couple of times.

I get this when I close the app:
[code]Total of 0 objects still alive.
D3D11: WARNING: Live Device: Name="ATI Radeon HD 4550 D3D11Device", Addr=0x000000000047EF00, ExtRef=1 [ STATE_CREATION WARNING #2097297: LIVE_DEVICE ]
D3D11: WARNING: Live Query: Name="unnamed", Addr=0x000000001E102CD0, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097280: LIVE_QUERY ]
D3D11: WARNING: Live Sampler: Name="unnamed", Addr=0x000000001E102A20, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097268: LIVE_SAMPLER ]
D3D11: WARNING: Live RasterizerState: Name="unnamed", Addr=0x000000001E102790, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097277: LIVE_RASTERIZERSTATE ]
D3D11: WARNING: Live DepthStencilState: Name="unnamed", Addr=0x000000001E102580, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097274: LIVE_DEPTHSTENCILSTATE ]
D3D11: WARNING: Live BlendState: Name="unnamed", Addr=0x000000001E1023D0, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097271: LIVE_BLENDSTATE ]
D3D11: WARNING: Live Context: Name="unnamed", Addr=0x000000001E0B0B80, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097226: LIVE_CONTEXT ]
D3D11: WARNING: Live Device Child Summary: Device Addr=0x000000000047EF00
Using ID3D11Debug::ReportLiveDeviceObjects with D3D11_RLDO_DETAIL will help drill into object lifetimes. Objects with ExtRef=0 and IntRef=0 will be eventually destroyed through typical Immediate Context usage. However, if the application requires these objects to be destroyed sooner, ClearState followed by Flush on the Immediate Context will realize their destruction.
Live Context: 1
Live Buffer: 0
Live Texture1D: 0
Live Texture2D: 0
Live Texture3D: 0
Live ShaderResourceView: 0
Live RenderTargetView: 0
Live DepthStencilView: 0
Live VertexShader: 0
Live GeometryShader: 0
Live PixelShader: 0
Live InputLayout: 0
Live Sampler: 1
Live BlendState: 1
Live DepthStencilState: 1
Live RasterizerState: 1
Live Query: 1
Live Predicate: 0
Live Counter: 0
Live CommandList: 0
Live HullShader: 0
Live DomainShader: 0
Live ClassInstance: 0
Live ClassLinkage: 0
Live ComputeShader: 0
Live UnorderedAccessView: 0
[ STATE_CREATION WARNING #2097298: LIVE_OBJECT_SUMMARY ]
[/code]


I've noted that there's an external reference to my D3D device object (ExtRef=1), but I'm absolutely certain I've disposed of the device object before the app closes. The weird thing is, if I ALT+ENTER back and forth many times between my application and another, it exits cleanly. Also, SlimDX is reporting that I have no outstanding references. If I run the application and just quit, it exits cleanly, if I run it, switch to full screen, it exits cleanly. It appears to only happen when I've clicked on another application outside of the window.

I'm at a loss as to why this could be happening. Any suggestions?

Share this post


Link to post
Share on other sites
Hope the following helps
I'm assuming Device.ComPointer is an address.


When you call Device.Dispose(),
1. check that Disposed is true
2. check its ComPointer and see if it matches
a. the ComPointer of the device you originally created
b. the ComPointer of the device it's warning about

Share this post


Link to post
Share on other sites
[quote name='jameszhao00' timestamp='1318872341' post='4873539']
Hope the following helps
I'm assuming Device.ComPointer is an address.


When you call Device.Dispose(),
1. check that Disposed is true
2. check its ComPointer and see if it matches
a. the ComPointer of the device you originally created
b. the ComPointer of the device it's warning about
[/quote]

I have confirmed that the pointers are the same, and that the device was not previously disposed. It is still messing up.

Share this post


Link to post
Share on other sites
Some extra info:

I've tested by doing absolutely nothing, no rendering, not even clearing the screen. Just creating a device, and a swap chain. That's it, and I -still- get this popping up. I'm wondering if it's not a SlimDX issue or a driver problem (I think that'd be pretty unlikely)? I walked through my code one line at a time, and it is indeed calling the Dispose method on the device object.


Maybe Promit or Mike can chime in?

Share this post


Link to post
Share on other sites
Hmm.

Try calling the following function repeatedly around your mode switching code

[code]int GetRefCount(ComObject co)
{
Marshal.AddRef(co.ComPtr);
return Marshal.Release(co.ComPtr);
}
[/code]
and see if the reported ref counts matches your expectations / agrees with the non-broken situation.

Share this post


Link to post
Share on other sites
[quote name='Tape_Worm' timestamp='1318879587' post='4873593']
Some extra info:

I've tested by doing absolutely nothing, no rendering, not even clearing the screen. Just creating a device, and a swap chain. That's it, and I -still- get this popping up. I'm wondering if it's not a SlimDX issue or a driver problem (I think that'd be pretty unlikely)? I walked through my code one line at a time, and it is indeed calling the Dispose method on the device object.


Maybe Promit or Mike can chime in?
[/quote]

Actually, I lied a little here. I completely forgot that I'm also creating a render target view as well. However, I am certain that I'm disposing it as my own logging shows the object being created and disposed every time. I'm going to disable it and see what happens.

Share this post


Link to post
Share on other sites
[quote name='Tape_Worm' timestamp='1318883059' post='4873617']
[quote name='Tape_Worm' timestamp='1318879587' post='4873593']
Some extra info:

I've tested by doing absolutely nothing, no rendering, not even clearing the screen. Just creating a device, and a swap chain. That's it, and I -still- get this popping up. I'm wondering if it's not a SlimDX issue or a driver problem (I think that'd be pretty unlikely)? I walked through my code one line at a time, and it is indeed calling the Dispose method on the device object.


Maybe Promit or Mike can chime in?
[/quote]

Actually, I lied a little here. I completely forgot that I'm also creating a render target view as well. However, I am certain that I'm disposing it as my own logging shows the object being created and disposed every time. I'm going to disable it and see what happens.
[/quote]

So, I commented out the code for the render target view, and it stopped messing up the reference count. However, I uncommented the code (1 line at a time, just to see which line might have been causing the issue) and even with the completely uncommented code, it still works. I am baffled. [img]http://public.gamedev.net/public/style_emoticons/default/dry.gif[/img]

I'd like to know why it messed up and said that the device wasn't released (when it definitely was) or else I'm sure it'll bite me in the ass when I'm least suspecting or prepared for it.

Update:
So, I just tried my code from earlier today (which was showing the issue) and now, mysteriously, it too is exiting cleanly. [img]http://public.gamedev.net/public/style_emoticons/default/huh.gif[/img] This just gets weirder and weirder. Edited by Tape_Worm

Share this post


Link to post
Share on other sites
[quote name='jameszhao00' timestamp='1318880299' post='4873597']
Hmm.

Try calling the following function repeatedly around your mode switching code

[code]int GetRefCount(ComObject co)
{
Marshal.AddRef(co.ComPtr);
return Marshal.Release(co.ComPtr);
}
[/code]
and see if the reported ref counts matches your expectations / agrees with the non-broken situation.
[/quote]

So I tried out your code to check the refcount. When I create the D3DDevice, it's got a count of 1 (naturally), and just before I destroy the device, it's got a count of 2, which is kind of odd. I only have a call to CreateSwapChain and the code to create the D3DDevice, so something's amiss. It claims the extra reference is an external reference, but I really have absolutely nothing else in here that's adding to the ref count. It just makes no sense.

Thanks for your help.

Share this post


Link to post
Share on other sites
[quote name='Tape_Worm' timestamp='1318900097' post='4873706']
[quote name='jameszhao00' timestamp='1318880299' post='4873597']
Hmm.

Try calling the following function repeatedly around your mode switching code

[code]int GetRefCount(ComObject co)
{
Marshal.AddRef(co.ComPtr);
return Marshal.Release(co.ComPtr);
}
[/code]
and see if the reported ref counts matches your expectations / agrees with the non-broken situation.
[/quote]

So I tried out your code to check the refcount. When I create the D3DDevice, it's got a count of 1 (naturally), and just before I destroy the device, it's got a count of 2, which is kind of odd. I only have a call to CreateSwapChain and the code to create the D3DDevice, so something's amiss. It claims the extra reference is an external reference, but I really have absolutely nothing else in here that's adding to the ref count. It just makes no sense.

Thanks for your help.
[/quote]

Locating where it broke:

Go into PIX. Select "A replayable Direct3D call stream". Run your app. Break your app. Then in PIX, find (binary search :P) the exact call site where "D3D11 Device" (in the Objects window) has unexpected "App Refs".

Note: To actually view the app refs, for some reason you have to a) select a random frame b) select render. Make sure you're in the Mesh or Render tab when selecting different calls (to force refresh)

Share this post


Link to post
Share on other sites
[quote name='jameszhao00' timestamp='1318902367' post='4873714']
[quote name='Tape_Worm' timestamp='1318900097' post='4873706']
[quote name='jameszhao00' timestamp='1318880299' post='4873597']
Hmm.

Try calling the following function repeatedly around your mode switching code

[code]int GetRefCount(ComObject co)
{
Marshal.AddRef(co.ComPtr);
return Marshal.Release(co.ComPtr);
}
[/code]
and see if the reported ref counts matches your expectations / agrees with the non-broken situation.
[/quote]

So I tried out your code to check the refcount. When I create the D3DDevice, it's got a count of 1 (naturally), and just before I destroy the device, it's got a count of 2, which is kind of odd. I only have a call to CreateSwapChain and the code to create the D3DDevice, so something's amiss. It claims the extra reference is an external reference, but I really have absolutely nothing else in here that's adding to the ref count. It just makes no sense.

Thanks for your help.
[/quote]

Locating where it broke:

Go into PIX. Select "A replayable Direct3D call stream". Run your app. Break your app. Then in PIX, find (binary search :P) the exact call site where "D3D11 Device" (in the Objects window) has unexpected "App Refs".

Note: To actually view the app refs, for some reason you have to a) select a random frame b) select render. Make sure you're in the Mesh or Render tab when selecting different calls (to force refresh)
[/quote]

Thanks for that. I've always had a hell of a time getting PIX to behave itself with .NET apps, and it was a little better tonight.

So, here's what my logging (and your ref counter code) told me before it destroyed the ID3D11Device:
[10/17/2011 08:24:04 PM] D3D Device Ref Count #: 3

So, according to that, there were 3 references to the device.

Then I poured through the calls in PIX, and I found a very different story. The AppRefs never went above 2, and always fell back to 1 (until the final Dispose call on the device object, which then said there were no more references). But, when I turn on the return result I can see in each AddRef/Release from the reference counting code that the values are higher. In some cases, it returns as high as 5. I understand these could be internal references, and as such, and my releasing of my only reference to the ID3D11Device is only going to decrement the count by 1, leaving those other references.

Share this post


Link to post
Share on other sites
So, I stripped everything down to a very minimal application and switching between applications still gives me an unreleased device object.

The funny thing is, if I ALT+TAB back and forth this does not happen when I close. If I click on an external application and go back to my application (multiple times) it gives me the warning about the unreleased device object when I close.

Again, here's the warning for anyone who might have an inkling as to what's going on here:
[code]

Total of 0 objects still alive.
D3D11: WARNING: Live Device: Name="unnamed", Addr=0x00000000005DDEE0, ExtRef=1 [ STATE_CREATION WARNING #2097297: LIVE_DEVICE ]
D3D11: WARNING: Live Texture2D: Name="unnamed", Addr=0x000000001DAF4EC0, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097235: LIVE_TEXTURE2D ]
D3D11: WARNING: Live RenderTargetView: Name="unnamed", Addr=0x000000001DAF9B00, ExtRef=0, IntRef=0 [ STATE_CREATION WARNING #2097244: LIVE_RENDERTARGETVIEW ]
D3D11: WARNING: Live Texture2D: Name="unnamed", Addr=0x000000001DAF43B0, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097235: LIVE_TEXTURE2D ]
D3D11: WARNING: Live Query: Name="unnamed", Addr=0x000000001DAF2190, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097280: LIVE_QUERY ]
D3D11: WARNING: Live Sampler: Name="unnamed", Addr=0x000000001DAF1E00, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097268: LIVE_SAMPLER ]
D3D11: WARNING: Live RasterizerState: Name="unnamed", Addr=0x000000001DAF1A80, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097277: LIVE_RASTERIZERSTATE ]
D3D11: WARNING: Live DepthStencilState: Name="unnamed", Addr=0x000000001DAF1730, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097274: LIVE_DEPTHSTENCILSTATE ]
D3D11: WARNING: Live BlendState: Name="unnamed", Addr=0x000000001DAF11A0, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097271: LIVE_BLENDSTATE ]
D3D11: WARNING: Live Context: Name="unnamed", Addr=0x000000001DAA00B0, ExtRef=0, IntRef=1 [ STATE_CREATION WARNING #2097226: LIVE_CONTEXT ]
D3D11: WARNING: Live Device Child Summary: Device Addr=0x00000000005DDEE0
Using ID3D11Debug::ReportLiveDeviceObjects with D3D11_RLDO_DETAIL will help drill into object lifetimes. Objects with ExtRef=0 and IntRef=0 will be eventually destroyed through typical Immediate Context usage. However, if the application requires these objects to be destroyed sooner, ClearState followed by Flush on the Immediate Context will realize their destruction.
Live Context: 1
Live Buffer: 0
Live Texture1D: 0
Live Texture2D: 2
Live Texture3D: 0
Live ShaderResourceView: 0
Live RenderTargetView: 1
Live DepthStencilView: 0
Live VertexShader: 0
Live GeometryShader: 0
Live PixelShader: 0
Live InputLayout: 0
Live Sampler: 1
Live BlendState: 1
Live DepthStencilState: 1
Live RasterizerState: 1
Live Query: 1
Live Predicate: 0
Live Counter: 0
Live CommandList: 0
Live HullShader: 0
Live DomainShader: 0
Live ClassInstance: 0
Live ClassLinkage: 0
Live ComputeShader: 0
Live UnorderedAccessView: 0
[ STATE_CREATION WARNING #2097298: LIVE_OBJECT_SUMMARY ]
[/code]

I'm about to give up and accept it as part of life, I really hope leaving this this doesn't cause any major issues in the future.

Share this post


Link to post
Share on other sites
I'm not using slimdx but I have the same issue (exact same error message) and I did a pix capture of it.
It happens when you close a full screen application. It doesn't show any warning when in window mode.
.
Did anyone find a solution for this?

[code]
// Initialization
4 D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 2, NULL, 0, 7, 0x0041FD88, 0x0041FDC4 --> 0x05566820, 0x0041FDC8 --> 0x05566070, NULL, 0x0041FDCC --> 0x055D9C78) 1262568822
5 CreateObject(D3D11 Device, 0x05566070) 1651416894
6 CreateObject(DXGI Factory, 0x05566718) 1651427760
7 CreateObject(DXGI Adapter, 0x05566768) 1651429571
8 CreateObject(DXGI Device, 0x055667C0) 1651431081
9 CreateObject(DXGI Swap Chain, 0x05566820) 1651432590
10 CreateObject(DXGI Surface, 0x055668B8) 1651434703
11 CreateObject(D3D11 Texture2D, 0x05566918) 1651437721
12 CreateObject(D3D11 Device Context, 0x055D9C78) 1651451305
13 <0x05566820> IDXGISwapChain::GetBuffer(0, IID_ID3D11Texture2D, 0x0041F67C --> 0x05566918) 1651467907
14 <0x05566070> ID3D11Device::CreateRenderTargetView(0x05566918, NULL, 0x0041F654 --> 0x05566DB8) 1651472133
15 CreateObject(D3D11 Render Target View, 0x05566DB8) 1651537031
16 <0x05566918> ID3D11Texture2D::AddRef() 1651547596
17 <0x05566DB8> ID3D11RenderTargetView::AddRef() 1651549407
18 <0x05566918> ID3D11Texture2D::Release() 1651550614
19 <0x05566DB8> ID3D11RenderTargetView::Release() 1651551520
20 <0x05566DB8> ID3D11RenderTargetView::AddRef() 1651557557

// Update frames ...
21 <0x05566820> IDXGISwapChain::GetFullscreenState(0x0041F778, NULL) 1683438579
22 <0x055D9C78> ID3D11DeviceContext::OMSetRenderTargets(1, 0x05737AA8 --> { 0x05566DB8 }, NULL) 1683450351
23 <0x055D9C78> ID3D11DeviceContext::RSSetViewports(1, 0x0041F52C) 1683475405
24 <0x05566820> IDXGISwapChain::Present(0, 0) 1728516577

...
// Uninitialization
81 <0x05566918> ID3D11Texture2D::Release() 1844018799
82 <0x05566DB8> ID3D11RenderTargetView::Release() 1844024534
83 <0x05566DB8> ID3D11RenderTargetView::Release() 1844029062
84 <0x055D9C78> ID3D11DeviceContext::OMSetRenderTargets(0, NULL, NULL) 1844036306
85 DestroyObject(D3D11 Render Target View, 0x05566DB8) 1844043853
86 <0x055D9C78> ID3D11DeviceContext::Release() 1844049286
87 <0x05566820> IDXGISwapChain::Release() 1844051701
88 DestroyObject(DXGI Swap Chain, 0x05566820) 1844260884
89 DestroyObject(DXGI Surface, 0x055668B8) 1844267223
90 DestroyObject(D3D11 Texture2D, 0x05566918) 1844269940
91 <0x05566070> ID3D11Device::Release() 1844274468
92 DestroyObject(D3D11 Device, 0x05566070) 1844276581
93 DestroyObject(D3D11 Device Context, 0x055D9C78) 1844278694
94 DestroyObject(DXGI Device, 0x055667C0) 1844280807
95 DestroyObject(DXGI Adapter, 0x05566768) 1844282919
[/code]

Seems like the DXGI Factory is not destroyed... I use CreateDeviceAndSwapChain, I do not manage the Factory.
I tried calling "ClearState" and "Flush" just before I release the context but "Flush" crash my application (again only in fullscreen).

Share this post


Link to post
Share on other sites
I fixed my problem by calling "SetFullscreenState(false, NULL);" just before releasing the swap chain. Not sure if its what I should have done in the first place but it kinda makes sense.

Share this post


Link to post
Share on other sites
[quote name='Shnoutz' timestamp='1321760447' post='4885785']
I fixed my problem by calling "SetFullscreenState(false, NULL);" just before releasing the swap chain. Not sure if its what I should have done in the first place but it kinda makes sense.
[/quote]

Yep, Microsoft [url="http://msdn.microsoft.com/en-us/library/windows/desktop/bb174537(v=vs.85).aspx"]recommends you do that before destroying a swap chain[/url]:
[font="Arial"][color=#2A2A2A][/color][quote][color=#2A2A2A]If the swap chain is in full-screen mode, before you release it you must use [/color][url="http://msdn.microsoft.com/en-us/library/windows/desktop/bb174579(v=vs.85).aspx"][b]SetFullscreenState[/b][/url][color=#2A2A2A] to switch it to windowed mode. For more information about releasing a swap chain, see the "Destroying a Swap Chain" section of [/color][url="http://msdn.microsoft.com/en-us/library/windows/desktop/bb205075(v=vs.85).aspx"]DXGI Overview[/url][color=#2A2A2A].[/color][/quote][color=#2A2A2A][/color][/font]
[font="Arial"]
[/font]
[font="Arial"]However, that didn't help with my issue. I just said to hell with it and moved on.[/font]

Share this post


Link to post
Share on other sites

This topic is 2247 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Similar Content

    • By mister345
      Hi, can somebody please tell me in clear simple steps how to debug and step through an hlsl shader file?
      I already did Debug > Start Graphics Debugging > then captured some frames from Visual Studio and
      double clicked on the frame to open it, but no idea where to go from there.
       
      I've been searching for hours and there's no information on this, not even on the Microsoft Website!
      They say "open the  Graphics Pixel History window" but there is no such window!
      Then they say, in the "Pipeline Stages choose Start Debugging"  but the Start Debugging option is nowhere to be found in the whole interface.
      Also, how do I even open the hlsl file that I want to set a break point in from inside the Graphics Debugger?
       
      All I want to do is set a break point in a specific hlsl file, step thru it, and see the data, but this is so unbelievably complicated
      and Microsoft's instructions are horrible! Somebody please, please help.
       
       
       

    • By mister345
      I finally ported Rastertek's tutorial # 42 on soft shadows and blur shading. This tutorial has a ton of really useful effects and there's no working version anywhere online.
      Unfortunately it just draws a black screen. Not sure what's causing it. I'm guessing the camera or ortho matrix transforms are wrong, light directions, or maybe texture resources not being properly initialized.  I didnt change any of the variables though, only upgraded all types and functions DirectX3DVector3 to XMFLOAT3, and used DirectXTK for texture loading. If anyone is willing to take a look at what might be causing the black screen, maybe something pops out to you, let me know, thanks.
      https://github.com/mister51213/DX11Port_SoftShadows
       
      Also, for reference, here's tutorial #40 which has normal shadows but no blur, which I also ported, and it works perfectly.
      https://github.com/mister51213/DX11Port_ShadowMapping
       
    • By xhcao
      Is Direct3D 11 an api function like glMemoryBarrier in OpenGL? For example, if binds a texture to compute shader, compute shader writes some values to texture, then dispatchCompute, after that, read texture content to CPU side. I know, In OpenGL, we could call glMemoryBarrier before reading to assure that texture all content has been updated by compute shader.
      How to handle incoherent memory access in Direct3D 11? Thank you.
    • By _Engine_
      Atum engine is a newcomer in a row of game engines. Most game engines focus on render
      techniques in features list. The main task of Atum is to deliver the best toolset; that’s why,
      as I hope, Atum will be a good light weighted alternative to Unity for indie games. Atum already
      has fully workable editor that has an ability to play test edited scene. All system code has
      simple ideas behind them and focuses on easy to use functionality. That’s why code is minimized
      as much as possible.
      Currently the engine consists from:
      - Scene Editor with ability to play test edited scene;
      - Powerful system for binding properties into the editor;
      - Render system based on DX11 but created as multi API; so, adding support of another GAPI
        is planned;
      - Controls system based on aliases;
      - Font system based on stb_truetype.h;
      - Support of PhysX 3.0, there are samples in repo that use physics;
      - Network code which allows to create server/clinet; there is some code in repo which allows
        to create a simple network game
      I plan to use this engine in multiplayer game - so, I definitely will evolve the engine. Also
      I plan to add support for mobile devices. And of course, the main focus is to create a toolset
      that will ease games creation.
      Link to repo on source code is - https://github.com/ENgineE777/Atum
      Video of work process in track based editor can be at follow link: 
       
       

    • By mister345
      I made a spotlight that
      1. Projects 3d models onto a render target from each light POV to simulate shadows
      2. Cuts a circle out of the square of light that has been projected onto the render target
      as a result of the light frustum, then only lights up the pixels inside that circle 
      (except the shadowed parts of course), so you dont see the square edges of the projected frustum.
       
      After doing an if check to see if the dot product of light direction and light to vertex vector is greater than .95
      to get my initial cutoff, I then multiply the light intensity value inside the resulting circle by the same dot product value,
      which should range between .95 and 1.0.
       
      This should give the light inside that circle a falloff from 100% lit to 0% lit toward the edge of the circle. However,
      there is no falloff. It's just all equally lit inside the circle. Why on earth, I have no idea. If someone could take a gander
      and let me know, please help, thank you so much.
      float CalculateSpotLightIntensity(     float3 LightPos_VertexSpace,      float3 LightDirection_WS,      float3 SurfaceNormal_WS) {     //float3 lightToVertex = normalize(SurfacePosition - LightPos_VertexSpace);     float3 lightToVertex_WS = -LightPos_VertexSpace;          float dotProduct = saturate(dot(normalize(lightToVertex_WS), normalize(LightDirection_WS)));     // METALLIC EFFECT (deactivate for now)     float metalEffect = saturate(dot(SurfaceNormal_WS, normalize(LightPos_VertexSpace)));     if(dotProduct > .95 /*&& metalEffect > .55*/)     {         return saturate(dot(SurfaceNormal_WS, normalize(LightPos_VertexSpace)));         //return saturate(dot(SurfaceNormal_WS, normalize(LightPos_VertexSpace))) * dotProduct;         //return dotProduct;     }     else     {         return 0;     } } float4 LightPixelShader(PixelInputType input) : SV_TARGET {     float2 projectTexCoord;     float depthValue;     float lightDepthValue;     float4 textureColor;     // Set the bias value for fixing the floating point precision issues.     float bias = 0.001f;     // Set the default output color to the ambient light value for all pixels.     float4 lightColor = cb_ambientColor;     /////////////////// NORMAL MAPPING //////////////////     float4 bumpMap = shaderTextures[4].Sample(SampleType, input.tex);     // Expand the range of the normal value from (0, +1) to (-1, +1).     bumpMap = (bumpMap * 2.0f) - 1.0f;     // Change the COORDINATE BASIS of the normal into the space represented by basis vectors tangent, binormal, and normal!     float3 bumpNormal = normalize((bumpMap.x * input.tangent) + (bumpMap.y * input.binormal) + (bumpMap.z * input.normal));     //////////////// LIGHT LOOP ////////////////     for(int i = 0; i < NUM_LIGHTS; ++i)     {     // Calculate the projected texture coordinates.     projectTexCoord.x =  input.vertex_ProjLightSpace[i].x / input.vertex_ProjLightSpace[i].w / 2.0f + 0.5f;     projectTexCoord.y = -input.vertex_ProjLightSpace[i].y / input.vertex_ProjLightSpace[i].w / 2.0f + 0.5f;     if((saturate(projectTexCoord.x) == projectTexCoord.x) && (saturate(projectTexCoord.y) == projectTexCoord.y))     {         // Sample the shadow map depth value from the depth texture using the sampler at the projected texture coordinate location.         depthValue = shaderTextures[6 + i].Sample(SampleTypeClamp, projectTexCoord).r;         // Calculate the depth of the light.         lightDepthValue = input.vertex_ProjLightSpace[i].z / input.vertex_ProjLightSpace[i].w;         // Subtract the bias from the lightDepthValue.         lightDepthValue = lightDepthValue - bias;         float lightVisibility = shaderTextures[6 + i].SampleCmp(SampleTypeComp, projectTexCoord, lightDepthValue );         // Compare the depth of the shadow map value and the depth of the light to determine whether to shadow or to light this pixel.         // If the light is in front of the object then light the pixel, if not then shadow this pixel since an object (occluder) is casting a shadow on it.             if(lightDepthValue < depthValue)             {                 // Calculate the amount of light on this pixel.                 float lightIntensity = saturate(dot(bumpNormal, normalize(input.lightPos_LS[i])));                 if(lightIntensity > 0.0f)                 {                     // Determine the final diffuse color based on the diffuse color and the amount of light intensity.                     float spotLightIntensity = CalculateSpotLightIntensity(                         input.lightPos_LS[i], // NOTE - this is NOT NORMALIZED!!!                         cb_lights[i].lightDirection,                          bumpNormal/*input.normal*/);                     lightColor += cb_lights[i].diffuseColor*spotLightIntensity* .18f; // spotlight                     //lightColor += cb_lights[i].diffuseColor*lightIntensity* .2f; // square light                 }             }         }     }     // Saturate the final light color.     lightColor = saturate(lightColor);    // lightColor = saturate( CalculateNormalMapIntensity(input, lightColor, cb_lights[0].lightDirection));     // TEXTURE ANIMATION -  Sample pixel color from texture at this texture coordinate location.     input.tex.x += textureTranslation;     // BLENDING     float4 color1 = shaderTextures[0].Sample(SampleTypeWrap, input.tex);     float4 color2 = shaderTextures[1].Sample(SampleTypeWrap, input.tex);     float4 alphaValue = shaderTextures[3].Sample(SampleTypeWrap, input.tex);     textureColor = saturate((alphaValue * color1) + ((1.0f - alphaValue) * color2));     // Combine the light and texture color.     float4 finalColor = lightColor * textureColor;     /////// TRANSPARENCY /////////     //finalColor.a = 0.2f;     return finalColor; }  
      Light_vs.hlsl
      Light_ps.hlsl
  • Popular Now