From 1ff6f221fb2a1963fadb48e786ec87d1a9c02fcd Mon Sep 17 00:00:00 2001 From: rextimmy Date: Sun, 20 Mar 2016 21:48:52 +1000 Subject: [PATCH 1/5] Direct3D11 GFX device. --- .../source/gfx/D3D11/gfxD3D11CardProfiler.cpp | 72 + .../source/gfx/D3D11/gfxD3D11CardProfiler.h | 46 + Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp | 352 ++++ Engine/source/gfx/D3D11/gfxD3D11Cubemap.h | 80 + Engine/source/gfx/D3D11/gfxD3D11Device.cpp | 1721 +++++++++++++++++ Engine/source/gfx/D3D11/gfxD3D11Device.h | 295 +++ .../gfx/D3D11/gfxD3D11EnumTranslate.cpp | 155 ++ .../source/gfx/D3D11/gfxD3D11EnumTranslate.h | 51 + .../gfx/D3D11/gfxD3D11OcclusionQuery.cpp | 177 ++ .../source/gfx/D3D11/gfxD3D11OcclusionQuery.h | 58 + .../gfx/D3D11/gfxD3D11PrimitiveBuffer.cpp | 222 +++ .../gfx/D3D11/gfxD3D11PrimitiveBuffer.h | 83 + .../source/gfx/D3D11/gfxD3D11QueryFence.cpp | 110 ++ Engine/source/gfx/D3D11/gfxD3D11QueryFence.h | 49 + Engine/source/gfx/D3D11/gfxD3D11Shader.cpp | 1542 +++++++++++++++ Engine/source/gfx/D3D11/gfxD3D11Shader.h | 471 +++++ .../source/gfx/D3D11/gfxD3D11StateBlock.cpp | 285 +++ Engine/source/gfx/D3D11/gfxD3D11StateBlock.h | 76 + Engine/source/gfx/D3D11/gfxD3D11Target.cpp | 409 ++++ Engine/source/gfx/D3D11/gfxD3D11Target.h | 110 ++ .../gfx/D3D11/gfxD3D11TextureManager.cpp | 587 ++++++ .../source/gfx/D3D11/gfxD3D11TextureManager.h | 62 + .../gfx/D3D11/gfxD3D11TextureObject.cpp | 280 +++ .../source/gfx/D3D11/gfxD3D11TextureObject.h | 89 + .../source/gfx/D3D11/gfxD3D11VertexBuffer.cpp | 233 +++ .../source/gfx/D3D11/gfxD3D11VertexBuffer.h | 95 + Engine/source/gfx/D3D11/screenshotD3D11.cpp | 98 + Engine/source/gfx/D3D11/screenshotD3D11.h | 39 + 28 files changed, 7847 insertions(+) create mode 100644 Engine/source/gfx/D3D11/gfxD3D11CardProfiler.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11CardProfiler.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11Cubemap.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11Device.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11Device.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11PrimitiveBuffer.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11PrimitiveBuffer.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11QueryFence.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11QueryFence.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11Shader.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11Shader.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11StateBlock.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11StateBlock.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11Target.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11Target.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11TextureManager.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11TextureManager.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11TextureObject.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11TextureObject.h create mode 100644 Engine/source/gfx/D3D11/gfxD3D11VertexBuffer.cpp create mode 100644 Engine/source/gfx/D3D11/gfxD3D11VertexBuffer.h create mode 100644 Engine/source/gfx/D3D11/screenshotD3D11.cpp create mode 100644 Engine/source/gfx/D3D11/screenshotD3D11.h diff --git a/Engine/source/gfx/D3D11/gfxD3D11CardProfiler.cpp b/Engine/source/gfx/D3D11/gfxD3D11CardProfiler.cpp new file mode 100644 index 000000000..14c37c63a --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11CardProfiler.cpp @@ -0,0 +1,72 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/D3D11/gfxD3D11CardProfiler.h" +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11EnumTranslate.h" +#include "platformWin32/videoInfo/wmiVideoInfo.h" +#include "console/console.h" +#include "gfx/primBuilder.h" + + +GFXD3D11CardProfiler::GFXD3D11CardProfiler() : GFXCardProfiler() +{ +} + +GFXD3D11CardProfiler::~GFXD3D11CardProfiler() +{ + +} + +void GFXD3D11CardProfiler::init() +{ + U32 adapterIndex = D3D11->getAdaterIndex(); + WMIVideoInfo wmiVidInfo; + if (wmiVidInfo.profileAdapters()) + { + const PlatformVideoInfo::PVIAdapter &adapter = wmiVidInfo.getAdapterInformation(adapterIndex); + + mCardDescription = adapter.description; + mChipSet = adapter.chipSet; + mVersionString = adapter.driverVersion; + mVideoMemory = adapter.vram; + } + Parent::init(); +} + +void GFXD3D11CardProfiler::setupCardCapabilities() +{ + setCapability("maxTextureWidth", D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION); + setCapability("maxTextureHeight", D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION); + setCapability("maxTextureSize", D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION); +} + +bool GFXD3D11CardProfiler::_queryCardCap(const String &query, U32 &foundResult) +{ + return false; +} + +bool GFXD3D11CardProfiler::_queryFormat( const GFXFormat fmt, const GFXTextureProfile *profile, bool &inOutAutogenMips ) +{ + // D3D11 feature level should guarantee that any format is valid! + return GFXD3D11TextureFormat[fmt] != DXGI_FORMAT_UNKNOWN; +} \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11CardProfiler.h b/Engine/source/gfx/D3D11/gfxD3D11CardProfiler.h new file mode 100644 index 000000000..c26432928 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11CardProfiler.h @@ -0,0 +1,46 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3D11CARDPROFILER_H_ +#define _GFXD3D11CARDPROFILER_H_ + +#include "gfx/gfxCardProfile.h" + +class GFXD3D11CardProfiler : public GFXCardProfiler +{ +private: + typedef GFXCardProfiler Parent; + +public: + GFXD3D11CardProfiler(); + ~GFXD3D11CardProfiler(); + void init(); + +protected: + const String &getRendererString() const { static String sRS("Direct3D11"); return sRS; } + + void setupCardCapabilities(); + bool _queryCardCap(const String &query, U32 &foundResult); + bool _queryFormat(const GFXFormat fmt, const GFXTextureProfile *profile, bool &inOutAutogenMips); +}; + +#endif diff --git a/Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp b/Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp new file mode 100644 index 000000000..281e7e786 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp @@ -0,0 +1,352 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/D3D11/gfxD3D11Cubemap.h" +#include "gfx/gfxCardProfile.h" +#include "gfx/gfxTextureManager.h" +#include "gfx/D3D11/gfxD3D11EnumTranslate.h" + +GFXD3D11Cubemap::GFXD3D11Cubemap() : mTexture(NULL), mSRView(NULL), mDSView(NULL) +{ + mDynamic = false; + mAutoGenMips = false; + mFaceFormat = GFXFormatR8G8B8A8; + + for (U32 i = 0; i < CubeFaces; i++) + { + mRTView[i] = NULL; + } +} + +GFXD3D11Cubemap::~GFXD3D11Cubemap() +{ + releaseSurfaces(); +} + +void GFXD3D11Cubemap::releaseSurfaces() +{ + if (mDynamic) + GFXTextureManager::removeEventDelegate(this, &GFXD3D11Cubemap::_onTextureEvent); + + for (U32 i = 0; i < CubeFaces; i++) + { + SAFE_RELEASE(mRTView[i]); + } + + SAFE_RELEASE(mDSView); + SAFE_RELEASE(mSRView); + SAFE_RELEASE(mTexture); +} + +void GFXD3D11Cubemap::_onTextureEvent(GFXTexCallbackCode code) +{ + if (code == GFXZombify) + releaseSurfaces(); + else if (code == GFXResurrect) + initDynamic(mTexSize); +} + +bool GFXD3D11Cubemap::isCompressed(GFXFormat format) +{ + if (format >= GFXFormatDXT1 && format <= GFXFormatDXT5) + return true; + + return false; +} + +void GFXD3D11Cubemap::initStatic(GFXTexHandle *faces) +{ + AssertFatal( faces, "GFXD3D11Cubemap::initStatic - Got null GFXTexHandle!" ); + AssertFatal( *faces, "empty texture passed to CubeMap::create" ); + + // NOTE - check tex sizes on all faces - they MUST be all same size + mTexSize = faces->getWidth(); + mFaceFormat = faces->getFormat(); + bool compressed = isCompressed(mFaceFormat); + + UINT bindFlags = D3D11_BIND_SHADER_RESOURCE; + UINT miscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE; + if (!compressed) + { + bindFlags |= D3D11_BIND_RENDER_TARGET; + miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; + } + + U32 mipLevels = faces->getPointer()->getMipLevels(); + if (mipLevels > 1) + mAutoGenMips = true; + + D3D11_TEXTURE2D_DESC desc; + ZeroMemory(&desc, sizeof(D3D11_TEXTURE2D_DESC)); + desc.Width = mTexSize; + desc.Height = mTexSize; + desc.MipLevels = mAutoGenMips ? 0 : mipLevels; + desc.ArraySize = 6; + desc.Format = GFXD3D11TextureFormat[mFaceFormat]; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = bindFlags; + desc.MiscFlags = miscFlags; + desc.CPUAccessFlags = 0; + + HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &mTexture); + + if (FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Cubemap:initStatic(GFXTexhandle *faces) - failed to create texcube texture"); + } + + for (U32 i = 0; i < CubeFaces; i++) + { + GFXD3D11TextureObject *texObj = static_cast((GFXTextureObject*)faces[i]); + U32 subResource = D3D11CalcSubresource(0, i, mipLevels); + D3D11DEVICECONTEXT->CopySubresourceRegion(mTexture, subResource, 0, 0, 0, texObj->get2DTex(), 0, NULL); + } + + D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc; + SMViewDesc.Format = GFXD3D11TextureFormat[mFaceFormat]; + SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; + SMViewDesc.TextureCube.MipLevels = mAutoGenMips ? -1 : mipLevels; + SMViewDesc.TextureCube.MostDetailedMip = 0; + + hr = D3D11DEVICE->CreateShaderResourceView(mTexture, &SMViewDesc, &mSRView); + if (FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Cubemap::initStatic(GFXTexHandle *faces) - texcube shader resource view creation failure"); + } + + if (mAutoGenMips && !compressed) + D3D11DEVICECONTEXT->GenerateMips(mSRView); +} + +void GFXD3D11Cubemap::initStatic(DDSFile *dds) +{ + AssertFatal(dds, "GFXD3D11Cubemap::initStatic - Got null DDS file!"); + AssertFatal(dds->isCubemap(), "GFXD3D11Cubemap::initStatic - Got non-cubemap DDS file!"); + AssertFatal(dds->mSurfaces.size() == 6, "GFXD3D11Cubemap::initStatic - DDS has less than 6 surfaces!"); + + // NOTE - check tex sizes on all faces - they MUST be all same size + mTexSize = dds->getWidth(); + mFaceFormat = dds->getFormat(); + U32 levels = dds->getMipLevels(); + + D3D11_TEXTURE2D_DESC desc; + + desc.Width = mTexSize; + desc.Height = mTexSize; + desc.MipLevels = levels; + desc.ArraySize = 6; + desc.Format = GFXD3D11TextureFormat[mFaceFormat]; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = D3D11_USAGE_IMMUTABLE; + desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.MiscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE | D3D11_RESOURCE_MISC_GENERATE_MIPS; + + D3D11_SUBRESOURCE_DATA* pData = new D3D11_SUBRESOURCE_DATA[6 + levels]; + + for (U32 i = 0; imSurfaces[i]) + continue; + + for(U32 j = 0; j < levels; j++) + { + pData[i + j].pSysMem = dds->mSurfaces[i]->mMips[j]; + pData[i + j].SysMemPitch = dds->getSurfacePitch(j); + pData[i + j].SysMemSlicePitch = dds->getSurfaceSize(j); + } + } + + HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, pData, &mTexture); + + delete [] pData; + + D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc; + SMViewDesc.Format = GFXD3D11TextureFormat[mFaceFormat]; + SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; + SMViewDesc.TextureCube.MipLevels = levels; + SMViewDesc.TextureCube.MostDetailedMip = 0; + + hr = D3D11DEVICE->CreateShaderResourceView(mTexture, &SMViewDesc, &mSRView); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Cubemap::initStatic(DDSFile *dds) - CreateTexture2D call failure"); + } +} + +void GFXD3D11Cubemap::initDynamic(U32 texSize, GFXFormat faceFormat) +{ + if(!mDynamic) + GFXTextureManager::addEventDelegate(this, &GFXD3D11Cubemap::_onTextureEvent); + + mDynamic = true; + mAutoGenMips = true; + mTexSize = texSize; + mFaceFormat = faceFormat; + bool compressed = isCompressed(mFaceFormat); + + UINT bindFlags = D3D11_BIND_SHADER_RESOURCE; + UINT miscFlags = D3D11_RESOURCE_MISC_TEXTURECUBE; + if (!compressed) + { + bindFlags |= D3D11_BIND_RENDER_TARGET; + miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; + } + + D3D11_TEXTURE2D_DESC desc; + + desc.Width = mTexSize; + desc.Height = mTexSize; + desc.MipLevels = 0; + desc.ArraySize = 6; + desc.Format = GFXD3D11TextureFormat[mFaceFormat]; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = 0; + desc.MiscFlags = miscFlags; + + + HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &mTexture); + + D3D11_SHADER_RESOURCE_VIEW_DESC SMViewDesc; + SMViewDesc.Format = GFXD3D11TextureFormat[mFaceFormat]; + SMViewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; + SMViewDesc.TextureCube.MipLevels = -1; + SMViewDesc.TextureCube.MostDetailedMip = 0; + + hr = D3D11DEVICE->CreateShaderResourceView(mTexture, &SMViewDesc, &mSRView); + + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateTexture2D call failure"); + } + + D3D11_RENDER_TARGET_VIEW_DESC viewDesc; + viewDesc.Format = desc.Format; + viewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; + viewDesc.Texture2DArray.ArraySize = 1; + viewDesc.Texture2DArray.MipSlice = 0; + + for (U32 i = 0; i < CubeFaces; i++) + { + viewDesc.Texture2DArray.FirstArraySlice = i; + hr = D3D11DEVICE->CreateRenderTargetView(mTexture, &viewDesc, &mRTView[i]); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateRenderTargetView call failure"); + } + } + + D3D11_TEXTURE2D_DESC depthTexDesc; + depthTexDesc.Width = mTexSize; + depthTexDesc.Height = mTexSize; + depthTexDesc.MipLevels = 1; + depthTexDesc.ArraySize = 1; + depthTexDesc.SampleDesc.Count = 1; + depthTexDesc.SampleDesc.Quality = 0; + depthTexDesc.Format = DXGI_FORMAT_D32_FLOAT; + depthTexDesc.Usage = D3D11_USAGE_DEFAULT; + depthTexDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; + depthTexDesc.CPUAccessFlags = 0; + depthTexDesc.MiscFlags = 0; + + ID3D11Texture2D* depthTex = 0; + hr = D3D11DEVICE->CreateTexture2D(&depthTexDesc, 0, &depthTex); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateTexture2D for depth stencil call failure"); + } + + // Create the depth stencil view for the entire cube + D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc; + dsvDesc.Format = depthTexDesc.Format; //The format must match the depth texture we created above + dsvDesc.Flags = 0; + dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; + dsvDesc.Texture2D.MipSlice = 0; + hr = D3D11DEVICE->CreateDepthStencilView(depthTex, &dsvDesc, &mDSView); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Cubemap::initDynamic - CreateDepthStencilView call failure"); + } + + SAFE_RELEASE(depthTex); + +} + +//----------------------------------------------------------------------------- +// Set the cubemap to the specified texture unit num +//----------------------------------------------------------------------------- +void GFXD3D11Cubemap::setToTexUnit(U32 tuNum) +{ + D3D11DEVICECONTEXT->PSSetShaderResources(tuNum, 1, &mSRView); +} + +void GFXD3D11Cubemap::zombify() +{ + // Static cubemaps are handled by D3D + if( mDynamic ) + releaseSurfaces(); +} + +void GFXD3D11Cubemap::resurrect() +{ + // Static cubemaps are handled by D3D + if( mDynamic ) + initDynamic( mTexSize, mFaceFormat ); +} + +ID3D11ShaderResourceView* GFXD3D11Cubemap::getSRView() +{ + return mSRView; +} + +ID3D11RenderTargetView* GFXD3D11Cubemap::getRTView(U32 faceIdx) +{ + AssertFatal(faceIdx < CubeFaces, "GFXD3D11Cubemap::getRTView - face index out of bounds"); + + return mRTView[faceIdx]; +} + +ID3D11RenderTargetView** GFXD3D11Cubemap::getRTViewArray() +{ + return mRTView; +} + +ID3D11DepthStencilView* GFXD3D11Cubemap::getDSView() +{ + return mDSView; +} + +ID3D11Texture2D* GFXD3D11Cubemap::get2DTex() +{ + return mTexture; +} \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11Cubemap.h b/Engine/source/gfx/D3D11/gfxD3D11Cubemap.h new file mode 100644 index 000000000..f24933d08 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11Cubemap.h @@ -0,0 +1,80 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3D11CUBEMAP_H_ +#define _GFXD3D11CUBEMAP_H_ + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/gfxCubemap.h" +#include "gfx/gfxResource.h" +#include "gfx/gfxTarget.h" + +const U32 CubeFaces = 6; + +class GFXD3D11Cubemap : public GFXCubemap +{ +public: + virtual void initStatic( GFXTexHandle *faces ); + virtual void initStatic( DDSFile *dds ); + virtual void initDynamic( U32 texSize, GFXFormat faceFormat = GFXFormatR8G8B8A8 ); + virtual void setToTexUnit( U32 tuNum ); + virtual U32 getSize() const { return mTexSize; } + virtual GFXFormat getFormat() const { return mFaceFormat; } + + GFXD3D11Cubemap(); + virtual ~GFXD3D11Cubemap(); + + // GFXResource interface + virtual void zombify(); + virtual void resurrect(); + + // Get functions + ID3D11ShaderResourceView* getSRView(); + ID3D11RenderTargetView* getRTView(U32 faceIdx); + ID3D11RenderTargetView** getRTViewArray(); + ID3D11DepthStencilView* getDSView(); + ID3D11Texture2D* get2DTex(); + +private: + + friend class GFXD3D11TextureTarget; + friend class GFXD3D11Device; + + ID3D11Texture2D* mTexture; + ID3D11ShaderResourceView* mSRView; // for shader resource input + ID3D11RenderTargetView* mRTView[CubeFaces]; // for render targets, 6 faces of the cubemap + ID3D11DepthStencilView* mDSView; //render target view for depth stencil + + bool mAutoGenMips; + bool mDynamic; + U32 mTexSize; + GFXFormat mFaceFormat; + + void releaseSurfaces(); + + bool isCompressed(GFXFormat format); + /// The callback used to get texture events. + /// @see GFXTextureManager::addEventDelegate + void _onTextureEvent(GFXTexCallbackCode code); +}; + +#endif diff --git a/Engine/source/gfx/D3D11/gfxD3D11Device.cpp b/Engine/source/gfx/D3D11/gfxD3D11Device.cpp new file mode 100644 index 000000000..e38ff546c --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11Device.cpp @@ -0,0 +1,1721 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "console/console.h" +#include "core/stream/fileStream.h" +#include "core/strings/unicode.h" +#include "core/util/journal/process.h" +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11CardProfiler.h" +#include "gfx/D3D11/gfxD3D11VertexBuffer.h" +#include "gfx/D3D11/gfxD3D11EnumTranslate.h" +#include "gfx/D3D11/gfxD3D11QueryFence.h" +#include "gfx/D3D11/gfxD3D11OcclusionQuery.h" +#include "gfx/D3D11/gfxD3D11Shader.h" +#include "gfx/D3D11/gfxD3D11Target.h" +#include "platformWin32/platformWin32.h" +#include "windowManager/win32/win32Window.h" +#include "windowManager/platformWindow.h" +#include "gfx/D3D11/screenshotD3D11.h" +#include "materials/shaderData.h" + +#ifdef TORQUE_DEBUG +#include "d3d11sdklayers.h" +#endif + +#pragma comment(lib, "dxgi.lib") +#pragma comment(lib, "d3d11.lib") + +GFXAdapter::CreateDeviceInstanceDelegate GFXD3D11Device::mCreateDeviceInstance(GFXD3D11Device::createInstance); + +GFXDevice *GFXD3D11Device::createInstance(U32 adapterIndex) +{ + GFXD3D11Device* dev = new GFXD3D11Device(adapterIndex); + return dev; +} + +GFXFormat GFXD3D11Device::selectSupportedFormat(GFXTextureProfile *profile, const Vector &formats, bool texture, bool mustblend, bool mustfilter) +{ + U32 features = 0; + if(texture) + features |= D3D11_FORMAT_SUPPORT_TEXTURE2D; + if(mustblend) + features |= D3D11_FORMAT_SUPPORT_BLENDABLE; + if(mustfilter) + features |= D3D11_FORMAT_SUPPORT_SHADER_SAMPLE; + + for(U32 i = 0; i < formats.size(); i++) + { + if(GFXD3D11TextureFormat[formats[i]] == DXGI_FORMAT_UNKNOWN) + continue; + + U32 supportFlag = 0; + mD3DDevice->CheckFormatSupport(GFXD3D11TextureFormat[formats[i]],&supportFlag); + if(supportFlag & features) + return formats[i]; + } + + return GFXFormatR8G8B8A8; +} + +DXGI_SWAP_CHAIN_DESC GFXD3D11Device::setupPresentParams(const GFXVideoMode &mode, const HWND &hwnd) +{ + DXGI_SWAP_CHAIN_DESC d3dpp; + ZeroMemory(&d3dpp, sizeof(d3dpp)); + + DXGI_SAMPLE_DESC sampleDesc; + sampleDesc.Count = 1; + sampleDesc.Quality = 0; + + mMultisampleDesc = sampleDesc; + + d3dpp.BufferCount = !smDisableVSync ? 2 : 1; // triple buffering when vsync is on. + d3dpp.BufferDesc.Width = mode.resolution.x; + d3dpp.BufferDesc.Height = mode.resolution.y; + d3dpp.BufferDesc.Format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8]; + d3dpp.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; + d3dpp.OutputWindow = hwnd; + d3dpp.SampleDesc = sampleDesc; + d3dpp.Windowed = !mode.fullScreen; + d3dpp.BufferDesc.RefreshRate.Numerator = mode.refreshRate; + d3dpp.BufferDesc.RefreshRate.Denominator = 1; + d3dpp.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; + + if (mode.fullScreen) + { + d3dpp.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; + d3dpp.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; + d3dpp.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; + } + + return d3dpp; +} + +void GFXD3D11Device::enumerateAdapters(Vector &adapterList) +{ + IDXGIAdapter1* EnumAdapter; + IDXGIFactory1* DXGIFactory; + + CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast(&DXGIFactory)); + + for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) + { + GFXAdapter *toAdd = new GFXAdapter; + toAdd->mType = Direct3D11; + toAdd->mIndex = adapterIndex; + toAdd->mCreateDeviceInstanceDelegate = mCreateDeviceInstance; + + toAdd->mShaderModel = 5.0f; + DXGI_ADAPTER_DESC1 desc; + EnumAdapter->GetDesc1(&desc); + + size_t size=wcslen(desc.Description); + char *str = new char[size+1]; + + wcstombs(str, desc.Description,size); + str[size]='\0'; + String Description=str; + SAFE_DELETE_ARRAY(str); + + dStrncpy(toAdd->mName, Description.c_str(), GFXAdapter::MaxAdapterNameLen); + dStrncat(toAdd->mName, " (D3D11)", GFXAdapter::MaxAdapterNameLen); + + IDXGIOutput* pOutput = NULL; + HRESULT hr; + + hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput); + + if(hr == DXGI_ERROR_NOT_FOUND) + { + SAFE_RELEASE(EnumAdapter); + break; + } + + if(FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> EnumOutputs call failure"); + + UINT numModes = 0; + DXGI_MODE_DESC* displayModes = NULL; + DXGI_FORMAT format = DXGI_FORMAT_B8G8R8A8_UNORM; + + // Get the number of elements + hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL); + + if(FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure"); + + displayModes = new DXGI_MODE_DESC[numModes]; + + // Get the list + hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes); + + if(FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::enumerateAdapters -> GetDisplayModeList call failure"); + + for(U32 numMode = 0; numMode < numModes; ++numMode) + { + GFXVideoMode vmAdd; + + vmAdd.fullScreen = true; + vmAdd.bitDepth = 32; + vmAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator; + vmAdd.resolution.x = displayModes[numMode].Width; + vmAdd.resolution.y = displayModes[numMode].Height; + toAdd->mAvailableModes.push_back(vmAdd); + } + + delete[] displayModes; + SAFE_RELEASE(pOutput); + SAFE_RELEASE(EnumAdapter); + adapterList.push_back(toAdd); + } + + SAFE_RELEASE(DXGIFactory); +} + +void GFXD3D11Device::enumerateVideoModes() +{ + mVideoModes.clear(); + + IDXGIAdapter1* EnumAdapter; + IDXGIFactory1* DXGIFactory; + HRESULT hr; + + hr = CreateDXGIFactory1(__uuidof(IDXGIFactory1), reinterpret_cast(&DXGIFactory)); + + if (FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> CreateDXGIFactory1 call failure"); + + for(U32 adapterIndex = 0; DXGIFactory->EnumAdapters1(adapterIndex, &EnumAdapter) != DXGI_ERROR_NOT_FOUND; ++adapterIndex) + { + IDXGIOutput* pOutput = NULL; + + hr = EnumAdapter->EnumOutputs(adapterIndex, &pOutput); + + if(hr == DXGI_ERROR_NOT_FOUND) + { + SAFE_RELEASE(EnumAdapter); + break; + } + + if(FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> EnumOutputs call failure"); + + UINT numModes = 0; + DXGI_MODE_DESC* displayModes = NULL; + DXGI_FORMAT format = GFXD3D11TextureFormat[GFXFormatR8G8B8A8]; + + // Get the number of elements + hr = pOutput->GetDisplayModeList(format, 0, &numModes, NULL); + + if(FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure"); + + displayModes = new DXGI_MODE_DESC[numModes]; + + // Get the list + hr = pOutput->GetDisplayModeList(format, 0, &numModes, displayModes); + + if(FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::enumerateVideoModes -> GetDisplayModeList call failure"); + + for(U32 numMode = 0; numMode < numModes; ++numMode) + { + GFXVideoMode toAdd; + + toAdd.fullScreen = false; + toAdd.bitDepth = 32; + toAdd.refreshRate = displayModes[numMode].RefreshRate.Numerator / displayModes[numMode].RefreshRate.Denominator; + toAdd.resolution.x = displayModes[numMode].Width; + toAdd.resolution.y = displayModes[numMode].Height; + mVideoModes.push_back(toAdd); + } + + delete[] displayModes; + SAFE_RELEASE(pOutput); + SAFE_RELEASE(EnumAdapter); + } + + SAFE_RELEASE(DXGIFactory); +} + +IDXGISwapChain* GFXD3D11Device::getSwapChain() +{ + return mSwapChain; +} + +void GFXD3D11Device::init(const GFXVideoMode &mode, PlatformWindow *window) +{ + AssertFatal(window, "GFXD3D11Device::init - must specify a window!"); + + HWND winHwnd = (HWND)window->getSystemWindow( PlatformWindow::WindowSystem_Windows ); + + UINT createDeviceFlags = D3D11_CREATE_DEVICE_SINGLETHREADED | D3D11_CREATE_DEVICE_BGRA_SUPPORT; +#ifdef TORQUE_DEBUG + createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; + mDebugLayers = true; +#endif + + DXGI_SWAP_CHAIN_DESC d3dpp = setupPresentParams(mode, winHwnd); + + D3D_FEATURE_LEVEL deviceFeature; + D3D_DRIVER_TYPE driverType = D3D_DRIVER_TYPE_HARDWARE;// use D3D_DRIVER_TYPE_REFERENCE for reference device + // create a device, device context and swap chain using the information in the d3dpp struct + HRESULT hres = D3D11CreateDeviceAndSwapChain(NULL, + driverType, + NULL, + createDeviceFlags, + NULL, + 0, + D3D11_SDK_VERSION, + &d3dpp, + &mSwapChain, + &mD3DDevice, + &deviceFeature, + &mD3DDeviceContext); + + if(FAILED(hres)) + { + #ifdef TORQUE_DEBUG + //try again without debug device layer enabled + createDeviceFlags &= ~D3D11_CREATE_DEVICE_DEBUG; + HRESULT hres = D3D11CreateDeviceAndSwapChain(NULL, driverType,NULL,createDeviceFlags,NULL, 0, + D3D11_SDK_VERSION, + &d3dpp, + &mSwapChain, + &mD3DDevice, + &deviceFeature, + &mD3DDeviceContext); + //if we failed again than we definitely have a problem + if (FAILED(hres)) + AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!"); + + Con::warnf("GFXD3D11Device::init - Debug layers not detected!"); + mDebugLayers = false; + #else + AssertFatal(false, "GFXD3D11Device::init - D3D11CreateDeviceAndSwapChain failed!"); + #endif + } + + //set the fullscreen state here if we need to + if(mode.fullScreen) + { + hres = mSwapChain->SetFullscreenState(TRUE, NULL); + if(FAILED(hres)) + { + AssertFatal(false, "GFXD3D11Device::init- Failed to set fullscreen state!"); + } + } + + mTextureManager = new GFXD3D11TextureManager(); + + // Now reacquire all the resources we trashed earlier + reacquireDefaultPoolResources(); + //TODO implement feature levels? + if (deviceFeature >= D3D_FEATURE_LEVEL_11_0) + mPixVersion = 5.0f; + else + AssertFatal(false, "GFXD3D11Device::init - We don't support anything below feature level 11."); + + D3D11_QUERY_DESC queryDesc; + queryDesc.Query = D3D11_QUERY_OCCLUSION; + queryDesc.MiscFlags = 0; + + ID3D11Query *testQuery = NULL; + + // detect occlusion query support + if (SUCCEEDED(mD3DDevice->CreateQuery(&queryDesc, &testQuery))) mOcclusionQuerySupported = true; + + SAFE_RELEASE(testQuery); + + Con::printf("Hardware occlusion query detected: %s", mOcclusionQuerySupported ? "Yes" : "No"); + + mCardProfiler = new GFXD3D11CardProfiler(); + mCardProfiler->init(); + + D3D11_TEXTURE2D_DESC desc; + desc.BindFlags = D3D11_BIND_DEPTH_STENCIL; + desc.CPUAccessFlags = 0; + desc.Format = GFXD3D11TextureFormat[GFXFormatD24S8]; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.Width = mode.resolution.x; + desc.Height = mode.resolution.y; + desc.SampleDesc.Count =1; + desc.SampleDesc.Quality =0; + desc.MiscFlags = 0; + + HRESULT hr = mD3DDevice->CreateTexture2D(&desc, NULL, &mDeviceDepthStencil); + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Device::init - couldn't create device's depth-stencil surface."); + } + + D3D11_DEPTH_STENCIL_VIEW_DESC depthDesc; + depthDesc.Format = GFXD3D11TextureFormat[GFXFormatD24S8]; + depthDesc.Flags =0 ; + depthDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; + depthDesc.Texture2D.MipSlice = 0; + + hr = mD3DDevice->CreateDepthStencilView(mDeviceDepthStencil, &depthDesc, &mDeviceDepthStencilView); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Device::init - couldn't create depth stencil view"); + } + + hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mDeviceBackbuffer); + if(FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::init - coudln't retrieve backbuffer ref"); + + //create back buffer view + D3D11_RENDER_TARGET_VIEW_DESC RTDesc; + + RTDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + RTDesc.Texture2D.MipSlice = 0; + RTDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; + + hr = mD3DDevice->CreateRenderTargetView(mDeviceBackbuffer, &RTDesc, &mDeviceBackBufferView); + + if(FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::init - couldn't create back buffer target view"); + +#ifdef TORQUE_DEBUG + String backBufferName = "MainBackBuffer"; + String depthSteniclName = "MainDepthStencil"; + String backBuffViewName = "MainBackBuffView"; + String depthStencViewName = "MainDepthView"; + mDeviceBackbuffer->SetPrivateData(WKPDID_D3DDebugObjectName, backBufferName.size(), backBufferName.c_str()); + mDeviceDepthStencil->SetPrivateData(WKPDID_D3DDebugObjectName, depthSteniclName.size(), depthSteniclName.c_str()); + mDeviceDepthStencilView->SetPrivateData(WKPDID_D3DDebugObjectName, depthStencViewName.size(), depthStencViewName.c_str()); + mDeviceBackBufferView->SetPrivateData(WKPDID_D3DDebugObjectName, backBuffViewName.size(), backBuffViewName.c_str()); + + _suppressDebugMessages(); + +#endif + + gScreenShot = new ScreenShotD3D11; + + mInitialized = true; + deviceInited(); +} + +// Supress any debug layer messages we don't want to see +void GFXD3D11Device::_suppressDebugMessages() +{ + if (mDebugLayers) + { + ID3D11Debug *pDebug = NULL; + if (SUCCEEDED(mD3DDevice->QueryInterface(__uuidof(ID3D11Debug), (void**)&pDebug))) + { + ID3D11InfoQueue *pInfoQueue = NULL; + if (SUCCEEDED(pDebug->QueryInterface(__uuidof(ID3D11InfoQueue), (void**)&pInfoQueue))) + { + //Disable breaking on error or corruption, this can be handy when using VS graphics debugging + pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_CORRUPTION, false); + pInfoQueue->SetBreakOnSeverity(D3D11_MESSAGE_SEVERITY_ERROR, false); + + D3D11_MESSAGE_ID hide[] = + { + //this is harmless and no need to spam the console + D3D11_MESSAGE_ID_QUERY_BEGIN_ABANDONING_PREVIOUS_RESULTS + }; + + D3D11_INFO_QUEUE_FILTER filter; + memset(&filter, 0, sizeof(filter)); + filter.DenyList.NumIDs = _countof(hide); + filter.DenyList.pIDList = hide; + pInfoQueue->AddStorageFilterEntries(&filter); + SAFE_RELEASE(pInfoQueue); + } + SAFE_RELEASE(pDebug); + } + } +} + +bool GFXD3D11Device::beginSceneInternal() +{ + mCanCurrentlyRender = true; + return mCanCurrentlyRender; +} + +GFXWindowTarget * GFXD3D11Device::allocWindowTarget(PlatformWindow *window) +{ + AssertFatal(window,"GFXD3D11Device::allocWindowTarget - no window provided!"); + + // Allocate the device. + init(window->getVideoMode(), window); + + // Set up a new window target... + GFXD3D11WindowTarget *gdwt = new GFXD3D11WindowTarget(); + gdwt->mWindow = window; + gdwt->mSize = window->getClientExtent(); + gdwt->initPresentationParams(); + gdwt->registerResourceWithDevice(this); + + return gdwt; +} + +GFXTextureTarget* GFXD3D11Device::allocRenderToTextureTarget() +{ + GFXD3D11TextureTarget *targ = new GFXD3D11TextureTarget(); + targ->registerResourceWithDevice(this); + + return targ; +} + +void GFXD3D11Device::reset(DXGI_SWAP_CHAIN_DESC &d3dpp) +{ + if (!mD3DDevice) + return; + + mInitialized = false; + + // Clean up some commonly dangling state. This helps prevents issues with + // items that are destroyed by the texture manager callbacks and recreated + // later, but still left bound. + setVertexBuffer(NULL); + setPrimitiveBuffer(NULL); + for (S32 i = 0; iClearState(); + + DXGI_MODE_DESC displayModes; + displayModes.Format = d3dpp.BufferDesc.Format; + displayModes.Height = d3dpp.BufferDesc.Height; + displayModes.Width = d3dpp.BufferDesc.Width; + displayModes.RefreshRate = d3dpp.BufferDesc.RefreshRate; + displayModes.Scaling = d3dpp.BufferDesc.Scaling; + displayModes.ScanlineOrdering = d3dpp.BufferDesc.ScanlineOrdering; + + HRESULT hr; + if (!d3dpp.Windowed) + { + hr = mSwapChain->ResizeTarget(&displayModes); + + if (FAILED(hr)) + { + AssertFatal(false, "D3D11Device::reset - failed to resize target!"); + } + } + + // First release all the stuff we allocated from D3DPOOL_DEFAULT + releaseDefaultPoolResources(); + + //release the backbuffer, depthstencil, and their views + SAFE_RELEASE(mDeviceBackBufferView); + SAFE_RELEASE(mDeviceBackbuffer); + SAFE_RELEASE(mDeviceDepthStencilView); + SAFE_RELEASE(mDeviceDepthStencil); + + hr = mSwapChain->ResizeBuffers(d3dpp.BufferCount, d3dpp.BufferDesc.Width, d3dpp.BufferDesc.Height, d3dpp.BufferDesc.Format, d3dpp.Windowed ? 0 : DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH); + + if (FAILED(hr)) + { + AssertFatal(false, "D3D11Device::reset - failed to resize back buffer!"); + } + + //recreate backbuffer view. depth stencil view and texture + D3D11_TEXTURE2D_DESC desc; + desc.BindFlags = D3D11_BIND_DEPTH_STENCIL; + desc.CPUAccessFlags = 0; + desc.Format = GFXD3D11TextureFormat[GFXFormatD24S8]; + desc.MipLevels = 1; + desc.ArraySize = 1; + desc.Usage = D3D11_USAGE_DEFAULT; + desc.Width = d3dpp.BufferDesc.Width; + desc.Height = d3dpp.BufferDesc.Height; + desc.SampleDesc.Count = 1; + desc.SampleDesc.Quality = 0; + desc.MiscFlags = 0; + + hr = mD3DDevice->CreateTexture2D(&desc, NULL, &mDeviceDepthStencil); + if (FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Device::reset - couldn't create device's depth-stencil surface."); + } + + D3D11_DEPTH_STENCIL_VIEW_DESC depthDesc; + depthDesc.Format = GFXD3D11TextureFormat[GFXFormatD24S8]; + depthDesc.Flags = 0; + depthDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; + depthDesc.Texture2D.MipSlice = 0; + + hr = mD3DDevice->CreateDepthStencilView(mDeviceDepthStencil, &depthDesc, &mDeviceDepthStencilView); + + if (FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Device::reset - couldn't create depth stencil view"); + } + + hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mDeviceBackbuffer); + if (FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::reset - coudln't retrieve backbuffer ref"); + + //create back buffer view + D3D11_RENDER_TARGET_VIEW_DESC RTDesc; + + RTDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; + RTDesc.Texture2D.MipSlice = 0; + RTDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; + + hr = mD3DDevice->CreateRenderTargetView(mDeviceBackbuffer, &RTDesc, &mDeviceBackBufferView); + + if (FAILED(hr)) + AssertFatal(false, "GFXD3D11Device::reset - couldn't create back buffer target view"); + + mD3DDeviceContext->OMSetRenderTargets(1, &mDeviceBackBufferView, mDeviceDepthStencilView); + + hr = mSwapChain->SetFullscreenState(!d3dpp.Windowed, NULL); + + if (FAILED(hr)) + { + AssertFatal(false, "D3D11Device::reset - failed to change screen states!"); + } + + //Microsoft recommend this, see DXGI documentation + if (!d3dpp.Windowed) + { + displayModes.RefreshRate.Numerator = 0; + displayModes.RefreshRate.Denominator = 0; + hr = mSwapChain->ResizeTarget(&displayModes); + + if (FAILED(hr)) + { + AssertFatal(false, "D3D11Device::reset - failed to resize target!"); + } + } + + mInitialized = true; + + // Now re aquire all the resources we trashed earlier + reacquireDefaultPoolResources(); + + // Mark everything dirty and flush to card, for sanity. + updateStates(true); +} + +class GFXPCD3D11RegisterDevice +{ +public: + GFXPCD3D11RegisterDevice() + { + GFXInit::getRegisterDeviceSignal().notify(&GFXD3D11Device::enumerateAdapters); + } +}; + +static GFXPCD3D11RegisterDevice pPCD3D11RegisterDevice; + +//----------------------------------------------------------------------------- +/// Parse command line arguments for window creation +//----------------------------------------------------------------------------- +static void sgPCD3D11DeviceHandleCommandLine(S32 argc, const char **argv) +{ + // useful to pass parameters by command line for d3d (e.g. -dx9 -dx11) + for (U32 i = 1; i < argc; i++) + { + argv[i]; + } +} + +// Register the command line parsing hook +static ProcessRegisterCommandLine sgCommandLine( sgPCD3D11DeviceHandleCommandLine ); + +GFXD3D11Device::GFXD3D11Device(U32 index) +{ + mDeviceSwizzle32 = &Swizzles::bgra; + GFXVertexColor::setSwizzle( mDeviceSwizzle32 ); + + mDeviceSwizzle24 = &Swizzles::bgr; + + mAdapterIndex = index; + mD3DDevice = NULL; + mVolatileVB = NULL; + + mCurrentPB = NULL; + mDynamicPB = NULL; + + mLastVertShader = NULL; + mLastPixShader = NULL; + + mCanCurrentlyRender = false; + mTextureManager = NULL; + mCurrentStateBlock = NULL; + mResourceListHead = NULL; + + mPixVersion = 0.0; + + mDrawInstancesCount = 0; + + mCardProfiler = NULL; + + mDeviceDepthStencil = NULL; + mDeviceBackbuffer = NULL; + mDeviceBackBufferView = NULL; + mDeviceDepthStencilView = NULL; + + mCreateFenceType = -1; // Unknown, test on first allocate + + mCurrentConstBuffer = NULL; + + mOcclusionQuerySupported = false; + + mDebugLayers = false; + + for(U32 i = 0; i < GS_COUNT; ++i) + mModelViewProjSC[i] = NULL; + + // Set up the Enum translation tables + GFXD3D11EnumTranslate::init(); +} + +GFXD3D11Device::~GFXD3D11Device() +{ + // Release our refcount on the current stateblock object + mCurrentStateBlock = NULL; + + releaseDefaultPoolResources(); + + mD3DDeviceContext->ClearState(); + mD3DDeviceContext->Flush(); + + // Free the vertex declarations. + VertexDeclMap::Iterator iter = mVertexDecls.begin(); + for ( ; iter != mVertexDecls.end(); iter++ ) + delete iter->value; + + // Forcibly clean up the pools + mVolatileVBList.setSize(0); + mDynamicPB = NULL; + + // And release our D3D resources. + SAFE_RELEASE(mDeviceDepthStencilView); + SAFE_RELEASE(mDeviceBackBufferView); + SAFE_RELEASE(mDeviceDepthStencil); + SAFE_RELEASE(mDeviceBackbuffer); + SAFE_RELEASE(mD3DDeviceContext); + + SAFE_DELETE(mCardProfiler); + SAFE_DELETE(gScreenShot); + +#ifdef TORQUE_DEBUG + if (mDebugLayers) + { + ID3D11Debug *pDebug = NULL; + mD3DDevice->QueryInterface(IID_PPV_ARGS(&pDebug)); + AssertFatal(pDebug, "~GFXD3D11Device- Failed to get debug layer"); + pDebug->ReportLiveDeviceObjects(D3D11_RLDO_DETAIL); + SAFE_RELEASE(pDebug); + } +#endif + + SAFE_RELEASE(mSwapChain); + SAFE_RELEASE(mD3DDevice); +} + +void GFXD3D11Device::setupGenericShaders(GenericShaderType type) +{ + AssertFatal(type != GSTargetRestore, ""); //not used + + if(mGenericShader[GSColor] == NULL) + { + ShaderData *shaderData; + + shaderData = new ShaderData(); + shaderData->setField("DXVertexShaderFile", "shaders/common/fixedFunction/colorV.hlsl"); + shaderData->setField("DXPixelShaderFile", "shaders/common/fixedFunction/colorP.hlsl"); + shaderData->setField("pixVersion", "5.0"); + shaderData->registerObject(); + mGenericShader[GSColor] = shaderData->getShader(); + mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer(); + mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle("$modelView"); + Sim::getRootGroup()->addObject(shaderData); + + shaderData = new ShaderData(); + shaderData->setField("DXVertexShaderFile", "shaders/common/fixedFunction/modColorTextureV.hlsl"); + shaderData->setField("DXPixelShaderFile", "shaders/common/fixedFunction/modColorTextureP.hlsl"); + shaderData->setField("pixVersion", "5.0"); + shaderData->registerObject(); + mGenericShader[GSModColorTexture] = shaderData->getShader(); + mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer(); + mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle("$modelView"); + Sim::getRootGroup()->addObject(shaderData); + + shaderData = new ShaderData(); + shaderData->setField("DXVertexShaderFile", "shaders/common/fixedFunction/addColorTextureV.hlsl"); + shaderData->setField("DXPixelShaderFile", "shaders/common/fixedFunction/addColorTextureP.hlsl"); + shaderData->setField("pixVersion", "5.0"); + shaderData->registerObject(); + mGenericShader[GSAddColorTexture] = shaderData->getShader(); + mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer(); + mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle("$modelView"); + Sim::getRootGroup()->addObject(shaderData); + + shaderData = new ShaderData(); + shaderData->setField("DXVertexShaderFile", "shaders/common/fixedFunction/textureV.hlsl"); + shaderData->setField("DXPixelShaderFile", "shaders/common/fixedFunction/textureP.hlsl"); + shaderData->setField("pixVersion", "5.0"); + shaderData->registerObject(); + mGenericShader[GSTexture] = shaderData->getShader(); + mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer(); + mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle("$modelView"); + Sim::getRootGroup()->addObject(shaderData); + + //Force an update + mViewportDirty = true; + _updateRenderTargets(); + } + + MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize]; + mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix); + + setShader(mGenericShader[type]); + setShaderConstBuffer(mGenericShaderBuffer[type]); +} + +//----------------------------------------------------------------------------- +/// Creates a state block object based on the desc passed in. This object +/// represents an immutable state. +GFXStateBlockRef GFXD3D11Device::createStateBlockInternal(const GFXStateBlockDesc& desc) +{ + return GFXStateBlockRef(new GFXD3D11StateBlock(desc)); +} + +/// Activates a stateblock +void GFXD3D11Device::setStateBlockInternal(GFXStateBlock* block, bool force) +{ + AssertFatal(static_cast(block), "Incorrect stateblock type for this device!"); + GFXD3D11StateBlock* d3dBlock = static_cast(block); + GFXD3D11StateBlock* d3dCurrent = static_cast(mCurrentStateBlock.getPointer()); + + if (force) + d3dCurrent = NULL; + + d3dBlock->activate(d3dCurrent); +} + +/// Called by base GFXDevice to actually set a const buffer +void GFXD3D11Device::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer) +{ + if (buffer) + { + PROFILE_SCOPE(GFXD3D11Device_setShaderConstBufferInternal); + AssertFatal(static_cast(buffer), "Incorrect shader const buffer type for this device!"); + GFXD3D11ShaderConstBuffer* d3dBuffer = static_cast(buffer); + + d3dBuffer->activate(mCurrentConstBuffer); + mCurrentConstBuffer = d3dBuffer; + } + else + { + mCurrentConstBuffer = NULL; + } +} + +//----------------------------------------------------------------------------- + +void GFXD3D11Device::clear(U32 flags, ColorI color, F32 z, U32 stencil) +{ + // Make sure we have flushed our render target state. + _updateRenderTargets(); + + UINT depthstencilFlag = 0; + + ID3D11RenderTargetView* rtView = NULL; + ID3D11DepthStencilView* dsView = NULL; + + mD3DDeviceContext->OMGetRenderTargets(1, &rtView, &dsView); + + const FLOAT clearColor[4] = { + static_cast(color.red) * (1.0f / 255.0f), + static_cast(color.green) * (1.0f / 255.0f), + static_cast(color.blue) * (1.0f / 255.0f), + static_cast(color.alpha) * (1.0f / 255.0f) + }; + + if (flags & GFXClearTarget && rtView) + mD3DDeviceContext->ClearRenderTargetView(rtView, clearColor); + + if (flags & GFXClearZBuffer) + depthstencilFlag |= D3D11_CLEAR_DEPTH; + + if (flags & GFXClearStencil) + depthstencilFlag |= D3D11_CLEAR_STENCIL; + + if (depthstencilFlag && dsView) + mD3DDeviceContext->ClearDepthStencilView(dsView, depthstencilFlag, z, stencil); + + SAFE_RELEASE(rtView); + SAFE_RELEASE(dsView); +} + +void GFXD3D11Device::endSceneInternal() +{ + mCanCurrentlyRender = false; +} + +void GFXD3D11Device::_updateRenderTargets() +{ + if (mRTDirty || (mCurrentRT && mCurrentRT->isPendingState())) + { + if (mRTDeactivate) + { + mRTDeactivate->deactivate(); + mRTDeactivate = NULL; + } + + // NOTE: The render target changes are not really accurate + // as the GFXTextureTarget supports MRT internally. So when + // we activate a GFXTarget it could result in multiple calls + // to SetRenderTarget on the actual device. + mDeviceStatistics.mRenderTargetChanges++; + + mCurrentRT->activate(); + + mRTDirty = false; + } + + if (mViewportDirty) + { + D3D11_VIEWPORT viewport; + + viewport.TopLeftX = mViewport.point.x; + viewport.TopLeftY = mViewport.point.y; + viewport.Width = mViewport.extent.x; + viewport.Height = mViewport.extent.y; + viewport.MinDepth = 0.0f; + viewport.MaxDepth = 1.0f; + + mD3DDeviceContext->RSSetViewports(1, &viewport); + + mViewportDirty = false; + } +} + +void GFXD3D11Device::releaseDefaultPoolResources() +{ + // Release all the dynamic vertex buffer arrays + // Forcibly clean up the pools + for(U32 i=0; ivb); + mVolatileVBList[i] = NULL; + } + mVolatileVBList.setSize(0); + + // We gotta clear the current const buffer else the next + // activate may erroneously think the device is still holding + // this state and fail to set it. + mCurrentConstBuffer = NULL; + + // Set current VB to NULL and set state dirty + for (U32 i=0; i < VERTEX_STREAM_COUNT; i++) + { + mCurrentVertexBuffer[i] = NULL; + mVertexBufferDirty[i] = true; + mVertexBufferFrequency[i] = 0; + mVertexBufferFrequencyDirty[i] = true; + } + + // Release dynamic index buffer + if(mDynamicPB != NULL) + { + SAFE_RELEASE(mDynamicPB->ib); + } + + // Set current PB/IB to NULL and set state dirty + mCurrentPrimitiveBuffer = NULL; + mCurrentPB = NULL; + mPrimitiveBufferDirty = true; + + // Zombify texture manager (for D3D this only modifies default pool textures) + if( mTextureManager ) + mTextureManager->zombify(); + + // Set global dirty state so the IB/PB and VB get reset + mStateDirty = true; + + // Walk the resource list and zombify everything. + GFXResource *walk = mResourceListHead; + while(walk) + { + walk->zombify(); + walk = walk->getNextResource(); + } +} + +void GFXD3D11Device::reacquireDefaultPoolResources() +{ + // Now do the dynamic index buffers + if( mDynamicPB == NULL ) + mDynamicPB = new GFXD3D11PrimitiveBuffer(this, 0, 0, GFXBufferTypeDynamic); + + D3D11_BUFFER_DESC desc; + desc.ByteWidth = sizeof(U16) * MAX_DYNAMIC_INDICES; + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.BindFlags = D3D11_BIND_INDEX_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.MiscFlags = 0; + desc.StructureByteStride = 0; + + HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &mDynamicPB->ib); + + if(FAILED(hr)) + { + AssertFatal(false, "Failed to allocate dynamic IB"); + } + + // Walk the resource list and zombify everything. + GFXResource *walk = mResourceListHead; + while(walk) + { + walk->resurrect(); + walk = walk->getNextResource(); + } + + if(mTextureManager) + mTextureManager->resurrect(); +} + +GFXD3D11VertexBuffer* GFXD3D11Device::findVBPool( const GFXVertexFormat *vertexFormat, U32 vertsNeeded ) +{ + PROFILE_SCOPE( GFXD3D11Device_findVBPool ); + + for( U32 i=0; imVertexFormat.isEqual( *vertexFormat ) ) + return mVolatileVBList[i]; + + return NULL; +} + +GFXD3D11VertexBuffer * GFXD3D11Device::createVBPool( const GFXVertexFormat *vertexFormat, U32 vertSize ) +{ + PROFILE_SCOPE( GFXD3D11Device_createVBPool ); + + // this is a bit funky, but it will avoid problems with (lack of) copy constructors + // with a push_back() situation + mVolatileVBList.increment(); + StrongRefPtr newBuff; + mVolatileVBList.last() = new GFXD3D11VertexBuffer(); + newBuff = mVolatileVBList.last(); + + newBuff->mNumVerts = 0; + newBuff->mBufferType = GFXBufferTypeVolatile; + newBuff->mVertexFormat.copy( *vertexFormat ); + newBuff->mVertexSize = vertSize; + newBuff->mDevice = this; + + // Requesting it will allocate it. + vertexFormat->getDecl(); + + D3D11_BUFFER_DESC desc; + desc.ByteWidth = vertSize * MAX_DYNAMIC_VERTS; + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.MiscFlags = 0; + desc.StructureByteStride = 0; + + HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &newBuff->vb); + + if(FAILED(hr)) + { + AssertFatal(false, "Failed to allocate dynamic VB"); + } + + return newBuff; +} + +//----------------------------------------------------------------------------- + +void GFXD3D11Device::setClipRect( const RectI &inRect ) +{ + // We transform the incoming rect by the view + // matrix first, so that it can be used to pan + // and scale the clip rect. + // + // This is currently used to take tiled screenshots. + Point3F pos( inRect.point.x, inRect.point.y, 0.0f ); + Point3F extent( inRect.extent.x, inRect.extent.y, 0.0f ); + getViewMatrix().mulP( pos ); + getViewMatrix().mulV( extent ); + RectI rect( pos.x, pos.y, extent.x, extent.y ); + + // Clip the rect against the renderable size. + Point2I size = mCurrentRT->getSize(); + + RectI maxRect(Point2I(0,0), size); + rect.intersect(maxRect); + + mClipRect = rect; + + F32 l = F32( mClipRect.point.x ); + F32 r = F32( mClipRect.point.x + mClipRect.extent.x ); + F32 b = F32( mClipRect.point.y + mClipRect.extent.y ); + F32 t = F32( mClipRect.point.y ); + + // Set up projection matrix, + static Point4F pt; + pt.set(2.0f / (r - l), 0.0f, 0.0f, 0.0f); + mTempMatrix.setColumn(0, pt); + + pt.set(0.0f, 2.0f/(t - b), 0.0f, 0.0f); + mTempMatrix.setColumn(1, pt); + + pt.set(0.0f, 0.0f, 1.0f, 0.0f); + mTempMatrix.setColumn(2, pt); + + pt.set((l+r)/(l-r), (t+b)/(b-t), 1.0f, 1.0f); + mTempMatrix.setColumn(3, pt); + + setProjectionMatrix( mTempMatrix ); + + // Set up world/view matrix + mTempMatrix.identity(); + setWorldMatrix( mTempMatrix ); + + setViewport( mClipRect ); +} + +void GFXD3D11Device::setVertexStream( U32 stream, GFXVertexBuffer *buffer ) +{ + GFXD3D11VertexBuffer *d3dBuffer = static_cast( buffer ); + + if ( stream == 0 ) + { + // Set the volatile buffer which is used to + // offset the start index when doing draw calls. + if ( d3dBuffer && d3dBuffer->mVolatileStart > 0 ) + mVolatileVB = d3dBuffer; + else + mVolatileVB = NULL; + } + + // NOTE: We do not use the stream offset here for stream 0 + // as that feature is *supposedly* not as well supported as + // using the start index in drawPrimitive. + // + // If we can verify that this is not the case then we should + // start using this method exclusively for all streams. + + U32 strides[1] = { d3dBuffer ? d3dBuffer->mVertexSize : 0 }; + U32 offset = d3dBuffer && stream != 0 ? d3dBuffer->mVolatileStart * d3dBuffer->mVertexSize : 0; + ID3D11Buffer* buff = d3dBuffer ? d3dBuffer->vb : NULL; + + getDeviceContext()->IASetVertexBuffers(stream, 1, &buff, strides, &offset); +} + +void GFXD3D11Device::setVertexStreamFrequency( U32 stream, U32 frequency ) +{ + if (stream == 0) + mDrawInstancesCount = frequency; // instances count +} + +void GFXD3D11Device::_setPrimitiveBuffer( GFXPrimitiveBuffer *buffer ) +{ + mCurrentPB = static_cast( buffer ); + + mD3DDeviceContext->IASetIndexBuffer(mCurrentPB->ib, DXGI_FORMAT_R16_UINT, 0); +} + +U32 GFXD3D11Device::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount) +{ + switch (primType) + { + case GFXPointList: + return primitiveCount; + break; + case GFXLineList: + return primitiveCount * 2; + break; + case GFXLineStrip: + return primitiveCount + 1; + break; + case GFXTriangleList: + return primitiveCount * 3; + break; + case GFXTriangleStrip: + return 2 + primitiveCount; + break; + default: + AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type"); + break; + + } + return 0; +} + + +void GFXD3D11Device::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount ) +{ + // This is done to avoid the function call overhead if possible + if( mStateDirty ) + updateStates(); + if (mCurrentShaderConstBuffer) + setShaderConstBufferInternal(mCurrentShaderConstBuffer); + + if ( mVolatileVB ) + vertexStart += mVolatileVB->mVolatileStart; + + mD3DDeviceContext->IASetPrimitiveTopology(GFXD3D11PrimType[primType]); + + if ( mDrawInstancesCount ) + mD3DDeviceContext->DrawInstanced(primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount, vertexStart, 0); + else + mD3DDeviceContext->Draw(primCountToIndexCount(primType, primitiveCount), vertexStart); + + mDeviceStatistics.mDrawCalls++; + if ( mVertexBufferFrequency[0] > 1 ) + mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0]; + else + mDeviceStatistics.mPolyCount += primitiveCount; +} + +void GFXD3D11Device::drawIndexedPrimitive( GFXPrimitiveType primType, + U32 startVertex, + U32 minIndex, + U32 numVerts, + U32 startIndex, + U32 primitiveCount ) +{ + // This is done to avoid the function call overhead if possible + if( mStateDirty ) + updateStates(); + if (mCurrentShaderConstBuffer) + setShaderConstBufferInternal(mCurrentShaderConstBuffer); + + AssertFatal( mCurrentPB != NULL, "Trying to call drawIndexedPrimitive with no current index buffer, call setIndexBuffer()" ); + + if ( mVolatileVB ) + startVertex += mVolatileVB->mVolatileStart; + + mD3DDeviceContext->IASetPrimitiveTopology(GFXD3D11PrimType[primType]); + + if ( mDrawInstancesCount ) + mD3DDeviceContext->DrawIndexedInstanced(primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount, mCurrentPB->mVolatileStart + startIndex, startVertex, 0); + else + mD3DDeviceContext->DrawIndexed(primCountToIndexCount(primType,primitiveCount), mCurrentPB->mVolatileStart + startIndex, startVertex); + + mDeviceStatistics.mDrawCalls++; + if ( mVertexBufferFrequency[0] > 1 ) + mDeviceStatistics.mPolyCount += primitiveCount * mVertexBufferFrequency[0]; + else + mDeviceStatistics.mPolyCount += primitiveCount; +} + +GFXShader* GFXD3D11Device::createShader() +{ + GFXD3D11Shader* shader = new GFXD3D11Shader(); + shader->registerResourceWithDevice( this ); + return shader; +} + +//----------------------------------------------------------------------------- +// Set shader - this function exists to make sure this is done in one place, +// and to make sure redundant shader states are not being +// sent to the card. +//----------------------------------------------------------------------------- +void GFXD3D11Device::setShader(GFXShader *shader, bool force) +{ + if(shader) + { + GFXD3D11Shader *d3dShader = static_cast(shader); + + if (d3dShader->mPixShader != mLastPixShader || force) + { + mD3DDeviceContext->PSSetShader( d3dShader->mPixShader, NULL, 0); + mLastPixShader = d3dShader->mPixShader; + } + + if (d3dShader->mVertShader != mLastVertShader || force) + { + mD3DDeviceContext->VSSetShader( d3dShader->mVertShader, NULL, 0); + mLastVertShader = d3dShader->mVertShader; + } + } + else + { + setupGenericShaders(); + } +} + +GFXPrimitiveBuffer * GFXD3D11Device::allocPrimitiveBuffer(U32 numIndices, U32 numPrimitives, GFXBufferType bufferType, void *data ) +{ + // Allocate a buffer to return + GFXD3D11PrimitiveBuffer * res = new GFXD3D11PrimitiveBuffer(this, numIndices, numPrimitives, bufferType); + + // Determine usage flags + D3D11_USAGE usage = D3D11_USAGE_DEFAULT; + + // Assumptions: + // - static buffers are write once, use many + // - dynamic buffers are write many, use many + // - volatile buffers are write once, use once + // You may never read from a buffer. + //TODO: enable proper support for D3D11_USAGE_IMMUTABLE + switch(bufferType) + { + case GFXBufferTypeImmutable: + case GFXBufferTypeStatic: + usage = D3D11_USAGE_DEFAULT; //D3D11_USAGE_IMMUTABLE; + break; + + case GFXBufferTypeDynamic: + case GFXBufferTypeVolatile: + usage = D3D11_USAGE_DYNAMIC; + break; + } + + // Register resource + res->registerResourceWithDevice(this); + + // Create d3d index buffer + if(bufferType == GFXBufferTypeVolatile) + { + // Get it from the pool if it's a volatile... + AssertFatal(numIndices < MAX_DYNAMIC_INDICES, "Cannot allocate that many indices in a volatile buffer, increase MAX_DYNAMIC_INDICES."); + + res->ib = mDynamicPB->ib; + res->mVolatileBuffer = mDynamicPB; + } + else + { + // Otherwise, get it as a seperate buffer... + D3D11_BUFFER_DESC desc; + desc.ByteWidth = sizeof(U16) * numIndices; + desc.Usage = usage; + if(bufferType == GFXBufferTypeDynamic) + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // We never allow reading from a primitive buffer. + else + desc.CPUAccessFlags = 0; + desc.BindFlags = D3D11_BIND_INDEX_BUFFER; + desc.MiscFlags = 0; + desc.StructureByteStride = 0; + + HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &res->ib); + + if(FAILED(hr)) + { + AssertFatal(false, "Failed to allocate an index buffer."); + } + } + + if (data) + { + void* dest; + res->lock(0, numIndices, &dest); + dMemcpy(dest, data, sizeof(U16) * numIndices); + res->unlock(); + } + + return res; +} + +GFXVertexBuffer * GFXD3D11Device::allocVertexBuffer(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize, GFXBufferType bufferType, void *data) +{ + PROFILE_SCOPE( GFXD3D11Device_allocVertexBuffer ); + + GFXD3D11VertexBuffer *res = new GFXD3D11VertexBuffer( this, + numVerts, + vertexFormat, + vertSize, + bufferType ); + + // Determine usage flags + D3D11_USAGE usage = D3D11_USAGE_DEFAULT; + + res->mNumVerts = 0; + + // Assumptions: + // - static buffers are write once, use many + // - dynamic buffers are write many, use many + // - volatile buffers are write once, use once + // You may never read from a buffer. + //TODO: enable proper support for D3D11_USAGE_IMMUTABLE + switch(bufferType) + { + case GFXBufferTypeImmutable: + case GFXBufferTypeStatic: + usage = D3D11_USAGE_DEFAULT; + break; + + case GFXBufferTypeDynamic: + case GFXBufferTypeVolatile: + usage = D3D11_USAGE_DYNAMIC; + break; + } + + // Register resource + res->registerResourceWithDevice(this); + + // Create vertex buffer + if(bufferType == GFXBufferTypeVolatile) + { + // NOTE: Volatile VBs are pooled and will be allocated at lock time. + AssertFatal(numVerts <= MAX_DYNAMIC_VERTS, "GFXD3D11Device::allocVertexBuffer - Volatile vertex buffer is too big... see MAX_DYNAMIC_VERTS!"); + } + else + { + // Requesting it will allocate it. + vertexFormat->getDecl(); //-ALEX disabled to postpone until after shader is actually set... + + // Get a new buffer... + D3D11_BUFFER_DESC desc; + desc.ByteWidth = vertSize * numVerts; + desc.Usage = usage; + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + if(bufferType == GFXBufferTypeDynamic) + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // We never allow reading from a vertex buffer. + else + desc.CPUAccessFlags = 0; + desc.MiscFlags = 0; + desc.StructureByteStride = 0; + + HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &res->vb); + + if(FAILED(hr)) + { + AssertFatal(false, "Failed to allocate VB"); + } + } + + res->mNumVerts = numVerts; + + if (data) + { + void* dest; + res->lock(0, numVerts, &dest); + dMemcpy(dest, data, vertSize * numVerts); + res->unlock(); + } + + return res; +} + +String GFXD3D11Device::_createTempShaderInternal(const GFXVertexFormat *vertexFormat) +{ + U32 elemCount = vertexFormat->getElementCount(); + //Input data + StringBuilder inputData; + inputData.append("struct VertIn {"); + //Output data + StringBuilder outputData; + outputData.append("struct VertOut {"); + // Shader main body data + StringBuilder mainBodyData; + //make shader + mainBodyData.append("VertOut main(VertIn IN){VertOut OUT;"); + for (U32 i = 0; i < elemCount; i++) + { + const GFXVertexElement &element = vertexFormat->getElement(i); + String semantic = element.getSemantic(); + String semanticOut = semantic; + String type; + + if (element.isSemantic(GFXSemantic::POSITION)) + { + semantic = "POSITION"; + semanticOut = "SV_Position"; + } + else if (element.isSemantic(GFXSemantic::NORMAL)) + { + semantic = "NORMAL"; + semanticOut = semantic; + } + else if (element.isSemantic(GFXSemantic::COLOR)) + { + semantic = "COLOR"; + semanticOut = semantic; + } + else if (element.isSemantic(GFXSemantic::TANGENT)) + { + semantic = "TANGENT"; + semanticOut = semantic; + } + else if (element.isSemantic(GFXSemantic::BINORMAL)) + { + semantic = "BINORMAL"; + semanticOut = semantic; + } + else + { + //Anything that falls thru to here will be a texture coord. + semantic = String::ToString("TEXCOORD%d", element.getSemanticIndex()); + semanticOut = semantic; + } + + switch (GFXD3D11DeclType[element.getType()]) + { + case DXGI_FORMAT_R32_FLOAT: + type = "float"; + break; + case DXGI_FORMAT_R32G32_FLOAT: + type = "float2"; + break; + case DXGI_FORMAT_R32G32B32_FLOAT: + type = "float3"; + break; + case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM: + type = "float4"; + break; + } + + StringBuilder in; + in.format("%s %s%d : %s;", type.c_str(), "var", i, semantic.c_str()); + inputData.append(in.data()); + + //SV_Position must be float4 + if (semanticOut == String("SV_Position")) + { + StringBuilder out; + out.format("float4 %s%d : %s;", "var", i, semanticOut.c_str()); + outputData.append(out.data()); + StringBuilder body; + body.format("OUT.%s%d = float4(IN.%s%d.xyz,1);", "var", i, "var", i); + mainBodyData.append(body.data()); + } + else + { + StringBuilder out; + out.format("%s %s%d : %s;", type.c_str(), "var", i, semanticOut.c_str()); + outputData.append(out.data()); + StringBuilder body; + body.format("OUT.%s%d = IN.%s%d;", "var", i, "var", i); + mainBodyData.append(body.data()); + } + } + + inputData.append("};"); + outputData.append("};"); + mainBodyData.append("return OUT;}"); + + //final data + StringBuilder finalData; + finalData.append(inputData.data()); + finalData.append(outputData.data()); + finalData.append(mainBodyData.data()); + + return String(finalData.data()); +} + +GFXVertexDecl* GFXD3D11Device::allocVertexDecl( const GFXVertexFormat *vertexFormat ) +{ + PROFILE_SCOPE( GFXD3D11Device_allocVertexDecl ); + + // First check the map... you shouldn't allocate VBs very often + // if you want performance. The map lookup should never become + // a performance bottleneck. + D3D11VertexDecl *decl = mVertexDecls[vertexFormat->getDescription()]; + if ( decl ) + return decl; + + U32 elemCount = vertexFormat->getElementCount(); + + ID3DBlob* code = NULL; + + // We have to generate a temporary shader here for now since the input layout creation + // expects a shader to be already compiled to verify the vertex layout structure. The problem + // is that most of the time the regular shaders are compiled AFTER allocVertexDecl is called. + if(!decl) + { + //TODO: Perhaps save/cache the ID3DBlob for later use on identical vertex formats,save creating/compiling the temp shader everytime + String shaderData = _createTempShaderInternal(vertexFormat); + +#ifdef TORQUE_DEBUG + U32 flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS; +#else + U32 flags = D3DCOMPILE_ENABLE_STRICTNESS; +#endif + + ID3DBlob *errorBlob = NULL; + HRESULT hr = D3DCompile(shaderData.c_str(), shaderData.length(), NULL, NULL, NULL, "main", "vs_5_0", flags, 0, &code, &errorBlob); + StringBuilder error; + + if(errorBlob) + { + error.append((char*)errorBlob->GetBufferPointer(), errorBlob->GetBufferSize()); + AssertFatal(hr, error.data()); + } + + SAFE_RELEASE(errorBlob); + } + + AssertFatal(code, "D3D11Device::allocVertexDecl - compiled vert shader code missing!"); + + // Setup the declaration struct. + + U32 stream; + D3D11_INPUT_ELEMENT_DESC *vd = new D3D11_INPUT_ELEMENT_DESC[ elemCount]; + + for ( U32 i=0; i < elemCount; i++ ) + { + + const GFXVertexElement &element = vertexFormat->getElement( i ); + + stream = element.getStreamIndex(); + + vd[i].InputSlot = stream; + + vd[i].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; + vd[i].Format = GFXD3D11DeclType[element.getType()]; + // If instancing is enabled, the per instance data is only used on stream 1. + if (vertexFormat->hasInstancing() && stream == 1) + { + vd[i].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; + vd[i].InstanceDataStepRate = 1; + } + else + { + vd[i].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; + vd[i].InstanceDataStepRate = 0; + } + // We force the usage index of 0 for everything but + // texture coords for now... this may change later. + vd[i].SemanticIndex = 0; + + if ( element.isSemantic( GFXSemantic::POSITION ) ) + vd[i].SemanticName = "POSITION"; + else if ( element.isSemantic( GFXSemantic::NORMAL ) ) + vd[i].SemanticName = "NORMAL"; + else if ( element.isSemantic( GFXSemantic::COLOR ) ) + vd[i].SemanticName = "COLOR"; + else if ( element.isSemantic( GFXSemantic::TANGENT ) ) + vd[i].SemanticName = "TANGENT"; + else if ( element.isSemantic( GFXSemantic::BINORMAL ) ) + vd[i].SemanticName = "BINORMAL"; + else + { + //Anything that falls thru to here will be a texture coord. + vd[i].SemanticName = "TEXCOORD"; + vd[i].SemanticIndex = element.getSemanticIndex(); + } + + } + + decl = new D3D11VertexDecl(); + HRESULT hr = mD3DDevice->CreateInputLayout(vd, elemCount,code->GetBufferPointer(), code->GetBufferSize(), &decl->decl); + + if (FAILED(hr)) + { + AssertFatal(false, "GFXD3D11Device::allocVertexDecl - Failed to create vertex input layout!"); + } + + delete [] vd; + SAFE_RELEASE(code); + + // Store it in the cache. + mVertexDecls[vertexFormat->getDescription()] = decl; + + return decl; +} + +void GFXD3D11Device::setVertexDecl( const GFXVertexDecl *decl ) +{ + ID3D11InputLayout *dx11Decl = NULL; + if (decl) + dx11Decl = static_cast(decl)->decl; + + mD3DDeviceContext->IASetInputLayout(dx11Decl); +} + +//----------------------------------------------------------------------------- +// This function should ONLY be called from GFXDevice::updateStates() !!! +//----------------------------------------------------------------------------- +void GFXD3D11Device::setTextureInternal( U32 textureUnit, const GFXTextureObject *texture) +{ + if( texture == NULL ) + { + ID3D11ShaderResourceView *pView = NULL; + mD3DDeviceContext->PSSetShaderResources(textureUnit, 1, &pView); + return; + } + + GFXD3D11TextureObject *tex = (GFXD3D11TextureObject*)(texture); + mD3DDeviceContext->PSSetShaderResources(textureUnit, 1, tex->getSRViewPtr()); +} + +GFXFence *GFXD3D11Device::createFence() +{ + // Figure out what fence type we should be making if we don't know + if( mCreateFenceType == -1 ) + { + D3D11_QUERY_DESC desc; + desc.MiscFlags = 0; + desc.Query = D3D11_QUERY_EVENT; + + ID3D11Query *testQuery = NULL; + + HRESULT hRes = mD3DDevice->CreateQuery(&desc, &testQuery); + + if(FAILED(hRes)) + { + mCreateFenceType = true; + } + + else + { + mCreateFenceType = false; + } + + SAFE_RELEASE(testQuery); + } + + // Cool, use queries + if(!mCreateFenceType) + { + GFXFence* fence = new GFXD3D11QueryFence( this ); + fence->registerResourceWithDevice(this); + return fence; + } + + // CodeReview: At some point I would like a specialized implementation of + // the method used by the general fence, only without the overhead incurred + // by using the GFX constructs. Primarily the lock() method on texture handles + // will do a data copy, and this method doesn't require a copy, just a lock + // [5/10/2007 Pat] + GFXFence* fence = new GFXGeneralFence( this ); + fence->registerResourceWithDevice(this); + return fence; +} + +GFXOcclusionQuery* GFXD3D11Device::createOcclusionQuery() +{ + GFXOcclusionQuery *query; + if (mOcclusionQuerySupported) + query = new GFXD3D11OcclusionQuery( this ); + else + return NULL; + + query->registerResourceWithDevice(this); + return query; +} + +GFXCubemap * GFXD3D11Device::createCubemap() +{ + GFXD3D11Cubemap* cube = new GFXD3D11Cubemap(); + cube->registerResourceWithDevice(this); + return cube; +} \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11Device.h b/Engine/source/gfx/D3D11/gfxD3D11Device.h new file mode 100644 index 000000000..97418d373 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11Device.h @@ -0,0 +1,295 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3D11DEVICE_H_ +#define _GFXD3D11DEVICE_H_ + +#include + +#include "platform/tmm_off.h" +#include "platformWin32/platformWin32.h" +#include "gfx/D3D11/gfxD3D11Shader.h" +#include "gfx/D3D11/gfxD3D11StateBlock.h" +#include "gfx/D3D11/gfxD3D11TextureManager.h" +#include "gfx/D3D11/gfxD3D11Cubemap.h" +#include "gfx/D3D11/gfxD3D11PrimitiveBuffer.h" +#include "gfx/gfxInit.h" +#include "gfx/gfxResource.h" +#include "platform/tmm_on.h" + +#define D3D11 static_cast(GFX) +#define D3D11DEVICE D3D11->getDevice() +#define D3D11DEVICECONTEXT D3D11->getDeviceContext() + +class PlatformWindow; +class GFXD3D11ShaderConstBuffer; + +//------------------------------------------------------------------------------ + +class GFXD3D11Device : public GFXDevice +{ + friend class GFXResource; + friend class GFXD3D11PrimitiveBuffer; + friend class GFXD3D11VertexBuffer; + friend class GFXD3D11TextureObject; + friend class GFXD3D11TextureTarget; + friend class GFXD3D11WindowTarget; + + virtual GFXFormat selectSupportedFormat(GFXTextureProfile *profile, + const Vector &formats, bool texture, bool mustblend, bool mustfilter); + + virtual void enumerateVideoModes(); + + virtual GFXWindowTarget *allocWindowTarget(PlatformWindow *window); + virtual GFXTextureTarget *allocRenderToTextureTarget(); + + virtual void enterDebugEvent(ColorI color, const char *name){}; + virtual void leaveDebugEvent(){}; + virtual void setDebugMarker(ColorI color, const char *name){}; + +protected: + + class D3D11VertexDecl : public GFXVertexDecl + { + public: + virtual ~D3D11VertexDecl() + { + SAFE_RELEASE( decl ); + } + + ID3D11InputLayout *decl; + }; + + virtual void initStates() { }; + + static GFXAdapter::CreateDeviceInstanceDelegate mCreateDeviceInstance; + + MatrixF mTempMatrix; ///< Temporary matrix, no assurances on value at all + RectI mClipRect; + + typedef StrongRefPtr RPGDVB; + Vector mVolatileVBList; + + /// Used to lookup a vertex declaration for the vertex format. + /// @see allocVertexDecl + typedef Map VertexDeclMap; + VertexDeclMap mVertexDecls; + + ID3D11RenderTargetView* mDeviceBackBufferView; + ID3D11DepthStencilView* mDeviceDepthStencilView; + + ID3D11Texture2D *mDeviceBackbuffer; + ID3D11Texture2D *mDeviceDepthStencil; + + /// The stream 0 vertex buffer used for volatile VB offseting. + GFXD3D11VertexBuffer *mVolatileVB; + + //----------------------------------------------------------------------- + StrongRefPtr mDynamicPB; + GFXD3D11PrimitiveBuffer *mCurrentPB; + + ID3D11VertexShader *mLastVertShader; + ID3D11PixelShader *mLastPixShader; + + S32 mCreateFenceType; + + IDXGISwapChain *mSwapChain; + ID3D11Device* mD3DDevice; + ID3D11DeviceContext* mD3DDeviceContext; + + GFXShader* mCurrentShader; + GFXShaderRef mGenericShader[GS_COUNT]; + GFXShaderConstBufferRef mGenericShaderBuffer[GS_COUNT]; + GFXShaderConstHandle *mModelViewProjSC[GS_COUNT]; + + U32 mAdapterIndex; + + F32 mPixVersion; + + bool mDebugLayers; + + DXGI_SAMPLE_DESC mMultisampleDesc; + + bool mOcclusionQuerySupported; + + U32 mDrawInstancesCount; + + /// To manage creating and re-creating of these when device is aquired + void reacquireDefaultPoolResources(); + + /// To release all resources we control from D3DPOOL_DEFAULT + void releaseDefaultPoolResources(); + + virtual GFXD3D11VertexBuffer* findVBPool( const GFXVertexFormat *vertexFormat, U32 numVertsNeeded ); + virtual GFXD3D11VertexBuffer* createVBPool( const GFXVertexFormat *vertexFormat, U32 vertSize ); + + IDXGISwapChain* getSwapChain(); + // State overrides + // { + + /// + virtual void setTextureInternal(U32 textureUnit, const GFXTextureObject* texture); + + /// Called by GFXDevice to create a device specific stateblock + virtual GFXStateBlockRef createStateBlockInternal(const GFXStateBlockDesc& desc); + /// Called by GFXDevice to actually set a stateblock. + virtual void setStateBlockInternal(GFXStateBlock* block, bool force); + + /// Track the last const buffer we've used. Used to notify new constant buffers that + /// they should send all of their constants up + StrongRefPtr mCurrentConstBuffer; + /// Called by base GFXDevice to actually set a const buffer + virtual void setShaderConstBufferInternal(GFXShaderConstBuffer* buffer); + + virtual void setMatrix( GFXMatrixType /*mtype*/, const MatrixF &/*mat*/ ) { }; + virtual void setLightInternal(U32 /*lightStage*/, const GFXLightInfo /*light*/, bool /*lightEnable*/) { }; + virtual void setLightMaterialInternal(const GFXLightMaterial /*mat*/) { }; + virtual void setGlobalAmbientInternal(ColorF /*color*/) { }; + + // } + + // Index buffer management + // { + virtual void _setPrimitiveBuffer( GFXPrimitiveBuffer *buffer ); + virtual void drawIndexedPrimitive( GFXPrimitiveType primType, + U32 startVertex, + U32 minIndex, + U32 numVerts, + U32 startIndex, + U32 primitiveCount ); + // } + + virtual GFXShader* createShader(); + + /// Device helper function + virtual DXGI_SWAP_CHAIN_DESC setupPresentParams( const GFXVideoMode &mode, const HWND &hwnd ); + + String _createTempShaderInternal(const GFXVertexFormat *vertexFormat); + // Supress any debug layer messages we don't want to see + void _suppressDebugMessages(); + +public: + + static GFXDevice *createInstance( U32 adapterIndex ); + + static void enumerateAdapters( Vector &adapterList ); + + GFXTextureObject* createRenderSurface( U32 width, U32 height, GFXFormat format, U32 mipLevel ); + + ID3D11DepthStencilView* getDepthStencilView() { return mDeviceDepthStencilView; } + ID3D11RenderTargetView* getRenderTargetView() { return mDeviceBackBufferView; } + ID3D11Texture2D* getBackBufferTexture() { return mDeviceBackbuffer; } + + /// Constructor + /// @param d3d Direct3D object to instantiate this device with + /// @param index Adapter index since D3D can use multiple graphics adapters + GFXD3D11Device( U32 index ); + virtual ~GFXD3D11Device(); + + // Activate/deactivate + // { + virtual void init( const GFXVideoMode &mode, PlatformWindow *window = NULL ); + + virtual void preDestroy() { GFXDevice::preDestroy(); if(mTextureManager) mTextureManager->kill(); } + + GFXAdapterType getAdapterType(){ return Direct3D11; } + + U32 getAdaterIndex() const { return mAdapterIndex; } + + virtual GFXCubemap *createCubemap(); + + virtual F32 getPixelShaderVersion() const { return mPixVersion; } + virtual void setPixelShaderVersion( F32 version ){ mPixVersion = version;} + + virtual void setShader(GFXShader *shader, bool force = false); + virtual U32 getNumSamplers() const { return 16; } + virtual U32 getNumRenderTargets() const { return 8; } + // } + + // Misc rendering control + // { + virtual void clear( U32 flags, ColorI color, F32 z, U32 stencil ); + virtual bool beginSceneInternal(); + virtual void endSceneInternal(); + + virtual void setClipRect( const RectI &rect ); + virtual const RectI& getClipRect() const { return mClipRect; } + + // } + + + + /// @name Render Targets + /// @{ + virtual void _updateRenderTargets(); + /// @} + + // Vertex/Index buffer management + // { + virtual GFXVertexBuffer* allocVertexBuffer( U32 numVerts, + const GFXVertexFormat *vertexFormat, + U32 vertSize, + GFXBufferType bufferType, + void* data = NULL); + + virtual GFXPrimitiveBuffer *allocPrimitiveBuffer( U32 numIndices, + U32 numPrimitives, + GFXBufferType bufferType, + void* data = NULL); + + virtual GFXVertexDecl* allocVertexDecl( const GFXVertexFormat *vertexFormat ); + virtual void setVertexDecl( const GFXVertexDecl *decl ); + + virtual void setVertexStream( U32 stream, GFXVertexBuffer *buffer ); + virtual void setVertexStreamFrequency( U32 stream, U32 frequency ); + // } + + virtual U32 getMaxDynamicVerts() { return MAX_DYNAMIC_VERTS; } + virtual U32 getMaxDynamicIndices() { return MAX_DYNAMIC_INDICES; } + + inline U32 primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount); + + // Rendering + // { + virtual void drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount ); + // } + + ID3D11DeviceContext* getDeviceContext(){ return mD3DDeviceContext; } + ID3D11Device* getDevice(){ return mD3DDevice; } + + /// Reset + void reset( DXGI_SWAP_CHAIN_DESC &d3dpp ); + + virtual void setupGenericShaders( GenericShaderType type = GSColor ); + + inline virtual F32 getFillConventionOffset() const { return 0.0f; } + virtual void doParanoidStateCheck() {}; + + GFXFence *createFence(); + + GFXOcclusionQuery* createOcclusionQuery(); + + // Default multisample parameters + DXGI_SAMPLE_DESC getMultisampleType() const { return mMultisampleDesc; } +}; + +#endif diff --git a/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp b/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp new file mode 100644 index 000000000..24f195247 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp @@ -0,0 +1,155 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11EnumTranslate.h" +#include "console/console.h" + +//------------------------------------------------------------------------------ + +DXGI_FORMAT GFXD3D11TextureFormat[GFXFormat_COUNT]; +D3D11_FILTER GFXD3D11TextureFilter[GFXTextureFilter_COUNT]; +D3D11_BLEND GFXD3D11Blend[GFXBlend_COUNT]; +D3D11_BLEND_OP GFXD3D11BlendOp[GFXBlendOp_COUNT]; +D3D11_STENCIL_OP GFXD3D11StencilOp[GFXStencilOp_COUNT]; +D3D11_COMPARISON_FUNC GFXD3D11CmpFunc[GFXCmp_COUNT]; +D3D11_CULL_MODE GFXD3D11CullMode[GFXCull_COUNT]; +D3D11_FILL_MODE GFXD3D11FillMode[GFXFill_COUNT]; +D3D11_PRIMITIVE_TOPOLOGY GFXD3D11PrimType[GFXPT_COUNT]; +D3D11_TEXTURE_ADDRESS_MODE GFXD3D11TextureAddress[GFXAddress_COUNT]; +DXGI_FORMAT GFXD3D11DeclType[GFXDeclType_COUNT]; + +//------------------------------------------------------------------------------ + +void GFXD3D11EnumTranslate::init() +{ + GFXD3D11TextureFormat[GFXFormatR8G8B8] = DXGI_FORMAT_B8G8R8X8_UNORM; + GFXD3D11TextureFormat[GFXFormatR8G8B8A8] = DXGI_FORMAT_B8G8R8A8_UNORM; + GFXD3D11TextureFormat[GFXFormatR8G8B8X8] = DXGI_FORMAT_B8G8R8X8_UNORM; + GFXD3D11TextureFormat[GFXFormatB8G8R8A8] = DXGI_FORMAT_B8G8R8A8_UNORM; + GFXD3D11TextureFormat[GFXFormatR5G6B5] = DXGI_FORMAT_B5G6R5_UNORM; + GFXD3D11TextureFormat[GFXFormatR5G5B5A1] = DXGI_FORMAT_B5G5R5A1_UNORM; + GFXD3D11TextureFormat[GFXFormatR5G5B5X1] = DXGI_FORMAT_UNKNOWN; + GFXD3D11TextureFormat[GFXFormatR32F] = DXGI_FORMAT_R32_FLOAT; + GFXD3D11TextureFormat[GFXFormatA4L4] = DXGI_FORMAT_UNKNOWN; + GFXD3D11TextureFormat[GFXFormatA8L8] = DXGI_FORMAT_R8G8_UNORM; + GFXD3D11TextureFormat[GFXFormatA8] = DXGI_FORMAT_A8_UNORM; + GFXD3D11TextureFormat[GFXFormatL8] = DXGI_FORMAT_R8_UNORM; + GFXD3D11TextureFormat[GFXFormatDXT1] = DXGI_FORMAT_BC1_UNORM; + GFXD3D11TextureFormat[GFXFormatDXT2] = DXGI_FORMAT_BC1_UNORM; + GFXD3D11TextureFormat[GFXFormatDXT3] = DXGI_FORMAT_BC2_UNORM; + GFXD3D11TextureFormat[GFXFormatDXT4] = DXGI_FORMAT_BC2_UNORM; + GFXD3D11TextureFormat[GFXFormatDXT5] = DXGI_FORMAT_BC3_UNORM; + GFXD3D11TextureFormat[GFXFormatR32G32B32A32F] = DXGI_FORMAT_R32G32B32A32_FLOAT; + GFXD3D11TextureFormat[GFXFormatR16G16B16A16F] = DXGI_FORMAT_R16G16B16A16_FLOAT; + GFXD3D11TextureFormat[GFXFormatL16] = DXGI_FORMAT_R16_UNORM; + GFXD3D11TextureFormat[GFXFormatR16G16B16A16] = DXGI_FORMAT_R16G16B16A16_UNORM; + GFXD3D11TextureFormat[GFXFormatR16G16] = DXGI_FORMAT_R16G16_UNORM; + GFXD3D11TextureFormat[GFXFormatR16F] = DXGI_FORMAT_R16_FLOAT; + GFXD3D11TextureFormat[GFXFormatR16G16F] = DXGI_FORMAT_R16G16_FLOAT; + GFXD3D11TextureFormat[GFXFormatR10G10B10A2] = DXGI_FORMAT_R10G10B10A2_UNORM; + GFXD3D11TextureFormat[GFXFormatD32] = DXGI_FORMAT_UNKNOWN; + GFXD3D11TextureFormat[GFXFormatD24X8] = DXGI_FORMAT_UNKNOWN; + GFXD3D11TextureFormat[GFXFormatD24S8] = DXGI_FORMAT_D24_UNORM_S8_UINT; + GFXD3D11TextureFormat[GFXFormatD24FS8] = DXGI_FORMAT_UNKNOWN; + GFXD3D11TextureFormat[GFXFormatD16] = DXGI_FORMAT_D16_UNORM; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11TextureFilter[GFXTextureFilterNone] = D3D11_FILTER_MIN_MAG_MIP_POINT; + GFXD3D11TextureFilter[GFXTextureFilterPoint] = D3D11_FILTER_MIN_MAG_MIP_POINT; + GFXD3D11TextureFilter[GFXTextureFilterLinear] = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + GFXD3D11TextureFilter[GFXTextureFilterAnisotropic] = D3D11_FILTER_ANISOTROPIC; + GFXD3D11TextureFilter[GFXTextureFilterPyramidalQuad] = D3D11_FILTER_ANISOTROPIC; + GFXD3D11TextureFilter[GFXTextureFilterGaussianQuad] = D3D11_FILTER_ANISOTROPIC; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11Blend[GFXBlendZero] = D3D11_BLEND_ZERO; + GFXD3D11Blend[GFXBlendOne] = D3D11_BLEND_ONE; + GFXD3D11Blend[GFXBlendSrcColor] = D3D11_BLEND_SRC_COLOR; + GFXD3D11Blend[GFXBlendInvSrcColor] = D3D11_BLEND_INV_SRC_COLOR; + GFXD3D11Blend[GFXBlendSrcAlpha] = D3D11_BLEND_SRC_ALPHA; + GFXD3D11Blend[GFXBlendInvSrcAlpha] = D3D11_BLEND_INV_SRC_ALPHA; + GFXD3D11Blend[GFXBlendDestAlpha] = D3D11_BLEND_DEST_ALPHA; + GFXD3D11Blend[GFXBlendInvDestAlpha] = D3D11_BLEND_INV_DEST_ALPHA; + GFXD3D11Blend[GFXBlendDestColor] = D3D11_BLEND_DEST_COLOR; + GFXD3D11Blend[GFXBlendInvDestColor] = D3D11_BLEND_INV_DEST_COLOR; + GFXD3D11Blend[GFXBlendSrcAlphaSat] = D3D11_BLEND_SRC_ALPHA_SAT; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11BlendOp[GFXBlendOpAdd] = D3D11_BLEND_OP_ADD; + GFXD3D11BlendOp[GFXBlendOpSubtract] = D3D11_BLEND_OP_SUBTRACT; + GFXD3D11BlendOp[GFXBlendOpRevSubtract] = D3D11_BLEND_OP_REV_SUBTRACT; + GFXD3D11BlendOp[GFXBlendOpMin] = D3D11_BLEND_OP_MIN; + GFXD3D11BlendOp[GFXBlendOpMax] = D3D11_BLEND_OP_MAX; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11StencilOp[GFXStencilOpKeep] = D3D11_STENCIL_OP_KEEP; + GFXD3D11StencilOp[GFXStencilOpZero] = D3D11_STENCIL_OP_ZERO; + GFXD3D11StencilOp[GFXStencilOpReplace] = D3D11_STENCIL_OP_REPLACE; + GFXD3D11StencilOp[GFXStencilOpIncrSat] = D3D11_STENCIL_OP_INCR_SAT; + GFXD3D11StencilOp[GFXStencilOpDecrSat] = D3D11_STENCIL_OP_DECR_SAT; + GFXD3D11StencilOp[GFXStencilOpInvert] = D3D11_STENCIL_OP_INVERT; + GFXD3D11StencilOp[GFXStencilOpIncr] = D3D11_STENCIL_OP_INCR; + GFXD3D11StencilOp[GFXStencilOpDecr] = D3D11_STENCIL_OP_DECR; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11CmpFunc[GFXCmpNever] = D3D11_COMPARISON_NEVER; + GFXD3D11CmpFunc[GFXCmpLess] = D3D11_COMPARISON_LESS; + GFXD3D11CmpFunc[GFXCmpEqual] = D3D11_COMPARISON_EQUAL; + GFXD3D11CmpFunc[GFXCmpLessEqual] = D3D11_COMPARISON_LESS_EQUAL; + GFXD3D11CmpFunc[GFXCmpGreater] = D3D11_COMPARISON_GREATER; + GFXD3D11CmpFunc[GFXCmpNotEqual] = D3D11_COMPARISON_NOT_EQUAL; + GFXD3D11CmpFunc[GFXCmpGreaterEqual] = D3D11_COMPARISON_GREATER_EQUAL; + GFXD3D11CmpFunc[GFXCmpAlways] = D3D11_COMPARISON_ALWAYS; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11CullMode[GFXCullNone] = D3D11_CULL_NONE; + GFXD3D11CullMode[GFXCullCW] = D3D11_CULL_FRONT; + GFXD3D11CullMode[GFXCullCCW] = D3D11_CULL_BACK; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11FillMode[GFXFillPoint] = D3D11_FILL_SOLID; + GFXD3D11FillMode[GFXFillWireframe] = D3D11_FILL_WIREFRAME; + GFXD3D11FillMode[GFXFillSolid] = D3D11_FILL_SOLID; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11PrimType[GFXPointList] = D3D_PRIMITIVE_TOPOLOGY_POINTLIST; + GFXD3D11PrimType[GFXLineList] = D3D_PRIMITIVE_TOPOLOGY_LINELIST; + GFXD3D11PrimType[GFXLineStrip] = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; + GFXD3D11PrimType[GFXTriangleList] = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; + GFXD3D11PrimType[GFXTriangleStrip] = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11TextureAddress[GFXAddressWrap] = D3D11_TEXTURE_ADDRESS_WRAP; + GFXD3D11TextureAddress[GFXAddressMirror] = D3D11_TEXTURE_ADDRESS_MIRROR; + GFXD3D11TextureAddress[GFXAddressClamp] = D3D11_TEXTURE_ADDRESS_CLAMP; + GFXD3D11TextureAddress[GFXAddressBorder] = D3D11_TEXTURE_ADDRESS_BORDER; + GFXD3D11TextureAddress[GFXAddressMirrorOnce] = D3D11_TEXTURE_ADDRESS_MIRROR_ONCE; +//------------------------------------------------------------------------------ +//------------------------------------------------------------------------------ + GFXD3D11DeclType[GFXDeclType_Float] = DXGI_FORMAT_R32_FLOAT; + GFXD3D11DeclType[GFXDeclType_Float2] = DXGI_FORMAT_R32G32_FLOAT; + GFXD3D11DeclType[GFXDeclType_Float3] = DXGI_FORMAT_R32G32B32_FLOAT; + GFXD3D11DeclType[GFXDeclType_Float4] = DXGI_FORMAT_R32G32B32A32_FLOAT; + GFXD3D11DeclType[GFXDeclType_Color] = DXGI_FORMAT_B8G8R8A8_UNORM; // DXGI_FORMAT_R8G8B8A8_UNORM; +} + diff --git a/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.h b/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.h new file mode 100644 index 000000000..daede2a1c --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.h @@ -0,0 +1,51 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + + +#ifndef _GFXD3D11ENUMTRANSLATE_H_ +#define _GFXD3D11ENUMTRANSLATE_H_ + +#include "gfx/D3D11/gfxD3D11Shader.h" +#include "gfx/gfxEnums.h" + +//------------------------------------------------------------------------------ + +namespace GFXD3D11EnumTranslate +{ + void init(); +}; + +//------------------------------------------------------------------------------ + +extern DXGI_FORMAT GFXD3D11TextureFormat[GFXFormat_COUNT]; +extern D3D11_FILTER GFXD3D11TextureFilter[GFXTextureFilter_COUNT]; +extern D3D11_BLEND GFXD3D11Blend[GFXBlend_COUNT]; +extern D3D11_BLEND_OP GFXD3D11BlendOp[GFXBlendOp_COUNT]; +extern D3D11_STENCIL_OP GFXD3D11StencilOp[GFXStencilOp_COUNT]; +extern D3D11_COMPARISON_FUNC GFXD3D11CmpFunc[GFXCmp_COUNT]; +extern D3D11_CULL_MODE GFXD3D11CullMode[GFXCull_COUNT]; +extern D3D11_FILL_MODE GFXD3D11FillMode[GFXFill_COUNT]; +extern D3D11_PRIMITIVE_TOPOLOGY GFXD3D11PrimType[GFXPT_COUNT]; +extern D3D11_TEXTURE_ADDRESS_MODE GFXD3D11TextureAddress[GFXAddress_COUNT]; +extern DXGI_FORMAT GFXD3D11DeclType[GFXDeclType_COUNT]; + +#endif \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.cpp b/Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.cpp new file mode 100644 index 000000000..6df92c68a --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.cpp @@ -0,0 +1,177 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11OcclusionQuery.h" + +#include "gui/3d/guiTSControl.h" + +#ifdef TORQUE_GATHER_METRICS +// For TickMs define +#include "T3D/gameBase/processList.h" +#endif + +GFXD3D11OcclusionQuery::GFXD3D11OcclusionQuery(GFXDevice *device) + : GFXOcclusionQuery(device), + mQuery(NULL) +{ +#ifdef TORQUE_GATHER_METRICS + mTimer = PlatformTimer::create(); + mTimer->getElapsedMs(); + + mTimeSinceEnd = 0; + mBeginFrame = 0; +#endif +} + +GFXD3D11OcclusionQuery::~GFXD3D11OcclusionQuery() +{ + SAFE_RELEASE(mQuery); + +#ifdef TORQUE_GATHER_METRICS + SAFE_DELETE(mTimer); +#endif +} + +bool GFXD3D11OcclusionQuery::begin() +{ + if(GFXDevice::getDisableOcclusionQuery()) + return true; + + if (mQuery == NULL) + { + D3D11_QUERY_DESC queryDesc; + queryDesc.Query = D3D11_QUERY_OCCLUSION; + queryDesc.MiscFlags = 0; + + HRESULT hRes = D3D11DEVICE->CreateQuery(&queryDesc, &mQuery); + + if(FAILED(hRes)) + { + AssertFatal(false, "GFXD3D11OcclusionQuery::begin - Hardware does not support D3D11 Occlusion-Queries, this should be caught before this type is created"); + } + + AssertISV(hRes != E_OUTOFMEMORY, "GFXD3D11OcclusionQuery::begin - Out of memory"); + } + + // Add a begin marker to the command buffer queue. + D3D11DEVICECONTEXT->Begin(mQuery); + +#ifdef TORQUE_GATHER_METRICS + mBeginFrame = GuiTSCtrl::getFrameCount(); +#endif + + return true; +} + +void GFXD3D11OcclusionQuery::end() +{ + if (GFXDevice::getDisableOcclusionQuery()) + return; + + // Add an end marker to the command buffer queue. + D3D11DEVICECONTEXT->End(mQuery); + +#ifdef TORQUE_GATHER_METRICS + AssertFatal( mBeginFrame == GuiTSCtrl::getFrameCount(), "GFXD3D11OcclusionQuery::end - ended query on different frame than begin!" ); + mTimer->getElapsedMs(); + mTimer->reset(); +#endif +} + +GFXD3D11OcclusionQuery::OcclusionQueryStatus GFXD3D11OcclusionQuery::getStatus(bool block, U32 *data) +{ + // If this ever shows up near the top of a profile then your system is + // GPU bound or you are calling getStatus too soon after submitting it. + // + // To test if you are GPU bound resize your window very small and see if + // this profile no longer appears at the top. + // + // To test if you are calling getStatus to soon after submitting it, + // check the value of mTimeSinceEnd in a debug build. If it is < half the length + // of time to render an individual frame you could have problems. + PROFILE_SCOPE(GFXD3D11OcclusionQuery_getStatus); + + if ( GFXDevice::getDisableOcclusionQuery() ) + return NotOccluded; + + if ( mQuery == NULL ) + return Unset; + +#ifdef TORQUE_GATHER_METRICS + //AssertFatal( mBeginFrame < GuiTSCtrl::getFrameCount(), "GFXD3D11OcclusionQuery::getStatus - called on the same frame as begin!" ); + + //U32 mTimeSinceEnd = mTimer->getElapsedMs(); + //AssertFatal( mTimeSinceEnd >= 5, "GFXD3DOcculsionQuery::getStatus - less than TickMs since called ::end!" ); +#endif + + HRESULT hRes; + U64 dwOccluded = 0; + + if ( block ) + { + while ((hRes = D3D11DEVICECONTEXT->GetData(mQuery, &dwOccluded, sizeof(U64), 0)) == S_FALSE); + } + else + { + hRes = D3D11DEVICECONTEXT->GetData(mQuery, &dwOccluded, sizeof(U64), 0); + } + + if (hRes == S_OK) + { + if (data != NULL) + *data = (U32)dwOccluded; + + return dwOccluded > 0 ? NotOccluded : Occluded; + } + + if (hRes == S_FALSE) + return Waiting; + + return Error; +} + +void GFXD3D11OcclusionQuery::zombify() +{ + SAFE_RELEASE( mQuery ); +} + +void GFXD3D11OcclusionQuery::resurrect() +{ + // Recreate the query + if( mQuery == NULL ) + { + D3D11_QUERY_DESC queryDesc; + queryDesc.Query = D3D11_QUERY_OCCLUSION; + queryDesc.MiscFlags = 0; + + HRESULT hRes = D3D11DEVICE->CreateQuery(&queryDesc, &mQuery); + + AssertISV( hRes != E_OUTOFMEMORY, "GFXD3D9QueryFence::resurrect - Out of memory" ); + } +} + +const String GFXD3D11OcclusionQuery::describeSelf() const +{ + // We've got nothing + return String(); +} \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.h b/Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.h new file mode 100644 index 000000000..9ec3774b9 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11OcclusionQuery.h @@ -0,0 +1,58 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFX_D3D11_OCCLUSIONQUERY_H_ +#define _GFX_D3D11_OCCLUSIONQUERY_H_ + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/gfxOcclusionQuery.h" + +#ifdef TORQUE_GATHER_METRICS + #include "platform/platformTimer.h" +#endif + +class GFXD3D11OcclusionQuery : public GFXOcclusionQuery +{ +private: + mutable ID3D11Query *mQuery; + +#ifdef TORQUE_GATHER_METRICS + U32 mBeginFrame; + U32 mTimeSinceEnd; + PlatformTimer *mTimer; +#endif + +public: + GFXD3D11OcclusionQuery(GFXDevice *device); + virtual ~GFXD3D11OcclusionQuery(); + + virtual bool begin(); + virtual void end(); + virtual OcclusionQueryStatus getStatus(bool block, U32 *data = NULL); + + // GFXResource + virtual void zombify(); + virtual void resurrect(); + virtual const String describeSelf() const; +}; + +#endif \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11PrimitiveBuffer.cpp b/Engine/source/gfx/D3D11/gfxD3D11PrimitiveBuffer.cpp new file mode 100644 index 000000000..74e5dbc4e --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11PrimitiveBuffer.cpp @@ -0,0 +1,222 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11EnumTranslate.h" +#include "gfx/D3D11/gfxD3D11PrimitiveBuffer.h" +#include "core/util/safeRelease.h" + +void GFXD3D11PrimitiveBuffer::prepare() +{ + D3D11->_setPrimitiveBuffer(this); +} + +void GFXD3D11PrimitiveBuffer::lock(U32 indexStart, U32 indexEnd, void **indexPtr) +{ + AssertFatal(!mLocked, "GFXD3D11PrimitiveBuffer::lock - Can't lock a primitive buffer more than once!"); + + mLocked = true; + D3D11_MAP flags = D3D11_MAP_WRITE_DISCARD; + + switch(mBufferType) + { + case GFXBufferTypeImmutable: + case GFXBufferTypeStatic: + case GFXBufferTypeDynamic: + flags = D3D11_MAP_WRITE_DISCARD; + break; + + case GFXBufferTypeVolatile: + // Get our range now... + AssertFatal(indexStart == 0, "Cannot get a subrange on a volatile buffer."); + AssertFatal(indexEnd < MAX_DYNAMIC_INDICES, "Cannot get more than MAX_DYNAMIC_INDICES in a volatile buffer. Up the constant!"); + + // Get the primtive buffer + mVolatileBuffer = D3D11->mDynamicPB; + + AssertFatal( mVolatileBuffer, "GFXD3D11PrimitiveBuffer::lock - No dynamic primitive buffer was available!"); + + // We created the pool when we requested this volatile buffer, so assume it exists... + if(mVolatileBuffer->mIndexCount + indexEnd > MAX_DYNAMIC_INDICES) + { + flags = D3D11_MAP_WRITE_DISCARD; + mVolatileStart = indexStart = 0; + indexEnd = indexEnd; + } + else + { + flags = D3D11_MAP_WRITE_NO_OVERWRITE; + mVolatileStart = indexStart = mVolatileBuffer->mIndexCount; + indexEnd += mVolatileBuffer->mIndexCount; + } + + mVolatileBuffer->mIndexCount = indexEnd + 1; + ib = mVolatileBuffer->ib; + + break; + } + + + mIndexStart = indexStart; + mIndexEnd = indexEnd; + + if (mBufferType == GFXBufferTypeStatic || mBufferType == GFXBufferTypeImmutable) + { + U32 sizeToLock = (indexEnd - indexStart) * sizeof(U16); + *indexPtr = new U8[sizeToLock]; + mLockedBuffer = *indexPtr; + } + else + { + D3D11_MAPPED_SUBRESOURCE pIndexData; + ZeroMemory(&pIndexData, sizeof(D3D11_MAPPED_SUBRESOURCE)); + + HRESULT hr = D3D11DEVICECONTEXT->Map(ib, 0, flags, 0, &pIndexData); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11PrimitiveBuffer::lock - Could not lock primitive buffer."); + } + + *indexPtr = (U8*)pIndexData.pData + (indexStart * sizeof(U16)) ; + } + + #ifdef TORQUE_DEBUG + + // Allocate a debug buffer large enough for the lock + // plus space for over and under run guard strings. + mLockedSize = (indexEnd - indexStart) * sizeof(U16); + const U32 guardSize = sizeof( _PBGuardString ); + mDebugGuardBuffer = new U8[mLockedSize+(guardSize*2)]; + + // Setup the guard strings. + dMemcpy( mDebugGuardBuffer, _PBGuardString, guardSize ); + dMemcpy( mDebugGuardBuffer + mLockedSize + guardSize, _PBGuardString, guardSize ); + + // Store the real lock pointer and return our debug pointer. + mLockedBuffer = *indexPtr; + *indexPtr = (U16*)( mDebugGuardBuffer + guardSize ); + + #endif // TORQUE_DEBUG +} + +void GFXD3D11PrimitiveBuffer::unlock() +{ + #ifdef TORQUE_DEBUG + + if ( mDebugGuardBuffer ) + { + const U32 guardSize = sizeof( _PBGuardString ); + + // First check the guard areas for overwrites. + AssertFatal( dMemcmp( mDebugGuardBuffer, _PBGuardString, guardSize ) == 0, + "GFXD3D11PrimitiveBuffer::unlock - Caught lock memory underrun!" ); + AssertFatal( dMemcmp( mDebugGuardBuffer + mLockedSize + guardSize, _PBGuardString, guardSize ) == 0, + "GFXD3D11PrimitiveBuffer::unlock - Caught lock memory overrun!" ); + + // Copy the debug content down to the real PB. + dMemcpy( mLockedBuffer, mDebugGuardBuffer + guardSize, mLockedSize ); + + // Cleanup. + delete [] mDebugGuardBuffer; + mDebugGuardBuffer = NULL; + //mLockedBuffer = NULL; + mLockedSize = 0; + } + + #endif // TORQUE_DEBUG + + const U32 totalSize = this->mIndexCount * sizeof(U16); + + if (mBufferType == GFXBufferTypeStatic || mBufferType == GFXBufferTypeImmutable) + { + //set up the update region of the buffer + D3D11_BOX box; + box.back = 1; + box.front = 0; + box.top = 0; + box.bottom =1; + box.left = mIndexStart *sizeof(U16); + box.right = mIndexEnd * sizeof(U16); + //update the real ib buffer + D3D11DEVICECONTEXT->UpdateSubresource(ib, 0, &box,mLockedBuffer,totalSize, 0); + //clean up the old buffer + delete[] mLockedBuffer; + mLockedBuffer = NULL; + } + else + { + D3D11DEVICECONTEXT->Unmap(ib,0); + } + + mLocked = false; + mIsFirstLock = false; + mVolatileBuffer = NULL; +} + +GFXD3D11PrimitiveBuffer::~GFXD3D11PrimitiveBuffer() +{ + if( mBufferType != GFXBufferTypeVolatile ) + { + SAFE_RELEASE(ib); + } +} + +void GFXD3D11PrimitiveBuffer::zombify() +{ + if (mBufferType == GFXBufferTypeStatic || mBufferType == GFXBufferTypeImmutable) + return; + + AssertFatal(!mLocked, "GFXD3D11PrimitiveBuffer::zombify - Cannot zombify a locked buffer!"); + + if (mBufferType == GFXBufferTypeVolatile) + { + // We must null the volatile buffer else we're holding + // a dead pointer which can be set on the device. + ib = NULL; + return; + } + + // Dynamic buffers get released. + SAFE_RELEASE(ib); +} + +void GFXD3D11PrimitiveBuffer::resurrect() +{ + if ( mBufferType != GFXBufferTypeDynamic ) + return; + + D3D11_BUFFER_DESC desc; + desc.ByteWidth = sizeof(U16) * mIndexCount; + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.BindFlags = D3D11_BIND_INDEX_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.MiscFlags = 0; + desc.StructureByteStride = 0; + + HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &ib); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11PrimitiveBuffer::resurrect - Failed to allocate an index buffer."); + } +} diff --git a/Engine/source/gfx/D3D11/gfxD3D11PrimitiveBuffer.h b/Engine/source/gfx/D3D11/gfxD3D11PrimitiveBuffer.h new file mode 100644 index 000000000..1be1952d4 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11PrimitiveBuffer.h @@ -0,0 +1,83 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3D11PRIMITIVEBUFFER_H_ +#define _GFXD3D11PRIMITIVEBUFFER_H_ + +#include "gfx/gfxPrimitiveBuffer.h" + +class GFXD3D11PrimitiveBuffer : public GFXPrimitiveBuffer +{ +public: + ID3D11Buffer *ib; + StrongRefPtr mVolatileBuffer; + U32 mVolatileStart; + U32 mIndexStart; + U32 mIndexEnd; + +#ifdef TORQUE_DEBUG + #define _PBGuardString "GFX_PRIMTIVE_BUFFER_GUARD_STRING" + U8 *mDebugGuardBuffer; + U32 mLockedSize; +#endif TORQUE_DEBUG + + void *mLockedBuffer; + bool mLocked; + bool mIsFirstLock; + + GFXD3D11PrimitiveBuffer( GFXDevice *device, + U32 indexCount, + U32 primitiveCount, + GFXBufferType bufferType ); + + virtual ~GFXD3D11PrimitiveBuffer(); + + virtual void lock(U32 indexStart, U32 indexEnd, void **indexPtr); + virtual void unlock(); + + virtual void prepare(); + + // GFXResource interface + virtual void zombify(); + virtual void resurrect(); +}; + +inline GFXD3D11PrimitiveBuffer::GFXD3D11PrimitiveBuffer( GFXDevice *device, + U32 indexCount, + U32 primitiveCount, + GFXBufferType bufferType ) + : GFXPrimitiveBuffer( device, indexCount, primitiveCount, bufferType ) +{ + mVolatileStart = 0; + ib = NULL; + mIsFirstLock = true; + mLocked = false; +#ifdef TORQUE_DEBUG + mDebugGuardBuffer = NULL; + mLockedBuffer = NULL; + mLockedSize = 0; + mIndexStart = 0; + mIndexEnd = 0; +#endif +} + +#endif diff --git a/Engine/source/gfx/D3D11/gfxD3D11QueryFence.cpp b/Engine/source/gfx/D3D11/gfxD3D11QueryFence.cpp new file mode 100644 index 000000000..f111ce432 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11QueryFence.cpp @@ -0,0 +1,110 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11QueryFence.h" + +GFXD3D11QueryFence::~GFXD3D11QueryFence() +{ + SAFE_RELEASE(mQuery); +} + +void GFXD3D11QueryFence::issue() +{ + PROFILE_START(GFXD3D11QueryFence_issue); + + // Create the query if we need to + if(mQuery == NULL) + { + D3D11_QUERY_DESC QueryDesc; + QueryDesc.Query = D3D11_QUERY_EVENT; + QueryDesc.MiscFlags = 0; + + HRESULT hRes = D3D11DEVICE->CreateQuery(&QueryDesc, &mQuery); + + if(FAILED(hRes)) + { + AssertFatal(false, "Hardware does not support D3D11 Queries, this should be caught before this fence type is created" ); + } + + AssertISV(hRes != E_OUTOFMEMORY, "Out of memory"); + } + + // Issue the query + D3D11DEVICECONTEXT->End(mQuery); + PROFILE_END(); +} + +GFXFence::FenceStatus GFXD3D11QueryFence::getStatus() const +{ + if(mQuery == NULL) + return GFXFence::Unset; + + HRESULT hRes = D3D11DEVICECONTEXT->GetData(mQuery, NULL, 0, 0); + + return (hRes == S_OK ? GFXFence::Processed : GFXFence::Pending); +} + +void GFXD3D11QueryFence::block() +{ + PROFILE_SCOPE(GFXD3D11QueryFence_block); + + // Calling block() before issue() is valid, catch this case + if( mQuery == NULL ) + return; + + HRESULT hRes; + while((hRes = D3D11DEVICECONTEXT->GetData(mQuery, NULL, 0, 0)) == S_FALSE); //D3DGETDATA_FLUSH + +} + +void GFXD3D11QueryFence::zombify() +{ + // Release our query + SAFE_RELEASE( mQuery ); +} + +void GFXD3D11QueryFence::resurrect() +{ + // Recreate the query + if(mQuery == NULL) + { + D3D11_QUERY_DESC QueryDesc; + QueryDesc.Query = D3D11_QUERY_EVENT; + QueryDesc.MiscFlags = 0; + + HRESULT hRes = D3D11DEVICE->CreateQuery(&QueryDesc, &mQuery); + + if(FAILED(hRes)) + { + AssertFatal(false, "GFXD3D11QueryFence::resurrect - Hardware does not support D3D11 Queries, this should be caught before this fence type is created"); + } + + AssertISV(hRes != E_OUTOFMEMORY, "GFXD3D11QueryFence::resurrect - Out of memory"); + } +} + +const String GFXD3D11QueryFence::describeSelf() const +{ + // We've got nothing + return String(); +} \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11QueryFence.h b/Engine/source/gfx/D3D11/gfxD3D11QueryFence.h new file mode 100644 index 000000000..5113651c9 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11QueryFence.h @@ -0,0 +1,49 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFX_D3D11_QUERYFENCE_H_ +#define _GFX_D3D11_QUERYFENCE_H_ + +#include "gfx/gfxFence.h" +#include "gfx/gfxResource.h" +#include "gfx/D3D11/gfxD3D11Device.h" + +class GFXD3D11QueryFence : public GFXFence +{ +private: + mutable ID3D11Query *mQuery; + +public: + GFXD3D11QueryFence( GFXDevice *device ) : GFXFence( device ), mQuery( NULL ) {}; + virtual ~GFXD3D11QueryFence(); + + virtual void issue(); + virtual FenceStatus getStatus() const; + virtual void block(); + + // GFXResource interface + virtual void zombify(); + virtual void resurrect(); + virtual const String describeSelf() const; +}; + +#endif \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11Shader.cpp b/Engine/source/gfx/D3D11/gfxD3D11Shader.cpp new file mode 100644 index 000000000..a5273a93e --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11Shader.cpp @@ -0,0 +1,1542 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "platform/platform.h" +#include "gfx/D3D11/gfxD3D11Shader.h" +#include "core/frameAllocator.h" +#include "core/stream/fileStream.h" +#include "core/util/safeDelete.h" +#include "console/console.h" + +extern bool gDisassembleAllShaders; + +#pragma comment(lib, "d3dcompiler.lib") + +gfxD3DIncludeRef GFXD3D11Shader::smD3DInclude = NULL; + +class gfxD3D11Include : public ID3DInclude, public StrongRefBase +{ +private: + + Vector mLastPath; + +public: + + void setPath(const String &path) + { + mLastPath.clear(); + mLastPath.push_back(path); + } + + gfxD3D11Include() {} + virtual ~gfxD3D11Include() {} + + STDMETHOD(Open)(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes); + STDMETHOD(Close)(THIS_ LPCVOID pData); +}; + +HRESULT gfxD3D11Include::Open(THIS_ D3D_INCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes) +{ + using namespace Torque; + // First try making the path relative to the parent. + Torque::Path path = Torque::Path::Join( mLastPath.last(), '/', pFileName ); + path = Torque::Path::CompressPath( path ); + + if ( !Torque::FS::ReadFile( path, (void *&)*ppData, *pBytes, true ) ) + { + // Ok... now try using the path as is. + path = String( pFileName ); + path = Torque::Path::CompressPath( path ); + + if ( !Torque::FS::ReadFile( path, (void *&)*ppData, *pBytes, true ) ) + { + AssertISV(false, avar( "Failed to open include '%s'.", pFileName)); + return E_FAIL; + } + } + + // If the data was of zero size then we cannot recurse + // into this file and DX won't call Close() below. + // + // So in this case don't push on the path. + if ( *pBytes > 0 ) + mLastPath.push_back( path.getRootAndPath() ); + + return S_OK; +} + +HRESULT gfxD3D11Include::Close( THIS_ LPCVOID pData ) +{ + // Free the data file and pop its path off the stack. + delete [] (U8*)pData; + mLastPath.pop_back(); + + return S_OK; +} + +GFXD3D11ShaderConstHandle::GFXD3D11ShaderConstHandle() +{ + clear(); +} + +const String& GFXD3D11ShaderConstHandle::getName() const +{ + if ( mVertexConstant ) + return mVertexHandle.name; + else + return mPixelHandle.name; +} + +GFXShaderConstType GFXD3D11ShaderConstHandle::getType() const +{ + if ( mVertexConstant ) + return mVertexHandle.constType; + else + return mPixelHandle.constType; +} + +U32 GFXD3D11ShaderConstHandle::getArraySize() const +{ + if ( mVertexConstant ) + return mVertexHandle.arraySize; + else + return mPixelHandle.arraySize; +} + +S32 GFXD3D11ShaderConstHandle::getSamplerRegister() const +{ + if ( !mValid || !isSampler() ) + return -1; + + // We always store sampler type and register index in the pixelHandle, + // sampler registers are shared between vertex and pixel shaders anyway. + + return mPixelHandle.offset; +} + +GFXD3D11ConstBufferLayout::GFXD3D11ConstBufferLayout() +{ + mSubBuffers.reserve(CBUFFER_MAX); +} + +bool GFXD3D11ConstBufferLayout::set(const ParamDesc& pd, const GFXShaderConstType constType, const U32 inSize, const void* data, U8* basePointer) +{ + PROFILE_SCOPE(GenericConstBufferLayout_set); + S32 size = inSize; + // Shader compilers like to optimize float4x4 uniforms into float3x3s. + // So long as the real paramater is a matrix of-some-type and the data + // passed in is a MatrixF ( which is will be ), we DO NOT have a + // mismatched const type. + AssertFatal(pd.constType == constType || + ( + (pd.constType == GFXSCT_Float2x2 || + pd.constType == GFXSCT_Float3x3 || + pd.constType == GFXSCT_Float4x4) && + (constType == GFXSCT_Float2x2 || + constType == GFXSCT_Float3x3 || + constType == GFXSCT_Float4x4) + ), "Mismatched const type!"); + + // This "cute" bit of code allows us to support 2x3 and 3x3 matrices in shader constants but use our MatrixF class. Yes, a hack. -BTR + switch (pd.constType) + { + case GFXSCT_Float2x2: + case GFXSCT_Float3x3: + case GFXSCT_Float4x4: + return setMatrix(pd, constType, size, data, basePointer); + break; + // TODO add other AlignedVector here + case GFXSCT_Float2: + if (size > sizeof(Point2F)) + size = pd.size; + default: + break; + } + + AssertFatal(pd.size >= size, "Not enough room in the buffer for this data!"); + + // Ok, we only set data if it's different than the data we already have, this maybe more expensive than just setting the data, but + // we'll have to do some timings to see. For example, the lighting shader constants rarely change, but we can't assume that at the + // renderInstMgr level, but we can check down here. -BTR + if (dMemcmp(basePointer + pd.offset, data, size) != 0) + { + dMemcpy(basePointer + pd.offset, data, size); + return true; + } + return false; +} + +bool GFXD3D11ConstBufferLayout::setMatrix(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer) +{ + PROFILE_SCOPE(GFXD3D11ConstBufferLayout_setMatrix); + + if (pd.constType == GFXSCT_Float4x4) + { + // Special case, we can just blast this guy. + AssertFatal(pd.size >= size, "Not enough room in the buffer for this data!"); + if (dMemcmp(basePointer+pd.offset, data, size) != 0) + { + dMemcpy(basePointer+pd.offset, data, size); + return true; + } + + return false; + } + else + { + PROFILE_SCOPE(GFXD3D11ConstBufferLayout_setMatrix_not4x4); + + // Figure out how big of a chunk we are copying. We're going to copy 4 columns by N rows of data + U32 csize; + switch (pd.constType) + { + case GFXSCT_Float2x2 : + csize = 24; //this takes up 16+8 + break; + case GFXSCT_Float3x3 : + csize = 44; //This takes up 16+16+12 + break; + default: + AssertFatal(false, "Unhandled case!"); + return false; + break; + } + + // Loop through and copy + bool ret = false; + U8* currDestPointer = basePointer+pd.offset; + const U8* currSourcePointer = static_cast(data); + const U8* endData = currSourcePointer + size; + while (currSourcePointer < endData) + { + if (dMemcmp(currDestPointer, currSourcePointer, csize) != 0) + { + dMemcpy(currDestPointer, currSourcePointer, csize); + ret = true; + } + + currDestPointer += csize; + currSourcePointer += sizeof(MatrixF); + } + + return ret; + } +} + +//------------------------------------------------------------------------------ +GFXD3D11ShaderConstBuffer::GFXD3D11ShaderConstBuffer( GFXD3D11Shader* shader, + GFXD3D11ConstBufferLayout* vertexLayout, + GFXD3D11ConstBufferLayout* pixelLayout) +{ + AssertFatal( shader, "GFXD3D11ShaderConstBuffer() - Got a null shader!" ); + + // We hold on to this so we don't have to call + // this virtual method during activation. + mShader = shader; + + for (U32 i = 0; i < CBUFFER_MAX; ++i) + { + mConstantBuffersV[i] = NULL; + mConstantBuffersP[i] = NULL; + } + + // TODO: Remove buffers and layouts that don't exist for performance? + //Mandatory + mVertexConstBufferLayout = vertexLayout; + mVertexConstBuffer = new GenericConstBuffer(vertexLayout); + + mPixelConstBufferLayout = pixelLayout; + mPixelConstBuffer = new GenericConstBuffer(pixelLayout); + + _createBuffers(); + +} + +GFXD3D11ShaderConstBuffer::~GFXD3D11ShaderConstBuffer() +{ + // release constant buffer + for (U32 i = 0; i < CBUFFER_MAX; ++i) + { + SAFE_RELEASE(mConstantBuffersP[i]); + SAFE_RELEASE(mConstantBuffersV[i]); + } + + SAFE_DELETE(mVertexConstBuffer); + SAFE_DELETE(mPixelConstBuffer); + + + if ( mShader ) + mShader->_unlinkBuffer( this ); +} + +void GFXD3D11ShaderConstBuffer::_createBuffers() +{ + HRESULT hr; + // Create a vertex constant buffer + if (mVertexConstBufferLayout->getBufferSize() > 0) + { + const Vector &subBuffers = mVertexConstBufferLayout->getSubBufferDesc(); + for (U32 i = 0; i < subBuffers.size(); ++i) + { + D3D11_BUFFER_DESC cbDesc; + cbDesc.ByteWidth = subBuffers[i].size; + cbDesc.Usage = D3D11_USAGE_DEFAULT; + cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + cbDesc.CPUAccessFlags = 0; + cbDesc.MiscFlags = 0; + cbDesc.StructureByteStride = 0; + + hr = D3D11DEVICE->CreateBuffer(&cbDesc, NULL, &mConstantBuffersV[i]); + + if (FAILED(hr)) + { + AssertFatal(false, "can't create constant mConstantBuffersV!"); + } + } + } + + // Create a pixel constant buffer + if (mPixelConstBufferLayout->getBufferSize()) + { + const Vector &subBuffers = mPixelConstBufferLayout->getSubBufferDesc(); + for (U32 i = 0; i < subBuffers.size(); ++i) + { + // Create a pixel float constant buffer + D3D11_BUFFER_DESC cbDesc; + cbDesc.ByteWidth = subBuffers[i].size; + cbDesc.Usage = D3D11_USAGE_DEFAULT; + cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; + cbDesc.CPUAccessFlags = 0; + cbDesc.MiscFlags = 0; + cbDesc.StructureByteStride = 0; + + hr = D3D11DEVICE->CreateBuffer(&cbDesc, NULL, &mConstantBuffersP[i]); + + if (FAILED(hr)) + { + AssertFatal(false, "can't create constant mConstantBuffersP!"); + } + } + } +} + +GFXShader* GFXD3D11ShaderConstBuffer::getShader() +{ + return mShader; +} + +// This is kind of cheesy, but I don't think templates would work well here because +// these functions potentially need to be handled differently by other derived types +template +inline void GFXD3D11ShaderConstBuffer::SET_CONSTANT( GFXShaderConstHandle* handle, const T& fv, + GenericConstBuffer *vBuffer, GenericConstBuffer *pBuffer ) +{ + AssertFatal(static_cast(handle), "Incorrect const buffer type!"); + const GFXD3D11ShaderConstHandle* h = static_cast(handle); + AssertFatal(h, "Handle is NULL!" ); + AssertFatal(h->isValid(), "Handle is not valid!" ); + AssertFatal(!h->isSampler(), "Handle is sampler constant!" ); + AssertFatal(!mShader.isNull(), "Buffer's shader is null!" ); + AssertFatal(!h->mShader.isNull(), "Handle's shader is null!" ); + AssertFatal(h->mShader.getPointer() == mShader.getPointer(), "Mismatched shaders!"); + + if ( h->mInstancingConstant ) + { + dMemcpy( mInstPtr+h->mPixelHandle.offset, &fv, sizeof( fv ) ); + return; + } + if (h->mVertexConstant) + vBuffer->set(h->mVertexHandle, fv); + if (h->mPixelConstant) + pBuffer->set(h->mPixelHandle, fv); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const F32 fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2F& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3F& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4F& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const PlaneF& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const ColorF& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const S32 f) +{ + // This is the only type that is allowed to be used + // with a sampler shader constant type, but it is only + // allowed to be set from GLSL. + // + // So we ignore it here... all other cases will assert. + // + if ( ((GFXD3D11ShaderConstHandle*)handle)->isSampler() ) + return; + + SET_CONSTANT(handle, f, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point2I& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point3I& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const Point4I& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const AlignedArray& fv) +{ + SET_CONSTANT(handle, fv, mVertexConstBuffer, mPixelConstBuffer); +} +#undef SET_CONSTANT + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF& mat, const GFXShaderConstType matrixType) +{ + AssertFatal(handle, "Handle is NULL!" ); + AssertFatal(handle->isValid(), "Handle is not valid!" ); + + AssertFatal(static_cast(handle), "Incorrect const buffer type!"); + const GFXD3D11ShaderConstHandle* h = static_cast(handle); + AssertFatal(!h->isSampler(), "Handle is sampler constant!" ); + AssertFatal(h->mShader == mShader, "Mismatched shaders!"); + + MatrixF transposed; + mat.transposeTo(transposed); + + if (h->mInstancingConstant) + { + if ( matrixType == GFXSCT_Float4x4 ) + dMemcpy( mInstPtr+h->mPixelHandle.offset, mat, sizeof( mat ) ); + + // TODO: Support 3x3 and 2x2 matricies? + return; + } + + if (h->mVertexConstant) + mVertexConstBuffer->set(h->mVertexHandle, transposed, matrixType); + if (h->mPixelConstant) + mPixelConstBuffer->set(h->mPixelHandle, transposed, matrixType); +} + +void GFXD3D11ShaderConstBuffer::set(GFXShaderConstHandle* handle, const MatrixF* mat, const U32 arraySize, const GFXShaderConstType matrixType) +{ + AssertFatal(handle, "Handle is NULL!" ); + AssertFatal(handle->isValid(), "Handle is not valid!" ); + + AssertFatal(static_cast(handle), "Incorrect const buffer type!"); + const GFXD3D11ShaderConstHandle* h = static_cast(handle); + AssertFatal(!h->isSampler(), "Handle is sampler constant!" ); + AssertFatal(h->mShader == mShader, "Mismatched shaders!"); + + static Vector transposed; + if (arraySize > transposed.size()) + transposed.setSize(arraySize); + for (U32 i = 0; i < arraySize; i++) + mat[i].transposeTo(transposed[i]); + + // TODO: Maybe support this in the future? + if (h->mInstancingConstant) + return; + + if (h->mVertexConstant) + mVertexConstBuffer->set(h->mVertexHandle, transposed.begin(), arraySize, matrixType); + if (h->mPixelConstant) + mPixelConstBuffer->set(h->mPixelHandle, transposed.begin(), arraySize, matrixType); +} + +const String GFXD3D11ShaderConstBuffer::describeSelf() const +{ + String ret; + ret = String(" GFXD3D11ShaderConstBuffer\n"); + + for (U32 i = 0; i < mVertexConstBufferLayout->getParameterCount(); i++) + { + GenericConstBufferLayout::ParamDesc pd; + mVertexConstBufferLayout->getDesc(i, pd); + + ret += String::ToString(" Constant name: %s", pd.name); + } + + return ret; +} + +void GFXD3D11ShaderConstBuffer::zombify() +{ +} + +void GFXD3D11ShaderConstBuffer::resurrect() +{ +} + +bool GFXD3D11ShaderConstBuffer::isDirty() +{ + bool ret = mVertexConstBuffer->isDirty(); + ret |= mPixelConstBuffer->isDirty(); + + return ret; +} + +void GFXD3D11ShaderConstBuffer::activate( GFXD3D11ShaderConstBuffer *prevShaderBuffer ) +{ + PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate); + + // NOTE: This is a really critical function as it gets + // called between every draw call to update the constants. + // + // Alot of the calls here are inlined... be careful + // what you change. + + // If the buffer has changed we need to compare it + // with the new buffer to see if we can skip copying + // equal buffer content. + // + // If the buffer hasn't changed then we only will + // be copying the changes that have occured since + // the last activate call. + if ( prevShaderBuffer != this ) + { + // If the previous buffer is dirty, than we can't compare + // against it, because it hasn't sent its contents to the + // card yet and must be copied. + if ( prevShaderBuffer && !prevShaderBuffer->isDirty() ) + { + PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate_dirty_check_1); + // If the buffer content is equal then we set the dirty + // flag to false knowing the current state of the card matches + // the new buffer. + // + // If the content is not equal we set the dirty flag to + // true which causes the full content of the buffer to be + // copied to the card. + // + mVertexConstBuffer->setDirty( !prevShaderBuffer->mVertexConstBuffer->isEqual( mVertexConstBuffer ) ); + mPixelConstBuffer->setDirty( !prevShaderBuffer->mPixelConstBuffer->isEqual( mPixelConstBuffer ) ); + } + else + { + // This happens rarely... but it can happen. + // We copy the entire dirty state to the card. + PROFILE_SCOPE(GFXD3D11ShaderConstBuffer_activate_dirty_check_2); + + mVertexConstBuffer->setDirty( true ); + mPixelConstBuffer->setDirty( true ); + } + } + + ID3D11DeviceContext* devCtx = D3D11DEVICECONTEXT; + + D3D11_MAPPED_SUBRESOURCE pConstData; + ZeroMemory(&pConstData, sizeof(D3D11_MAPPED_SUBRESOURCE)); + + const U8* buf; + HRESULT hr; + U32 nbBuffers = 0; + if(mVertexConstBuffer->isDirty()) + { + const Vector &subBuffers = mVertexConstBufferLayout->getSubBufferDesc(); + // TODO: This is not very effecient updating the whole lot, re-implement the dirty system to work with multiple constant buffers. + // TODO: Implement DX 11.1 UpdateSubresource1 which supports updating ranges with constant buffers + buf = mVertexConstBuffer->getEntireBuffer(); + for (U32 i = 0; i < subBuffers.size(); ++i) + { + const ConstSubBufferDesc &desc = subBuffers[i]; + devCtx->UpdateSubresource(mConstantBuffersV[i], 0, NULL, buf + desc.start, desc.size, 0); + nbBuffers++; + } + + devCtx->VSSetConstantBuffers(0, nbBuffers, mConstantBuffersV); + } + + nbBuffers = 0; + + if(mPixelConstBuffer->isDirty()) + { + const Vector &subBuffers = mPixelConstBufferLayout->getSubBufferDesc(); + // TODO: This is not very effecient updating the whole lot, re-implement the dirty system to work with multiple constant buffers. + // TODO: Implement DX 11.1 UpdateSubresource1 which supports updating ranges with constant buffers + buf = mPixelConstBuffer->getEntireBuffer(); + for (U32 i = 0; i < subBuffers.size(); ++i) + { + const ConstSubBufferDesc &desc = subBuffers[i]; + devCtx->UpdateSubresource(mConstantBuffersP[i], 0, NULL, buf + desc.start, desc.size, 0); + nbBuffers++; + } + + devCtx->PSSetConstantBuffers(0, nbBuffers, mConstantBuffersP); + } + + #ifdef TORQUE_DEBUG + // Make sure all the constants for this buffer were assigned. + if(mWasLost) + { + mVertexConstBuffer->assertUnassignedConstants( mShader->getVertexShaderFile().c_str() ); + mPixelConstBuffer->assertUnassignedConstants( mShader->getPixelShaderFile().c_str() ); + } + #endif + + // Clear the lost state. + mWasLost = false; +} + +void GFXD3D11ShaderConstBuffer::onShaderReload( GFXD3D11Shader *shader ) +{ + AssertFatal( shader == mShader, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" ); + + // release constant buffers + for (U32 i = 0; i < CBUFFER_MAX; ++i) + { + SAFE_RELEASE(mConstantBuffersP[i]); + SAFE_RELEASE(mConstantBuffersV[i]); + } + + SAFE_DELETE( mVertexConstBuffer ); + SAFE_DELETE( mPixelConstBuffer ); + + AssertFatal( mVertexConstBufferLayout == shader->mVertexConstBufferLayout, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" ); + AssertFatal( mPixelConstBufferLayout == shader->mPixelConstBufferLayout, "GFXD3D11ShaderConstBuffer::onShaderReload is hosed!" ); + + mVertexConstBuffer = new GenericConstBuffer( mVertexConstBufferLayout ); + mPixelConstBuffer = new GenericConstBuffer( mPixelConstBufferLayout ); + + _createBuffers(); + + // Set the lost state. + mWasLost = true; +} + +//------------------------------------------------------------------------------ + +GFXD3D11Shader::GFXD3D11Shader() +{ + VECTOR_SET_ASSOCIATION( mShaderConsts ); + + AssertFatal(D3D11DEVICE, "Invalid device for shader."); + mVertShader = NULL; + mPixShader = NULL; + mVertexConstBufferLayout = NULL; + mPixelConstBufferLayout = NULL; + + if( smD3DInclude == NULL ) + smD3DInclude = new gfxD3D11Include; +} + +//------------------------------------------------------------------------------ + +GFXD3D11Shader::~GFXD3D11Shader() +{ + for (HandleMap::Iterator i = mHandles.begin(); i != mHandles.end(); i++) + delete i->value; + + // delete const buffer layouts + SAFE_DELETE(mVertexConstBufferLayout); + SAFE_DELETE(mPixelConstBufferLayout); + + // release shaders + SAFE_RELEASE(mVertShader); + SAFE_RELEASE(mPixShader); + //maybe add SAFE_RELEASE(mVertexCode) ? +} + +bool GFXD3D11Shader::_init() +{ + PROFILE_SCOPE( GFXD3D11Shader_Init ); + + SAFE_RELEASE(mVertShader); + SAFE_RELEASE(mPixShader); + + // Create the macro array including the system wide macros. + const U32 macroCount = smGlobalMacros.size() + mMacros.size() + 2; + FrameTemp d3dMacros( macroCount ); + + for ( U32 i=0; i < smGlobalMacros.size(); i++ ) + { + d3dMacros[i].Name = smGlobalMacros[i].name.c_str(); + d3dMacros[i].Definition = smGlobalMacros[i].value.c_str(); + } + + for ( U32 i=0; i < mMacros.size(); i++ ) + { + d3dMacros[i+smGlobalMacros.size()].Name = mMacros[i].name.c_str(); + d3dMacros[i+smGlobalMacros.size()].Definition = mMacros[i].value.c_str(); + } + + //TODO support D3D_FEATURE_LEVEL properly with shaders instead of hard coding at hlsl 5 + d3dMacros[macroCount - 2].Name = "TORQUE_SM"; + d3dMacros[macroCount - 2].Definition = "50"; + + memset(&d3dMacros[macroCount - 1], 0, sizeof(D3D_SHADER_MACRO)); + + if ( !mVertexConstBufferLayout ) + mVertexConstBufferLayout = new GFXD3D11ConstBufferLayout(); + else + mVertexConstBufferLayout->clear(); + + if ( !mPixelConstBufferLayout ) + mPixelConstBufferLayout = new GFXD3D11ConstBufferLayout(); + else + mPixelConstBufferLayout->clear(); + + + mSamplerDescriptions.clear(); + mShaderConsts.clear(); + + if ( !Con::getBoolVariable( "$shaders::forceLoadCSF", false ) ) + { + if (!mVertexFile.isEmpty() && !_compileShader( mVertexFile, "vs_5_0", d3dMacros, mVertexConstBufferLayout, mSamplerDescriptions ) ) + return false; + + if (!mPixelFile.isEmpty() && !_compileShader( mPixelFile, "ps_5_0", d3dMacros, mPixelConstBufferLayout, mSamplerDescriptions ) ) + return false; + + } + else + { + if ( !_loadCompiledOutput( mVertexFile, "vs_5_0", mVertexConstBufferLayout, mSamplerDescriptions ) ) + { + if ( smLogErrors ) + Con::errorf( "GFXD3D11Shader::init - Unable to load precompiled vertex shader for '%s'.", mVertexFile.getFullPath().c_str() ); + + return false; + } + + if ( !_loadCompiledOutput( mPixelFile, "ps_5_0", mPixelConstBufferLayout, mSamplerDescriptions ) ) + { + if ( smLogErrors ) + Con::errorf( "GFXD3D11Shader::init - Unable to load precompiled pixel shader for '%s'.", mPixelFile.getFullPath().c_str() ); + + return false; + } + } + + // Existing handles are resored to an uninitialized state. + // Those that are found when parsing the layout parameters + // will then be re-initialized. + HandleMap::Iterator iter = mHandles.begin(); + for ( ; iter != mHandles.end(); iter++ ) + (iter->value)->clear(); + + _buildShaderConstantHandles(mVertexConstBufferLayout, true); + _buildShaderConstantHandles(mPixelConstBufferLayout, false); + + _buildSamplerShaderConstantHandles( mSamplerDescriptions ); + _buildInstancingShaderConstantHandles(); + + // Notify any existing buffers that the buffer + // layouts have changed and they need to update. + Vector::iterator biter = mActiveBuffers.begin(); + for ( ; biter != mActiveBuffers.end(); biter++ ) + ((GFXD3D11ShaderConstBuffer*)(*biter))->onShaderReload( this ); + + return true; +} + +bool GFXD3D11Shader::_compileShader( const Torque::Path &filePath, + const String& target, + const D3D_SHADER_MACRO *defines, + GenericConstBufferLayout* bufferLayout, + Vector &samplerDescriptions ) +{ + PROFILE_SCOPE( GFXD3D11Shader_CompileShader ); + + using namespace Torque; + + HRESULT res = E_FAIL; + ID3DBlob* code = NULL; + ID3DBlob* errorBuff = NULL; + ID3D11ShaderReflection* reflectionTable = NULL; + +#ifdef TORQUE_DEBUG + U32 flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS; +#else + U32 flags = D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_OPTIMIZATION_LEVEL3; //TODO double check load times with D3DCOMPILE_OPTIMIZATION_LEVEL3 + //recommended flags for NSight, uncomment to use. NSight should be used in release mode only. *Still works with above flags however + //flags = D3DCOMPILE_DEBUG | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_PREFER_FLOW_CONTROL | D3DCOMPILE_SKIP_OPTIMIZATION; +#endif + +#ifdef D3D11_DEBUG_SPEW + Con::printf( "Compiling Shader: '%s'", filePath.getFullPath().c_str() ); +#endif + + // Is it an HLSL shader? + if(filePath.getExtension().equal("hlsl", String::NoCase)) + { + // Set this so that the D3DInclude::Open will have this + // information for relative paths. + smD3DInclude->setPath(filePath.getRootAndPath()); + + FileStream s; + if (!s.open(filePath, Torque::FS::File::Read)) + { + AssertISV(false, avar("GFXD3D11Shader::initShader - failed to open shader '%s'.", filePath.getFullPath().c_str())); + + if ( smLogErrors ) + Con::errorf( "GFXD3D11Shader::_compileShader - Failed to open shader file '%s'.", filePath.getFullPath().c_str() ); + + return false; + } + + // Convert the path which might have virtualized + // mount paths to a real file system path. + Torque::Path realPath; + if (!FS::GetFSPath( filePath, realPath)) + realPath = filePath; + + U32 bufSize = s.getStreamSize(); + + FrameAllocatorMarker fam; + char *buffer = NULL; + + buffer = (char*)fam.alloc(bufSize + 1); + s.read(bufSize, buffer); + buffer[bufSize] = 0; + + res = D3DCompile(buffer, bufSize, realPath.getFullPath().c_str(), defines, smD3DInclude, "main", target, flags, 0, &code, &errorBuff); + + } + + // Is it a precompiled obj shader? + else if(filePath.getExtension().equal("obj", String::NoCase)) + { + FileStream s; + if(!s.open(filePath, Torque::FS::File::Read)) + { + AssertISV(false, avar("GFXD3D11Shader::initShader - failed to open shader '%s'.", filePath.getFullPath().c_str())); + + if ( smLogErrors ) + Con::errorf( "GFXD3D11Shader::_compileShader - Failed to open shader file '%s'.", filePath.getFullPath().c_str() ); + + return false; + } + + res = D3DCreateBlob(s.getStreamSize(), &code); + AssertISV(SUCCEEDED(res), "Unable to create buffer!"); + s.read(s.getStreamSize(), code->GetBufferPointer()); + } + else + { + if (smLogErrors) + Con::errorf("GFXD3D11Shader::_compileShader - Unsupported shader file type '%s'.", filePath.getFullPath().c_str()); + + return false; + } + + if(errorBuff) + { + // remove \n at end of buffer + U8 *buffPtr = (U8*) errorBuff->GetBufferPointer(); + U32 len = dStrlen( (const char*) buffPtr ); + buffPtr[len-1] = '\0'; + + if(FAILED(res)) + { + if(smLogErrors) + Con::errorf("failed to compile shader: %s", buffPtr); + } + else + { + if(smLogWarnings) + Con::errorf("shader compiled with warning(s): %s", buffPtr); + } + } + else if (code == NULL && smLogErrors) + Con::errorf( "GFXD3D11Shader::_compileShader - no compiled code produced; possibly missing file '%s'.", filePath.getFullPath().c_str() ); + + AssertISV(SUCCEEDED(res), "Unable to compile shader!"); + + if(code != NULL) + { +#ifndef TORQUE_SHIPPING + + if(gDisassembleAllShaders) + { + ID3DBlob* disassem = NULL; + D3DDisassemble(code->GetBufferPointer(), code->GetBufferSize(), 0, NULL, &disassem); + mDissasembly = (const char*)disassem->GetBufferPointer(); + + String filename = filePath.getFullPath(); + filename.replace( ".hlsl", "_dis.txt" ); + + FileStream *fstream = FileStream::createAndOpen( filename, Torque::FS::File::Write ); + if ( fstream ) + { + fstream->write( mDissasembly ); + fstream->close(); + delete fstream; + } + + SAFE_RELEASE(disassem); + } + +#endif + + if (target.compare("ps_", 3) == 0) + res = D3D11DEVICE->CreatePixelShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mPixShader); + else if (target.compare("vs_", 3) == 0) + res = D3D11DEVICE->CreateVertexShader(code->GetBufferPointer(), code->GetBufferSize(), NULL, &mVertShader); + + if (FAILED(res)) + { + AssertFatal(false, "D3D11Shader::_compilershader- failed to create shader"); + } + + if(res == S_OK){ + HRESULT reflectionResult = D3DReflect(code->GetBufferPointer(), code->GetBufferSize(), IID_ID3D11ShaderReflection, (void**)&reflectionTable); + if(FAILED(reflectionResult)) + AssertFatal(false, "D3D11Shader::_compilershader - Failed to get shader reflection table interface"); + } + + if(res == S_OK) + _getShaderConstants(reflectionTable, bufferLayout, samplerDescriptions); + +#ifdef TORQUE_ENABLE_CSF_GENERATION + + // Ok, we've got a valid shader and constants, let's write them all out. + if (!_saveCompiledOutput(filePath, code, bufferLayout) && smLogErrors) + Con::errorf( "GFXD3D11Shader::_compileShader - Unable to save shader compile output for: %s", + filePath.getFullPath().c_str()); +#endif + + if(FAILED(res) && smLogErrors) + Con::errorf("GFXD3D11Shader::_compileShader - Unable to create shader for '%s'.", filePath.getFullPath().c_str()); + } + + //bool result = code && SUCCEEDED(res) && HasValidConstants; + bool result = code && SUCCEEDED(res); + +#ifdef TORQUE_DEBUG + if (target.compare("vs_", 3) == 0) + { + String vertShader = mVertexFile.getFileName(); + mVertShader->SetPrivateData(WKPDID_D3DDebugObjectName, vertShader.size(), vertShader.c_str()); + } + else if (target.compare("ps_", 3) == 0) + { + String pixelShader = mPixelFile.getFileName(); + mPixShader->SetPrivateData(WKPDID_D3DDebugObjectName, pixelShader.size(), pixelShader.c_str()); + } +#endif + + SAFE_RELEASE(code); + SAFE_RELEASE(reflectionTable); + SAFE_RELEASE(errorBuff); + + return result; +} +void GFXD3D11Shader::_getShaderConstants( ID3D11ShaderReflection *table, + GenericConstBufferLayout *bufferLayoutIn, + Vector &samplerDescriptions ) +{ + PROFILE_SCOPE( GFXD3D11Shader_GetShaderConstants ); + + AssertFatal(table, "NULL constant table not allowed, is this an assembly shader?"); + + GFXD3D11ConstBufferLayout *bufferLayout = (GFXD3D11ConstBufferLayout*)bufferLayoutIn; + Vector &subBuffers = bufferLayout->getSubBufferDesc(); + subBuffers.clear(); + + D3D11_SHADER_DESC tableDesc; + HRESULT hr = table->GetDesc(&tableDesc); + if (FAILED(hr)) + { + AssertFatal(false, "Shader Reflection table unable to be created"); + } + + //offset for sub constant buffers + U32 bufferOffset = 0; + for (U32 i = 0; i < tableDesc.ConstantBuffers; i++) + { + ID3D11ShaderReflectionConstantBuffer* constantBuffer = table->GetConstantBufferByIndex(i); + D3D11_SHADER_BUFFER_DESC constantBufferDesc; + + if (constantBuffer->GetDesc(&constantBufferDesc) == S_OK) + { + + #ifdef TORQUE_DEBUG + AssertFatal(constantBufferDesc.Type == D3D_CT_CBUFFER, "Only scalar cbuffers supported for now."); + + if (dStrcmp(constantBufferDesc.Name, "$Globals") != 0 && dStrcmp(constantBufferDesc.Name, "$Params") != 0) + AssertFatal(false, "Only $Global and $Params cbuffer supported for now."); + #endif + #ifdef D3D11_DEBUG_SPEW + Con::printf("Constant Buffer Name: %s", constantBufferDesc.Name); + #endif + + for(U32 j =0; j< constantBufferDesc.Variables; j++) + { + GFXShaderConstDesc desc; + ID3D11ShaderReflectionVariable* variable = constantBuffer->GetVariableByIndex(j); + D3D11_SHADER_VARIABLE_DESC variableDesc; + D3D11_SHADER_TYPE_DESC variableTypeDesc; + + variable->GetDesc(&variableDesc); + + ID3D11ShaderReflectionType* variableType =variable->GetType(); + + variableType->GetDesc(&variableTypeDesc); + desc.name = String(variableDesc.Name); + // Prepend a "$" if it doesn't exist. Just to make things consistent. + if (desc.name.find("$") != 0) + desc.name = String::ToString("$%s", desc.name.c_str()); + + bool unusedVar = variableDesc.uFlags & D3D_SVF_USED ? false : true; + + if (variableTypeDesc.Elements == 0) + desc.arraySize = 1; + else + desc.arraySize = variableTypeDesc.Elements; + + #ifdef D3D11_DEBUG_SPEW + Con::printf("Variable Name %s:, offset: %d, size: %d, constantDesc.Elements: %d", desc.name.c_str(), variableDesc.StartOffset, variableDesc.Size, desc.arraySize); + #endif + if (_convertShaderVariable(variableTypeDesc, desc)) + { + //The HLSL compiler for 4.0 and above doesn't strip out unused registered constants. We'll have to do it manually + if (!unusedVar) + { + mShaderConsts.push_back(desc); + U32 alignBytes = getAlignmentValue(desc.constType); + U32 paramSize = variableDesc.Size; + bufferLayout->addParameter( desc.name, + desc.constType, + variableDesc.StartOffset + bufferOffset, + paramSize, + desc.arraySize, + alignBytes); + + } //unusedVar + } //_convertShaderVariable + } //constantBufferDesc.Variables + + // fill out our const sub buffer sizes etc + ConstSubBufferDesc subBufferDesc; + subBufferDesc.size = constantBufferDesc.Size; + subBufferDesc.start = bufferOffset; + subBuffers.push_back(subBufferDesc); + // increase our bufferOffset by the constant buffer size + bufferOffset += constantBufferDesc.Size; + + } + else + AssertFatal(false, "Unable to get shader constant description! (may need more elements of constantDesc"); + } + + // Set buffer size to the aligned size + bufferLayout->setSize(bufferOffset); + + + //get the sampler descriptions from the resource binding description + U32 resourceCount = tableDesc.BoundResources; + for (U32 i = 0; i < resourceCount; i++) + { + GFXShaderConstDesc desc; + D3D11_SHADER_INPUT_BIND_DESC bindDesc; + table->GetResourceBindingDesc(i, &bindDesc); + + switch (bindDesc.Type) + { + case D3D_SIT_SAMPLER: + // Prepend a "$" if it doesn't exist. Just to make things consistent. + desc.name = String(bindDesc.Name); + if (desc.name.find("$") != 0) + desc.name = String::ToString("$%s", desc.name.c_str()); + desc.constType = GFXSCT_Sampler; + desc.arraySize = bindDesc.BindPoint; + samplerDescriptions.push_back(desc); + break; + + } + } + +} + +bool GFXD3D11Shader::_convertShaderVariable(const D3D11_SHADER_TYPE_DESC &typeDesc, GFXShaderConstDesc &desc) +{ + switch (typeDesc.Type) + { + case D3D_SVT_INT: + { + switch (typeDesc.Class) + { + case D3D_SVC_SCALAR: + desc.constType = GFXSCT_Int; + break; + case D3D_SVC_VECTOR: + { + switch (typeDesc.Columns) + { + case 1: + desc.constType = GFXSCT_Int; + break; + case 2: + desc.constType = GFXSCT_Int2; + break; + case 3: + desc.constType = GFXSCT_Int3; + break; + case 4: + desc.constType = GFXSCT_Int4; + break; + } + } + break; + } + break; + } + case D3D_SVT_FLOAT: + { + switch (typeDesc.Class) + { + case D3D_SVC_SCALAR: + desc.constType = GFXSCT_Float; + break; + case D3D_SVC_VECTOR: + { + switch (typeDesc.Columns) + { + case 1: + desc.constType = GFXSCT_Float; + break; + case 2: + desc.constType = GFXSCT_Float2; + break; + case 3: + desc.constType = GFXSCT_Float3; + break; + case 4: + desc.constType = GFXSCT_Float4; + break; + } + } + break; + case D3D_SVC_MATRIX_ROWS: + case D3D_SVC_MATRIX_COLUMNS: + { + switch (typeDesc.Columns) + { + case 3: + if (typeDesc.Rows == 3) + { + desc.constType = GFXSCT_Float3x3; + } + break; + case 4: + if (typeDesc.Rows == 4) + { + desc.constType = GFXSCT_Float4x4; + } + break; + } + } + break; + case D3D_SVC_OBJECT: + case D3D_SVC_STRUCT: + return false; + } + } + break; + + default: + AssertFatal(false, "Unknown shader constant class enum"); + break; + } + + return true; +} + +const U32 GFXD3D11Shader::smCompiledShaderTag = MakeFourCC('t','c','s','f'); + +bool GFXD3D11Shader::_saveCompiledOutput( const Torque::Path &filePath, + ID3DBlob *buffer, + GenericConstBufferLayout *bufferLayout, + Vector &samplerDescriptions ) +{ + Torque::Path outputPath(filePath); + outputPath.setExtension("csf"); // "C"ompiled "S"hader "F"ile (fancy!) + + FileStream f; + if (!f.open(outputPath, Torque::FS::File::Write)) + return false; + if (!f.write(smCompiledShaderTag)) + return false; + // We could reverse engineer the structure in the compiled output, but this + // is a bit easier because we can just read it into the struct that we want. + if (!bufferLayout->write(&f)) + return false; + + U32 bufferSize = buffer->GetBufferSize(); + if (!f.write(bufferSize)) + return false; + if (!f.write(bufferSize, buffer->GetBufferPointer())) + return false; + + // Write out sampler descriptions. + + f.write( samplerDescriptions.size() ); + + for ( U32 i = 0; i < samplerDescriptions.size(); i++ ) + { + f.write( samplerDescriptions[i].name ); + f.write( (U32)(samplerDescriptions[i].constType) ); + f.write( samplerDescriptions[i].arraySize ); + } + + f.close(); + + return true; +} + +bool GFXD3D11Shader::_loadCompiledOutput( const Torque::Path &filePath, + const String &target, + GenericConstBufferLayout *bufferLayout, + Vector &samplerDescriptions ) +{ + Torque::Path outputPath(filePath); + outputPath.setExtension("csf"); // "C"ompiled "S"hader "F"ile (fancy!) + + FileStream f; + if (!f.open(outputPath, Torque::FS::File::Read)) + return false; + U32 fileTag; + if (!f.read(&fileTag)) + return false; + if (fileTag != smCompiledShaderTag) + return false; + if (!bufferLayout->read(&f)) + return false; + U32 bufferSize; + if (!f.read(&bufferSize)) + return false; + U32 waterMark = FrameAllocator::getWaterMark(); + DWORD* buffer = static_cast(FrameAllocator::alloc(bufferSize)); + if (!f.read(bufferSize, buffer)) + return false; + + // Read sampler descriptions. + + U32 samplerCount; + f.read( &samplerCount ); + + for ( U32 i = 0; i < samplerCount; i++ ) + { + GFXShaderConstDesc samplerDesc; + f.read( &(samplerDesc.name) ); + f.read( (U32*)&(samplerDesc.constType) ); + f.read( &(samplerDesc.arraySize) ); + + samplerDescriptions.push_back( samplerDesc ); + } + + f.close(); + + HRESULT res; + if (target.compare("ps_", 3) == 0) + res = D3D11DEVICE->CreatePixelShader(buffer, bufferSize, NULL, &mPixShader); + else + res = D3D11DEVICE->CreateVertexShader(buffer, bufferSize, NULL, &mVertShader); + AssertFatal(SUCCEEDED(res), "Unable to load shader!"); + + FrameAllocator::setWaterMark(waterMark); + return SUCCEEDED(res); +} + +void GFXD3D11Shader::_buildShaderConstantHandles(GenericConstBufferLayout* layout, bool vertexConst) +{ + for (U32 i = 0; i < layout->getParameterCount(); i++) + { + GenericConstBufferLayout::ParamDesc pd; + layout->getDesc(i, pd); + + GFXD3D11ShaderConstHandle* handle; + HandleMap::Iterator j = mHandles.find(pd.name); + + if (j != mHandles.end()) + { + handle = j->value; + handle->mShader = this; + handle->setValid( true ); + } + else + { + handle = new GFXD3D11ShaderConstHandle(); + handle->mShader = this; + mHandles[pd.name] = handle; + handle->setValid( true ); + } + + if (vertexConst) + { + handle->mVertexConstant = true; + handle->mVertexHandle = pd; + } + else + { + handle->mPixelConstant = true; + handle->mPixelHandle = pd; + } + } +} + +void GFXD3D11Shader::_buildSamplerShaderConstantHandles( Vector &samplerDescriptions ) +{ + Vector::iterator iter = samplerDescriptions.begin(); + for ( ; iter != samplerDescriptions.end(); iter++ ) + { + const GFXShaderConstDesc &desc = *iter; + + AssertFatal( desc.constType == GFXSCT_Sampler || + desc.constType == GFXSCT_SamplerCube, + "GFXD3D11Shader::_buildSamplerShaderConstantHandles - Invalid samplerDescription type!" ); + + GFXD3D11ShaderConstHandle *handle; + HandleMap::Iterator j = mHandles.find(desc.name); + + if ( j != mHandles.end() ) + handle = j->value; + else + { + handle = new GFXD3D11ShaderConstHandle(); + mHandles[desc.name] = handle; + } + + handle->mShader = this; + handle->setValid( true ); + handle->mPixelConstant = true; + handle->mPixelHandle.name = desc.name; + handle->mPixelHandle.constType = desc.constType; + handle->mPixelHandle.offset = desc.arraySize; + } +} + +void GFXD3D11Shader::_buildInstancingShaderConstantHandles() +{ + // If we have no instancing than just return + if (!mInstancingFormat) + return; + + U32 offset = 0; + for ( U32 i=0; i < mInstancingFormat->getElementCount(); i++ ) + { + const GFXVertexElement &element = mInstancingFormat->getElement( i ); + + String constName = String::ToString( "$%s", element.getSemantic().c_str() ); + + GFXD3D11ShaderConstHandle *handle; + HandleMap::Iterator j = mHandles.find( constName ); + + if ( j != mHandles.end() ) + handle = j->value; + else + { + handle = new GFXD3D11ShaderConstHandle(); + mHandles[ constName ] = handle; + } + + handle->mShader = this; + handle->setValid( true ); + handle->mInstancingConstant = true; + + // We shouldn't have an instancing constant that is also + // a vertex or pixel constant! This means the shader features + // are confused as to what is instanced. + // + AssertFatal( !handle->mVertexConstant && + !handle->mPixelConstant, + "GFXD3D11Shader::_buildInstancingShaderConstantHandles - Bad instanced constant!" ); + + // HACK: The GFXD3D11ShaderConstHandle will check mVertexConstant then + // fall back to reading the mPixelHandle values. We depend on this here + // and store the data we need in the mPixelHandle constant although its + // not a pixel shader constant. + // + handle->mPixelHandle.name = constName; + handle->mPixelHandle.offset = offset; + + // If this is a matrix we will have 2 or 3 more of these + // semantics with the same name after it. + for ( ; i < mInstancingFormat->getElementCount(); i++ ) + { + const GFXVertexElement &nextElement = mInstancingFormat->getElement( i ); + if ( nextElement.getSemantic() != element.getSemantic() ) + { + i--; + break; + } + offset += nextElement.getSizeInBytes(); + } + } +} + +GFXShaderConstBufferRef GFXD3D11Shader::allocConstBuffer() +{ + if (mVertexConstBufferLayout && mPixelConstBufferLayout) + { + GFXD3D11ShaderConstBuffer* buffer = new GFXD3D11ShaderConstBuffer(this, mVertexConstBufferLayout, mPixelConstBufferLayout); + mActiveBuffers.push_back( buffer ); + buffer->registerResourceWithDevice(getOwningDevice()); + return buffer; + } + + return NULL; +} + +/// Returns a shader constant handle for name, if the variable doesn't exist NULL is returned. +GFXShaderConstHandle* GFXD3D11Shader::getShaderConstHandle(const String& name) +{ + HandleMap::Iterator i = mHandles.find(name); + if ( i != mHandles.end() ) + { + return i->value; + } + else + { + GFXD3D11ShaderConstHandle *handle = new GFXD3D11ShaderConstHandle(); + handle->setValid( false ); + handle->mShader = this; + mHandles[name] = handle; + + return handle; + } +} + +GFXShaderConstHandle* GFXD3D11Shader::findShaderConstHandle(const String& name) +{ + HandleMap::Iterator i = mHandles.find(name); + if(i != mHandles.end()) + return i->value; + else + { + return NULL; + } +} + +const Vector& GFXD3D11Shader::getShaderConstDesc() const +{ + return mShaderConsts; +} + +U32 GFXD3D11Shader::getAlignmentValue(const GFXShaderConstType constType) const +{ + const U32 mRowSizeF = 16; + const U32 mRowSizeI = 16; + + switch (constType) + { + case GFXSCT_Float : + case GFXSCT_Float2 : + case GFXSCT_Float3 : + case GFXSCT_Float4 : + return mRowSizeF; + break; + // Matrices + case GFXSCT_Float2x2 : + return mRowSizeF * 2; + break; + case GFXSCT_Float3x3 : + return mRowSizeF * 3; + break; + case GFXSCT_Float4x4 : + return mRowSizeF * 4; + break; + //// Scalar + case GFXSCT_Int : + case GFXSCT_Int2 : + case GFXSCT_Int3 : + case GFXSCT_Int4 : + return mRowSizeI; + break; + default: + AssertFatal(false, "Unsupported type!"); + return 0; + break; + } +} + +void GFXD3D11Shader::zombify() +{ + // Shaders don't need zombification +} + +void GFXD3D11Shader::resurrect() +{ + // Shaders are never zombies, and therefore don't have to be brought back. +} diff --git a/Engine/source/gfx/D3D11/gfxD3D11Shader.h b/Engine/source/gfx/D3D11/gfxD3D11Shader.h new file mode 100644 index 000000000..2e4074a8f --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11Shader.h @@ -0,0 +1,471 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3D11SHADER_H_ +#define _GFXD3D11SHADER_H_ + +#include + +#include "core/util/path.h" +#include "core/util/tDictionary.h" +#include "gfx/gfxShader.h" +#include "gfx/gfxResource.h" +#include "gfx/genericConstBuffer.h" +#include "gfx/D3D11/gfxD3D11Device.h" + +class GFXD3D11Shader; + +enum CONST_CLASS +{ + D3DPC_SCALAR, + D3DPC_VECTOR, + D3DPC_MATRIX_ROWS, + D3DPC_MATRIX_COLUMNS, + D3DPC_OBJECT, + D3DPC_STRUCT +}; + +enum CONST_TYPE +{ + D3DPT_VOID, + D3DPT_BOOL, + D3DPT_INT, + D3DPT_FLOAT, + D3DPT_STRING, + D3DPT_TEXTURE, + D3DPT_TEXTURE1D, + D3DPT_TEXTURE2D, + D3DPT_TEXTURE3D, + D3DPT_TEXTURECUBE, + D3DPT_SAMPLER, + D3DPT_SAMPLER1D, + D3DPT_SAMPLER2D, + D3DPT_SAMPLER3D, + D3DPT_SAMPLERCUBE, + D3DPT_PIXELSHADER, + D3DPT_VERTEXSHADER, + D3DPT_PIXELFRAGMENT, + D3DPT_VERTEXFRAGMENT +}; + +enum REGISTER_TYPE +{ + D3DRS_BOOL, + D3DRS_INT4, + D3DRS_FLOAT4, + D3DRS_SAMPLER +}; + +struct ConstantDesc +{ + String Name; + S32 RegisterIndex; + S32 RegisterCount; + S32 Rows; + S32 Columns; + S32 Elements; + S32 StructMembers; + REGISTER_TYPE RegisterSet; + CONST_CLASS Class; + CONST_TYPE Type; + U32 Bytes; +}; + +class ConstantTable +{ +public: + bool Create(const void* data); + + U32 GetConstantCount() const { return m_constants.size(); } + const String& GetCreator() const { return m_creator; } + + const ConstantDesc* GetConstantByIndex(U32 i) const { return &m_constants[i]; } + const ConstantDesc* GetConstantByName(const String& name) const; + + void ClearConstants() { m_constants.clear(); } + +private: + Vector m_constants; + String m_creator; +}; + +// Structs +struct CTHeader +{ + U32 Size; + U32 Creator; + U32 Version; + U32 Constants; + U32 ConstantInfo; + U32 Flags; + U32 Target; +}; + +struct CTInfo +{ + U32 Name; + U16 RegisterSet; + U16 RegisterIndex; + U16 RegisterCount; + U16 Reserved; + U32 TypeInfo; + U32 DefaultValue; +}; + +struct CTType +{ + U16 Class; + U16 Type; + U16 Rows; + U16 Columns; + U16 Elements; + U16 StructMembers; + U32 StructMemberInfo; +}; + +// Shader instruction opcodes +const U32 SIO_COMMENT = 0x0000FFFE; +const U32 SIO_END = 0x0000FFFF; +const U32 SI_OPCODE_MASK = 0x0000FFFF; +const U32 SI_COMMENTSIZE_MASK = 0x7FFF0000; +const U32 CTAB_CONSTANT = 0x42415443; + +// Member functions +inline bool ConstantTable::Create(const void* data) +{ + const U32* ptr = static_cast(data); + while(*++ptr != SIO_END) + { + if((*ptr & SI_OPCODE_MASK) == SIO_COMMENT) + { + // Check for CTAB comment + U32 comment_size = (*ptr & SI_COMMENTSIZE_MASK) >> 16; + if(*(ptr+1) != CTAB_CONSTANT) + { + ptr += comment_size; + continue; + } + + // Read header + const char* ctab = reinterpret_cast(ptr+2); + size_t ctab_size = (comment_size-1)*4; + + const CTHeader* header = reinterpret_cast(ctab); + if(ctab_size < sizeof(*header) || header->Size != sizeof(*header)) + return false; + m_creator = ctab + header->Creator; + + // Read constants + m_constants.reserve(header->Constants); + const CTInfo* info = reinterpret_cast(ctab + header->ConstantInfo); + for(U32 i = 0; i < header->Constants; ++i) + { + const CTType* type = reinterpret_cast(ctab + info[i].TypeInfo); + + // Fill struct + ConstantDesc desc; + desc.Name = ctab + info[i].Name; + desc.RegisterSet = static_cast(info[i].RegisterSet); + desc.RegisterIndex = info[i].RegisterIndex; + desc.RegisterCount = info[i].RegisterCount; + desc.Rows = type->Rows; + desc.Class = static_cast(type->Class); + desc.Type = static_cast(type->Type); + desc.Columns = type->Columns; + desc.Elements = type->Elements; + desc.StructMembers = type->StructMembers; + desc.Bytes = 4 * desc.Elements * desc.Rows * desc.Columns; + m_constants.push_back(desc); + } + + return true; + } + } + return false; +} + +inline const ConstantDesc* ConstantTable::GetConstantByName(const String& name) const +{ + Vector::const_iterator it; + for(it = m_constants.begin(); it != m_constants.end(); ++it) + { + if(it->Name == name) + return &(*it); + } + return NULL; +} + +/////////////////// Constant Buffers ///////////////////////////// + +// Maximum number of CBuffers ($Globals & $Params) +const U32 CBUFFER_MAX = 2; + +struct ConstSubBufferDesc +{ + U32 start; + U32 size; + + ConstSubBufferDesc() : start(0), size(0){} +}; + +class GFXD3D11ConstBufferLayout : public GenericConstBufferLayout +{ +public: + GFXD3D11ConstBufferLayout(); + /// Get our constant sub buffer data + Vector &getSubBufferDesc(){ return mSubBuffers; } + + /// We need to manually set the size due to D3D11 alignment + void setSize(U32 size){ mBufferSize = size;} + + /// Set a parameter, given a base pointer + virtual bool set(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer); + +protected: + /// Set a matrix, given a base pointer + virtual bool setMatrix(const ParamDesc& pd, const GFXShaderConstType constType, const U32 size, const void* data, U8* basePointer); + + Vector mSubBuffers; +}; + +class GFXD3D11ShaderConstHandle : public GFXShaderConstHandle +{ +public: + + // GFXShaderConstHandle + const String& getName() const; + GFXShaderConstType getType() const; + U32 getArraySize() const; + + WeakRefPtr mShader; + + bool mVertexConstant; + GenericConstBufferLayout::ParamDesc mVertexHandle; + bool mPixelConstant; + GenericConstBufferLayout::ParamDesc mPixelHandle; + + /// Is true if this constant is for hardware mesh instancing. + /// + /// Note: We currently store its settings in mPixelHandle. + /// + bool mInstancingConstant; + + void setValid( bool valid ) { mValid = valid; } + S32 getSamplerRegister() const; + + // Returns true if this is a handle to a sampler register. + bool isSampler() const + { + return ( mPixelConstant && mPixelHandle.constType >= GFXSCT_Sampler ) || ( mVertexConstant && mVertexHandle.constType >= GFXSCT_Sampler ); + } + + /// Restore to uninitialized state. + void clear() + { + mShader = NULL; + mVertexConstant = false; + mPixelConstant = false; + mInstancingConstant = false; + mVertexHandle.clear(); + mPixelHandle.clear(); + mValid = false; + } + + GFXD3D11ShaderConstHandle(); +}; + +/// The D3D11 implementation of a shader constant buffer. +class GFXD3D11ShaderConstBuffer : public GFXShaderConstBuffer +{ + friend class GFXD3D11Shader; + +public: + + GFXD3D11ShaderConstBuffer(GFXD3D11Shader* shader, + GFXD3D11ConstBufferLayout* vertexLayout, + GFXD3D11ConstBufferLayout* pixelLayout); + + virtual ~GFXD3D11ShaderConstBuffer(); + + /// Called by GFXD3D11Device to activate this buffer. + /// @param mPrevShaderBuffer The previously active buffer + void activate(GFXD3D11ShaderConstBuffer *prevShaderBuffer); + + /// Used internally by GXD3D11ShaderConstBuffer to determine if it's dirty. + bool isDirty(); + + /// Called from GFXD3D11Shader when constants have changed and need + /// to be the shader this buffer references is reloaded. + void onShaderReload(GFXD3D11Shader *shader); + + // GFXShaderConstBuffer + virtual GFXShader* getShader(); + virtual void set(GFXShaderConstHandle* handle, const F32 fv); + virtual void set(GFXShaderConstHandle* handle, const Point2F& fv); + virtual void set(GFXShaderConstHandle* handle, const Point3F& fv); + virtual void set(GFXShaderConstHandle* handle, const Point4F& fv); + virtual void set(GFXShaderConstHandle* handle, const PlaneF& fv); + virtual void set(GFXShaderConstHandle* handle, const ColorF& fv); + virtual void set(GFXShaderConstHandle* handle, const S32 f); + virtual void set(GFXShaderConstHandle* handle, const Point2I& fv); + virtual void set(GFXShaderConstHandle* handle, const Point3I& fv); + virtual void set(GFXShaderConstHandle* handle, const Point4I& fv); + virtual void set(GFXShaderConstHandle* handle, const AlignedArray& fv); + virtual void set(GFXShaderConstHandle* handle, const AlignedArray& fv); + virtual void set(GFXShaderConstHandle* handle, const AlignedArray& fv); + virtual void set(GFXShaderConstHandle* handle, const AlignedArray& fv); + virtual void set(GFXShaderConstHandle* handle, const AlignedArray& fv); + virtual void set(GFXShaderConstHandle* handle, const AlignedArray& fv); + virtual void set(GFXShaderConstHandle* handle, const AlignedArray& fv); + virtual void set(GFXShaderConstHandle* handle, const AlignedArray& fv); + virtual void set(GFXShaderConstHandle* handle, const MatrixF& mat, const GFXShaderConstType matType = GFXSCT_Float4x4); + virtual void set(GFXShaderConstHandle* handle, const MatrixF* mat, const U32 arraySize, const GFXShaderConstType matrixType = GFXSCT_Float4x4); + + // GFXResource + virtual const String describeSelf() const; + virtual void zombify(); + virtual void resurrect(); + +protected: + + void _createBuffers(); + + template + inline void SET_CONSTANT(GFXShaderConstHandle* handle, + const T& fv, + GenericConstBuffer *vBuffer, + GenericConstBuffer *pBuffer); + + // Constant buffers, VSSetConstantBuffers1 has issues on win 7. So unfortunately for now we have multiple constant buffers + ID3D11Buffer* mConstantBuffersV[CBUFFER_MAX]; + ID3D11Buffer* mConstantBuffersP[CBUFFER_MAX]; + + /// We keep a weak reference to the shader + /// because it will often be deleted. + WeakRefPtr mShader; + + //vertex + GFXD3D11ConstBufferLayout* mVertexConstBufferLayout; + GenericConstBuffer* mVertexConstBuffer; + //pixel + GFXD3D11ConstBufferLayout* mPixelConstBufferLayout; + GenericConstBuffer* mPixelConstBuffer; +}; + +class gfxD3D11Include; +typedef StrongRefPtr gfxD3DIncludeRef; + +/////////////////// GFXShader implementation ///////////////////////////// + +class GFXD3D11Shader : public GFXShader +{ + friend class GFXD3D11Device; + friend class GFXD3D11ShaderConstBuffer; + +public: + typedef Map HandleMap; + + GFXD3D11Shader(); + virtual ~GFXD3D11Shader(); + + // GFXShader + virtual GFXShaderConstBufferRef allocConstBuffer(); + virtual const Vector& getShaderConstDesc() const; + virtual GFXShaderConstHandle* getShaderConstHandle(const String& name); + virtual GFXShaderConstHandle* findShaderConstHandle(const String& name); + virtual U32 getAlignmentValue(const GFXShaderConstType constType) const; + virtual bool getDisassembly( String &outStr ) const; + + // GFXResource + virtual void zombify(); + virtual void resurrect(); + +protected: + + virtual bool _init(); + + static const U32 smCompiledShaderTag; + + ConstantTable table; + + ID3D11VertexShader *mVertShader; + ID3D11PixelShader *mPixShader; + + GFXD3D11ConstBufferLayout* mVertexConstBufferLayout; + GFXD3D11ConstBufferLayout* mPixelConstBufferLayout; + + static gfxD3DIncludeRef smD3DInclude; + + HandleMap mHandles; + + /// The shader disassembly from DX when this shader is compiled. + /// We only store this data in non-release builds. + String mDissasembly; + + /// Vector of sampler type descriptions consolidated from _compileShader. + Vector mSamplerDescriptions; + + /// Vector of descriptions (consolidated for the getShaderConstDesc call) + Vector mShaderConsts; + + // These two functions are used when compiling shaders from hlsl + virtual bool _compileShader( const Torque::Path &filePath, + const String &target, + const D3D_SHADER_MACRO *defines, + GenericConstBufferLayout *bufferLayout, + Vector &samplerDescriptions ); + + void _getShaderConstants( ID3D11ShaderReflection* table, + GenericConstBufferLayout *bufferLayout, + Vector &samplerDescriptions ); + + bool _convertShaderVariable(const D3D11_SHADER_TYPE_DESC &typeDesc, GFXShaderConstDesc &desc); + + + bool _saveCompiledOutput( const Torque::Path &filePath, + ID3DBlob *buffer, + GenericConstBufferLayout *bufferLayout, + Vector &samplerDescriptions ); + + // Loads precompiled shaders + bool _loadCompiledOutput( const Torque::Path &filePath, + const String &target, + GenericConstBufferLayout *bufferLayoutF, + Vector &samplerDescriptions ); + + // This is used in both cases + virtual void _buildShaderConstantHandles(GenericConstBufferLayout *layout, bool vertexConst); + + virtual void _buildSamplerShaderConstantHandles( Vector &samplerDescriptions ); + + /// Used to build the instancing shader constants from + /// the instancing vertex format. + void _buildInstancingShaderConstantHandles(); +}; + +inline bool GFXD3D11Shader::getDisassembly(String &outStr) const +{ + outStr = mDissasembly; + return (outStr.isNotEmpty()); +} + +#endif diff --git a/Engine/source/gfx/D3D11/gfxD3D11StateBlock.cpp b/Engine/source/gfx/D3D11/gfxD3D11StateBlock.cpp new file mode 100644 index 000000000..fb5f43936 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11StateBlock.cpp @@ -0,0 +1,285 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/gfxDevice.h" +#include "gfx/D3D11/gfxD3D11StateBlock.h" +#include "gfx/D3D11/gfxD3D11EnumTranslate.h" + +GFXD3D11StateBlock::GFXD3D11StateBlock(const GFXStateBlockDesc& desc) +{ + AssertFatal(D3D11DEVICE, "Invalid D3DDevice!"); + + mDesc = desc; + mCachedHashValue = desc.getHashValue(); + + // Color writes + mColorMask = 0; + mColorMask |= (mDesc.colorWriteRed ? D3D11_COLOR_WRITE_ENABLE_RED : 0); + mColorMask |= (mDesc.colorWriteGreen ? D3D11_COLOR_WRITE_ENABLE_GREEN : 0); + mColorMask |= (mDesc.colorWriteBlue ? D3D11_COLOR_WRITE_ENABLE_BLUE : 0); + mColorMask |= (mDesc.colorWriteAlpha ? D3D11_COLOR_WRITE_ENABLE_ALPHA : 0); + + mBlendState = NULL; + for (U32 i = 0; i < GFX->getNumSamplers(); i++) + { + mSamplerStates[i] = NULL; + } + + mDepthStencilState = NULL; + mRasterizerState = NULL; + + mBlendDesc.AlphaToCoverageEnable = false; + mBlendDesc.IndependentBlendEnable = false; + + mBlendDesc.RenderTarget[0].BlendEnable = mDesc.blendEnable; + mBlendDesc.RenderTarget[0].BlendOp = GFXD3D11BlendOp[mDesc.blendOp]; + mBlendDesc.RenderTarget[0].BlendOpAlpha = GFXD3D11BlendOp[mDesc.separateAlphaBlendOp]; + mBlendDesc.RenderTarget[0].DestBlend = GFXD3D11Blend[mDesc.blendDest]; + mBlendDesc.RenderTarget[0].DestBlendAlpha = GFXD3D11Blend[mDesc.separateAlphaBlendDest]; + mBlendDesc.RenderTarget[0].SrcBlend = GFXD3D11Blend[mDesc.blendSrc]; + mBlendDesc.RenderTarget[0].SrcBlendAlpha = GFXD3D11Blend[mDesc.separateAlphaBlendSrc]; + mBlendDesc.RenderTarget[0].RenderTargetWriteMask = mColorMask; + + HRESULT hr = D3D11DEVICE->CreateBlendState(&mBlendDesc, &mBlendState); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11StateBlock::GFXD3D11StateBlock - CreateBlendState call failure."); + } + + mDepthStencilDesc.DepthWriteMask = mDesc.zWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; + mDepthStencilDesc.DepthEnable = mDesc.zEnable; + mDepthStencilDesc.DepthFunc = GFXD3D11CmpFunc[mDesc.zFunc]; + mDepthStencilDesc.StencilWriteMask = mDesc.stencilWriteMask; + mDepthStencilDesc.StencilReadMask = mDesc.stencilMask; + mDepthStencilDesc.StencilEnable = mDesc.stencilEnable; + + mDepthStencilDesc.FrontFace.StencilFunc = GFXD3D11CmpFunc[mDesc.stencilFunc]; + mDepthStencilDesc.FrontFace.StencilFailOp = GFXD3D11StencilOp[mDesc.stencilFailOp]; + mDepthStencilDesc.FrontFace.StencilDepthFailOp = GFXD3D11StencilOp[mDesc.stencilZFailOp]; + mDepthStencilDesc.FrontFace.StencilPassOp = GFXD3D11StencilOp[mDesc.stencilPassOp]; + mDepthStencilDesc.BackFace = mDepthStencilDesc.FrontFace; + + hr = D3D11DEVICE->CreateDepthStencilState(&mDepthStencilDesc, &mDepthStencilState); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11StateBlock::GFXD3D11StateBlock - CreateDepthStencilState call failure."); + } + + mRasterizerDesc.CullMode = GFXD3D11CullMode[mDesc.cullMode]; + mRasterizerDesc.FillMode = GFXD3D11FillMode[mDesc.fillMode]; + mRasterizerDesc.DepthBias = mDesc.zBias; + mRasterizerDesc.SlopeScaledDepthBias = mDesc.zSlopeBias; + mRasterizerDesc.AntialiasedLineEnable = FALSE; + mRasterizerDesc.MultisampleEnable = FALSE; + mRasterizerDesc.ScissorEnable = FALSE; + mRasterizerDesc.DepthClipEnable = TRUE; + mRasterizerDesc.FrontCounterClockwise = FALSE; + mRasterizerDesc.DepthBiasClamp = D3D11_DEFAULT_DEPTH_BIAS_CLAMP; + + hr = D3D11DEVICE->CreateRasterizerState(&mRasterizerDesc, &mRasterizerState); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11StateBlock::GFXD3D11StateBlock - CreateDepthStencilState call failure."); + } + + for ( U32 i = 0; i < GFX->getNumSamplers(); i++ ) + { + mSamplerDesc[i].AddressU = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeU]; + mSamplerDesc[i].AddressV = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeV]; + mSamplerDesc[i].AddressW = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeW]; + mSamplerDesc[i].MaxAnisotropy = mDesc.samplers[i].maxAnisotropy; + + mSamplerDesc[i].MipLODBias = mDesc.samplers[i].mipLODBias; + mSamplerDesc[i].MinLOD = 0; + mSamplerDesc[i].MaxLOD = FLT_MAX; + + if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + else + mSamplerDesc[i].Filter = D3D11_FILTER_ANISOTROPIC; + + mSamplerDesc[i].BorderColor[0] = 1.0f; + mSamplerDesc[i].BorderColor[1] = 1.0f; + mSamplerDesc[i].BorderColor[2] = 1.0f; + mSamplerDesc[i].BorderColor[3] = 1.0f; + mSamplerDesc[i].ComparisonFunc = D3D11_COMPARISON_NEVER; + + hr = D3D11DEVICE->CreateSamplerState(&mSamplerDesc[i], &mSamplerStates[i]); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11StateBlock::GFXD3D11StateBlock - CreateSamplerState call failure."); + } + } +} + +GFXD3D11StateBlock::~GFXD3D11StateBlock() +{ + SAFE_RELEASE(mBlendState); + SAFE_RELEASE(mRasterizerState); + SAFE_RELEASE(mDepthStencilState); + + //Use TEXTURE_STAGE_COUNT here, not safe to rely on GFX pointer + for (U32 i = 0; i < TEXTURE_STAGE_COUNT; ++i) + { + SAFE_RELEASE(mSamplerStates[i]); + } +} + +/// Returns the hash value of the desc that created this block +U32 GFXD3D11StateBlock::getHashValue() const +{ + return mCachedHashValue; +} + +/// Returns a GFXStateBlockDesc that this block represents +const GFXStateBlockDesc& GFXD3D11StateBlock::getDesc() const +{ + return mDesc; +} + +/// Called by D3D11 device to active this state block. +/// @param oldState The current state, used to make sure we don't set redundant states on the device. Pass NULL to reset all states. +void GFXD3D11StateBlock::activate(GFXD3D11StateBlock* oldState) +{ + PROFILE_SCOPE( GFXD3D11StateBlock_Activate ); + + ID3D11DeviceContext* pDevCxt = D3D11DEVICECONTEXT; + + mBlendDesc.AlphaToCoverageEnable = false; + mBlendDesc.IndependentBlendEnable = mDesc.separateAlphaBlendEnable; + + mBlendDesc.RenderTarget[0].BlendEnable = mDesc.blendEnable; + mBlendDesc.RenderTarget[0].BlendOp = GFXD3D11BlendOp[mDesc.blendOp]; + mBlendDesc.RenderTarget[0].BlendOpAlpha = GFXD3D11BlendOp[mDesc.separateAlphaBlendOp]; + mBlendDesc.RenderTarget[0].DestBlend = GFXD3D11Blend[mDesc.blendDest]; + mBlendDesc.RenderTarget[0].DestBlendAlpha = GFXD3D11Blend[mDesc.separateAlphaBlendDest]; + mBlendDesc.RenderTarget[0].SrcBlend = GFXD3D11Blend[mDesc.blendSrc]; + mBlendDesc.RenderTarget[0].SrcBlendAlpha = GFXD3D11Blend[mDesc.separateAlphaBlendSrc]; + mBlendDesc.RenderTarget[0].RenderTargetWriteMask = mColorMask; + + float blendFactor[] = { 1.0f, 1.0f, 1.0f, 1.0f }; + + pDevCxt->OMSetBlendState(mBlendState, blendFactor, 0xFFFFFFFF); + + mDepthStencilDesc.DepthWriteMask = mDesc.zWriteEnable ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; + mDepthStencilDesc.DepthEnable = mDesc.zEnable; + mDepthStencilDesc.DepthFunc = GFXD3D11CmpFunc[mDesc.zFunc]; + mDepthStencilDesc.StencilWriteMask = mDesc.stencilWriteMask; + mDepthStencilDesc.StencilReadMask = mDesc.stencilMask; + mDepthStencilDesc.StencilEnable = mDesc.stencilEnable; + + mDepthStencilDesc.FrontFace.StencilFunc = GFXD3D11CmpFunc[mDesc.stencilFunc]; + mDepthStencilDesc.FrontFace.StencilFailOp = GFXD3D11StencilOp[mDesc.stencilFailOp]; + mDepthStencilDesc.FrontFace.StencilDepthFailOp = GFXD3D11StencilOp[mDesc.stencilZFailOp]; + mDepthStencilDesc.FrontFace.StencilPassOp = GFXD3D11StencilOp[mDesc.stencilPassOp]; + + if (mDesc.stencilEnable) + mDepthStencilDesc.BackFace = mDepthStencilDesc.FrontFace; + else + { + mDepthStencilDesc.BackFace.StencilFunc = GFXD3D11CmpFunc[GFXCmpAlways]; + mDepthStencilDesc.BackFace.StencilFailOp = GFXD3D11StencilOp[GFXStencilOpKeep]; + mDepthStencilDesc.BackFace.StencilDepthFailOp = GFXD3D11StencilOp[GFXStencilOpKeep]; + mDepthStencilDesc.BackFace.StencilPassOp = GFXD3D11StencilOp[GFXStencilOpKeep]; + } + + pDevCxt->OMSetDepthStencilState(mDepthStencilState, mDesc.stencilRef); + + mRasterizerDesc.CullMode = GFXD3D11CullMode[mDesc.cullMode]; + mRasterizerDesc.FillMode = GFXD3D11FillMode[mDesc.fillMode]; + mRasterizerDesc.DepthBias = mDesc.zBias; + mRasterizerDesc.SlopeScaledDepthBias = mDesc.zSlopeBias; + mRasterizerDesc.AntialiasedLineEnable = FALSE; + mRasterizerDesc.MultisampleEnable = FALSE; + mRasterizerDesc.ScissorEnable = FALSE; + + if (mDesc.zEnable) + mRasterizerDesc.DepthClipEnable = true; + else + mRasterizerDesc.DepthClipEnable = false; + + mRasterizerDesc.FrontCounterClockwise = FALSE; + mRasterizerDesc.DepthBiasClamp = 0.0f; + + pDevCxt->RSSetState(mRasterizerState); + + U32 numSamplers = GFX->getNumSamplers(); + for (U32 i = 0; i < numSamplers; i++) + { + mSamplerDesc[i].AddressU = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeU]; + mSamplerDesc[i].AddressV = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeV]; + mSamplerDesc[i].AddressW = GFXD3D11TextureAddress[mDesc.samplers[i].addressModeW]; + mSamplerDesc[i].MaxAnisotropy = mDesc.samplers[i].maxAnisotropy; + + mSamplerDesc[i].MipLODBias = mDesc.samplers[i].mipLODBias; + mSamplerDesc[i].MinLOD = 0; + mSamplerDesc[i].MaxLOD = FLT_MAX; + + if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_MIP_POINT; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterPoint && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterPoint && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterPoint) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT; + else if(mDesc.samplers[i].magFilter == GFXTextureFilterLinear && mDesc.samplers[i].minFilter == GFXTextureFilterLinear && mDesc.samplers[i].mipFilter == GFXTextureFilterLinear) + mSamplerDesc[i].Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; + else + mSamplerDesc[i].Filter = D3D11_FILTER_ANISOTROPIC; + + mSamplerDesc[i].BorderColor[0] = 0.0f; + mSamplerDesc[i].BorderColor[1] = 0.0f; + mSamplerDesc[i].BorderColor[2] = 0.0f; + mSamplerDesc[i].BorderColor[3] = 0.0f; + mSamplerDesc[i].ComparisonFunc = D3D11_COMPARISON_NEVER; + } + + //TODO samplers for vertex shader + // Set all the samplers with one call + //pDevCxt->VSSetSamplers(0, numSamplers, &mSamplerStates[0]); + pDevCxt->PSSetSamplers(0, numSamplers, &mSamplerStates[0]); +} diff --git a/Engine/source/gfx/D3D11/gfxD3D11StateBlock.h b/Engine/source/gfx/D3D11/gfxD3D11StateBlock.h new file mode 100644 index 000000000..6e55b962f --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11StateBlock.h @@ -0,0 +1,76 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3D11STATEBLOCK_H_ +#define _GFXD3D11STATEBLOCK_H_ + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/gfxStateBlock.h" + +class GFXD3D11StateBlock : public GFXStateBlock +{ +public: + + GFXD3D11StateBlock(const GFXStateBlockDesc& desc); + virtual ~GFXD3D11StateBlock(); + + /// Called by D3D11 device to active this state block. + /// @param oldState The current state, used to make sure we don't set redundant states on the device. Pass NULL to reset all states. + void activate(GFXD3D11StateBlock* oldState); + + // + // GFXStateBlock interface + // + + /// Returns the hash value of the desc that created this block + virtual U32 getHashValue() const; + + /// Returns a GFXStateBlockDesc that this block represents + virtual const GFXStateBlockDesc& getDesc() const; + + // + // GFXResource + // + virtual void zombify() { } + /// When called the resource should restore all device sensitive information destroyed by zombify() + virtual void resurrect() { } +private: + + D3D11_BLEND_DESC mBlendDesc; + D3D11_RASTERIZER_DESC mRasterizerDesc; + D3D11_DEPTH_STENCIL_DESC mDepthStencilDesc; + D3D11_SAMPLER_DESC mSamplerDesc[TEXTURE_STAGE_COUNT]; + + ID3D11BlendState* mBlendState; + ID3D11DepthStencilState* mDepthStencilState; + ID3D11RasterizerState* mRasterizerState; + ID3D11SamplerState* mSamplerStates[TEXTURE_STAGE_COUNT]; + + GFXStateBlockDesc mDesc; + U32 mCachedHashValue; + // Cached D3D specific things, these are "calculated" from GFXStateBlock + U32 mColorMask; +}; + +typedef StrongRefPtr GFXD3D11StateBlockRef; + +#endif \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11Target.cpp b/Engine/source/gfx/D3D11/gfxD3D11Target.cpp new file mode 100644 index 000000000..a74b3e54d --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11Target.cpp @@ -0,0 +1,409 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "platform/platform.h" +#include "gfx/D3D11/gfxD3D11Target.h" +#include "gfx/D3D11/gfxD3D11Cubemap.h" +#include "gfx/D3D11/gfxD3D11EnumTranslate.h" +#include "gfx/gfxDebugEvent.h" +#include "gfx/gfxStringEnumTranslate.h" +#include "windowManager/win32/win32Window.h" + +GFXD3D11TextureTarget::GFXD3D11TextureTarget() + : mTargetSize( Point2I::Zero ), + mTargetFormat( GFXFormatR8G8B8A8 ) +{ + for(S32 i=0; imDeviceDepthStencil; + mTargetViews[slot] = D3D11->mDeviceDepthStencilView; + mTargets[slot]->AddRef(); + mTargetViews[slot]->AddRef(); + } + else + { + // Cast the texture object to D3D... + AssertFatal(static_cast(tex), "GFXD3D11TextureTarget::attachTexture - invalid texture object."); + + GFXD3D11TextureObject *d3dto = static_cast(tex); + + // Grab the surface level. + if( slot == DepthStencil ) + { + mTargets[slot] = d3dto->getSurface(); + if ( mTargets[slot] ) + mTargets[slot]->AddRef(); + + mTargetViews[slot] = d3dto->getDSView(); + if( mTargetViews[slot]) + mTargetViews[slot]->AddRef(); + + } + else + { + // getSurface will almost always return NULL. It will only return non-NULL + // if the surface that it needs to render to is different than the mip level + // in the actual texture. This will happen with MSAA. + if( d3dto->getSurface() == NULL ) + { + + mTargets[slot] = d3dto->get2DTex(); + mTargets[slot]->AddRef(); + mTargetViews[slot] = d3dto->getRTView(); + mTargetViews[slot]->AddRef(); + } + else + { + mTargets[slot] = d3dto->getSurface(); + mTargets[slot]->AddRef(); + mTargetViews[slot]->AddRef(); + // Only assign resolve target if d3dto has a surface to give us. + // + // That usually means there is an MSAA target involved, which is why + // the resolve is needed to get the data out of the target. + mResolveTargets[slot] = d3dto; + + if ( tex && slot == Color0 ) + { + mTargetSize.set( tex->getSize().x, tex->getSize().y ); + mTargetFormat = tex->getFormat(); + } + } + } + + // Update surface size + if(slot == Color0) + { + ID3D11Texture2D *surface = mTargets[Color0]; + if ( surface ) + { + D3D11_TEXTURE2D_DESC sd; + surface->GetDesc(&sd); + mTargetSize = Point2I(sd.Width, sd.Height); + + S32 format = sd.Format; + GFXREVERSE_LOOKUP( GFXD3D11TextureFormat, GFXFormat, format ); + mTargetFormat = (GFXFormat)format; + } + } + } + +} + + +void GFXD3D11TextureTarget::attachTexture( RenderSlot slot, GFXCubemap *tex, U32 face, U32 mipLevel/*=0*/ ) +{ + GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_attachTexture_Cubemap, ColorI::RED ); + + AssertFatal(slot < MaxRenderSlotId, "GFXD3D11TextureTarget::attachTexture - out of range slot."); + + // Mark state as dirty so device can know to update. + invalidateState(); + + // Release what we had, it's definitely going to change. + SAFE_RELEASE(mTargetViews[slot]); + SAFE_RELEASE(mTargets[slot]); + SAFE_RELEASE(mTargetSRViews[slot]); + + mResolveTargets[slot] = NULL; + + // Cast the texture object to D3D... + AssertFatal(!tex || static_cast(tex), "GFXD3DTextureTarget::attachTexture - invalid cubemap object."); + + if(slot == Color0) + { + mTargetSize = Point2I::Zero; + mTargetFormat = GFXFormatR8G8B8A8; + } + + // Are we clearing? + if(!tex) + { + // Yup - just exit, it'll stay NULL. + return; + } + + GFXD3D11Cubemap *cube = static_cast(tex); + + mTargets[slot] = cube->get2DTex(); + mTargets[slot]->AddRef(); + mTargetViews[slot] = cube->getRTView(face); + mTargetViews[slot]->AddRef(); + mTargetSRViews[slot] = cube->getSRView(); + mTargetSRViews[slot]->AddRef(); + + // Update surface size + if(slot == Color0) + { + ID3D11Texture2D *surface = mTargets[Color0]; + if ( surface ) + { + D3D11_TEXTURE2D_DESC sd; + surface->GetDesc(&sd); + mTargetSize = Point2I(sd.Width, sd.Height); + + S32 format = sd.Format; + GFXREVERSE_LOOKUP( GFXD3D11TextureFormat, GFXFormat, format ); + mTargetFormat = (GFXFormat)format; + } + } + +} + +void GFXD3D11TextureTarget::activate() +{ + GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_activate, ColorI::RED ); + + AssertFatal( mTargets[GFXTextureTarget::Color0], "GFXD3D11TextureTarget::activate() - You can never have a NULL primary render target!" ); + + // Clear the state indicator. + stateApplied(); + + // Now set all the new surfaces into the appropriate slots. + ID3D11RenderTargetView* rtViews[MaxRenderSlotId] = { NULL, NULL, NULL, NULL, NULL, NULL}; + + ID3D11DepthStencilView* dsView = (ID3D11DepthStencilView*)(mTargetViews[GFXTextureTarget::DepthStencil]); + for (U32 i = 0; i < 4; i++) + { + rtViews[i] = (ID3D11RenderTargetView*)mTargetViews[GFXTextureTarget::Color0 + i]; + } + + D3D11DEVICECONTEXT->OMSetRenderTargets(MaxRenderSlotId, rtViews, dsView); + +} + +void GFXD3D11TextureTarget::deactivate() +{ + //re-gen mip maps + for (U32 i = 0; i < 4; i++) + { + ID3D11ShaderResourceView* pSRView = mTargetSRViews[GFXTextureTarget::Color0 + i]; + if (pSRView) + D3D11DEVICECONTEXT->GenerateMips(pSRView); + } + +} + +void GFXD3D11TextureTarget::resolve() +{ + GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_resolve, ColorI::RED ); + + for (U32 i = 0; i < MaxRenderSlotId; i++) + { + // We use existance @ mResolveTargets as a flag that we need to copy + // data from the rendertarget into the texture. + if (mResolveTargets[i]) + { + D3D11_TEXTURE2D_DESC desc; + mTargets[i]->GetDesc(&desc); + D3D11DEVICECONTEXT->CopySubresourceRegion(mResolveTargets[i]->get2DTex(), 0, 0, 0, 0, mTargets[i], 0, NULL); + } + } +} + +void GFXD3D11TextureTarget::resolveTo( GFXTextureObject *tex ) +{ + GFXDEBUGEVENT_SCOPE( GFXPCD3D11TextureTarget_resolveTo, ColorI::RED ); + + if ( mTargets[Color0] == NULL ) + return; + + D3D11_TEXTURE2D_DESC desc; + mTargets[Color0]->GetDesc(&desc); + D3D11DEVICECONTEXT->CopySubresourceRegion(((GFXD3D11TextureObject*)(tex))->get2DTex(), 0, 0, 0, 0, mTargets[Color0], 0, NULL); + +} + +void GFXD3D11TextureTarget::zombify() +{ + for(U32 i = 0; i < MaxRenderSlotId; i++) + attachTexture(RenderSlot(i), NULL); +} + +void GFXD3D11TextureTarget::resurrect() +{ +} + +GFXD3D11WindowTarget::GFXD3D11WindowTarget() +{ + mWindow = NULL; + mBackbuffer = NULL; +} + +GFXD3D11WindowTarget::~GFXD3D11WindowTarget() +{ + SAFE_RELEASE(mBackbuffer); +} + +void GFXD3D11WindowTarget::initPresentationParams() +{ + // Get some video mode related info. + GFXVideoMode vm = mWindow->getVideoMode(); + Win32Window* win = static_cast(mWindow); + HWND hwnd = win->getHWND(); + + mPresentationParams = D3D11->setupPresentParams(vm, hwnd); +} + +const Point2I GFXD3D11WindowTarget::getSize() +{ + return mWindow->getVideoMode().resolution; +} + +GFXFormat GFXD3D11WindowTarget::getFormat() +{ + S32 format = mPresentationParams.BufferDesc.Format; + GFXREVERSE_LOOKUP( GFXD3D11TextureFormat, GFXFormat, format ); + return (GFXFormat)format; +} + +bool GFXD3D11WindowTarget::present() +{ + return (D3D11->getSwapChain()->Present(!D3D11->smDisableVSync, 0) == S_OK); +} + +void GFXD3D11WindowTarget::setImplicitSwapChain() +{ + if (!mBackbuffer) + D3D11->mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&mBackbuffer); +} + +void GFXD3D11WindowTarget::resetMode() +{ + mWindow->setSuppressReset(true); + + // Setup our presentation params. + initPresentationParams(); + + // Otherwise, we have to reset the device, if we're the implicit swapchain. + D3D11->reset(mPresentationParams); + + // Update our size, too. + mSize = Point2I(mPresentationParams.BufferDesc.Width, mPresentationParams.BufferDesc.Height); + + mWindow->setSuppressReset(false); + GFX->beginReset(); +} + +void GFXD3D11WindowTarget::zombify() +{ + SAFE_RELEASE(mBackbuffer); +} + +void GFXD3D11WindowTarget::resurrect() +{ + setImplicitSwapChain(); +} + +void GFXD3D11WindowTarget::activate() +{ + GFXDEBUGEVENT_SCOPE(GFXPCD3D11WindowTarget_activate, ColorI::RED); + + //clear ther rendertargets first + ID3D11RenderTargetView* rtViews[8] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }; + + D3D11DEVICECONTEXT->OMSetRenderTargets(8, rtViews, NULL); + D3D11DEVICECONTEXT->OMSetRenderTargets(1, &D3D11->mDeviceBackBufferView, D3D11->mDeviceDepthStencilView); + + DXGI_SWAP_CHAIN_DESC pp; + D3D11->mSwapChain->GetDesc(&pp); + + // Update our video mode here, too. + GFXVideoMode vm; + vm = mWindow->getVideoMode(); + vm.resolution.x = pp.BufferDesc.Width; + vm.resolution.y = pp.BufferDesc.Height; + vm.fullScreen = !pp.Windowed; + mSize = vm.resolution; +} + +void GFXD3D11WindowTarget::resolveTo(GFXTextureObject *tex) +{ + GFXDEBUGEVENT_SCOPE(GFXPCD3D11WindowTarget_resolveTo, ColorI::RED); + + D3D11_TEXTURE2D_DESC desc; + ID3D11Texture2D* surf = ((GFXD3D11TextureObject*)(tex))->get2DTex(); + surf->GetDesc(&desc); + D3D11DEVICECONTEXT->ResolveSubresource(surf, 0, D3D11->mDeviceBackbuffer, 0, desc.Format); +} \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11Target.h b/Engine/source/gfx/D3D11/gfxD3D11Target.h new file mode 100644 index 000000000..ff4b193d6 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11Target.h @@ -0,0 +1,110 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFX_D3D_GFXD3D11TARGET_H_ +#define _GFX_D3D_GFXD3D11TARGET_H_ + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11TextureObject.h" +#include "gfx/gfxTarget.h" +#include "math/mPoint3.h" +#include "math/mPoint2.h" + +class GFXD3D11TextureTarget : public GFXTextureTarget +{ + friend class GFXD3D11Device; + + // Array of target surfaces, this is given to us by attachTexture + ID3D11Texture2D* mTargets[MaxRenderSlotId]; + + // Array of shader resource views + ID3D11ShaderResourceView* mTargetSRViews[MaxRenderSlotId]; + + //ID3D11DepthStencilView* mDepthTargetView; + ID3D11View* mTargetViews[MaxRenderSlotId]; + // Array of texture objects which correspond to the target surfaces above, + // needed for copy from RenderTarget to texture situations. Current only valid in those situations + GFXD3D11TextureObject* mResolveTargets[MaxRenderSlotId]; + + Point2I mTargetSize; + + GFXFormat mTargetFormat; + +public: + + GFXD3D11TextureTarget(); + ~GFXD3D11TextureTarget(); + + // Public interface. + virtual const Point2I getSize() { return mTargetSize; } + virtual GFXFormat getFormat() { return mTargetFormat; } + virtual void attachTexture(RenderSlot slot, GFXTextureObject *tex, U32 mipLevel=0, U32 zOffset = 0); + virtual void attachTexture(RenderSlot slot, GFXCubemap *tex, U32 face, U32 mipLevel=0); + virtual void resolve(); + + /// Note we always copy the Color0 RenderSlot. + virtual void resolveTo( GFXTextureObject *tex ); + + virtual void activate(); + virtual void deactivate(); + + void zombify(); + void resurrect(); +}; + +class GFXD3D11WindowTarget : public GFXWindowTarget +{ + friend class GFXD3D11Device; + + /// Our backbuffer + ID3D11Texture2D *mBackbuffer; + + /// Maximum size we can render to. + Point2I mSize; + + /// D3D presentation info. + DXGI_SWAP_CHAIN_DESC mPresentationParams; + + /// Internal interface that notifies us we need to reset our video mode. + void resetMode(); + +public: + + GFXD3D11WindowTarget(); + ~GFXD3D11WindowTarget(); + + virtual const Point2I getSize(); + virtual GFXFormat getFormat(); + virtual bool present(); + + void initPresentationParams(); + void setImplicitSwapChain(); + + virtual void activate(); + + void zombify(); + void resurrect(); + + virtual void resolveTo( GFXTextureObject *tex ); +}; + +#endif diff --git a/Engine/source/gfx/D3D11/gfxD3D11TextureManager.cpp b/Engine/source/gfx/D3D11/gfxD3D11TextureManager.cpp new file mode 100644 index 000000000..ba90c4064 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11TextureManager.cpp @@ -0,0 +1,587 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11EnumTranslate.h" +#include "gfx/bitmap/bitmapUtils.h" +#include "gfx/gfxCardProfile.h" +#include "gfx/gfxStringEnumTranslate.h" +#include "core/strings/unicode.h" +#include "core/util/swizzle.h" +#include "core/util/safeDelete.h" +#include "console/console.h" +#include "core/resourceManager.h" + +GFXD3D11TextureManager::GFXD3D11TextureManager() +{ + ZeroMemory(mCurTexSet, sizeof(mCurTexSet)); +} + +GFXD3D11TextureManager::~GFXD3D11TextureManager() +{ + // Destroy texture table now so just in case some texture objects + // are still left, we don't crash on a pure virtual method call. + SAFE_DELETE_ARRAY( mHashTable ); +} + +void GFXD3D11TextureManager::_innerCreateTexture( GFXD3D11TextureObject *retTex, + U32 height, + U32 width, + U32 depth, + GFXFormat format, + GFXTextureProfile *profile, + U32 numMipLevels, + bool forceMips, + S32 antialiasLevel) +{ + U32 usage = 0; + U32 bindFlags = 0; + U32 miscFlags = 0; + + if(!retTex->mProfile->isZTarget() && !retTex->mProfile->isSystemMemory()) + bindFlags = D3D11_BIND_SHADER_RESOURCE; + + U32 cpuFlags = 0; + + retTex->mProfile = profile; + retTex->isManaged = false; + DXGI_FORMAT d3dTextureFormat = GFXD3D11TextureFormat[format]; + + if( retTex->mProfile->isDynamic() ) + { + usage = D3D11_USAGE_DYNAMIC; + cpuFlags |= D3D11_CPU_ACCESS_WRITE; + retTex->isManaged = false; + } + else if ( retTex->mProfile->isSystemMemory() ) + { + usage |= D3D11_USAGE_STAGING; + cpuFlags |= D3D11_CPU_ACCESS_READ; + } + else + { + usage = D3D11_USAGE_DEFAULT; + retTex->isManaged = true; + } + + if( retTex->mProfile->isRenderTarget() ) + { + bindFlags |= D3D11_BIND_RENDER_TARGET; + //need to check to make sure this format supports render targets + U32 supportFlag = 0; + + D3D11DEVICE->CheckFormatSupport(d3dTextureFormat, &supportFlag); + //if it doesn't support render targets then default to R8G8B8A8 + if(!(supportFlag & D3D11_FORMAT_SUPPORT_RENDER_TARGET)) + d3dTextureFormat = DXGI_FORMAT_R8G8B8A8_UNORM; + + retTex->isManaged =false; + } + + if( retTex->mProfile->isZTarget() ) + { + bindFlags |= D3D11_BIND_DEPTH_STENCIL; + retTex->isManaged = false; + } + + if( !forceMips && !retTex->mProfile->isSystemMemory() && + numMipLevels == 0 && + !(depth > 0) ) + { + miscFlags |= D3D11_RESOURCE_MISC_GENERATE_MIPS; + bindFlags |= D3D11_BIND_RENDER_TARGET; // in order to automatically generate mips. Resource needs to be a rendertarget and shader resource + } + + if( depth > 0 ) + { + D3D11_TEXTURE3D_DESC desc; + ZeroMemory(&desc, sizeof(D3D11_TEXTURE3D_DESC)); + + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuFlags; + desc.Depth = depth; + desc.Width = width; + desc.Height = height; + desc.Format = d3dTextureFormat; + desc.Usage = (D3D11_USAGE)usage; + desc.MipLevels = numMipLevels; + + HRESULT hr = D3D11DEVICE->CreateTexture3D(&desc, NULL, retTex->get3DTexPtr()); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11TextureManager::_createTexture - failed to create volume texture!"); + } + + retTex->mTextureSize.set(width, height, depth); + retTex->get3DTex()->GetDesc(&desc); + retTex->mMipLevels = numMipLevels; + retTex->mFormat = format; + } + else + { + UINT numQualityLevels = 0; + + switch (antialiasLevel) + { + case 0: + case AA_MATCH_BACKBUFFER: + antialiasLevel = 1; + break; + + default: + { + antialiasLevel = 0; + UINT numQualityLevels; + D3D11DEVICE->CheckMultisampleQualityLevels(d3dTextureFormat, antialiasLevel, &numQualityLevels); + AssertFatal(numQualityLevels, "Invalid AA level!"); + break; + } + } + + if(retTex->mProfile->isZTarget()) + { + D3D11_TEXTURE2D_DESC desc; + + ZeroMemory(&desc, sizeof(D3D11_TEXTURE2D_DESC)); + desc.ArraySize = 1; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuFlags; + //depth stencil must be a typeless format if it is bound on render target and shader resource simultaneously + // we'll send the real format for the creation of the views + desc.Format = DXGI_FORMAT_R24G8_TYPELESS; + desc.MipLevels = numMipLevels; + desc.SampleDesc.Count = antialiasLevel; + desc.SampleDesc.Quality = numQualityLevels; + desc.Height = height; + desc.Width = width; + desc.Usage = (D3D11_USAGE)usage; + HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, retTex->getSurfacePtr()); + + if(FAILED(hr)) + { + AssertFatal(false, "Failed to create Zbuffer texture"); + } + + retTex->mFormat = format; // Assigning format like this should be fine. + } + else + { + D3D11_TEXTURE2D_DESC desc; + + ZeroMemory(&desc, sizeof(D3D11_TEXTURE2D_DESC)); + desc.ArraySize = 1; + desc.BindFlags = bindFlags; + desc.CPUAccessFlags = cpuFlags; + desc.Format = d3dTextureFormat; + desc.MipLevels = numMipLevels; + desc.SampleDesc.Count = antialiasLevel; + desc.SampleDesc.Quality = numQualityLevels; + desc.Height = height; + desc.Width = width; + desc.Usage = (D3D11_USAGE)usage; + desc.MiscFlags = miscFlags; + HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, retTex->get2DTexPtr()); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11TextureManager::_createTexture - failed to create texture!"); + } + + retTex->get2DTex()->GetDesc(&desc); + retTex->mMipLevels = desc.MipLevels; + } + + // start creating the resource views... + // don't bother creating views for system memory/staging textures + // they are just used for copying + + if (!retTex->mProfile->isSystemMemory()) + { + createResourceView(height, width, depth, d3dTextureFormat, numMipLevels, bindFlags, retTex); + } + + // Get the actual size of the texture... + D3D11_TEXTURE2D_DESC probeDesc; + ZeroMemory(&probeDesc, sizeof(D3D11_TEXTURE2D_DESC)); + + if( retTex->get2DTex() != NULL ) + { + retTex->get2DTex()->GetDesc(&probeDesc); + } + else if( retTex->getSurface() != NULL ) + { + retTex->getSurface()->GetDesc(&probeDesc); + } + + retTex->mTextureSize.set(probeDesc.Width, probeDesc.Height, 0); + S32 fmt = 0; + + if(!profile->isZTarget()) + fmt = probeDesc.Format; + else + fmt = DXGI_FORMAT_D24_UNORM_S8_UINT; // we need to assign this manually. + + GFXREVERSE_LOOKUP( GFXD3D11TextureFormat, GFXFormat, fmt ); + retTex->mFormat = (GFXFormat)fmt; + } +} + +//----------------------------------------------------------------------------- +// createTexture +//----------------------------------------------------------------------------- +GFXTextureObject *GFXD3D11TextureManager::_createTextureObject( U32 height, + U32 width, + U32 depth, + GFXFormat format, + GFXTextureProfile *profile, + U32 numMipLevels, + bool forceMips, + S32 antialiasLevel, + GFXTextureObject *inTex ) +{ + GFXD3D11TextureObject *retTex; + if ( inTex ) + { + AssertFatal(static_cast( inTex ), "GFXD3D11TextureManager::_createTexture() - Bad inTex type!"); + retTex = static_cast( inTex ); + retTex->release(); + } + else + { + retTex = new GFXD3D11TextureObject(GFX, profile); + retTex->registerResourceWithDevice(GFX); + } + + _innerCreateTexture(retTex, height, width, depth, format, profile, numMipLevels, forceMips, antialiasLevel); + + return retTex; +} + +bool GFXD3D11TextureManager::_loadTexture(GFXTextureObject *aTexture, GBitmap *pDL) +{ + PROFILE_SCOPE(GFXD3D11TextureManager_loadTexture); + + GFXD3D11TextureObject *texture = static_cast(aTexture); + + // Check with profiler to see if we can do automatic mipmap generation. + const bool supportsAutoMips = GFX->getCardProfiler()->queryProfile("autoMipMapLevel", true); + + // Helper bool + const bool isCompressedTexFmt = aTexture->mFormat >= GFXFormatDXT1 && aTexture->mFormat <= GFXFormatDXT5; + + // Settings for mipmap generation + U32 maxDownloadMip = pDL->getNumMipLevels(); + U32 nbMipMapLevel = pDL->getNumMipLevels(); + + if( supportsAutoMips && !isCompressedTexFmt ) + { + maxDownloadMip = 1; + nbMipMapLevel = aTexture->mMipLevels; + } + GFXD3D11Device* dev = D3D11; + + bool isDynamic = texture->mProfile->isDynamic(); + // Fill the texture... + for( U32 i = 0; i < maxDownloadMip; i++ ) + { + U32 subResource = D3D11CalcSubresource(i, 0, aTexture->mMipLevels); + + if(!isDynamic) + { + U8* copyBuffer = NULL; + + switch(texture->mFormat) + { + case GFXFormatR8G8B8: + { + PROFILE_SCOPE(Swizzle24_Upload); + AssertFatal(pDL->getFormat() == GFXFormatR8G8B8, "Assumption failed"); + + U8* Bits = new U8[pDL->getWidth(i) * pDL->getHeight(i) * 4]; + dMemcpy(Bits, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * 3); + bitmapConvertRGB_to_RGBX(&Bits, pDL->getWidth(i) * pDL->getHeight(i)); + copyBuffer = new U8[pDL->getWidth(i) * pDL->getHeight(i) * 4]; + + dev->getDeviceSwizzle32()->ToBuffer(copyBuffer, Bits, pDL->getWidth(i) * pDL->getHeight(i) * 4); + dev->getDeviceContext()->UpdateSubresource(texture->get2DTex(), subResource, NULL, copyBuffer, pDL->getWidth() * 4, pDL->getHeight() *4); + SAFE_DELETE_ARRAY(Bits); + break; + } + + case GFXFormatR8G8B8A8: + case GFXFormatR8G8B8X8: + { + PROFILE_SCOPE(Swizzle32_Upload); + copyBuffer = new U8[pDL->getWidth(i) * pDL->getHeight(i) * pDL->getBytesPerPixel()]; + dev->getDeviceSwizzle32()->ToBuffer(copyBuffer, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * pDL->getBytesPerPixel()); + dev->getDeviceContext()->UpdateSubresource(texture->get2DTex(), subResource, NULL, copyBuffer, pDL->getWidth() * pDL->getBytesPerPixel(), pDL->getHeight() *pDL->getBytesPerPixel()); + break; + } + + default: + { + // Just copy the bits in no swizzle or padding + PROFILE_SCOPE(SwizzleNull_Upload); + AssertFatal( pDL->getFormat() == texture->mFormat, "Format mismatch"); + dev->getDeviceContext()->UpdateSubresource(texture->get2DTex(), subResource, NULL, pDL->getBits(i), pDL->getWidth() *pDL->getBytesPerPixel(), pDL->getHeight() *pDL->getBytesPerPixel()); + } + } + + SAFE_DELETE_ARRAY(copyBuffer); + } + + else + { + D3D11_MAPPED_SUBRESOURCE mapping; + HRESULT res = dev->getDeviceContext()->Map(texture->get2DTex(), subResource, D3D11_MAP_WRITE, 0, &mapping); + + AssertFatal(res, "tex2d map call failure"); + + switch( texture->mFormat ) + { + case GFXFormatR8G8B8: + { + PROFILE_SCOPE(Swizzle24_Upload); + AssertFatal(pDL->getFormat() == GFXFormatR8G8B8, "Assumption failed"); + + U8* Bits = new U8[pDL->getWidth(i) * pDL->getHeight(i) * 4]; + dMemcpy(Bits, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * 3); + bitmapConvertRGB_to_RGBX(&Bits, pDL->getWidth(i) * pDL->getHeight(i)); + + dev->getDeviceSwizzle32()->ToBuffer(mapping.pData, Bits, pDL->getWidth(i) * pDL->getHeight(i) * 4); + SAFE_DELETE_ARRAY(Bits); + } + break; + + case GFXFormatR8G8B8A8: + case GFXFormatR8G8B8X8: + { + PROFILE_SCOPE(Swizzle32_Upload); + dev->getDeviceSwizzle32()->ToBuffer(mapping.pData, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * pDL->getBytesPerPixel()); + } + break; + + default: + { + // Just copy the bits in no swizzle or padding + PROFILE_SCOPE(SwizzleNull_Upload); + AssertFatal( pDL->getFormat() == texture->mFormat, "Format mismatch"); + dMemcpy(mapping.pData, pDL->getBits(i), pDL->getWidth(i) * pDL->getHeight(i) * pDL->getBytesPerPixel()); + } + } + + dev->getDeviceContext()->Unmap(texture->get2DTex(), subResource); + } + } + + D3D11_TEXTURE2D_DESC desc; + // if the texture asked for mip generation. lets generate it. + texture->get2DTex()->GetDesc(&desc); + if (desc.MiscFlags &D3D11_RESOURCE_MISC_GENERATE_MIPS) + { + dev->getDeviceContext()->GenerateMips(texture->getSRView()); + //texture->mMipLevels = desc.MipLevels; + } + + return true; +} + +bool GFXD3D11TextureManager::_loadTexture(GFXTextureObject *inTex, void *raw) +{ + PROFILE_SCOPE(GFXD3D11TextureManager_loadTextureRaw); + + GFXD3D11TextureObject *texture = (GFXD3D11TextureObject *) inTex; + GFXD3D11Device* dev = static_cast(GFX); + // currently only for volume textures... + if(texture->getDepth() < 1) return false; + + U8* Bits = NULL; + + if(texture->mFormat == GFXFormatR8G8B8) + { + // convert 24 bit to 32 bit + Bits = new U8[texture->getWidth() * texture->getHeight() * texture->getDepth() * 4]; + dMemcpy(Bits, raw, texture->getWidth() * texture->getHeight() * texture->getDepth() * 3); + bitmapConvertRGB_to_RGBX(&Bits, texture->getWidth() * texture->getHeight() * texture->getDepth()); + } + + U32 bytesPerPix = 1; + + switch(texture->mFormat) + { + case GFXFormatR8G8B8: + case GFXFormatR8G8B8A8: + case GFXFormatR8G8B8X8: + bytesPerPix = 4; + break; + } + + D3D11_BOX box; + box.left = 0; + box.right = texture->getWidth(); + box.front = 0; + box.back = texture->getDepth(); + box.top = 0; + box.bottom = texture->getHeight(); + + if(texture->mFormat == GFXFormatR8G8B8) // converted format also for volume textures + dev->getDeviceContext()->UpdateSubresource(texture->get3DTex(), 0, &box, Bits, texture->getWidth() * bytesPerPix, texture->getHeight() * bytesPerPix); + else + dev->getDeviceContext()->UpdateSubresource(texture->get3DTex(), 0, &box, raw, texture->getWidth() * bytesPerPix, texture->getHeight() * bytesPerPix); + + SAFE_DELETE_ARRAY(Bits); + + return true; +} + +bool GFXD3D11TextureManager::_refreshTexture(GFXTextureObject *texture) +{ + U32 usedStrategies = 0; + GFXD3D11TextureObject *realTex = static_cast(texture); + + if(texture->mProfile->doStoreBitmap()) + { + if(texture->mBitmap) + _loadTexture(texture, texture->mBitmap); + + if(texture->mDDS) + _loadTexture(texture, texture->mDDS); + + usedStrategies++; + } + + if(texture->mProfile->isRenderTarget() || texture->mProfile->isDynamic() || texture->mProfile->isZTarget()) + { + realTex->release(); + _innerCreateTexture(realTex, texture->getHeight(), texture->getWidth(), texture->getDepth(), texture->mFormat, texture->mProfile, texture->mMipLevels, false, texture->mAntialiasLevel); + usedStrategies++; + } + + AssertFatal(usedStrategies < 2, "GFXD3D11TextureManager::_refreshTexture - Inconsistent profile flags!"); + + return true; +} + +bool GFXD3D11TextureManager::_freeTexture(GFXTextureObject *texture, bool zombify) +{ + AssertFatal(dynamic_cast(texture),"Not an actual d3d texture object!"); + GFXD3D11TextureObject *tex = static_cast( texture ); + + // If it's a managed texture and we're zombifying, don't blast it, D3D allows + // us to keep it. + if(zombify && tex->isManaged) + return true; + + tex->release(); + + return true; +} + +/// Load a texture from a proper DDSFile instance. +bool GFXD3D11TextureManager::_loadTexture(GFXTextureObject *aTexture, DDSFile *dds) +{ + PROFILE_SCOPE(GFXD3D11TextureManager_loadTextureDDS); + + GFXD3D11TextureObject *texture = static_cast(aTexture); + GFXD3D11Device* dev = static_cast(GFX); + // Fill the texture... + for( U32 i = 0; i < aTexture->mMipLevels; i++ ) + { + PROFILE_SCOPE(GFXD3DTexMan_loadSurface); + + AssertFatal( dds->mSurfaces.size() > 0, "Assumption failed. DDSFile has no surfaces." ); + + U32 subresource = D3D11CalcSubresource(i, 0, aTexture->mMipLevels); + dev->getDeviceContext()->UpdateSubresource(texture->get2DTex(), subresource, 0, dds->mSurfaces[0]->mMips[i], dds->getSurfacePitch(i), 0); + } + + D3D11_TEXTURE2D_DESC desc; + // if the texture asked for mip generation. lets generate it. + texture->get2DTex()->GetDesc(&desc); + if (desc.MiscFlags & D3D11_RESOURCE_MISC_GENERATE_MIPS) + dev->getDeviceContext()->GenerateMips(texture->getSRView()); + + return true; +} + +void GFXD3D11TextureManager::createResourceView(U32 height, U32 width, U32 depth, DXGI_FORMAT format, U32 numMipLevels,U32 usageFlags, GFXTextureObject *inTex) +{ + GFXD3D11TextureObject *tex = static_cast(inTex); + ID3D11Resource* resource = NULL; + + if(tex->get2DTex()) + resource = tex->get2DTex(); + else if(tex->getSurface()) + resource = tex->getSurface(); + else + resource = tex->get3DTex(); + + HRESULT hr; + //TODO: add MSAA support later. + if(usageFlags & D3D11_BIND_SHADER_RESOURCE) + { + D3D11_SHADER_RESOURCE_VIEW_DESC desc; + + if(usageFlags & D3D11_BIND_DEPTH_STENCIL) + desc.Format = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; // reads the depth + else + desc.Format = format; + + if(depth > 0) + { + desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE3D; + desc.Texture3D.MipLevels = -1; + desc.Texture3D.MostDetailedMip = 0; + } + else + { + desc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; + desc.Texture2D.MipLevels = -1; + desc.Texture2D.MostDetailedMip = 0; + } + + hr = D3D11DEVICE->CreateShaderResourceView(resource,&desc, tex->getSRViewPtr()); + AssertFatal(SUCCEEDED(hr), "CreateShaderResourceView:: failed to create view!"); + } + + if(usageFlags & D3D11_BIND_RENDER_TARGET) + { + D3D11_RENDER_TARGET_VIEW_DESC desc; + desc.Format = format; + desc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; + desc.Texture2D.MipSlice = 0; + hr = D3D11DEVICE->CreateRenderTargetView(resource, &desc, tex->getRTViewPtr()); + AssertFatal(SUCCEEDED(hr), "CreateRenderTargetView:: failed to create view!"); + } + + if(usageFlags & D3D11_BIND_DEPTH_STENCIL) + { + D3D11_DEPTH_STENCIL_VIEW_DESC desc; + desc.Format = format; + desc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; + desc.Texture2D.MipSlice = 0; + desc.Flags = 0; + hr = D3D11DEVICE->CreateDepthStencilView(resource,&desc, tex->getDSViewPtr()); + AssertFatal(SUCCEEDED(hr), "CreateDepthStencilView:: failed to create view!"); + } +} \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11TextureManager.h b/Engine/source/gfx/D3D11/gfxD3D11TextureManager.h new file mode 100644 index 000000000..fa32941d8 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11TextureManager.h @@ -0,0 +1,62 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3DTEXTUREMANAGER_H_ +#define _GFXD3DTEXTUREMANAGER_H_ + +#include "gfx/D3D11/gfxD3D11TextureObject.h" +#include "core/util/safeRelease.h" + +class GFXD3D11TextureManager : public GFXTextureManager +{ + friend class GFXD3D11TextureObject; + +public: + GFXD3D11TextureManager(); + virtual ~GFXD3D11TextureManager(); + void createResourceView(U32 height, U32 width, U32 depth, DXGI_FORMAT format, U32 numMipLevels,U32 usageFlags, GFXTextureObject *inTex); +protected: + + // GFXTextureManager + GFXTextureObject *_createTextureObject( U32 height, + U32 width, + U32 depth, + GFXFormat format, + GFXTextureProfile *profile, + U32 numMipLevels, + bool forceMips = false, + S32 antialiasLevel = 0, + GFXTextureObject *inTex = NULL ); + + bool _loadTexture(GFXTextureObject *texture, DDSFile *dds); + bool _loadTexture(GFXTextureObject *texture, GBitmap *bmp); + bool _loadTexture(GFXTextureObject *texture, void *raw); + bool _refreshTexture(GFXTextureObject *texture); + bool _freeTexture(GFXTextureObject *texture, bool zombify = false); + +private: + U32 mCurTexSet[TEXTURE_STAGE_COUNT]; + + void _innerCreateTexture(GFXD3D11TextureObject *obj, U32 height, U32 width, U32 depth, GFXFormat format, GFXTextureProfile *profile, U32 numMipLevels, bool forceMips = false, S32 antialiasLevel = 0); +}; + +#endif diff --git a/Engine/source/gfx/D3D11/gfxD3D11TextureObject.cpp b/Engine/source/gfx/D3D11/gfxD3D11TextureObject.cpp new file mode 100644 index 000000000..8f15cf550 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11TextureObject.cpp @@ -0,0 +1,280 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/D3D11/gfxD3D11TextureObject.h" +#include "platform/profiler.h" +#include "console/console.h" + +#ifdef TORQUE_DEBUG +U32 GFXD3D11TextureObject::mTexCount = 0; +#endif + + +// GFXFormatR8G8B8 has now the same behaviour as GFXFormatR8G8B8X8. +// This is because 24 bit format are now deprecated by microsoft, for data alignment reason there's no changes beetween 24 and 32 bit formats. +// DirectX 10-11 both have 24 bit format no longer. + + +GFXD3D11TextureObject::GFXD3D11TextureObject( GFXDevice * d, GFXTextureProfile *profile) : GFXTextureObject( d, profile ) +{ +#ifdef D3D11_DEBUG_SPEW + mTexCount++; + Con::printf("+ texMake %d %x", mTexCount, this); +#endif + + mD3DTexture = NULL; + mLocked = false; + + mD3DSurface = NULL; + mLockedSubresource = 0; + mDSView = NULL; + mRTView = NULL; + mSRView = NULL; +} + +GFXD3D11TextureObject::~GFXD3D11TextureObject() +{ + kill(); +#ifdef D3D11_DEBUG_SPEW + mTexCount--; + Con::printf("+ texkill %d %x", mTexCount, this); +#endif +} + +GFXLockedRect *GFXD3D11TextureObject::lock(U32 mipLevel /*= 0*/, RectI *inRect /*= NULL*/) +{ + AssertFatal( !mLocked, "GFXD3D11TextureObject::lock - The texture is already locked!" ); + + D3D11_MAPPED_SUBRESOURCE mapInfo; + + if( mProfile->isRenderTarget() ) + { + //AssertFatal( 0, "GFXD3D11TextureObject::lock - Need to handle mapping render targets" ); + if( !mLockTex || + mLockTex->getWidth() != getWidth() || + mLockTex->getHeight() != getHeight() ) + { + mLockTex.set( getWidth(), getHeight(), mFormat, &GFXSystemMemProfile, avar("%s() - mLockTex (line %d)", __FUNCTION__, __LINE__) ); + } + + PROFILE_START(GFXD3D11TextureObject_lockRT); + + GFXD3D11Device* dev = D3D11; + + GFXD3D11TextureObject* to = (GFXD3D11TextureObject*) &(*mLockTex); + dev->getDeviceContext()->CopyResource(to->get2DTex(), mD3DTexture); + + mLockedSubresource = D3D11CalcSubresource(0, 0, 1); + HRESULT hr = dev->getDeviceContext()->Map(to->get2DTex(), mLockedSubresource, D3D11_MAP_READ, 0, &mapInfo); + + if (FAILED(hr)) + AssertFatal(false, "GFXD3D11TextureObject:lock- failed to map render target resource!"); + + mLocked = true; + + + PROFILE_END(); + } + else + { + RECT r; + + if(inRect) + { + r.top = inRect->point.y; + r.left = inRect->point.x; + r.bottom = inRect->point.y + inRect->extent.y; + r.right = inRect->point.x + inRect->extent.x; + } + + mLockedSubresource = D3D11CalcSubresource(mipLevel, 0, getMipLevels()); + HRESULT hr = D3D11DEVICECONTEXT->Map(mD3DTexture, mLockedSubresource, D3D11_MAP_WRITE_DISCARD, 0, &mapInfo); + + if ( FAILED(hr) ) + AssertFatal(false, "GFXD3D11TextureObject::lock - Failed to map subresource."); + + mLocked = true; + + } + + mLockRect.pBits = static_cast(mapInfo.pData); + mLockRect.Pitch = mapInfo.RowPitch; + + return (GFXLockedRect*)&mLockRect; +} + +void GFXD3D11TextureObject::unlock(U32 mipLevel) +{ + AssertFatal( mLocked, "GFXD3D11TextureObject::unlock - Attempting to unlock a surface that has not been locked" ); + + if( mProfile->isRenderTarget() ) + { + //AssertFatal( 0, "GFXD3D11TextureObject::unlock - Need to handle mapping render targets" ); + GFXD3D11TextureObject* to = (GFXD3D11TextureObject*)&(*mLockTex); + + D3D11->getDeviceContext()->Unmap(to->get2DTex(), mLockedSubresource); + + mLockedSubresource = 0; + mLocked = false; + } + else + { + D3D11DEVICECONTEXT->Unmap(get2DTex(), mLockedSubresource); + mLockedSubresource = 0; + mLocked = false; + } +} + +void GFXD3D11TextureObject::release() +{ + SAFE_RELEASE(mSRView); + SAFE_RELEASE(mRTView); + SAFE_RELEASE(mDSView); + SAFE_RELEASE(mD3DTexture); + SAFE_RELEASE(mD3DSurface); +} + +void GFXD3D11TextureObject::zombify() +{ + // Managed textures are managed by D3D + AssertFatal(!mLocked, "GFXD3D11TextureObject::zombify - Cannot zombify a locked texture!"); + if(isManaged) + return; + release(); +} + +void GFXD3D11TextureObject::resurrect() +{ + // Managed textures are managed by D3D + if(isManaged) + return; + + static_cast(TEXMGR)->refreshTexture(this); +} + +bool GFXD3D11TextureObject::copyToBmp(GBitmap* bmp) +{ + if (!bmp) + return false; + + // check format limitations + // at the moment we only support RGBA for the source (other 4 byte formats should + // be easy to add though) + AssertFatal(mFormat == GFXFormatR8G8B8A8, "copyToBmp: invalid format"); + if (mFormat != GFXFormatR8G8B8A8) + return false; + + PROFILE_START(GFXD3D11TextureObject_copyToBmp); + + AssertFatal(bmp->getWidth() == getWidth(), "doh"); + AssertFatal(bmp->getHeight() == getHeight(), "doh"); + U32 width = getWidth(); + U32 height = getHeight(); + + bmp->setHasTransparency(mHasTransparency); + + // set some constants + const U32 sourceBytesPerPixel = 4; + U32 destBytesPerPixel = 0; + + if(bmp->getFormat() == GFXFormatR8G8B8A8) + destBytesPerPixel = 4; + else if(bmp->getFormat() == GFXFormatR8G8B8) + destBytesPerPixel = 3; + else + // unsupported + AssertFatal(false, "unsupported bitmap format"); + + + // lock the texture + DXGI_MAPPED_RECT* lockRect = (DXGI_MAPPED_RECT*) lock(); + + // set pointers + U8* srcPtr = (U8*)lockRect->pBits; + U8* destPtr = bmp->getWritableBits(); + + // we will want to skip over any D3D cache data in the source texture + const S32 sourceCacheSize = lockRect->Pitch - width * sourceBytesPerPixel; + AssertFatal(sourceCacheSize >= 0, "copyToBmp: cache size is less than zero?"); + + PROFILE_START(GFXD3D11TextureObject_copyToBmp_pixCopy); + // copy data into bitmap + for (U32 row = 0; row < height; ++row) + { + for (U32 col = 0; col < width; ++col) + { + destPtr[0] = srcPtr[2]; // red + destPtr[1] = srcPtr[1]; // green + destPtr[2] = srcPtr[0]; // blue + if (destBytesPerPixel == 4) + destPtr[3] = srcPtr[3]; // alpha + + // go to next pixel in src + srcPtr += sourceBytesPerPixel; + + // go to next pixel in dest + destPtr += destBytesPerPixel; + } + // skip past the cache data for this row (if any) + srcPtr += sourceCacheSize; + } + PROFILE_END(); + + // assert if we stomped or underran memory + AssertFatal(U32(destPtr - bmp->getWritableBits()) == width * height * destBytesPerPixel, "copyToBmp: doh, memory error"); + AssertFatal(U32(srcPtr - (U8*)lockRect->pBits) == height * lockRect->Pitch, "copyToBmp: doh, memory error"); + + // unlock + unlock(); + + PROFILE_END(); + + return true; +} + +ID3D11ShaderResourceView* GFXD3D11TextureObject::getSRView() +{ + return mSRView; +} +ID3D11RenderTargetView* GFXD3D11TextureObject::getRTView() +{ + return mRTView; +} +ID3D11DepthStencilView* GFXD3D11TextureObject::getDSView() +{ + return mDSView; +} + +ID3D11ShaderResourceView** GFXD3D11TextureObject::getSRViewPtr() +{ + return &mSRView; +} +ID3D11RenderTargetView** GFXD3D11TextureObject::getRTViewPtr() +{ + return &mRTView; +} + +ID3D11DepthStencilView** GFXD3D11TextureObject::getDSViewPtr() +{ + return &mDSView; +} \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/gfxD3D11TextureObject.h b/Engine/source/gfx/D3D11/gfxD3D11TextureObject.h new file mode 100644 index 000000000..b50cc2465 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11TextureObject.h @@ -0,0 +1,89 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3D11TEXTUREOBJECT_H_ +#define _GFXD3D11TEXTUREOBJECT_H_ + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "gfx/gfxTextureHandle.h" +#include "gfx/gfxTextureManager.h" + +class GFXD3D11TextureObject : public GFXTextureObject +{ +protected: + static U32 mTexCount; + GFXTexHandle mLockTex; + DXGI_MAPPED_RECT mLockRect; + bool mLocked; + + U32 mLockedSubresource; + ID3D11Resource *mD3DTexture; + + // used for z buffers... + ID3D11Texture2D *mD3DSurface; + + ID3D11ShaderResourceView* mSRView; // for shader resource input + ID3D11RenderTargetView* mRTView; // for render targets + ID3D11DepthStencilView* mDSView; //render target view for depth stencil + +public: + + GFXD3D11TextureObject( GFXDevice * d, GFXTextureProfile *profile); + ~GFXD3D11TextureObject(); + + ID3D11Resource* getResource(){ return mD3DTexture; } + ID3D11Texture2D* get2DTex(){ return (ID3D11Texture2D*) mD3DTexture; } + ID3D11Texture2D** get2DTexPtr(){ return (ID3D11Texture2D**) &mD3DTexture; } + ID3D11Texture3D* get3DTex(){ return (ID3D11Texture3D*) mD3DTexture; } + ID3D11Texture3D** get3DTexPtr(){ return (ID3D11Texture3D**) &mD3DTexture; } + + ID3D11ShaderResourceView* getSRView(); + ID3D11RenderTargetView* getRTView(); + ID3D11DepthStencilView* getDSView(); + + ID3D11ShaderResourceView** getSRViewPtr(); + ID3D11RenderTargetView** getRTViewPtr(); + ID3D11DepthStencilView** getDSViewPtr(); + + + void release(); + + bool isManaged; //setting to true tells this texture not to be released from being zombify + + virtual GFXLockedRect * lock(U32 mipLevel = 0, RectI *inRect = NULL); + virtual void unlock(U32 mipLevel = 0 ); + + virtual bool copyToBmp(GBitmap* bmp); + ID3D11Texture2D* getSurface() {return mD3DSurface;} + ID3D11Texture2D** getSurfacePtr() {return &mD3DSurface;} + + // GFXResource + void zombify(); + void resurrect(); + +#ifdef TORQUE_DEBUG + virtual void pureVirtualCrash() {}; +#endif +}; + + +#endif diff --git a/Engine/source/gfx/D3D11/gfxD3D11VertexBuffer.cpp b/Engine/source/gfx/D3D11/gfxD3D11VertexBuffer.cpp new file mode 100644 index 000000000..1a8729e76 --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11VertexBuffer.cpp @@ -0,0 +1,233 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "platform/platform.h" +#include "gfx/D3D11/gfxD3D11VertexBuffer.h" +#include "console/console.h" + +GFXD3D11VertexBuffer::~GFXD3D11VertexBuffer() +{ + if(getOwningDevice() != NULL) + { + if(mBufferType != GFXBufferTypeVolatile) + { + SAFE_RELEASE(vb); + } + } +} + +void GFXD3D11VertexBuffer::lock(U32 vertexStart, U32 vertexEnd, void **vertexPtr) +{ + PROFILE_SCOPE(GFXD3D11VertexBuffer_lock); + + AssertFatal(lockedVertexStart == 0 && lockedVertexEnd == 0, "Cannot lock a buffer more than once!"); + + D3D11_MAP flags = D3D11_MAP_WRITE_DISCARD; + + switch(mBufferType) + { + case GFXBufferTypeStatic: + case GFXBufferTypeDynamic: + flags = D3D11_MAP_WRITE_DISCARD; + break; + + case GFXBufferTypeVolatile: + + // Get or create the volatile buffer... + mVolatileBuffer = D3D11->findVBPool( &mVertexFormat, vertexEnd ); + + if( !mVolatileBuffer ) + mVolatileBuffer = D3D11->createVBPool( &mVertexFormat, mVertexSize ); + + vb = mVolatileBuffer->vb; + + // Get our range now... + AssertFatal(vertexStart == 0, "Cannot get a subrange on a volatile buffer."); + AssertFatal(vertexEnd <= MAX_DYNAMIC_VERTS, "Cannot get more than MAX_DYNAMIC_VERTS in a volatile buffer. Up the constant!"); + AssertFatal(mVolatileBuffer->lockedVertexStart == 0 && mVolatileBuffer->lockedVertexEnd == 0, "Got more than one lock on the volatile pool."); + + // We created the pool when we requested this volatile buffer, so assume it exists... + if( mVolatileBuffer->mNumVerts + vertexEnd > MAX_DYNAMIC_VERTS ) + { + flags = D3D11_MAP_WRITE_DISCARD; + mVolatileStart = vertexStart = 0; + vertexEnd = vertexEnd; + } + else + { + flags = D3D11_MAP_WRITE_NO_OVERWRITE; + mVolatileStart = vertexStart = mVolatileBuffer->mNumVerts; + vertexEnd += mVolatileBuffer->mNumVerts; + } + + mVolatileBuffer->mNumVerts = vertexEnd+1; + + mVolatileBuffer->lockedVertexStart = vertexStart; + mVolatileBuffer->lockedVertexEnd = vertexEnd; + break; + } + + lockedVertexStart = vertexStart; + lockedVertexEnd = vertexEnd; + + // uncomment it for debugging purpose. called many times per frame... spammy! + //Con::printf("%x: Locking %s range (%d, %d)", this, (mBufferType == GFXBufferTypeVolatile ? "volatile" : "static"), lockedVertexStart, lockedVertexEnd); + + U32 sizeToLock = (vertexEnd - vertexStart) * mVertexSize; + if(mBufferType == GFXBufferTypeStatic) + { + *vertexPtr = new U8[sizeToLock]; + mLockedBuffer = *vertexPtr; + } + else + { + D3D11_MAPPED_SUBRESOURCE pVertexData; + ZeroMemory(&pVertexData, sizeof(D3D11_MAPPED_SUBRESOURCE)); + + HRESULT hr = D3D11DEVICECONTEXT->Map(vb, 0, flags, 0, &pVertexData); + + if(FAILED(hr)) + { + AssertFatal(false, "Unable to lock vertex buffer."); + } + + *vertexPtr = (U8*)pVertexData.pData + (vertexStart * mVertexSize); + } + + + + #ifdef TORQUE_DEBUG + + // Allocate a debug buffer large enough for the lock + // plus space for over and under run guard strings. + const U32 guardSize = sizeof( _VBGuardString ); + mDebugGuardBuffer = new U8[sizeToLock+(guardSize*2)]; + + // Setup the guard strings. + dMemcpy( mDebugGuardBuffer, _VBGuardString, guardSize ); + dMemcpy( mDebugGuardBuffer + sizeToLock + guardSize, _VBGuardString, guardSize ); + + // Store the real lock pointer and return our debug pointer. + mLockedBuffer = *vertexPtr; + *vertexPtr = mDebugGuardBuffer + guardSize; + + #endif // TORQUE_DEBUG +} + +void GFXD3D11VertexBuffer::unlock() +{ + PROFILE_SCOPE(GFXD3D11VertexBuffer_unlock); + + #ifdef TORQUE_DEBUG + + if ( mDebugGuardBuffer ) + { + const U32 guardSize = sizeof( _VBGuardString ); + const U32 sizeLocked = (lockedVertexEnd - lockedVertexStart) * mVertexSize; + + // First check the guard areas for overwrites. + AssertFatal(dMemcmp( mDebugGuardBuffer, _VBGuardString, guardSize) == 0, + "GFXD3D11VertexBuffer::unlock - Caught lock memory underrun!" ); + AssertFatal(dMemcmp( mDebugGuardBuffer + sizeLocked + guardSize, _VBGuardString, guardSize) == 0, + "GFXD3D11VertexBuffer::unlock - Caught lock memory overrun!" ); + + // Copy the debug content down to the real VB. + dMemcpy(mLockedBuffer, mDebugGuardBuffer + guardSize, sizeLocked); + + // Cleanup. + delete [] mDebugGuardBuffer; + mDebugGuardBuffer = NULL; + //mLockedBuffer = NULL; + } + + #endif // TORQUE_DEBUG + + if(mBufferType == GFXBufferTypeStatic) + { + const U32 sizeLocked = (lockedVertexEnd - lockedVertexStart) * mVertexSize; + //set up the update region of the buffer + D3D11_BOX box; + box.back = 1; + box.front = 0; + box.top = 0; + box.bottom = 1; + box.left = lockedVertexStart * mVertexSize; + box.right = lockedVertexEnd * mVertexSize; + //update the real vb buffer + D3D11DEVICECONTEXT->UpdateSubresource(vb, 0, &box,mLockedBuffer,sizeLocked, 0); + //clean up the old buffer + delete[] mLockedBuffer; + mLockedBuffer = NULL; + } + else + { + D3D11DEVICECONTEXT->Unmap(vb,0); + } + + + mIsFirstLock = false; + + //uncomment it for debugging purpose. called many times per frame... spammy! + //Con::printf("%x: Unlocking %s range (%d, %d)", this, (mBufferType == GFXBufferTypeVolatile ? "volatile" : "static"), lockedVertexStart, lockedVertexEnd); + + lockedVertexEnd = lockedVertexStart = 0; + + if(mVolatileBuffer.isValid()) + { + mVolatileBuffer->lockedVertexStart = 0; + mVolatileBuffer->lockedVertexEnd = 0; + mVolatileBuffer = NULL; + } +} + +void GFXD3D11VertexBuffer::zombify() +{ + AssertFatal(lockedVertexStart == 0 && lockedVertexEnd == 0, "GFXD3D11VertexBuffer::zombify - Cannot zombify a locked buffer!"); + // Static buffers are managed by D3D11 so we don't deal with them. + if(mBufferType == GFXBufferTypeDynamic) + { + SAFE_RELEASE(vb); + } +} + +void GFXD3D11VertexBuffer::resurrect() +{ + // Static buffers are managed by D3D11 so we don't deal with them. + if(mBufferType == GFXBufferTypeDynamic) + { + D3D11_BUFFER_DESC desc; + desc.ByteWidth = mVertexSize * mNumVerts; + desc.Usage = D3D11_USAGE_DYNAMIC; + desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; + desc.MiscFlags = 0; + desc.StructureByteStride = 0; + + HRESULT hr = D3D11DEVICE->CreateBuffer(&desc, NULL, &vb); + + if(FAILED(hr)) + { + AssertFatal(false, "GFXD3D11VertexBuffer::resurrect - Failed to allocate VB"); + } + } +} + diff --git a/Engine/source/gfx/D3D11/gfxD3D11VertexBuffer.h b/Engine/source/gfx/D3D11/gfxD3D11VertexBuffer.h new file mode 100644 index 000000000..380a0f93b --- /dev/null +++ b/Engine/source/gfx/D3D11/gfxD3D11VertexBuffer.h @@ -0,0 +1,95 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _GFXD3D_VERTEXBUFFER_H_ +#define _GFXD3D_VERTEXBUFFER_H_ + +#include "gfx/D3D11/gfxD3D11Device.h" +#include "core/util/safeDelete.h" + +class GFXD3D11VertexBuffer : public GFXVertexBuffer +{ +public: + ID3D11Buffer *vb; + StrongRefPtr mVolatileBuffer; + void *mLockedBuffer; +#ifdef TORQUE_DEBUG + #define _VBGuardString "GFX_VERTEX_BUFFER_GUARD_STRING" + U8 *mDebugGuardBuffer; + +#endif TORQUE_DEBUG + + bool mIsFirstLock; + bool mClearAtFrameEnd; + + GFXD3D11VertexBuffer(); + GFXD3D11VertexBuffer( GFXDevice *device, + U32 numVerts, + const GFXVertexFormat *vertexFormat, + U32 vertexSize, + GFXBufferType bufferType ); + virtual ~GFXD3D11VertexBuffer(); + + void lock(U32 vertexStart, U32 vertexEnd, void **vertexPtr); + void unlock(); + void prepare() {} + + // GFXResource interface + virtual void zombify(); + virtual void resurrect(); +}; + +//----------------------------------------------------------------------------- +// This is for debugging vertex buffers and trying to track down which vbs +// aren't getting free'd + +inline GFXD3D11VertexBuffer::GFXD3D11VertexBuffer() : GFXVertexBuffer(0,0,0,0,(GFXBufferType)0) +{ + vb = NULL; + mIsFirstLock = true; + lockedVertexEnd = lockedVertexStart = 0; + mClearAtFrameEnd = false; + +#ifdef TORQUE_DEBUG + mDebugGuardBuffer = NULL; + mLockedBuffer = NULL; +#endif +} + +inline GFXD3D11VertexBuffer::GFXD3D11VertexBuffer( GFXDevice *device, + U32 numVerts, + const GFXVertexFormat *vertexFormat, + U32 vertexSize, + GFXBufferType bufferType ) + : GFXVertexBuffer( device, numVerts, vertexFormat, vertexSize, bufferType ) +{ + vb = NULL; + mIsFirstLock = true; + mClearAtFrameEnd = false; + lockedVertexEnd = lockedVertexStart = 0; + mLockedBuffer = NULL; +#ifdef TORQUE_DEBUG + mDebugGuardBuffer = NULL; +#endif +} + +#endif // _GFXD3D_VERTEXBUFFER_H_ \ No newline at end of file diff --git a/Engine/source/gfx/D3D11/screenshotD3D11.cpp b/Engine/source/gfx/D3D11/screenshotD3D11.cpp new file mode 100644 index 000000000..89fa5f90c --- /dev/null +++ b/Engine/source/gfx/D3D11/screenshotD3D11.cpp @@ -0,0 +1,98 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2016 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "platform/platform.h" +#include "gfx/D3D11/screenshotD3D11.h" +#include "gfx/D3D11/gfxD3D11Device.h" + +//Note if MSAA is ever enabled this will need fixing +GBitmap* ScreenShotD3D11::_captureBackBuffer() +{ + ID3D11Texture2D* backBuf = D3D11->getBackBufferTexture(); + D3D11_TEXTURE2D_DESC desc; + backBuf->GetDesc(&desc); + desc.BindFlags = 0; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE; + desc.Usage = D3D11_USAGE_STAGING; + + //create temp texure + ID3D11Texture2D* pNewTexture = NULL; + HRESULT hr = D3D11DEVICE->CreateTexture2D(&desc, NULL, &pNewTexture); + if (FAILED(hr)) + return NULL; + + U32 width = desc.Width; + U32 height = desc.Height; + // pixel data + U8 *pData = new U8[width * height * 4]; + + D3D11DEVICECONTEXT->CopyResource(pNewTexture, backBuf); + D3D11_MAPPED_SUBRESOURCE Resource; + + hr = D3D11DEVICECONTEXT->Map(pNewTexture, 0, D3D11_MAP_READ, 0, &Resource); + if (FAILED(hr)) + { + //cleanup + SAFE_DELETE(pData); + SAFE_RELEASE(pNewTexture); + return NULL; + } + + const U32 pitch = width << 2; + const U8* pSource = (U8*)Resource.pData; + U32 totalPitch = 0; + for (U32 i = 0; i < height; ++i) + { + dMemcpy(pData, pSource, width * 4); + pSource += Resource.RowPitch; + pData += pitch; + totalPitch += pitch; + } + + D3D11DEVICECONTEXT->Unmap(pNewTexture, 0); + pData -= totalPitch; + GBitmap *gb = new GBitmap(width, height); + + //Set GBitmap data and convert from bgr to rgb + ColorI c; + for (S32 i = 0; isetColor(j, i, c); + } + } + + //cleanup + SAFE_DELETE(pData); + SAFE_RELEASE(pNewTexture); + + + return gb; + +} + diff --git a/Engine/source/gfx/D3D11/screenshotD3D11.h b/Engine/source/gfx/D3D11/screenshotD3D11.h new file mode 100644 index 000000000..1a3de23b7 --- /dev/null +++ b/Engine/source/gfx/D3D11/screenshotD3D11.h @@ -0,0 +1,39 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2016 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- +#ifndef _SCREENSHOTD3D11_H_ +#define _SCREENSHOTD3D11_H_ + +#include "gfx/screenshot.h" + +//************************************************************************** +// D3D implementation of screenshot +//************************************************************************** +class ScreenShotD3D11 : public ScreenShot +{ +protected: + + GBitmap* _captureBackBuffer(); + +}; + + +#endif // _SCREENSHOTD3D11_H_ From 3a9b50f702563d99317c8bd45f28146f67df362c Mon Sep 17 00:00:00 2001 From: rextimmy Date: Sun, 20 Mar 2016 21:50:21 +1000 Subject: [PATCH 2/5] Direct3D11 common shader changes. --- .../shaders/common/VolumetricFog/VFogP.hlsl | 34 ++--- .../common/VolumetricFog/VFogPreP.hlsl | 5 +- .../common/VolumetricFog/VFogPreV.hlsl | 14 +- .../common/VolumetricFog/VFogRefl.hlsl | 6 +- .../shaders/common/VolumetricFog/VFogV.hlsl | 13 +- .../game/shaders/common/basicCloudsP.hlsl | 8 +- .../game/shaders/common/basicCloudsV.hlsl | 27 ++-- .../game/shaders/common/cloudLayerP.hlsl | 15 ++- .../game/shaders/common/cloudLayerV.hlsl | 11 +- .../fixedFunction/addColorTextureP.hlsl | 17 ++- .../fixedFunction/addColorTextureV.hlsl | 14 +- .../shaders/common/fixedFunction/colorP.hlsl | 12 +- .../shaders/common/fixedFunction/colorV.hlsl | 14 +- .../fixedFunction/modColorTextureP.hlsl | 17 ++- .../fixedFunction/modColorTextureV.hlsl | 14 +- .../common/fixedFunction/textureP.hlsl | 36 ++++++ .../common/fixedFunction/textureV.hlsl | 46 +++++++ .../Empty/game/shaders/common/foliage.hlsl | 4 +- .../shaders/common/fxFoliageReplicatorP.hlsl | 25 ++-- .../shaders/common/fxFoliageReplicatorV.hlsl | 39 +++--- .../game/shaders/common/gl/basicCloudsV.glsl | 1 + .../game/shaders/common/gl/cloudLayerV.glsl | 1 + .../game/shaders/common/gl/lighting.glsl | 43 ++++++- .../game/shaders/common/gl/scatterSkyP.glsl | 3 + .../Empty/game/shaders/common/gl/torque.glsl | 33 +++++ .../game/shaders/common/guiMaterialV.hlsl | 12 +- .../game/shaders/common/hlslStructs.hlsl | 114 +++++++++++++++++ .../Empty/game/shaders/common/lighting.hlsl | 43 ++++++- .../lighting/advanced/convexGeometryV.hlsl | 19 ++- .../lighting/advanced/dbgColorBufferP.hlsl | 30 +++++ .../lighting/advanced/dbgDepthVisualizeP.hlsl | 12 +- .../lighting/advanced/dbgGlowVisualizeP.hlsl | 7 +- .../advanced/dbgLightColorVisualizeP.hlsl | 12 +- .../advanced/dbgLightSpecularVisualizeP.hlsl | 11 +- .../advanced/dbgNormalVisualizeP.hlsl | 8 +- .../advanced/dbgShadowVisualizeP.hlsl | 14 +- .../advanced/dbgSpecMapVisualizeP.hlsl | 31 +++++ .../advanced/deferredClearGBufferP.hlsl | 54 ++++++++ .../advanced/deferredClearGBufferV.hlsl | 43 +++++++ .../advanced/deferredColorShaderP.hlsl | 46 +++++++ .../lighting/advanced/deferredShadingP.hlsl | 54 ++++++++ .../lighting/advanced/farFrustumQuad.hlsl | 4 +- .../lighting/advanced/farFrustumQuadV.hlsl | 6 +- .../lighting/advanced/gl/dbgColorBufferP.glsl | 34 +++++ .../advanced/gl/dbgDepthVisualizeP.glsl | 4 +- .../advanced/gl/dbgLightColorVisualizeP.glsl | 8 +- .../gl/dbgLightSpecularVisualizeP.glsl | 6 +- .../advanced/gl/dbgNormalVisualizeP.glsl | 4 +- .../advanced/gl/dbgSpecMapVisualizeP.glsl | 34 +++++ .../advanced/gl/deferredClearGBufferP.glsl | 40 ++++++ .../advanced/gl/deferredColorShaderP.glsl | 37 ++++++ .../advanced/gl/deferredShadingP.glsl | 59 +++++++++ .../lighting/advanced/gl/pointLightP.glsl | 17 ++- .../lighting/advanced/gl/spotLightP.glsl | 18 ++- .../lighting/advanced/gl/vectorLightP.glsl | 29 +++-- .../advanced/particlePointLightP.hlsl | 25 ++-- .../advanced/particlePointLightV.hlsl | 20 +-- .../common/lighting/advanced/pointLightP.hlsl | 76 ++++++----- .../common/lighting/advanced/softShadow.hlsl | 19 ++- .../common/lighting/advanced/spotLightP.hlsl | 66 ++++++---- .../lighting/advanced/vectorLightP.hlsl | 120 ++++++++++-------- .../common/lighting/basic/shadowFilterP.hlsl | 12 +- .../common/lighting/basic/shadowFilterV.hlsl | 4 +- .../common/lighting/shadowMap/boxFilterP.hlsl | 22 ++-- .../common/lighting/shadowMap/boxFilterV.hlsl | 11 +- .../shaders/common/particleCompositeP.hlsl | 20 ++- .../shaders/common/particleCompositeV.hlsl | 18 ++- .../Empty/game/shaders/common/particlesP.hlsl | 22 ++-- .../Empty/game/shaders/common/particlesV.hlsl | 10 +- .../shaders/common/planarReflectBumpP.hlsl | 26 ++-- .../shaders/common/planarReflectBumpV.hlsl | 15 ++- .../game/shaders/common/planarReflectP.hlsl | 21 +-- .../game/shaders/common/planarReflectV.hlsl | 13 +- .../shaders/common/postFx/VolFogGlowP.hlsl | 22 ++-- .../common/postFx/caustics/causticsP.hlsl | 21 +-- .../shaders/common/postFx/chromaticLens.hlsl | 7 +- .../common/postFx/dof/DOF_CalcCoC_P.hlsl | 11 +- .../common/postFx/dof/DOF_CalcCoC_V.hlsl | 2 +- .../common/postFx/dof/DOF_DownSample_P.hlsl | 80 ++++++------ .../common/postFx/dof/DOF_DownSample_V.hlsl | 6 +- .../common/postFx/dof/DOF_Final_P.hlsl | 41 +++--- .../common/postFx/dof/DOF_Final_V.hlsl | 2 +- .../common/postFx/dof/DOF_Gausian_P.hlsl | 22 ++-- .../common/postFx/dof/DOF_Gausian_V.hlsl | 6 +- .../common/postFx/dof/DOF_Passthrough_V.hlsl | 2 +- .../common/postFx/dof/DOF_SmallBlur_P.hlsl | 15 ++- .../common/postFx/dof/DOF_SmallBlur_V.hlsl | 6 +- .../common/postFx/dof/gl/DOF_CalcCoC_P.glsl | 2 +- .../common/postFx/edgeaa/dbgEdgeDisplayP.hlsl | 8 +- .../shaders/common/postFx/edgeaa/edgeAAP.hlsl | 14 +- .../common/postFx/edgeaa/edgeDetectP.hlsl | 17 ++- .../game/shaders/common/postFx/flashP.hlsl | 6 +- .../game/shaders/common/postFx/fogP.hlsl | 9 +- .../shaders/common/postFx/fxaa/fxaaP.hlsl | 29 ++++- .../shaders/common/postFx/fxaa/fxaaV.hlsl | 4 +- .../game/shaders/common/postFx/gammaP.hlsl | 23 ++-- .../game/shaders/common/postFx/gl/gammaP.glsl | 8 ++ .../shaders/common/postFx/gl/glowBlurP.glsl | 4 +- .../game/shaders/common/postFx/glowBlurP.hlsl | 22 ++-- .../game/shaders/common/postFx/glowBlurV.hlsl | 4 +- .../common/postFx/hdr/bloomGaussBlurHP.hlsl | 7 +- .../common/postFx/hdr/bloomGaussBlurVP.hlsl | 7 +- .../common/postFx/hdr/brightPassFilterP.hlsl | 11 +- .../postFx/hdr/calculateAdaptedLumP.hlsl | 11 +- .../common/postFx/hdr/downScale4x4P.hlsl | 11 +- .../common/postFx/hdr/downScale4x4V.hlsl | 9 +- .../common/postFx/hdr/finalPassCombineP.hlsl | 41 +++--- .../postFx/hdr/gl/finalPassCombineP.glsl | 11 +- .../common/postFx/hdr/luminanceVisP.hlsl | 7 +- .../common/postFx/hdr/sampleLumInitialP.hlsl | 6 +- .../postFx/hdr/sampleLumIterativeP.hlsl | 6 +- .../postFx/lightRay/lightRayOccludeP.hlsl | 12 +- .../common/postFx/lightRay/lightRayP.hlsl | 17 +-- .../shaders/common/postFx/motionBlurP.hlsl | 15 +-- .../oculusvr/barrelDistortionChromaP.hlsl | 10 +- .../postFx/oculusvr/barrelDistortionP.hlsl | 7 +- .../common/postFx/oculusvr/monoToStereoP.hlsl | 7 +- .../game/shaders/common/postFx/passthruP.hlsl | 6 +- .../game/shaders/common/postFx/postFx.hlsl | 5 +- .../game/shaders/common/postFx/postFxV.hlsl | 2 +- .../common/postFx/ssao/SSAO_Blur_P.hlsl | 24 ++-- .../common/postFx/ssao/SSAO_Blur_V.hlsl | 6 +- .../shaders/common/postFx/ssao/SSAO_P.hlsl | 20 +-- .../common/postFx/ssao/SSAO_PowerTable_P.hlsl | 2 +- .../common/postFx/ssao/SSAO_PowerTable_V.hlsl | 2 +- .../shaders/common/postFx/turbulenceP.hlsl | 6 +- .../shaders/common/postFx/underwaterFogP.hlsl | 20 +-- .../common/postFx/vignette/VignetteP.hlsl | 7 +- .../Empty/game/shaders/common/precipP.hlsl | 16 ++- .../Empty/game/shaders/common/precipV.hlsl | 21 +-- .../game/shaders/common/projectedShadowP.hlsl | 11 +- .../game/shaders/common/projectedShadowV.hlsl | 18 +-- .../common/ribbons/basicRibbonShaderP.hlsl | 7 +- .../common/ribbons/basicRibbonShaderV.hlsl | 23 ++-- .../common/ribbons/texRibbonShaderP.hlsl | 13 +- .../common/ribbons/texRibbonShaderV.hlsl | 23 ++-- .../game/shaders/common/scatterSkyP.hlsl | 10 +- .../game/shaders/common/scatterSkyV.hlsl | 33 +++-- .../game/shaders/common/shaderModel.hlsl | 97 ++++++++++++++ .../shaders/common/shaderModelAutoGen.hlsl | 35 +++++ .../game/shaders/common/terrain/blendP.hlsl | 19 +-- .../game/shaders/common/terrain/blendV.hlsl | 11 +- .../game/shaders/common/terrain/terrain.glsl | 1 + .../game/shaders/common/terrain/terrain.hlsl | 1 + .../Empty/game/shaders/common/torque.hlsl | 51 ++++++-- .../shaders/common/water/gl/waterBasicP.glsl | 1 + .../game/shaders/common/water/gl/waterP.glsl | 3 +- .../shaders/common/water/waterBasicP.hlsl | 29 +++-- .../shaders/common/water/waterBasicV.hlsl | 23 ++-- .../game/shaders/common/water/waterP.hlsl | 49 +++---- .../game/shaders/common/water/waterV.hlsl | 18 +-- .../Empty/game/shaders/common/wavesP.hlsl | 29 +++-- .../Empty/game/shaders/common/wavesV.hlsl | 17 ++- .../lighting/advanced/deferredShading.cs | 2 +- .../shaders/common/VolumetricFog/VFogP.hlsl | 34 ++--- .../common/VolumetricFog/VFogPreP.hlsl | 5 +- .../common/VolumetricFog/VFogPreV.hlsl | 14 +- .../common/VolumetricFog/VFogRefl.hlsl | 5 +- .../shaders/common/VolumetricFog/VFogV.hlsl | 13 +- .../game/shaders/common/basicCloudsP.hlsl | 8 +- .../game/shaders/common/basicCloudsV.hlsl | 26 ++-- .../Full/game/shaders/common/cloudLayerP.hlsl | 15 ++- .../Full/game/shaders/common/cloudLayerV.hlsl | 11 +- .../fixedFunction/addColorTextureP.hlsl | 17 ++- .../fixedFunction/addColorTextureV.hlsl | 14 +- .../shaders/common/fixedFunction/colorP.hlsl | 12 +- .../shaders/common/fixedFunction/colorV.hlsl | 14 +- .../fixedFunction/modColorTextureP.hlsl | 17 ++- .../fixedFunction/modColorTextureV.hlsl | 14 +- .../common/fixedFunction/textureP.hlsl | 36 ++++++ .../common/fixedFunction/textureV.hlsl | 46 +++++++ .../Full/game/shaders/common/foliage.hlsl | 4 +- .../shaders/common/fxFoliageReplicatorP.hlsl | 25 ++-- .../shaders/common/fxFoliageReplicatorV.hlsl | 39 +++--- .../game/shaders/common/guiMaterialV.hlsl | 12 +- .../Full/game/shaders/common/hlslStructs.hlsl | 114 +++++++++++++++++ .../Full/game/shaders/common/lighting.hlsl | 2 +- .../lighting/advanced/convexGeometryV.hlsl | 19 ++- .../lighting/advanced/dbgColorBufferP.hlsl | 7 +- .../lighting/advanced/dbgDepthVisualizeP.hlsl | 12 +- .../lighting/advanced/dbgGlowVisualizeP.hlsl | 7 +- .../advanced/dbgLightColorVisualizeP.hlsl | 8 +- .../advanced/dbgLightSpecularVisualizeP.hlsl | 9 +- .../advanced/dbgNormalVisualizeP.hlsl | 8 +- .../advanced/dbgShadowVisualizeP.hlsl | 14 +- .../advanced/dbgSpecMapVisualizeP.hlsl | 7 +- .../advanced/deferredClearGBufferP.hlsl | 15 ++- .../advanced/deferredClearGBufferV.hlsl | 43 +++++++ .../advanced/deferredColorShaderP.hlsl | 8 +- .../lighting/advanced/deferredShadingP.hlsl | 20 +-- .../lighting/advanced/farFrustumQuad.hlsl | 4 +- .../lighting/advanced/farFrustumQuadV.hlsl | 6 +- .../advanced/particlePointLightP.hlsl | 25 ++-- .../advanced/particlePointLightV.hlsl | 20 +-- .../common/lighting/advanced/pointLightP.hlsl | 70 +++++----- .../common/lighting/advanced/softShadow.hlsl | 19 ++- .../common/lighting/advanced/spotLightP.hlsl | 62 ++++----- .../lighting/advanced/vectorLightP.hlsl | 111 ++++++++-------- .../common/lighting/basic/shadowFilterP.hlsl | 12 +- .../common/lighting/basic/shadowFilterV.hlsl | 4 +- .../common/lighting/shadowMap/boxFilterP.hlsl | 22 ++-- .../common/lighting/shadowMap/boxFilterV.hlsl | 11 +- .../shaders/common/particleCompositeP.hlsl | 20 ++- .../shaders/common/particleCompositeV.hlsl | 18 ++- .../Full/game/shaders/common/particlesP.hlsl | 22 ++-- .../Full/game/shaders/common/particlesV.hlsl | 10 +- .../shaders/common/planarReflectBumpP.hlsl | 26 ++-- .../shaders/common/planarReflectBumpV.hlsl | 15 ++- .../game/shaders/common/planarReflectP.hlsl | 21 +-- .../game/shaders/common/planarReflectV.hlsl | 13 +- .../shaders/common/postFx/VolFogGlowP.hlsl | 22 ++-- .../common/postFx/caustics/causticsP.hlsl | 21 +-- .../shaders/common/postFx/chromaticLens.hlsl | 7 +- .../common/postFx/dof/DOF_CalcCoC_P.hlsl | 11 +- .../common/postFx/dof/DOF_CalcCoC_V.hlsl | 2 +- .../common/postFx/dof/DOF_DownSample_P.hlsl | 80 ++++++------ .../common/postFx/dof/DOF_DownSample_V.hlsl | 6 +- .../common/postFx/dof/DOF_Final_P.hlsl | 41 +++--- .../common/postFx/dof/DOF_Final_V.hlsl | 2 +- .../common/postFx/dof/DOF_Gausian_P.hlsl | 22 ++-- .../common/postFx/dof/DOF_Gausian_V.hlsl | 6 +- .../common/postFx/dof/DOF_Passthrough_V.hlsl | 2 +- .../common/postFx/dof/DOF_SmallBlur_P.hlsl | 15 ++- .../common/postFx/dof/DOF_SmallBlur_V.hlsl | 6 +- .../common/postFx/edgeaa/dbgEdgeDisplayP.hlsl | 8 +- .../shaders/common/postFx/edgeaa/edgeAAP.hlsl | 14 +- .../common/postFx/edgeaa/edgeDetectP.hlsl | 17 ++- .../game/shaders/common/postFx/flashP.hlsl | 6 +- .../Full/game/shaders/common/postFx/fogP.hlsl | 9 +- .../shaders/common/postFx/fxaa/fxaaP.hlsl | 29 ++++- .../shaders/common/postFx/fxaa/fxaaV.hlsl | 4 +- .../game/shaders/common/postFx/gammaP.hlsl | 14 +- .../game/shaders/common/postFx/glowBlurP.hlsl | 22 ++-- .../game/shaders/common/postFx/glowBlurV.hlsl | 4 +- .../common/postFx/hdr/bloomGaussBlurHP.hlsl | 7 +- .../common/postFx/hdr/bloomGaussBlurVP.hlsl | 7 +- .../common/postFx/hdr/brightPassFilterP.hlsl | 11 +- .../postFx/hdr/calculateAdaptedLumP.hlsl | 11 +- .../common/postFx/hdr/downScale4x4P.hlsl | 11 +- .../common/postFx/hdr/downScale4x4V.hlsl | 9 +- .../common/postFx/hdr/finalPassCombineP.hlsl | 32 +++-- .../common/postFx/hdr/luminanceVisP.hlsl | 7 +- .../common/postFx/hdr/sampleLumInitialP.hlsl | 6 +- .../postFx/hdr/sampleLumIterativeP.hlsl | 6 +- .../postFx/lightRay/lightRayOccludeP.hlsl | 12 +- .../common/postFx/lightRay/lightRayP.hlsl | 17 +-- .../shaders/common/postFx/motionBlurP.hlsl | 15 +-- .../oculusvr/barrelDistortionChromaP.hlsl | 10 +- .../postFx/oculusvr/barrelDistortionP.hlsl | 7 +- .../common/postFx/oculusvr/monoToStereoP.hlsl | 7 +- .../game/shaders/common/postFx/passthruP.hlsl | 6 +- .../game/shaders/common/postFx/postFx.hlsl | 5 +- .../game/shaders/common/postFx/postFxV.hlsl | 2 +- .../common/postFx/ssao/SSAO_Blur_P.hlsl | 24 ++-- .../common/postFx/ssao/SSAO_Blur_V.hlsl | 6 +- .../shaders/common/postFx/ssao/SSAO_P.hlsl | 20 +-- .../common/postFx/ssao/SSAO_PowerTable_P.hlsl | 2 +- .../common/postFx/ssao/SSAO_PowerTable_V.hlsl | 2 +- .../shaders/common/postFx/turbulenceP.hlsl | 6 +- .../shaders/common/postFx/underwaterFogP.hlsl | 20 +-- .../common/postFx/vignette/VignetteP.hlsl | 7 +- .../Full/game/shaders/common/precipP.hlsl | 16 ++- .../Full/game/shaders/common/precipV.hlsl | 21 +-- .../game/shaders/common/projectedShadowP.hlsl | 11 +- .../game/shaders/common/projectedShadowV.hlsl | 18 +-- .../common/ribbons/basicRibbonShaderP.hlsl | 7 +- .../common/ribbons/basicRibbonShaderV.hlsl | 23 ++-- .../common/ribbons/texRibbonShaderP.hlsl | 13 +- .../common/ribbons/texRibbonShaderV.hlsl | 23 ++-- .../Full/game/shaders/common/scatterSkyP.hlsl | 10 +- .../Full/game/shaders/common/scatterSkyV.hlsl | 33 +++-- .../Full/game/shaders/common/shaderModel.hlsl | 97 ++++++++++++++ .../shaders/common/shaderModelAutoGen.hlsl | 35 +++++ .../game/shaders/common/terrain/blendP.hlsl | 19 +-- .../game/shaders/common/terrain/blendV.hlsl | 11 +- .../game/shaders/common/terrain/terrain.hlsl | 1 + .../Full/game/shaders/common/torque.hlsl | 19 +-- .../shaders/common/water/waterBasicP.hlsl | 28 ++-- .../shaders/common/water/waterBasicV.hlsl | 23 ++-- .../game/shaders/common/water/waterP.hlsl | 48 +++---- .../game/shaders/common/water/waterV.hlsl | 18 +-- .../Full/game/shaders/common/wavesP.hlsl | 29 +++-- .../Full/game/shaders/common/wavesV.hlsl | 17 ++- 283 files changed, 3547 insertions(+), 1834 deletions(-) create mode 100644 Templates/Empty/game/shaders/common/fixedFunction/textureP.hlsl create mode 100644 Templates/Empty/game/shaders/common/fixedFunction/textureV.hlsl create mode 100644 Templates/Empty/game/shaders/common/hlslStructs.hlsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/dbgColorBufferP.hlsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/dbgSpecMapVisualizeP.hlsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/deferredClearGBufferP.hlsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/deferredClearGBufferV.hlsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/deferredColorShaderP.hlsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/deferredShadingP.hlsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgColorBufferP.glsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgSpecMapVisualizeP.glsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredClearGBufferP.glsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredColorShaderP.glsl create mode 100644 Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredShadingP.glsl create mode 100644 Templates/Empty/game/shaders/common/shaderModel.hlsl create mode 100644 Templates/Empty/game/shaders/common/shaderModelAutoGen.hlsl create mode 100644 Templates/Full/game/shaders/common/fixedFunction/textureP.hlsl create mode 100644 Templates/Full/game/shaders/common/fixedFunction/textureV.hlsl create mode 100644 Templates/Full/game/shaders/common/hlslStructs.hlsl create mode 100644 Templates/Full/game/shaders/common/lighting/advanced/deferredClearGBufferV.hlsl create mode 100644 Templates/Full/game/shaders/common/shaderModel.hlsl create mode 100644 Templates/Full/game/shaders/common/shaderModelAutoGen.hlsl diff --git a/Templates/Empty/game/shaders/common/VolumetricFog/VFogP.hlsl b/Templates/Empty/game/shaders/common/VolumetricFog/VFogP.hlsl index aaadbf479..e900f7548 100644 --- a/Templates/Empty/game/shaders/common/VolumetricFog/VFogP.hlsl +++ b/Templates/Empty/game/shaders/common/VolumetricFog/VFogP.hlsl @@ -21,44 +21,44 @@ //----------------------------------------------------------------------------- // Volumetric Fog final pixel shader V2.00 - -#include "shadergen:/autogenConditioners.h" +#include "../shaderModel.hlsl" +#include "../shaderModelAutoGen.hlsl" #include "../torque.hlsl" -uniform sampler2D prepassTex : register(S0); -uniform sampler2D depthBuffer : register(S1); -uniform sampler2D frontBuffer : register(S2); -uniform sampler2D density : register(S3); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); +TORQUE_UNIFORM_SAMPLER2D(depthBuffer, 1); +TORQUE_UNIFORM_SAMPLER2D(frontBuffer, 2); +TORQUE_UNIFORM_SAMPLER2D(density, 3); +uniform float3 ambientColor; uniform float accumTime; uniform float4 fogColor; +uniform float4 modspeed;//xy speed layer 1, zw speed layer 2 +uniform float2 viewpoint; +uniform float2 texscale; uniform float fogDensity; uniform float preBias; uniform float textured; uniform float modstrength; -uniform float4 modspeed;//xy speed layer 1, zw speed layer 2 -uniform float2 viewpoint; -uniform float2 texscale; -uniform float3 ambientColor; uniform float numtiles; uniform float fadesize; uniform float2 PixelSize; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 htpos : TEXCOORD0; float2 uv0 : TEXCOORD1; }; -float4 main( ConnectData IN ) : COLOR0 +float4 main( ConnectData IN ) : TORQUE_TARGET0 { float2 uvscreen=((IN.htpos.xy/IN.htpos.w) + 1.0 ) / 2.0; uvscreen.y = 1.0 - uvscreen.y; - float obj_test = prepassUncondition( prepassTex, uvscreen).w * preBias; - float depth = tex2D(depthBuffer,uvscreen).r; - float front = tex2D(frontBuffer,uvscreen).r; + float obj_test = TORQUE_PREPASS_UNCONDITION(prepassTex, uvscreen).w * preBias; + float depth = TORQUE_TEX2D(depthBuffer, uvscreen).r; + float front = TORQUE_TEX2D(frontBuffer, uvscreen).r; if (depth <= front) return float4(0,0,0,0); @@ -73,8 +73,8 @@ float4 main( ConnectData IN ) : COLOR0 { float2 offset = viewpoint + ((-0.5 + (texscale * uvscreen)) * numtiles); - float2 mod1 = tex2D(density,(offset + (modspeed.xy*accumTime))).rg; - float2 mod2= tex2D(density,(offset + (modspeed.zw*accumTime))).rg; + float2 mod1 = TORQUE_TEX2D(density, (offset + (modspeed.xy*accumTime))).rg; + float2 mod2 = TORQUE_TEX2D(density, (offset + (modspeed.zw*accumTime))).rg; diff = (mod2.r + mod1.r) * modstrength; col *= (2.0 - ((mod1.g + mod2.g) * fadesize))/2.0; } diff --git a/Templates/Empty/game/shaders/common/VolumetricFog/VFogPreP.hlsl b/Templates/Empty/game/shaders/common/VolumetricFog/VFogPreP.hlsl index bb06f5f7c..fdc839507 100644 --- a/Templates/Empty/game/shaders/common/VolumetricFog/VFogPreP.hlsl +++ b/Templates/Empty/game/shaders/common/VolumetricFog/VFogPreP.hlsl @@ -21,14 +21,15 @@ //----------------------------------------------------------------------------- // Volumetric Fog prepass pixel shader V1.00 +#include "../shaderModel.hlsl" struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 pos : TEXCOORD0; }; -float4 main( ConnectData IN ) : COLOR0 +float4 main( ConnectData IN ) : TORQUE_TARGET0 { float OUT; diff --git a/Templates/Empty/game/shaders/common/VolumetricFog/VFogPreV.hlsl b/Templates/Empty/game/shaders/common/VolumetricFog/VFogPreV.hlsl index 2d13cdf01..aba7a745d 100644 --- a/Templates/Empty/game/shaders/common/VolumetricFog/VFogPreV.hlsl +++ b/Templates/Empty/game/shaders/common/VolumetricFog/VFogPreV.hlsl @@ -22,11 +22,12 @@ // Volumetric Fog prepass vertex shader V1.00 -#include "shaders/common/hlslstructs.h" +#include "../shaderModel.hlsl" +#include "../hlslStructs.hlsl" struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 pos : TEXCOORD0; }; @@ -35,12 +36,9 @@ uniform float4x4 modelView; ConnectData main( VertexIn_P IN) { ConnectData OUT; - - float4 inPos = IN.pos; - inPos.w = 1.0; - OUT.hpos = mul( modelView, inPos ); - OUT.pos = OUT.hpos; + OUT.hpos = mul(modelView, float4(IN.pos, 1.0)); + OUT.pos = OUT.hpos; - return OUT; + return OUT; } diff --git a/Templates/Empty/game/shaders/common/VolumetricFog/VFogRefl.hlsl b/Templates/Empty/game/shaders/common/VolumetricFog/VFogRefl.hlsl index 87226a1ac..380233b5f 100644 --- a/Templates/Empty/game/shaders/common/VolumetricFog/VFogRefl.hlsl +++ b/Templates/Empty/game/shaders/common/VolumetricFog/VFogRefl.hlsl @@ -20,17 +20,19 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +// Volumetric Fog Reflection pixel shader V1.00 +#include "../shaderModel.hlsl" uniform float4 fogColor; uniform float fogDensity; uniform float reflStrength; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 pos : TEXCOORD0; }; -float4 main( ConnectData IN ) : COLOR0 +float4 main( ConnectData IN ) : TORQUE_TARGET0 { return float4(fogColor.rgb,saturate(fogDensity*reflStrength)); } diff --git a/Templates/Empty/game/shaders/common/VolumetricFog/VFogV.hlsl b/Templates/Empty/game/shaders/common/VolumetricFog/VFogV.hlsl index 7f86802b5..167f83946 100644 --- a/Templates/Empty/game/shaders/common/VolumetricFog/VFogV.hlsl +++ b/Templates/Empty/game/shaders/common/VolumetricFog/VFogV.hlsl @@ -22,24 +22,25 @@ // Volumetric Fog final vertex shader V1.00 -#include "shaders/common/hlslstructs.h" +#include "../shaderModel.hlsl" +#include "../hlslStructs.hlsl" struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 htpos : TEXCOORD0; float2 uv0 : TEXCOORD1; }; uniform float4x4 modelView; -ConnectData main( VertexIn_PNT IN) +ConnectData main( VertexIn_PNTT IN) { - ConnectData OUT; + ConnectData OUT; - OUT.hpos = mul(modelView, IN.pos); + OUT.hpos = mul(modelView, float4(IN.pos,1.0)); OUT.htpos = OUT.hpos; OUT.uv0 = IN.uv0; - return OUT; + return OUT; } diff --git a/Templates/Empty/game/shaders/common/basicCloudsP.hlsl b/Templates/Empty/game/shaders/common/basicCloudsP.hlsl index 53b88d8b7..4b40e5e8c 100644 --- a/Templates/Empty/game/shaders/common/basicCloudsP.hlsl +++ b/Templates/Empty/game/shaders/common/basicCloudsP.hlsl @@ -24,14 +24,14 @@ struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 texCoord : TEXCOORD0; }; -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); -float4 main( ConnectData IN ) : COLOR +float4 main( ConnectData IN ) : TORQUE_TARGET0 { - float4 col = tex2D( diffuseMap, IN.texCoord ); + float4 col = TORQUE_TEX2D(diffuseMap, IN.texCoord); return hdrEncode( col ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/basicCloudsV.hlsl b/Templates/Empty/game/shaders/common/basicCloudsV.hlsl index 49842fd37..477f17d50 100644 --- a/Templates/Empty/game/shaders/common/basicCloudsV.hlsl +++ b/Templates/Empty/game/shaders/common/basicCloudsV.hlsl @@ -20,39 +20,40 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "shaderModel.hlsl" + struct CloudVert { - float4 pos : POSITION; - float3 normal : NORMAL; - float3 binormal : BINORMAL; - float3 tangent : TANGENT; + float3 pos : POSITION; float2 uv0 : TEXCOORD0; }; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 texCoord : TEXCOORD0; }; uniform float4x4 modelview; -uniform float accumTime; -uniform float texScale; uniform float2 texDirection; uniform float2 texOffset; +uniform float accumTime; +uniform float texScale; + ConnectData main( CloudVert IN ) -{ +{ ConnectData OUT; - - OUT.hpos = mul(modelview, IN.pos); - + + OUT.hpos = mul(modelview, float4(IN.pos,1.0)); + OUT.hpos.w = OUT.hpos.z; + float2 uv = IN.uv0; uv += texOffset; uv *= texScale; uv += accumTime * texDirection; - OUT.texCoord = uv; - + OUT.texCoord = uv; + return OUT; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/cloudLayerP.hlsl b/Templates/Empty/game/shaders/common/cloudLayerP.hlsl index a3c2d06e8..efa8fe0b4 100644 --- a/Templates/Empty/game/shaders/common/cloudLayerP.hlsl +++ b/Templates/Empty/game/shaders/common/cloudLayerP.hlsl @@ -20,6 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "shaderModel.hlsl" #include "torque.hlsl" //----------------------------------------------------------------------------- @@ -27,7 +28,7 @@ //----------------------------------------------------------------------------- struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoord12 : TEXCOORD0; float4 texCoord34 : TEXCOORD1; float3 vLightTS : TEXCOORD2; // light vector in tangent space, denormalized @@ -38,7 +39,7 @@ struct ConnectData //----------------------------------------------------------------------------- // Uniforms //----------------------------------------------------------------------------- -uniform sampler2D normalHeightMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(normalHeightMap, 0); uniform float3 ambientColor; uniform float3 sunColor; uniform float cloudCoverage; @@ -99,7 +100,7 @@ float3 ComputeIllumination( float2 texCoord, return finalColor; } -float4 main( ConnectData IN ) : COLOR +float4 main( ConnectData IN ) : TORQUE_TARGET0 { // Normalize the interpolated vectors: float3 vViewTS = normalize( IN.vViewTS ); @@ -109,11 +110,11 @@ float4 main( ConnectData IN ) : COLOR float2 texSample = IN.texCoord12.xy; - float4 noise1 = tex2D( normalHeightMap, IN.texCoord12.zw ); + float4 noise1 = TORQUE_TEX2D( normalHeightMap, IN.texCoord12.zw ); noise1 = normalize( ( noise1 - 0.5 ) * 2.0 ); //return noise1; - float4 noise2 = tex2D( normalHeightMap, IN.texCoord34.xy ); + float4 noise2 = TORQUE_TEX2D(normalHeightMap, IN.texCoord34.xy); noise2 = normalize( ( noise2 - 0.5 ) * 2.0 ); //return noise2; @@ -122,7 +123,7 @@ float4 main( ConnectData IN ) : COLOR float noiseHeight = noise1.a * noise2.a * ( cloudCoverage / 2.0 + 0.5 ); - float3 vNormalTS = normalize( tex2D( normalHeightMap, texSample ).xyz * 2.0 - 1.0 ); + float3 vNormalTS = normalize( TORQUE_TEX2D(normalHeightMap, texSample).xyz * 2.0 - 1.0); vNormalTS += noiseNormal; vNormalTS = normalize( vNormalTS ); @@ -130,7 +131,7 @@ float4 main( ConnectData IN ) : COLOR cResultColor.rgb = ComputeIllumination( texSample, vLightTS, vViewTS, vNormalTS ); float coverage = ( cloudCoverage - 0.5 ) * 2.0; - cResultColor.a = tex2D( normalHeightMap, texSample ).a + coverage + noiseHeight; + cResultColor.a = TORQUE_TEX2D(normalHeightMap, texSample).a + coverage + noiseHeight; if ( cloudCoverage > -1.0 ) cResultColor.a /= 1.0 + coverage; diff --git a/Templates/Empty/game/shaders/common/cloudLayerV.hlsl b/Templates/Empty/game/shaders/common/cloudLayerV.hlsl index 8c1cc555f..94f8b62cb 100644 --- a/Templates/Empty/game/shaders/common/cloudLayerV.hlsl +++ b/Templates/Empty/game/shaders/common/cloudLayerV.hlsl @@ -23,10 +23,11 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- +#include "shaderModel.hlsl" struct CloudVert { - float4 pos : POSITION; + float3 pos : POSITION; float3 normal : NORMAL; float3 binormal : BINORMAL; float3 tangent : TANGENT; @@ -35,7 +36,7 @@ struct CloudVert struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoord12 : TEXCOORD0; float4 texCoord34 : TEXCOORD1; float3 vLightTS : TEXCOORD2; // light vector in tangent space, denormalized @@ -61,8 +62,8 @@ ConnectData main( CloudVert IN ) { ConnectData OUT; - OUT.hpos = mul(modelview, IN.pos); - + OUT.hpos = mul(modelview, float4(IN.pos,1.0)); + OUT.hpos.w = OUT.hpos.z; // Offset the uv so we don't have a seam directly over our head. float2 uv = IN.uv0 + float2( 0.5, 0.5 ); @@ -85,7 +86,7 @@ ConnectData main( CloudVert IN ) float3 vBinormalWS = -IN.binormal; // Compute position in world space: - float4 vPositionWS = IN.pos + float4( eyePosWorld, 1 ); //mul( IN.pos, objTrans ); + float4 vPositionWS = float4(IN.pos, 1.0) + float4(eyePosWorld, 1); //mul( IN.pos, objTrans ); // Compute and output the world view vector (unnormalized): float3 vViewWS = eyePosWorld - vPositionWS.xyz; diff --git a/Templates/Empty/game/shaders/common/fixedFunction/addColorTextureP.hlsl b/Templates/Empty/game/shaders/common/fixedFunction/addColorTextureP.hlsl index 52ae4e955..d0577428f 100644 --- a/Templates/Empty/game/shaders/common/fixedFunction/addColorTextureP.hlsl +++ b/Templates/Empty/game/shaders/common/fixedFunction/addColorTextureP.hlsl @@ -20,9 +20,18 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -float4 main( float4 color_in : COLOR0, - float2 texCoord_in : TEXCOORD0, - uniform sampler2D diffuseMap : register(S0) ) : COLOR0 +#include "../shaderModel.hlsl" + +struct Conn { - return float4(color_in.rgb, color_in.a * tex2D(diffuseMap, texCoord_in).a); + float4 HPOS : TORQUE_POSITION; + float4 color : COLOR; + float2 texCoord : TEXCOORD0; +}; + +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); + +float4 main( Conn IN ) : TORQUE_TARGET0 +{ + return float4(IN.color.rgb, IN.color.a * TORQUE_TEX2D(diffuseMap, IN.texCoord).a); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/fixedFunction/addColorTextureV.hlsl b/Templates/Empty/game/shaders/common/fixedFunction/addColorTextureV.hlsl index 43a82dca6..8bf4e88d8 100644 --- a/Templates/Empty/game/shaders/common/fixedFunction/addColorTextureV.hlsl +++ b/Templates/Empty/game/shaders/common/fixedFunction/addColorTextureV.hlsl @@ -20,22 +20,28 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../shaderModel.hlsl" + struct Appdata { - float4 position : POSITION; + float3 position : POSITION; float4 color : COLOR; float2 texCoord : TEXCOORD0; }; + struct Conn { - float4 HPOS : POSITION; + float4 HPOS : TORQUE_POSITION; float4 color : COLOR; float2 texCoord : TEXCOORD0; }; -Conn main( Appdata In, uniform float4x4 modelview : register(C0) ) + +uniform float4x4 modelview; + +Conn main( Appdata In ) { Conn Out; - Out.HPOS = mul(modelview, In.position); + Out.HPOS = mul(modelview, float4(In.position,1.0)); Out.color = In.color; Out.texCoord = In.texCoord; return Out; diff --git a/Templates/Empty/game/shaders/common/fixedFunction/colorP.hlsl b/Templates/Empty/game/shaders/common/fixedFunction/colorP.hlsl index 90bb08112..dd9990e07 100644 --- a/Templates/Empty/game/shaders/common/fixedFunction/colorP.hlsl +++ b/Templates/Empty/game/shaders/common/fixedFunction/colorP.hlsl @@ -20,7 +20,15 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -float4 main( float4 color_in : COLOR0, uniform sampler2D diffuseMap : register(S0) ) : COLOR0 +#include "../shaderModel.hlsl" + +struct Conn { - return color_in; + float4 HPOS : TORQUE_POSITION; + float4 color : COLOR; +}; + +float4 main(Conn IN) : TORQUE_TARGET0 +{ + return IN.color; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/fixedFunction/colorV.hlsl b/Templates/Empty/game/shaders/common/fixedFunction/colorV.hlsl index f0efe1493..d16dfb863 100644 --- a/Templates/Empty/game/shaders/common/fixedFunction/colorV.hlsl +++ b/Templates/Empty/game/shaders/common/fixedFunction/colorV.hlsl @@ -20,20 +20,26 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../shaderModel.hlsl" + struct Appdata { - float4 position : POSITION; + float3 position : POSITION; float4 color : COLOR; }; + struct Conn { - float4 HPOS : POSITION; + float4 HPOS : TORQUE_POSITION; float4 color : COLOR; }; -Conn main( Appdata In, uniform float4x4 modelview : register(C0) ) + +uniform float4x4 modelview; + +Conn main( Appdata In ) { Conn Out; - Out.HPOS = mul(modelview, In.position); + Out.HPOS = mul(modelview, float4(In.position,1.0)); Out.color = In.color; return Out; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/fixedFunction/modColorTextureP.hlsl b/Templates/Empty/game/shaders/common/fixedFunction/modColorTextureP.hlsl index ccf22845c..63afec2a4 100644 --- a/Templates/Empty/game/shaders/common/fixedFunction/modColorTextureP.hlsl +++ b/Templates/Empty/game/shaders/common/fixedFunction/modColorTextureP.hlsl @@ -20,9 +20,18 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -float4 main( float4 color_in : COLOR0, - float2 texCoord_in : TEXCOORD0, - uniform sampler2D diffuseMap : register(S0) ) : COLOR0 +#include "../shaderModel.hlsl" + +struct Conn { - return tex2D(diffuseMap, texCoord_in) * color_in; + float4 HPOS : TORQUE_POSITION; + float4 color : COLOR; + float2 texCoord : TEXCOORD0; +}; + +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); + +float4 main( Conn IN ) : TORQUE_TARGET0 +{ + return TORQUE_TEX2D(diffuseMap, IN.texCoord) * IN.color; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/fixedFunction/modColorTextureV.hlsl b/Templates/Empty/game/shaders/common/fixedFunction/modColorTextureV.hlsl index 43a82dca6..8bf4e88d8 100644 --- a/Templates/Empty/game/shaders/common/fixedFunction/modColorTextureV.hlsl +++ b/Templates/Empty/game/shaders/common/fixedFunction/modColorTextureV.hlsl @@ -20,22 +20,28 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../shaderModel.hlsl" + struct Appdata { - float4 position : POSITION; + float3 position : POSITION; float4 color : COLOR; float2 texCoord : TEXCOORD0; }; + struct Conn { - float4 HPOS : POSITION; + float4 HPOS : TORQUE_POSITION; float4 color : COLOR; float2 texCoord : TEXCOORD0; }; -Conn main( Appdata In, uniform float4x4 modelview : register(C0) ) + +uniform float4x4 modelview; + +Conn main( Appdata In ) { Conn Out; - Out.HPOS = mul(modelview, In.position); + Out.HPOS = mul(modelview, float4(In.position,1.0)); Out.color = In.color; Out.texCoord = In.texCoord; return Out; diff --git a/Templates/Empty/game/shaders/common/fixedFunction/textureP.hlsl b/Templates/Empty/game/shaders/common/fixedFunction/textureP.hlsl new file mode 100644 index 000000000..82dbd4ce9 --- /dev/null +++ b/Templates/Empty/game/shaders/common/fixedFunction/textureP.hlsl @@ -0,0 +1,36 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../shaderModel.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); + +struct Conn +{ + float4 hpos : TORQUE_POSITION; + float2 texCoord : TEXCOORD0; +}; + +float4 main(Conn IN) : TORQUE_TARGET0 +{ + return TORQUE_TEX2D(diffuseMap, IN.texCoord); +} \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/fixedFunction/textureV.hlsl b/Templates/Empty/game/shaders/common/fixedFunction/textureV.hlsl new file mode 100644 index 000000000..204cf9514 --- /dev/null +++ b/Templates/Empty/game/shaders/common/fixedFunction/textureV.hlsl @@ -0,0 +1,46 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../shaderModel.hlsl" + +struct Appdata +{ + float3 position : POSITION; + float4 color : COLOR; + float2 texCoord : TEXCOORD0; +}; + +struct Conn +{ + float4 hpos : TORQUE_POSITION; + float2 texCoord : TEXCOORD0; +}; + +uniform float4x4 modelview; + +Conn main( Appdata In ) +{ + Conn Out; + Out.hpos = mul(modelview, float4(In.position, 1.0)); + Out.texCoord = In.texCoord; + return Out; +} \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/foliage.hlsl b/Templates/Empty/game/shaders/common/foliage.hlsl index e875bb23f..9952c29d6 100644 --- a/Templates/Empty/game/shaders/common/foliage.hlsl +++ b/Templates/Empty/game/shaders/common/foliage.hlsl @@ -30,11 +30,11 @@ #define MAX_COVERTYPES 8 +uniform float2 gc_fadeParams; +uniform float2 gc_windDir; uniform float3 gc_camRight; uniform float3 gc_camUp; uniform float4 gc_typeRects[MAX_COVERTYPES]; -uniform float2 gc_fadeParams; -uniform float2 gc_windDir; // .x = gust length // .y = premultiplied simulation time and gust frequency diff --git a/Templates/Empty/game/shaders/common/fxFoliageReplicatorP.hlsl b/Templates/Empty/game/shaders/common/fxFoliageReplicatorP.hlsl index dfa2e4de0..a8bb68e28 100644 --- a/Templates/Empty/game/shaders/common/fxFoliageReplicatorP.hlsl +++ b/Templates/Empty/game/shaders/common/fxFoliageReplicatorP.hlsl @@ -21,36 +21,39 @@ //----------------------------------------------------------------------------- #include "shdrConsts.h" - +#include "shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- struct ConnectData { - float2 texCoord : TEXCOORD0; - float4 lum : COLOR0; + float4 hpos : TORQUE_POSITION; + float2 outTexCoord : TEXCOORD0; + float4 color : COLOR0; float4 groundAlphaCoeff : COLOR1; float2 alphaLookup : TEXCOORD1; }; struct Fragout { - float4 col : COLOR0; + float4 col : TORQUE_TARGET0; }; +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); +TORQUE_UNIFORM_SAMPLER2D(alphaMap, 1); + +uniform float4 groundAlpha; +uniform float4 ambient; + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main( ConnectData IN, - uniform sampler2D diffuseMap : register(S0), - uniform sampler2D alphaMap : register(S1), - uniform float4 groundAlpha, - uniform float4 ambient ) +Fragout main( ConnectData IN ) { Fragout OUT; - float4 alpha = tex2D(alphaMap, IN.alphaLookup); - OUT.col = float4( ambient.rgb * IN.lum.rgb, 1.0 ) * tex2D(diffuseMap, IN.texCoord); + float4 alpha = TORQUE_TEX2D(alphaMap, IN.alphaLookup); + OUT.col = float4( ambient.rgb * IN.lum.rgb, 1.0 ) * TORQUE_TEX2D(diffuseMap, IN.texCoord); OUT.col.a = OUT.col.a * min(alpha, groundAlpha + IN.groundAlphaCoeff.x).x; return OUT; diff --git a/Templates/Empty/game/shaders/common/fxFoliageReplicatorV.hlsl b/Templates/Empty/game/shaders/common/fxFoliageReplicatorV.hlsl index 06a9cf5e5..70ec9ff4c 100644 --- a/Templates/Empty/game/shaders/common/fxFoliageReplicatorV.hlsl +++ b/Templates/Empty/game/shaders/common/fxFoliageReplicatorV.hlsl @@ -23,39 +23,42 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- + +#include "shaderModel.hlsl" + struct VertData { - float2 texCoord : TEXCOORD0; - float2 waveScale : TEXCOORD1; + float3 position : POSITION; float3 normal : NORMAL; - float4 position : POSITION; + float2 texCoord : TEXCOORD0; + float2 waveScale : TEXCOORD1; }; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 outTexCoord : TEXCOORD0; float4 color : COLOR0; float4 groundAlphaCoeff : COLOR1; float2 alphaLookup : TEXCOORD1; }; +uniform float4x4 projection : register(C0); +uniform float4x4 world : register(C4); +uniform float GlobalSwayPhase : register(C8); +uniform float SwayMagnitudeSide : register(C9); +uniform float SwayMagnitudeFront : register(C10); +uniform float GlobalLightPhase : register(C11); +uniform float LuminanceMagnitude : register(C12); +uniform float LuminanceMidpoint : register(C13); +uniform float DistanceRange : register(C14); +uniform float3 CameraPos : register(C15); +uniform float TrueBillboard : register(C16); + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -ConnectData main( VertData IN, - uniform float4x4 projection : register(C0), - uniform float4x4 world : register(C4), - uniform float GlobalSwayPhase : register(C8), - uniform float SwayMagnitudeSide : register(C9), - uniform float SwayMagnitudeFront : register(C10), - uniform float GlobalLightPhase : register(C11), - uniform float LuminanceMagnitude : register(C12), - uniform float LuminanceMidpoint : register(C13), - uniform float DistanceRange : register(C14), - uniform float3 CameraPos : register(C15), - uniform float TrueBillboard : register(C16) -) +ConnectData main( VertData IN ) { ConnectData OUT; @@ -113,7 +116,7 @@ ConnectData main( VertData IN, float Luminance = LuminanceMidpoint + LuminanceMagnitude * cos(GlobalLightPhase + IN.normal.y); // Alpha - float3 worldPos = float3(IN.position.x, IN.position.y, IN.position.z); + float3 worldPos = IN.position; float alpha = abs(distance(worldPos, CameraPos)) / DistanceRange; alpha = clamp(alpha, 0.0f, 1.0f); //pass it through diff --git a/Templates/Empty/game/shaders/common/gl/basicCloudsV.glsl b/Templates/Empty/game/shaders/common/gl/basicCloudsV.glsl index cccbafa8c..40c597120 100644 --- a/Templates/Empty/game/shaders/common/gl/basicCloudsV.glsl +++ b/Templates/Empty/game/shaders/common/gl/basicCloudsV.glsl @@ -41,6 +41,7 @@ out vec2 texCoord; void main() { gl_Position = tMul(modelview, IN_pos); + gl_Position.w = gl_Position.z; vec2 uv = IN_uv0; uv += texOffset; diff --git a/Templates/Empty/game/shaders/common/gl/cloudLayerV.glsl b/Templates/Empty/game/shaders/common/gl/cloudLayerV.glsl index 395c6f286..cba5c009a 100644 --- a/Templates/Empty/game/shaders/common/gl/cloudLayerV.glsl +++ b/Templates/Empty/game/shaders/common/gl/cloudLayerV.glsl @@ -62,6 +62,7 @@ void main() vec2 IN_uv0 = vTexCoord0.st; gl_Position = modelview * IN_pos; + gl_Position.w = gl_Position.z; // Offset the uv so we don't have a seam directly over our head. vec2 uv = IN_uv0 + vec2( 0.5, 0.5 ); diff --git a/Templates/Empty/game/shaders/common/gl/lighting.glsl b/Templates/Empty/game/shaders/common/gl/lighting.glsl index eb1c9b355..804ab1e3b 100644 --- a/Templates/Empty/game/shaders/common/gl/lighting.glsl +++ b/Templates/Empty/game/shaders/common/gl/lighting.glsl @@ -20,6 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "./torque.glsl" #ifndef TORQUE_SHADERGEN @@ -207,14 +208,42 @@ void compute4Lights( vec3 wsView, /// float AL_CalcSpecular( vec3 toLight, vec3 normal, vec3 toEye ) { - #ifdef PHONG_SPECULAR - // (R.V)^c - float specVal = dot( normalize( -reflect( toLight, normal ) ), toEye ); - #else - // (N.H)^c [Blinn-Phong, TGEA style, default] - float specVal = dot( normal, normalize( toLight + toEye ) ); - #endif + // (R.V)^c + float specVal = dot( normalize( -reflect( toLight, normal ) ), toEye ); // Return the specular factor. return pow( max( specVal, 0.00001f ), AL_ConstantSpecularPower ); } + +/// The output for Deferred Lighting +/// +/// @param toLight Normalized vector representing direction from the pixel +/// being lit, to the light source, in world space. +/// +/// @param normal Normalized surface normal. +/// +/// @param toEye The normalized vector representing direction from the pixel +/// being lit to the camera. +/// +vec4 AL_DeferredOutput( + vec3 lightColor, + vec3 diffuseColor, + vec4 matInfo, + vec4 ambient, + float specular, + float shadowAttenuation) +{ + vec3 specularColor = vec3(specular); + bool metalness = getFlag(matInfo.r, 3); + if ( metalness ) + { + specularColor = 0.04 * (1 - specular) + diffuseColor * specular; + } + + //specular = color * map * spec^gloss + float specularOut = (specularColor * matInfo.b * min(pow(max(specular,1.0f), max((matInfo.a / AL_ConstantSpecularPower),1.0f)),matInfo.a)).r; + + lightColor *= vec3(shadowAttenuation); + lightColor += ambient.rgb; + return vec4(lightColor.rgb, specularOut); +} diff --git a/Templates/Empty/game/shaders/common/gl/scatterSkyP.glsl b/Templates/Empty/game/shaders/common/gl/scatterSkyP.glsl index d9fa80bcf..b4e70f902 100644 --- a/Templates/Empty/game/shaders/common/gl/scatterSkyP.glsl +++ b/Templates/Empty/game/shaders/common/gl/scatterSkyP.glsl @@ -73,5 +73,8 @@ void main() discard; OUT_col.a = 1; + + OUT_col = clamp(OUT_col, 0.0, 1.0); + OUT_col = hdrEncode( OUT_col ); } diff --git a/Templates/Empty/game/shaders/common/gl/torque.glsl b/Templates/Empty/game/shaders/common/gl/torque.glsl index 9032a57f7..d4a7c4538 100644 --- a/Templates/Empty/game/shaders/common/gl/torque.glsl +++ b/Templates/Empty/game/shaders/common/gl/torque.glsl @@ -284,4 +284,37 @@ void fizzle(vec2 vpos, float visibility) /// @note This macro will only work in the void main() method of a pixel shader. #define assert(condition, color) { if(!any(condition)) { OUT_col = color; return; } } +// Deferred Shading: Material Info Flag Check +bool getFlag(float flags, float num) +{ + float process = round(flags * 255); + float squareNum = pow(2.0, num); + return (mod(process, pow(2.0, squareNum)) >= squareNum); +} + +// #define TORQUE_STOCK_GAMMA +#ifdef TORQUE_STOCK_GAMMA +// Sample in linear space. Decodes gamma. +vec4 toLinear(vec4 tex) +{ + return tex; +} +// Encodes gamma. +vec4 toGamma(vec4 tex) +{ + return tex; +} +#else +// Sample in linear space. Decodes gamma. +vec4 toLinear(vec4 tex) +{ + return vec4(pow(abs(tex.rgb), vec3(2.2)), tex.a); +} +// Encodes gamma. +vec4 toGamma(vec4 tex) +{ + return vec4(pow(abs(tex.rgb), vec3(1.0/2.2)), tex.a); +} +#endif // + #endif // _TORQUE_GLSL_ diff --git a/Templates/Empty/game/shaders/common/guiMaterialV.hlsl b/Templates/Empty/game/shaders/common/guiMaterialV.hlsl index 425da5da4..5d725338f 100644 --- a/Templates/Empty/game/shaders/common/guiMaterialV.hlsl +++ b/Templates/Empty/game/shaders/common/guiMaterialV.hlsl @@ -20,23 +20,25 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "hlslStructs.h" +#include "hlslStructs.hlsl" +#include "shaderModel.hlsl" struct MaterialDecoratorConnectV { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; }; +uniform float4x4 modelview : register(C0); + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -MaterialDecoratorConnectV main( VertexIn_PCT IN, - uniform float4x4 modelview : register(C0) ) +MaterialDecoratorConnectV main( VertexIn_PCT IN ) { MaterialDecoratorConnectV OUT; - OUT.hpos = mul(modelview, IN.pos); + OUT.hpos = mul(modelview, float4(IN.pos,1.0)); OUT.uv0 = IN.uv0; return OUT; diff --git a/Templates/Empty/game/shaders/common/hlslStructs.hlsl b/Templates/Empty/game/shaders/common/hlslStructs.hlsl new file mode 100644 index 000000000..ce0ca305c --- /dev/null +++ b/Templates/Empty/game/shaders/common/hlslStructs.hlsl @@ -0,0 +1,114 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +// The purpose of this file is to get all of our HLSL structures into one place. +// Please use the structures here instead of redefining input and output structures +// in each shader file. If structures are added, please adhere to the naming convention. + +//------------------------------------------------------------------------------ +// Vertex Input Structures +// +// These structures map to FVFs/Vertex Declarations in Torque. See gfxStructs.h +//------------------------------------------------------------------------------ + +// Notes +// +// Position should be specified as a float3 as our vertex structures in +// the engine output float3s for position. + +struct VertexIn_P +{ + float3 pos : POSITION; +}; + +struct VertexIn_PT +{ + float3 pos : POSITION; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PTTT +{ + float3 pos : POSITION; + float2 uv0 : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float2 uv2 : TEXCOORD2; +}; + +struct VertexIn_PC +{ + float3 pos : POSITION; + float4 color : DIFFUSE; +}; + +struct VertexIn_PNC +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float4 color : DIFFUSE; +}; + +struct VertexIn_PCT +{ + float3 pos : POSITION; + float4 color : DIFFUSE; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PN +{ + float3 pos : POSITION; + float3 normal : NORMAL; +}; + +struct VertexIn_PNT +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PNTT +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float3 tangent : TANGENT; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PNCT +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float4 color : DIFFUSE; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PNTTTB +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float2 uv0 : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float3 T : TEXCOORD2; + float3 B : TEXCOORD3; +}; \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting.hlsl b/Templates/Empty/game/shaders/common/lighting.hlsl index ec8129e94..a41b8a873 100644 --- a/Templates/Empty/game/shaders/common/lighting.hlsl +++ b/Templates/Empty/game/shaders/common/lighting.hlsl @@ -20,6 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "./torque.hlsl" #ifndef TORQUE_SHADERGEN @@ -207,14 +208,42 @@ void compute4Lights( float3 wsView, /// float AL_CalcSpecular( float3 toLight, float3 normal, float3 toEye ) { - #ifdef PHONG_SPECULAR - // (R.V)^c - float specVal = dot( normalize( -reflect( toLight, normal ) ), toEye ); - #else - // (N.H)^c [Blinn-Phong, TGEA style, default] - float specVal = dot( normal, normalize( toLight + toEye ) ); - #endif + // (R.V)^c + float specVal = dot( normalize( -reflect( toLight, normal ) ), toEye ); // Return the specular factor. return pow( max( specVal, 0.00001f ), AL_ConstantSpecularPower ); } + +/// The output for Deferred Lighting +/// +/// @param toLight Normalized vector representing direction from the pixel +/// being lit, to the light source, in world space. +/// +/// @param normal Normalized surface normal. +/// +/// @param toEye The normalized vector representing direction from the pixel +/// being lit to the camera. +/// +float4 AL_DeferredOutput( + float3 lightColor, + float3 diffuseColor, + float4 matInfo, + float4 ambient, + float specular, + float shadowAttenuation) +{ + float3 specularColor = float3(specular, specular, specular); + bool metalness = getFlag(matInfo.r, 3); + if ( metalness ) + { + specularColor = 0.04 * (1 - specular) + diffuseColor * specular; + } + + //specular = color * map * spec^gloss + float specularOut = (specularColor * matInfo.b * min(pow(abs(specular), max(( matInfo.a/ AL_ConstantSpecularPower),1.0f)),matInfo.a)).r; + + lightColor *= shadowAttenuation; + lightColor += ambient.rgb; + return float4(lightColor.rgb, specularOut); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/convexGeometryV.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/convexGeometryV.hlsl index c86cd4e89..064fcffa6 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/convexGeometryV.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/convexGeometryV.hlsl @@ -20,17 +20,24 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "../../hlslStructs.h" +#include "../../hlslStructs.hlsl" +#include "../../shaderModel.hlsl" + +struct VertData +{ + float3 pos : POSITION; + float4 color : COLOR; +}; struct ConvexConnectV { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 wsEyeDir : TEXCOORD0; float4 ssPos : TEXCOORD1; float4 vsEyeDir : TEXCOORD2; }; -ConvexConnectV main( VertexIn_P IN, +ConvexConnectV main( VertData IN, uniform float4x4 modelview, uniform float4x4 objTrans, uniform float4x4 worldViewOnly, @@ -38,9 +45,9 @@ ConvexConnectV main( VertexIn_P IN, { ConvexConnectV OUT; - OUT.hpos = mul( modelview, IN.pos ); - OUT.wsEyeDir = mul( objTrans, IN.pos ) - float4( eyePosWorld, 0.0 ); - OUT.vsEyeDir = mul( worldViewOnly, IN.pos ); + OUT.hpos = mul( modelview, float4(IN.pos,1.0) ); + OUT.wsEyeDir = mul(objTrans, float4(IN.pos, 1.0)) - float4(eyePosWorld, 0.0); + OUT.vsEyeDir = mul(worldViewOnly, float4(IN.pos, 1.0)); OUT.ssPos = OUT.hpos; return OUT; diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/dbgColorBufferP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/dbgColorBufferP.hlsl new file mode 100644 index 000000000..ad3debbaf --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/dbgColorBufferP.hlsl @@ -0,0 +1,30 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../postfx/postFx.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(colorBufferTex,0); + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 +{ + return float4(TORQUE_TEX2D( colorBufferTex, IN.uv0 ).rgb, 1.0); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl index a2b2b5d7d..68df09a78 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl @@ -20,14 +20,14 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" +#include "../../shaderModelAutoGen.hlsl" +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); +TORQUE_UNIFORM_SAMPLER1D(depthViz, 1); -float4 main( PFXVertToPix IN, - uniform sampler2D prepassTex : register(S0), - uniform sampler1D depthViz : register(S1) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float depth = prepassUncondition( prepassTex, IN.uv0 ).w; - return float4( tex1D( depthViz, depth ).rgb, 1.0 ); + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; + return float4( TORQUE_TEX1D( depthViz, depth ).rgb, 1.0 ); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl index 3c31c897e..257383659 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl @@ -20,12 +20,11 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" +TORQUE_UNIFORM_SAMPLER2D(glowBuffer, 0); -float4 main( PFXVertToPix IN, - uniform sampler2D glowBuffer : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - return tex2D(glowBuffer, IN.uv0); + return TORQUE_TEX2D(glowBuffer, IN.uv0); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl index 487b4c740..ca6d8d677 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl @@ -20,15 +20,13 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "../../postfx/postFx.hlsl" +TORQUE_UNIFORM_SAMPLER2D(lightPrePassTex,0); -float4 main( PFXVertToPix IN, - uniform sampler2D lightPrePassTex : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float3 lightcolor; - float nl_Att, specular; - lightinfoUncondition( tex2D( lightPrePassTex, IN.uv0 ), lightcolor, nl_Att, specular ); - return float4( lightcolor, 1.0 ); + float4 lightColor = TORQUE_TEX2D( lightPrePassTex, IN.uv0 ); + return float4( lightColor.rgb, 1.0 ); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl index edc25ed03..072f07e00 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl @@ -20,15 +20,12 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(lightPrePassTex,0); - -float4 main( PFXVertToPix IN, - uniform sampler2D lightPrePassTex : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float3 lightcolor; - float nl_Att, specular; - lightinfoUncondition( tex2D( lightPrePassTex, IN.uv0 ), lightcolor, nl_Att, specular ); + float specular = TORQUE_TEX2D( lightPrePassTex, IN.uv0 ).a; return float4( specular, specular, specular, 1.0 ); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl index c160045b4..4f31d2c53 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl @@ -20,13 +20,13 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" +#include "../../shaderModelAutoGen.hlsl" +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); -float4 main( PFXVertToPix IN, - uniform sampler2D prepassTex : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float3 normal = prepassUncondition( prepassTex, IN.uv0 ).xyz; + float3 normal = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).xyz; return float4( ( normal + 1.0 ) * 0.5, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/dbgShadowVisualizeP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/dbgShadowVisualizeP.hlsl index b1f2bca29..b54833499 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/dbgShadowVisualizeP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/dbgShadowVisualizeP.hlsl @@ -20,15 +20,19 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" + struct MaterialDecoratorConnectV { + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; }; -float4 main( MaterialDecoratorConnectV IN, - uniform sampler2D shadowMap : register(S0), - uniform sampler1D depthViz : register(S1) ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(shadowMap, 0); +TORQUE_UNIFORM_SAMPLER1D(depthViz, 1); + +float4 main( MaterialDecoratorConnectV IN ) : TORQUE_TARGET0 { - float depth = saturate( tex2D( shadowMap, IN.uv0 ).r ); - return float4( tex1D( depthViz, depth ).rgb, 1 ); + float depth = saturate( TORQUE_TEX2D( shadowMap, IN.uv0 ).r ); + return float4( TORQUE_TEX1D( depthViz, depth ).rgb, 1 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/dbgSpecMapVisualizeP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/dbgSpecMapVisualizeP.hlsl new file mode 100644 index 000000000..eba38a879 --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/dbgSpecMapVisualizeP.hlsl @@ -0,0 +1,31 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../postfx/postFx.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(matinfoTex,0); + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 +{ + float specular = TORQUE_TEX2D( matinfoTex, IN.uv0 ).b; + return float4( specular, specular, specular, 1.0 ); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/deferredClearGBufferP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/deferredClearGBufferP.hlsl new file mode 100644 index 000000000..cefebe8c7 --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/deferredClearGBufferP.hlsl @@ -0,0 +1,54 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../shaderModel.hlsl" + +struct Conn +{ + float4 hpos : TORQUE_POSITION; +}; + +struct Fragout +{ + float4 col : TORQUE_TARGET0; + float4 col1 : TORQUE_TARGET1; + float4 col2 : TORQUE_TARGET2; +}; + +//----------------------------------------------------------------------------- +// Main +//----------------------------------------------------------------------------- +Fragout main( Conn IN ) +{ + Fragout OUT; + + // Clear Prepass Buffer ( Normals/Depth ); + OUT.col = float4(1.0, 1.0, 1.0, 1.0); + + // Clear Color Buffer. + OUT.col1 = float4(0.0, 0.0, 0.0, 1.0); + + // Clear Material Info Buffer. + OUT.col2 = float4(0.0, 0.0, 0.0, 1.0); + + return OUT; +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/deferredClearGBufferV.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/deferredClearGBufferV.hlsl new file mode 100644 index 000000000..20ba4d509 --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/deferredClearGBufferV.hlsl @@ -0,0 +1,43 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../shaderModel.hlsl" + +struct Appdata +{ + float3 pos : POSITION; + float4 color : COLOR; +}; + +struct Conn +{ + float4 hpos : TORQUE_POSITION; +}; + +uniform float4x4 modelview; + +Conn main( Appdata In ) +{ + Conn Out; + Out.hpos = float4(In.pos,1.0); + return Out; +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/deferredColorShaderP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/deferredColorShaderP.hlsl new file mode 100644 index 000000000..d91d2eb38 --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/deferredColorShaderP.hlsl @@ -0,0 +1,46 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../shaderModel.hlsl" + +struct Fragout +{ + float4 col : TORQUE_TARGET0; + float4 col1 : TORQUE_TARGET1; + float4 col2 : TORQUE_TARGET2; +}; + +//----------------------------------------------------------------------------- +// Main +//----------------------------------------------------------------------------- +Fragout main( ) +{ + Fragout OUT; + + OUT.col = float4(0.0, 0.0, 0.0, 0.0); + OUT.col1 = float4(1.0, 1.0, 1.0, 1.0); + + // Draw on color buffer. + OUT.col2 = float4(1.0, 0.0, 0.0, 1.0); + + return OUT; +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/deferredShadingP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/deferredShadingP.hlsl new file mode 100644 index 000000000..c710656f8 --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/deferredShadingP.hlsl @@ -0,0 +1,54 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../shaderModelAutoGen.hlsl" +#include "../../postfx/postFx.hlsl" +#include "shaders/common/torque.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(colorBufferTex,0); +TORQUE_UNIFORM_SAMPLER2D(lightPrePassTex,1); +TORQUE_UNIFORM_SAMPLER2D(matInfoTex,2); +TORQUE_UNIFORM_SAMPLER2D(prepassTex,3); + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 +{ + float4 lightBuffer = TORQUE_TEX2D( lightPrePassTex, IN.uv0 ); + float4 colorBuffer = TORQUE_TEX2D( colorBufferTex, IN.uv0 ); + float4 matInfo = TORQUE_TEX2D( matInfoTex, IN.uv0 ); + float specular = saturate(lightBuffer.a); + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; + + if (depth>0.9999) + return float4(0,0,0,0); + + // Diffuse Color Altered by Metalness + bool metalness = getFlag(matInfo.r, 3); + if ( metalness ) + { + colorBuffer *= (1.0 - colorBuffer.a); + } + + colorBuffer *= float4(lightBuffer.rgb, 1.0); + colorBuffer += float4(specular, specular, specular, 1.0); + + return hdrEncode( float4(colorBuffer.rgb, 1.0) ); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/farFrustumQuad.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/farFrustumQuad.hlsl index 567dd11ce..543e21677 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/farFrustumQuad.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/farFrustumQuad.hlsl @@ -19,10 +19,11 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" struct FarFrustumQuadConnectV { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float3 wsEyeRay : TEXCOORD1; float3 vsEyeRay : TEXCOORD2; @@ -30,6 +31,7 @@ struct FarFrustumQuadConnectV struct FarFrustumQuadConnectP { + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float3 wsEyeRay : TEXCOORD1; float3 vsEyeRay : TEXCOORD2; diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/farFrustumQuadV.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/farFrustumQuadV.hlsl index 08cf61285..0167d901a 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/farFrustumQuadV.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/farFrustumQuadV.hlsl @@ -20,7 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "../../hlslStructs.h" +#include "../../hlslStructs.hlsl" #include "farFrustumQuad.hlsl" @@ -36,8 +36,8 @@ FarFrustumQuadConnectV main( VertexIn_PNTT IN, // Interpolators will generate eye rays the // from far-frustum corners. - OUT.wsEyeRay = IN.tangent.xyz; - OUT.vsEyeRay = IN.normal.xyz; + OUT.wsEyeRay = IN.tangent; + OUT.vsEyeRay = IN.normal; return OUT; } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgColorBufferP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgColorBufferP.glsl new file mode 100644 index 000000000..48a96d47d --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgColorBufferP.glsl @@ -0,0 +1,34 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../../gl/hlslCompat.glsl" +#include "shadergen:/autogenConditioners.h" +#include "../../../postfx/gl/postFx.glsl" + +uniform sampler2D colorBufferTex; + +out vec4 OUT_FragColor0; + +void main() +{ + OUT_FragColor0 = vec4(texture( colorBufferTex, uv0 ).rgb, 1.0); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl index 7c1754097..eb3d6f761 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgDepthVisualizeP.glsl @@ -24,13 +24,13 @@ #include "shadergen:/autogenConditioners.h" in vec2 uv0; -uniform sampler2D prepassBuffer; +uniform sampler2D prepassTex; uniform sampler1D depthViz; out vec4 OUT_col; void main() { - float depth = prepassUncondition( prepassBuffer, uv0 ).w; + float depth = prepassUncondition( prepassTex, uv0 ).w; OUT_col = vec4( texture( depthViz, depth ).rgb, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl index 05645e193..501e261ca 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightColorVisualizeP.glsl @@ -24,14 +24,12 @@ #include "shadergen:/autogenConditioners.h" in vec2 uv0; -uniform sampler2D lightInfoBuffer; +uniform sampler2D lightPrePassTex; out vec4 OUT_col; void main() { - vec3 lightcolor; - float nl_Att, specular; - lightinfoUncondition( texture( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); - OUT_col = vec4( lightcolor, 1.0 ); + vec4 lightColor = texture( lightPrePassTex, uv0 ); + OUT_col = vec4( lightColor.rgb, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl index 7e3e41ee9..c21c9b60f 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgLightSpecularVisualizeP.glsl @@ -24,14 +24,12 @@ #include "shadergen:/autogenConditioners.h" in vec2 uv0; -uniform sampler2D lightInfoBuffer; +uniform sampler2D lightPrePassTex; out vec4 OUT_col; void main() { - vec3 lightcolor; - float nl_Att, specular; - lightinfoUncondition( texture( lightInfoBuffer, uv0 ), lightcolor, nl_Att, specular ); + float specular = texture( lightPrePassTex, uv0 ).a; OUT_col = vec4( specular, specular, specular, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl index dfc611e88..84ea4d3fb 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgNormalVisualizeP.glsl @@ -24,12 +24,12 @@ #include "shadergen:/autogenConditioners.h" in vec2 uv0; -uniform sampler2D prepassBuffer; +uniform sampler2D prepassTex; out vec4 OUT_col; void main() { - vec3 normal = prepassUncondition( prepassBuffer, uv0 ).xyz; + vec3 normal = prepassUncondition( prepassTex, uv0 ).xyz; OUT_col = vec4( ( normal + 1.0 ) * 0.5, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgSpecMapVisualizeP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgSpecMapVisualizeP.glsl new file mode 100644 index 000000000..4ba9f6734 --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/dbgSpecMapVisualizeP.glsl @@ -0,0 +1,34 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- +#include "../../../gl/hlslCompat.glsl" +#include "shadergen:/autogenConditioners.h" +#include "../../../postfx/gl/postFx.glsl" + +uniform sampler2D matinfoTex; + +out vec4 OUT_FragColor0; + +void main() +{ + float specular = texture( matinfoTex, uv0 ).a; + OUT_FragColor0 = vec4( specular, specular, specular, 1.0 ); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredClearGBufferP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredClearGBufferP.glsl new file mode 100644 index 000000000..39dc0dc9f --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredClearGBufferP.glsl @@ -0,0 +1,40 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +out vec4 OUT_col; +out vec4 OUT_col1; +out vec4 OUT_col2; + +//----------------------------------------------------------------------------- +// Main +//----------------------------------------------------------------------------- +void main() +{ + // Clear Prepass Buffer ( Normals/Depth ); + OUT_col = vec4(1.0, 1.0, 1.0, 1.0); + + // Clear Color Buffer. + OUT_col1 = vec4(0.0, 0.0, 0.0, 1.0); + + // Clear Material Info Buffer. + OUT_col2 = vec4(0.0, 0.0, 0.0, 1.0); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredColorShaderP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredColorShaderP.glsl new file mode 100644 index 000000000..85c553089 --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredColorShaderP.glsl @@ -0,0 +1,37 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +layout (location = 0) out vec4 col; +layout (location = 1) out vec4 col1; +layout (location = 2) out vec4 col2; + +//----------------------------------------------------------------------------- +// Main +//----------------------------------------------------------------------------- +void main() +{ + col = vec4(0.0, 0.0, 0.0, 0.0); + col1 = vec4(1.0, 1.0, 1.0, 1.0); + + // Draw on color buffer. + col2 = vec4(1.0, 0.0, 0.0, 1.0); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredShadingP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredShadingP.glsl new file mode 100644 index 000000000..4ee4b1d81 --- /dev/null +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/deferredShadingP.glsl @@ -0,0 +1,59 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../../gl/hlslCompat.glsl" +#include "shadergen:/autogenConditioners.h" +#include "../../../postfx/gl/postFx.glsl" +#include "../../../gl/torque.glsl" + +uniform sampler2D colorBufferTex; +uniform sampler2D lightPrePassTex; +uniform sampler2D matInfoTex; +uniform sampler2D prepassTex; + +out vec4 OUT_col; + +void main() +{ + float depth = prepassUncondition( prepassTex, uv0 ).w; + if (depth>0.9999) + { + OUT_col = vec4(0.0); + return; + } + vec4 lightBuffer = texture( lightPrePassTex, uv0 ); + vec4 colorBuffer = texture( colorBufferTex, uv0 ); + vec4 matInfo = texture( matInfoTex, uv0 ); + float specular = clamp(lightBuffer.a,0.0,1.0); + + // Diffuse Color Altered by Metalness + bool metalness = getFlag(matInfo.r, 3); + if ( metalness ) + { + colorBuffer *= (1.0 - colorBuffer.a); + } + + colorBuffer *= vec4(lightBuffer.rgb, 1.0); + colorBuffer += vec4(specular, specular, specular, 1.0); + + OUT_col = hdrEncode( vec4(colorBuffer.rgb, 1.0) ); +} diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/pointLightP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/pointLightP.glsl index 92c9369a7..8a1aae3ca 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/pointLightP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/pointLightP.glsl @@ -33,6 +33,7 @@ in vec4 wsEyeDir; in vec4 ssPos; in vec4 vsEyeDir; +in vec4 color; #ifdef USE_COOKIE_TEX @@ -111,6 +112,10 @@ uniform sampler2D prePassBuffer; uniform sampler2D dynamicShadowMap; #endif +uniform sampler2D lightBuffer; +uniform sampler2D colorBuffer; +uniform sampler2D matInfoBuffer; + uniform vec4 rtParams0; uniform vec3 lightPosition; @@ -133,6 +138,15 @@ void main() vec3 ssPos = ssPos.xyz / ssPos.w; vec2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); + // Emissive. + vec4 matInfo = texture( matInfoBuffer, uvScene ); + bool emissive = getFlag( matInfo.r, 0 ); + if ( emissive ) + { + OUT_col = vec4(0.0, 0.0, 0.0, 0.0); + return; + } + // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); vec3 normal = prepassSample.rgb; @@ -244,5 +258,6 @@ void main() addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); } - OUT_col = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); + vec4 colorSample = texture( colorBuffer, uvScene ); + OUT_col = AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/spotLightP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/spotLightP.glsl index 29c278508..e7f3e88a7 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/spotLightP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/spotLightP.glsl @@ -32,10 +32,12 @@ in vec4 wsEyeDir; in vec4 ssPos; in vec4 vsEyeDir; +in vec4 color; #define IN_wsEyeDir wsEyeDir #define IN_ssPos ssPos #define IN_vsEyeDir vsEyeDir +#define IN_color color #ifdef USE_COOKIE_TEX @@ -48,6 +50,10 @@ uniform sampler2D prePassBuffer; uniform sampler2D shadowMap; uniform sampler2D dynamicShadowMap; +uniform sampler2D lightBuffer; +uniform sampler2D colorBuffer; +uniform sampler2D matInfoBuffer; + uniform vec4 rtParams0; uniform vec3 lightPosition; @@ -74,6 +80,15 @@ void main() vec3 ssPos = IN_ssPos.xyz / IN_ssPos.w; vec2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); + // Emissive. + vec4 matInfo = texture( matInfoBuffer, uvScene ); + bool emissive = getFlag( matInfo.r, 0 ); + if ( emissive ) + { + OUT_col = vec4(0.0, 0.0, 0.0, 0.0); + return; + } + // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); vec3 normal = prepassSample.rgb; @@ -180,5 +195,6 @@ void main() addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); } - OUT_col = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); + vec4 colorSample = texture( colorBuffer, uvScene ); + OUT_col = AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl b/Templates/Empty/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl index 4eb4973a3..608524a5a 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/gl/vectorLightP.glsl @@ -39,10 +39,13 @@ uniform sampler2D dynamicShadowMap; #ifdef USE_SSAO_MASK uniform sampler2D ssaoMask ; -uniform vec4 rtParams2; +uniform vec4 rtParams3; #endif -uniform sampler2D prePassBuffer; +uniform sampler2D prePassBuffer; +uniform sampler2D lightBuffer; +uniform sampler2D colorBuffer; +uniform sampler2D matInfoBuffer; uniform vec3 lightDirection; uniform vec4 lightColor; uniform float lightBrightness; @@ -189,7 +192,16 @@ vec4 AL_VectorLightShadowCast( sampler2D _sourceshadowMap, out vec4 OUT_col; void main() -{ +{ + // Emissive. + float4 matInfo = texture( matInfoBuffer, uv0 ); + bool emissive = getFlag( matInfo.r, 0 ); + if ( emissive ) + { + OUT_col = vec4(1.0, 1.0, 1.0, 0.0); + return; + } + // Sample/unpack the normal/z data vec4 prepassSample = prepassUncondition( prePassBuffer, uv0 ); vec3 normal = prepassSample.rgb; @@ -228,8 +240,6 @@ void main() shadowSoftness, dotNL, overDarkPSSM); - - vec4 dynamic_shadowed_colors = AL_VectorLightShadowCast( dynamicShadowMap, uv0.xy, dynamicWorldToLightProj, @@ -242,14 +252,13 @@ void main() shadowSoftness, dotNL, overDarkPSSM); - float static_shadowed = static_shadowed_colors.a; float dynamic_shadowed = dynamic_shadowed_colors.a; #ifdef PSSM_DEBUG_RENDER debugColor = static_shadowed_colors.rgb*0.5+dynamic_shadowed_colors.rgb*0.5; #endif - + // Fade out the shadow at the end of the range. vec4 zDist = vec4(zNearFarInvNearFar.x + zNearFarInvNearFar.y * depth); float fadeOutAmt = ( zDist.x - fadeStartLength.x ) * fadeStartLength.y; @@ -295,7 +304,7 @@ void main() // Sample the AO texture. #ifdef USE_SSAO_MASK - float ao = 1.0 - texture( ssaoMask, viewportCoordToRenderTarget( uv0.xy, rtParams2 ) ).r; + float ao = 1.0 - texture( ssaoMask, viewportCoordToRenderTarget( uv0.xy, rtParams3 ) ).r; addToResult *= ao; #endif @@ -303,6 +312,6 @@ void main() lightColorOut = debugColor; #endif - OUT_col = lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); - + vec4 colorSample = texture( colorBuffer, uv0 ); + OUT_col = AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/particlePointLightP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/particlePointLightP.hlsl index bc4784980..7ff5d50d2 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/particlePointLightP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/particlePointLightP.hlsl @@ -20,35 +20,36 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" - #include "farFrustumQuad.hlsl" #include "lightingUtils.hlsl" #include "../../lighting.hlsl" +#include "../../shaderModel.hlsl" +#include "../../shaderModelAutoGen.hlsl" struct ConvexConnectP { + float4 pos : TORQUE_POSITION; float4 ssPos : TEXCOORD0; float3 vsEyeDir : TEXCOORD1; }; -float4 main( ConvexConnectP IN, - uniform sampler2D prePassBuffer : register(S0), - - uniform float4 lightPosition, - uniform float4 lightColor, - uniform float lightRange, - - uniform float4 vsFarPlane, - uniform float4 rtParams0 ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(prePassBuffer, 0); + +uniform float4 lightPosition; +uniform float4 lightColor; +uniform float lightRange; +uniform float4 vsFarPlane; +uniform float4 rtParams0; + +float4 main( ConvexConnectP IN ) : TORQUE_TARGET0 { // Compute scene UV float3 ssPos = IN.ssPos.xyz / IN.ssPos.w; float2 uvScene = getUVFromSSPos(ssPos, rtParams0); // Sample/unpack the normal/z data - float4 prepassSample = prepassUncondition(prePassBuffer, uvScene); + float4 prepassSample = TORQUE_PREPASS_UNCONDITION(prePassBuffer, uvScene); float3 normal = prepassSample.rgb; float depth = prepassSample.a; diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/particlePointLightV.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/particlePointLightV.hlsl index f5dc9e444..faa2ec115 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/particlePointLightV.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/particlePointLightV.hlsl @@ -20,24 +20,26 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "../../hlslStructs.h" +#include "../../hlslStructs.hlsl" +#include "../../shaderModel.hlsl" struct ConvexConnectV { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 ssPos : TEXCOORD0; float3 vsEyeDir : TEXCOORD1; }; -ConvexConnectV main( VertexIn_P IN, - uniform float4x4 viewProj, - uniform float4x4 view, - uniform float3 particlePosWorld, - uniform float lightRange ) +uniform float4x4 viewProj; +uniform float4x4 view; +uniform float3 particlePosWorld; +uniform float lightRange; + +ConvexConnectV main( VertexIn_P IN ) { ConvexConnectV OUT; - - float4 vPosWorld = IN.pos + float4(particlePosWorld, 0.0) + float4(IN.pos.xyz, 0.0) * lightRange; + float4 pos = float4(IN.pos, 0.0); + float4 vPosWorld = pos + float4(particlePosWorld, 0.0) + pos * lightRange; OUT.hpos = mul(viewProj, vPosWorld); OUT.vsEyeDir = mul(view, vPosWorld); OUT.ssPos = OUT.hpos; diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/pointLightP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/pointLightP.hlsl index 48c0d76e3..540fd65c7 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/pointLightP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/pointLightP.hlsl @@ -20,7 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "farFrustumQuad.hlsl" #include "lightingUtils.hlsl" @@ -31,6 +31,7 @@ struct ConvexConnectP { + float4 pos : TORQUE_POSITION; float4 wsEyeDir : TEXCOORD0; float4 ssPos : TEXCOORD1; float4 vsEyeDir : TEXCOORD2; @@ -40,7 +41,7 @@ struct ConvexConnectP #ifdef USE_COOKIE_TEX /// The texture for cookie rendering. -uniform samplerCUBE cookieMap : register(S3); +TORQUE_UNIFORM_SAMPLERCUBE(cookieMap, 3); #endif @@ -52,9 +53,9 @@ uniform samplerCUBE cookieMap : register(S3); return shadowCoord; } - float4 shadowSample( samplerCUBE shadowMap, float3 shadowCoord ) + float4 shadowSample( TORQUE_SAMPLERCUBE(shadowMap), float3 shadowCoord ) { - return texCUBE( shadowMap, shadowCoord ); + return TORQUE_TEXCUBE( shadowMap, shadowCoord ); } #else @@ -105,40 +106,52 @@ uniform samplerCUBE cookieMap : register(S3); #endif +TORQUE_UNIFORM_SAMPLER2D(prePassBuffer, 0); -float4 main( ConvexConnectP IN, +#ifdef SHADOW_CUBE +TORQUE_UNIFORM_SAMPLERCUBE(shadowMap, 1); +#else +TORQUE_UNIFORM_SAMPLER2D(shadowMap, 1); +TORQUE_UNIFORM_SAMPLER2D(dynamicShadowMap, 2); +#endif - uniform sampler2D prePassBuffer : register(S0), +TORQUE_UNIFORM_SAMPLER2D(lightBuffer, 5); +TORQUE_UNIFORM_SAMPLER2D(colorBuffer, 6); +TORQUE_UNIFORM_SAMPLER2D(matInfoBuffer, 7); - #ifdef SHADOW_CUBE - uniform samplerCUBE shadowMap : register(S1), - #else - uniform sampler2D shadowMap : register(S1), - uniform sampler2D dynamicShadowMap : register(S2), - #endif +uniform float4 rtParams0; +uniform float4 lightColor; - uniform float4 rtParams0, +uniform float lightBrightness; +uniform float3 lightPosition; - uniform float3 lightPosition, - uniform float4 lightColor, - uniform float lightBrightness, - uniform float lightRange, - uniform float2 lightAttenuation, - uniform float4 lightMapParams, +uniform float4 lightMapParams; +uniform float4 vsFarPlane; +uniform float4 lightParams; - uniform float4 vsFarPlane, - uniform float3x3 viewToLightProj, - uniform float3x3 dynamicViewToLightProj, +uniform float lightRange; +uniform float shadowSoftness; +uniform float2 lightAttenuation; - uniform float4 lightParams, - uniform float shadowSoftness ) : COLOR0 +uniform float3x3 viewToLightProj; +uniform float3x3 dynamicViewToLightProj; + +float4 main( ConvexConnectP IN ) : TORQUE_TARGET0 { // Compute scene UV float3 ssPos = IN.ssPos.xyz / IN.ssPos.w; float2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); - + + // Emissive. + float4 matInfo = TORQUE_TEX2D( matInfoBuffer, uvScene ); + bool emissive = getFlag( matInfo.r, 0 ); + if ( emissive ) + { + return float4(0.0, 0.0, 0.0, 0.0); + } + // Sample/unpack the normal/z data - float4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); + float4 prepassSample = TORQUE_PREPASS_UNCONDITION( prePassBuffer, uvScene ); float3 normal = prepassSample.rgb; float depth = prepassSample.a; @@ -175,14 +188,14 @@ float4 main( ConvexConnectP IN, #ifdef SHADOW_CUBE // TODO: We need to fix shadow cube to handle soft shadows! - float occ = texCUBE( shadowMap, mul( viewToLightProj, -lightVec ) ).r; + float occ = TORQUE_TEXCUBE( shadowMap, mul( viewToLightProj, -lightVec ) ).r; float shadowed = saturate( exp( lightParams.y * ( occ - distToLight ) ) ); #else // Static float2 shadowCoord = decodeShadowCoord( mul( viewToLightProj, -lightVec ) ).xy; - float static_shadowed = softShadow_filter( shadowMap, + float static_shadowed = softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(shadowMap), ssPos.xy, shadowCoord, shadowSoftness, @@ -192,7 +205,7 @@ float4 main( ConvexConnectP IN, // Dynamic float2 dynamicShadowCoord = decodeShadowCoord( mul( dynamicViewToLightProj, -lightVec ) ).xy; - float dynamic_shadowed = softShadow_filter( dynamicShadowMap, + float dynamic_shadowed = softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), ssPos.xy, dynamicShadowCoord, shadowSoftness, @@ -210,7 +223,7 @@ float4 main( ConvexConnectP IN, #ifdef USE_COOKIE_TEX // Lookup the cookie sample. - float4 cookie = texCUBE( cookieMap, mul( viewToLightProj, -lightVec ) ); + float4 cookie = TORQUE_TEXCUBE( cookieMap, mul( viewToLightProj, -lightVec ) ); // Multiply the light with the cookie tex. lightcol *= cookie.rgb; @@ -250,5 +263,6 @@ float4 main( ConvexConnectP IN, addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); } - return lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); + float4 colorSample = TORQUE_TEX2D( colorBuffer, uvScene ); + return AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/softShadow.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/softShadow.hlsl index 36bffbfd9..0faf3e1fb 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/softShadow.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/softShadow.hlsl @@ -20,6 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" #if defined( SOFTSHADOW ) && defined( SOFTSHADOW_HIGH_QUALITY ) @@ -69,10 +70,9 @@ static float2 sNonUniformTaps[NUM_PRE_TAPS] = /// The texture used to do per-pixel pseudorandom /// rotations of the filter taps. -uniform sampler2D gTapRotationTex : register(S4); +TORQUE_UNIFORM_SAMPLER2D(gTapRotationTex, 4); - -float softShadow_sampleTaps( sampler2D shadowMap, +float softShadow_sampleTaps( TORQUE_SAMPLER2D(shadowMap1), float2 sinCos, float2 shadowPos, float filterRadius, @@ -88,7 +88,7 @@ float softShadow_sampleTaps( sampler2D shadowMap, { tap.x = ( sNonUniformTaps[t].x * sinCos.y - sNonUniformTaps[t].y * sinCos.x ) * filterRadius; tap.y = ( sNonUniformTaps[t].y * sinCos.y + sNonUniformTaps[t].x * sinCos.x ) * filterRadius; - float occluder = tex2Dlod( shadowMap, float4( shadowPos + tap, 0, 0 ) ).r; + float occluder = TORQUE_TEX2DLOD( shadowMap1, float4( shadowPos + tap, 0, 0 ) ).r; float esm = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); shadow += esm / float( endTap - startTap ); @@ -98,7 +98,7 @@ float softShadow_sampleTaps( sampler2D shadowMap, } -float softShadow_filter( sampler2D shadowMap, +float softShadow_filter( TORQUE_SAMPLER2D(shadowMap), float2 vpos, float2 shadowPos, float filterRadius, @@ -111,16 +111,15 @@ float softShadow_filter( sampler2D shadowMap, // If softshadow is undefined then we skip any complex // filtering... just do a single sample ESM. - float occluder = tex2Dlod( shadowMap, float4( shadowPos, 0, 0 ) ).r; + float occluder = TORQUE_TEX2DLOD(shadowMap, float4(shadowPos, 0, 0)).r; float shadow = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); #else - // Lookup the random rotation for this screen pixel. - float2 sinCos = ( tex2Dlod( gTapRotationTex, float4( vpos * 16, 0, 0 ) ).rg - 0.5 ) * 2; + float2 sinCos = ( TORQUE_TEX2DLOD(gTapRotationTex, float4(vpos * 16, 0, 0)).rg - 0.5) * 2; // Do the prediction taps first. - float shadow = softShadow_sampleTaps( shadowMap, + float shadow = softShadow_sampleTaps( TORQUE_SAMPLER2D_MAKEARG(shadowMap), sinCos, shadowPos, filterRadius, @@ -137,7 +136,7 @@ float softShadow_filter( sampler2D shadowMap, // in a partially shadowed area. if ( shadow * ( 1.0 - shadow ) * max( dotNL, 0 ) > 0.06 ) { - shadow += softShadow_sampleTaps( shadowMap, + shadow += softShadow_sampleTaps( TORQUE_SAMPLER2D_MAKEARG(shadowMap), sinCos, shadowPos, filterRadius, diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/spotLightP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/spotLightP.hlsl index 33c7f333e..e1f3baf93 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/spotLightP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/spotLightP.hlsl @@ -20,7 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModel.hlsl" +#include "../../shaderModelAutoGen.hlsl" #include "farFrustumQuad.hlsl" #include "lightingUtils.hlsl" @@ -31,49 +32,63 @@ struct ConvexConnectP { + float4 pos : TORQUE_POSITION; float4 wsEyeDir : TEXCOORD0; float4 ssPos : TEXCOORD1; float4 vsEyeDir : TEXCOORD2; }; +TORQUE_UNIFORM_SAMPLER2D(prePassBuffer, 0); +TORQUE_UNIFORM_SAMPLER2D(shadowMap, 1); +TORQUE_UNIFORM_SAMPLER2D(dynamicShadowMap,2); + #ifdef USE_COOKIE_TEX /// The texture for cookie rendering. -uniform sampler2D cookieMap : register(S3); +TORQUE_UNIFORM_SAMPLER2D(cookieMap, 3); #endif +TORQUE_UNIFORM_SAMPLER2D(lightBuffer, 5); +TORQUE_UNIFORM_SAMPLER2D(colorBuffer, 6); +TORQUE_UNIFORM_SAMPLER2D(matInfoBuffer, 7); -float4 main( ConvexConnectP IN, +uniform float4 rtParams0; - uniform sampler2D prePassBuffer : register(S0), - uniform sampler2D shadowMap : register(S1), - uniform sampler2D dynamicShadowMap : register(S2), +uniform float lightBrightness; +uniform float3 lightPosition; - uniform float4 rtParams0, +uniform float4 lightColor; - uniform float3 lightPosition, - uniform float4 lightColor, - uniform float lightBrightness, - uniform float lightRange, - uniform float2 lightAttenuation, - uniform float3 lightDirection, - uniform float4 lightSpotParams, - uniform float4 lightMapParams, +uniform float lightRange; +uniform float3 lightDirection; - uniform float4 vsFarPlane, - uniform float4x4 viewToLightProj, - uniform float4x4 dynamicViewToLightProj, +uniform float4 lightSpotParams; +uniform float4 lightMapParams; +uniform float4 vsFarPlane; +uniform float4x4 viewToLightProj; +uniform float4 lightParams; +uniform float4x4 dynamicViewToLightProj; - uniform float4 lightParams, - uniform float shadowSoftness ) : COLOR0 +uniform float2 lightAttenuation; +uniform float shadowSoftness; + +float4 main( ConvexConnectP IN ) : TORQUE_TARGET0 { // Compute scene UV float3 ssPos = IN.ssPos.xyz / IN.ssPos.w; float2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); + // Emissive. + float4 matInfo = TORQUE_TEX2D( matInfoBuffer, uvScene ); + bool emissive = getFlag( matInfo.r, 0 ); + if ( emissive ) + { + return float4(0.0, 0.0, 0.0, 0.0); + } + // Sample/unpack the normal/z data - float4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); + float4 prepassSample = TORQUE_PREPASS_UNCONDITION( prePassBuffer, uvScene ); float3 normal = prepassSample.rgb; float depth = prepassSample.a; @@ -117,7 +132,7 @@ float4 main( ConvexConnectP IN, // Get a linear depth from the light source. float distToLight = pxlPosLightProj.z / lightRange; - float static_shadowed = softShadow_filter( shadowMap, + float static_shadowed = softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(shadowMap), ssPos.xy, shadowCoord, shadowSoftness, @@ -125,7 +140,7 @@ float4 main( ConvexConnectP IN, nDotL, lightParams.y ); - float dynamic_shadowed = softShadow_filter( dynamicShadowMap, + float dynamic_shadowed = softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), ssPos.xy, dynshadowCoord, shadowSoftness, @@ -139,7 +154,7 @@ float4 main( ConvexConnectP IN, #ifdef USE_COOKIE_TEX // Lookup the cookie sample. - float4 cookie = tex2D( cookieMap, shadowCoord ); + float4 cookie = TORQUE_TEX2D( cookieMap, shadowCoord ); // Multiply the light with the cookie tex. lightcol *= cookie.rgb; @@ -179,5 +194,6 @@ float4 main( ConvexConnectP IN, addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); } - return lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); + float4 colorSample = TORQUE_TEX2D( colorBuffer, uvScene ); + return AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Empty/game/shaders/common/lighting/advanced/vectorLightP.hlsl b/Templates/Empty/game/shaders/common/lighting/advanced/vectorLightP.hlsl index 1b4548575..1a9726171 100644 --- a/Templates/Empty/game/shaders/common/lighting/advanced/vectorLightP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/advanced/vectorLightP.hlsl @@ -20,7 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModel.hlsl" +#include "../../shaderModelAutoGen.hlsl" #include "farFrustumQuad.hlsl" #include "../../torque.hlsl" @@ -29,16 +30,55 @@ #include "../shadowMap/shadowMapIO_HLSL.h" #include "softShadow.hlsl" - -uniform sampler2D shadowMap : register(S1); -uniform sampler2D dynamicShadowMap : register(S2); +TORQUE_UNIFORM_SAMPLER2D(prePassBuffer, 0); +TORQUE_UNIFORM_SAMPLER2D(shadowMap, 1); +TORQUE_UNIFORM_SAMPLER2D(dynamicShadowMap, 2); #ifdef USE_SSAO_MASK -uniform sampler2D ssaoMask : register(S3); -uniform float4 rtParams2; +TORQUE_UNIFORM_SAMPLER2D(ssaoMask, 3); +uniform float4 rtParams3; #endif +//register 4? +TORQUE_UNIFORM_SAMPLER2D(lightBuffer, 5); +TORQUE_UNIFORM_SAMPLER2D(colorBuffer, 6); +TORQUE_UNIFORM_SAMPLER2D(matInfoBuffer, 7); -float4 AL_VectorLightShadowCast( sampler2D sourceShadowMap, +uniform float lightBrightness; +uniform float3 lightDirection; + +uniform float4 lightColor; +uniform float4 lightAmbient; + +uniform float shadowSoftness; +uniform float3 eyePosWorld; + +uniform float4 atlasXOffset; +uniform float4 atlasYOffset; +uniform float4 zNearFarInvNearFar; +uniform float4 lightMapParams; +uniform float4 farPlaneScalePSSM; +uniform float4 overDarkPSSM; + +uniform float2 fadeStartLength; +uniform float2 atlasScale; + +uniform float4x4 eyeMat; + +// Static Shadows +uniform float4x4 worldToLightProj; +uniform float4 scaleX; +uniform float4 scaleY; +uniform float4 offsetX; +uniform float4 offsetY; +// Dynamic Shadows +uniform float4x4 dynamicWorldToLightProj; +uniform float4 dynamicScaleX; +uniform float4 dynamicScaleY; +uniform float4 dynamicOffsetX; +uniform float4 dynamicOffsetY; +uniform float4 dynamicFarPlaneScalePSSM; + +float4 AL_VectorLightShadowCast( TORQUE_SAMPLER2D(sourceShadowMap), float2 texCoord, float4x4 worldToLightProj, float4 worldPos, @@ -52,8 +92,7 @@ float4 AL_VectorLightShadowCast( sampler2D sourceShadowMap, float2 atlasScale, float shadowSoftness, float dotNL , - float4 overDarkPSSM -) + float4 overDarkPSSM) { // Compute shadow map coordinate float4 pxlPosLightProj = mul(worldToLightProj, worldPos); @@ -144,7 +183,7 @@ float4 AL_VectorLightShadowCast( sampler2D sourceShadowMap, distToLight *= farPlaneScale; return float4(debugColor, - softShadow_filter( sourceShadowMap, + softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(sourceShadowMap), texCoord, shadowCoord, farPlaneScale * shadowSoftness, @@ -153,46 +192,18 @@ float4 AL_VectorLightShadowCast( sampler2D sourceShadowMap, dot( finalMask, overDarkPSSM ) ) ); }; -float4 main( FarFrustumQuadConnectP IN, - - uniform sampler2D prePassBuffer : register(S0), - - uniform float3 lightDirection, - uniform float4 lightColor, - uniform float lightBrightness, - uniform float4 lightAmbient, - uniform float4x4 eyeMat, - - uniform float3 eyePosWorld, - uniform float4 atlasXOffset, - uniform float4 atlasYOffset, - uniform float2 atlasScale, - uniform float4 zNearFarInvNearFar, - uniform float4 lightMapParams, - uniform float2 fadeStartLength, - uniform float4 overDarkPSSM, - uniform float shadowSoftness, - - // Static Shadows - uniform float4x4 worldToLightProj, - uniform float4 scaleX, - uniform float4 scaleY, - uniform float4 offsetX, - uniform float4 offsetY, - uniform float4 farPlaneScalePSSM, - - // Dynamic Shadows - uniform float4x4 dynamicWorldToLightProj, - uniform float4 dynamicScaleX, - uniform float4 dynamicScaleY, - uniform float4 dynamicOffsetX, - uniform float4 dynamicOffsetY, - uniform float4 dynamicFarPlaneScalePSSM - - ) : COLOR0 -{ +float4 main( FarFrustumQuadConnectP IN ) : TORQUE_TARGET0 +{ + // Emissive. + float4 matInfo = TORQUE_TEX2D( matInfoBuffer, IN.uv0 ); + bool emissive = getFlag( matInfo.r, 0 ); + if ( emissive ) + { + return float4(1.0, 1.0, 1.0, 0.0); + } + // Sample/unpack the normal/z data - float4 prepassSample = prepassUncondition( prePassBuffer, IN.uv0 ); + float4 prepassSample = TORQUE_PREPASS_UNCONDITION( prePassBuffer, IN.uv0 ); float3 normal = prepassSample.rgb; float depth = prepassSample.a; @@ -217,7 +228,7 @@ float4 main( FarFrustumQuadConnectP IN, #else - float4 static_shadowed_colors = AL_VectorLightShadowCast( shadowMap, + float4 static_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(shadowMap), IN.uv0.xy, worldToLightProj, worldPos, @@ -229,8 +240,7 @@ float4 main( FarFrustumQuadConnectP IN, shadowSoftness, dotNL, overDarkPSSM); - - float4 dynamic_shadowed_colors = AL_VectorLightShadowCast( dynamicShadowMap, + float4 dynamic_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), IN.uv0.xy, dynamicWorldToLightProj, worldPos, @@ -276,6 +286,7 @@ float4 main( FarFrustumQuadConnectP IN, float Sat_NL_Att = saturate( dotNL * shadowed ) * lightBrightness; float3 lightColorOut = lightMapParams.rgb * lightColor.rgb; + float4 addToResult = (lightAmbient * (1 - ambientCameraFactor)) + ( lightAmbient * ambientCameraFactor * saturate(dot(normalize(-IN.vsEyeRay), normal)) ); // TODO: This needs to be removed when lightmapping is disabled @@ -295,7 +306,7 @@ float4 main( FarFrustumQuadConnectP IN, // Sample the AO texture. #ifdef USE_SSAO_MASK - float ao = 1.0 - tex2D( ssaoMask, viewportCoordToRenderTarget( IN.uv0.xy, rtParams2 ) ).r; + float ao = 1.0 - TORQUE_TEX2D( ssaoMask, viewportCoordToRenderTarget( IN.uv0.xy, rtParams3 ) ).r; addToResult *= ao; #endif @@ -303,5 +314,6 @@ float4 main( FarFrustumQuadConnectP IN, lightColorOut = debugColor; #endif - return lightinfoCondition( lightColorOut, Sat_NL_Att, specular, addToResult ); + float4 colorSample = TORQUE_TEX2D( colorBuffer, IN.uv0 ); + return AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Empty/game/shaders/common/lighting/basic/shadowFilterP.hlsl b/Templates/Empty/game/shaders/common/lighting/basic/shadowFilterP.hlsl index f161fb5d3..b56aade8d 100644 --- a/Templates/Empty/game/shaders/common/lighting/basic/shadowFilterP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/basic/shadowFilterP.hlsl @@ -22,11 +22,11 @@ #include "shaders/common/postFx/postFx.hlsl" -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv : TEXCOORD0; }; @@ -35,15 +35,15 @@ static float weight[3] = { 0.2270270270, 0.3162162162, 0.0702702703 }; uniform float2 oneOverTargetSize; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { - float4 OUT = tex2D( diffuseMap, IN.uv ) * weight[0]; + float4 OUT = TORQUE_TEX2D( diffuseMap, IN.uv ) * weight[0]; for ( int i=1; i < 3; i++ ) { float2 sample = (BLUR_DIR * offset[i]) * oneOverTargetSize; - OUT += tex2D( diffuseMap, IN.uv + sample ) * weight[i]; - OUT += tex2D( diffuseMap, IN.uv - sample ) * weight[i]; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv + sample ) * weight[i]; + OUT += TORQUE_TEX2D(diffuseMap, IN.uv - sample) * weight[i]; } return OUT; diff --git a/Templates/Empty/game/shaders/common/lighting/basic/shadowFilterV.hlsl b/Templates/Empty/game/shaders/common/lighting/basic/shadowFilterV.hlsl index bf6a36249..c89af7357 100644 --- a/Templates/Empty/game/shaders/common/lighting/basic/shadowFilterV.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/basic/shadowFilterV.hlsl @@ -27,7 +27,7 @@ float4 rtParams0; struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv : TEXCOORD0; }; @@ -35,7 +35,7 @@ VertToPix main( PFXVert IN ) { VertToPix OUT; - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); OUT.uv = viewportCoordToRenderTarget( IN.uv, rtParams0 ); return OUT; diff --git a/Templates/Empty/game/shaders/common/lighting/shadowMap/boxFilterP.hlsl b/Templates/Empty/game/shaders/common/lighting/shadowMap/boxFilterP.hlsl index dd691de23..a187c3c63 100644 --- a/Templates/Empty/game/shaders/common/lighting/shadowMap/boxFilterP.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/shadowMap/boxFilterP.hlsl @@ -23,10 +23,12 @@ //***************************************************************************** // Box Filter //***************************************************************************** +#include "../ShaderModel.hlsl" struct ConnectData { - float2 tex0 : TEXCOORD0; + float4 hpos : TORQUE_POSITION; + float2 tex0 : TEXCOORD0; }; // If not defined from ShaderData then define @@ -40,12 +42,12 @@ float log_conv ( float x0, float X, float y0, float Y ) return (X + log(x0 + (y0 * exp(Y - X)))); } -float4 main( ConnectData IN, - uniform sampler2D diffuseMap0 : register(S0), - uniform float texSize : register(C0), - uniform float2 blurDimension : register(C2), - uniform float2 blurBoundaries : register(C3) - ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(diffuseMap0, 0); +uniform float texSize : register(C0); +uniform float2 blurDimension : register(C2); +uniform float2 blurBoundaries : register(C3); + +float4 main( ConnectData IN ) : TORQUE_TARGET0 { // 5x5 if (IN.tex0.x <= blurBoundaries.x) @@ -56,8 +58,8 @@ float4 main( ConnectData IN, float2 texCoord = IN.tex0; - float accum = log_conv(0.3125, tex2D(diffuseMap0, texCoord - sampleOffset), 0.375, tex2D(diffuseMap0, texCoord)); - accum = log_conv(1, accum, 0.3125, tex2D(diffuseMap0, texCoord + sampleOffset)); + float accum = log_conv(0.3125, TORQUE_TEX2D(diffuseMap0, texCoord - sampleOffset), 0.375, tex2D(diffuseMap0, texCoord)); + accum = log_conv(1, accum, 0.3125, TORQUE_TEX2D(diffuseMap0, texCoord + sampleOffset)); return accum; } else { @@ -73,7 +75,7 @@ float4 main( ConnectData IN, return accum; } else { - return tex2D(diffuseMap0, IN.tex0); + return TORQUE_TEX2D(diffuseMap0, IN.tex0); } } } diff --git a/Templates/Empty/game/shaders/common/lighting/shadowMap/boxFilterV.hlsl b/Templates/Empty/game/shaders/common/lighting/shadowMap/boxFilterV.hlsl index 75d9af000..3679e41bb 100644 --- a/Templates/Empty/game/shaders/common/lighting/shadowMap/boxFilterV.hlsl +++ b/Templates/Empty/game/shaders/common/lighting/shadowMap/boxFilterV.hlsl @@ -26,15 +26,18 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- + +#include "../ShaderModel.hlsl" + struct VertData { - float2 texCoord : TEXCOORD0; - float4 position : POSITION; + float3 position : POSITION; + float2 texCoord : TEXCOORD0; }; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 tex0 : TEXCOORD0; }; @@ -47,7 +50,7 @@ ConnectData main( VertData IN, { ConnectData OUT; - OUT.hpos = mul(modelview, IN.position); + OUT.hpos = mul(modelview, float4(IN.position,1.0)); OUT.tex0 = IN.texCoord; return OUT; diff --git a/Templates/Empty/game/shaders/common/particleCompositeP.hlsl b/Templates/Empty/game/shaders/common/particleCompositeP.hlsl index 35c2cb4c5..6e26ddbdb 100644 --- a/Templates/Empty/game/shaders/common/particleCompositeP.hlsl +++ b/Templates/Empty/game/shaders/common/particleCompositeP.hlsl @@ -20,22 +20,30 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "torque.hlsl" +#include "shaderModel.hlsl" -uniform sampler2D colorSource : register(S0); +TORQUE_UNIFORM_SAMPLER2D(colorSource, 0); uniform float4 offscreenTargetParams; #ifdef TORQUE_LINEAR_DEPTH #define REJECT_EDGES -uniform sampler2D edgeSource : register(S1); +TORQUE_UNIFORM_SAMPLER2D(edgeSource, 1); uniform float4 edgeTargetParams; #endif +struct Conn +{ + float4 hpos : TORQUE_POSITION; + float4 offscreenPos : TEXCOORD0; + float4 backbufferPos : TEXCOORD1; +}; -float4 main( float4 offscreenPos : TEXCOORD0, float4 backbufferPos : TEXCOORD1 ) : COLOR + +float4 main(Conn IN) : TORQUE_TARGET0 { // Off-screen particle source screenspace position in XY // Back-buffer screenspace position in ZW - float4 ssPos = float4(offscreenPos.xy / offscreenPos.w, backbufferPos.xy / backbufferPos.w); + float4 ssPos = float4(IN.offscreenPos.xy / IN.offscreenPos.w, IN.backbufferPos.xy / IN.backbufferPos.w); float4 uvScene = ( ssPos + 1.0 ) / 2.0; uvScene.yw = 1.0 - uvScene.yw; @@ -44,10 +52,10 @@ float4 main( float4 offscreenPos : TEXCOORD0, float4 backbufferPos : TEXCOORD1 ) #ifdef REJECT_EDGES // Cut out particles along the edges, this will create the stencil mask uvScene.zw = viewportCoordToRenderTarget(uvScene.zw, edgeTargetParams); - float edge = tex2D( edgeSource, uvScene.zw ).r; + float edge = TORQUE_TEX2D( edgeSource, uvScene.zw ).r; clip( -edge ); #endif // Sample offscreen target and return - return tex2D( colorSource, uvScene.xy ); + return TORQUE_TEX2D( colorSource, uvScene.xy ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/particleCompositeV.hlsl b/Templates/Empty/game/shaders/common/particleCompositeV.hlsl index 87fac0d94..c4c51204a 100644 --- a/Templates/Empty/game/shaders/common/particleCompositeV.hlsl +++ b/Templates/Empty/game/shaders/common/particleCompositeV.hlsl @@ -20,22 +20,28 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "hlslStructs.h" +#include "shaderModel.hlsl" -struct VertOut +struct Vertex { - float4 hpos : POSITION; + float3 pos : POSITION; + float4 uvCoord : COLOR0; +}; + +struct Conn +{ + float4 hpos : TORQUE_POSITION; float4 offscreenPos : TEXCOORD0; float4 backbufferPos : TEXCOORD1; }; uniform float4 screenRect; // point, extent -VertOut main( float4 uvCoord : COLOR ) +Conn main(Vertex IN) { - VertOut OUT; + Conn OUT; - OUT.hpos = float4(uvCoord.xy, 1.0, 1.0); + OUT.hpos = float4(IN.uvCoord.xy, 1.0, 1.0); OUT.hpos.xy *= screenRect.zw; OUT.hpos.xy += screenRect.xy; diff --git a/Templates/Empty/game/shaders/common/particlesP.hlsl b/Templates/Empty/game/shaders/common/particlesP.hlsl index 80e3c7105..37439c59a 100644 --- a/Templates/Empty/game/shaders/common/particlesP.hlsl +++ b/Templates/Empty/game/shaders/common/particlesP.hlsl @@ -21,7 +21,7 @@ //----------------------------------------------------------------------------- #include "torque.hlsl" - +#include "shaderModel.hlsl" // With advanced lighting we get soft particles. #ifdef TORQUE_LINEAR_DEPTH #define SOFTPARTICLES @@ -29,11 +29,11 @@ #ifdef SOFTPARTICLES - #include "shadergen:/autogenConditioners.h" + #include "shaderModelAutoGen.hlsl" uniform float oneOverSoftness; uniform float oneOverFar; - uniform sampler2D prepassTex : register(S1); + TORQUE_UNIFORM_SAMPLER2D(prepassTex, 1); //uniform float3 vEye; uniform float4 prePassTargetParams; #endif @@ -42,14 +42,14 @@ struct Conn { + float4 hpos : TORQUE_POSITION; float4 color : TEXCOORD0; float2 uv0 : TEXCOORD1; - float4 pos : TEXCOORD2; + float4 pos : TEXCOORD2; }; -uniform sampler2D diffuseMap : register(S0); - -uniform sampler2D paraboloidLightMap : register(S2); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); +TORQUE_UNIFORM_SAMPLER2D(paraboloidLightMap, 2); float4 lmSample( float3 nrm ) { @@ -69,14 +69,14 @@ float4 lmSample( float3 nrm ) // Atlasing front and back maps, so scale lmCoord.x *= 0.5; - return tex2D(paraboloidLightMap, lmCoord); + return TORQUE_TEX2D(paraboloidLightMap, lmCoord); } uniform float alphaFactor; uniform float alphaScale; -float4 main( Conn IN ) : COLOR +float4 main( Conn IN ) : TORQUE_TARGET0 { float softBlend = 1; @@ -84,7 +84,7 @@ float4 main( Conn IN ) : COLOR float2 tc = IN.pos.xy * float2(1.0, -1.0) / IN.pos.w; tc = viewportCoordToRenderTarget(saturate( ( tc + 1.0 ) * 0.5 ), prePassTargetParams); - float sceneDepth = prepassUncondition( prepassTex, tc ).w; + float sceneDepth = TORQUE_PREPASS_UNCONDITION(prepassTex, tc).w; float depth = IN.pos.w * oneOverFar; float diff = sceneDepth - depth; #ifdef CLIP_Z @@ -96,7 +96,7 @@ float4 main( Conn IN ) : COLOR softBlend = saturate( diff * oneOverSoftness ); #endif - float4 diffuse = tex2D( diffuseMap, IN.uv0 ); + float4 diffuse = TORQUE_TEX2D( diffuseMap, IN.uv0 ); //return float4( lmSample(float3(0, 0, -1)).rgb, IN.color.a * diffuse.a * softBlend * alphaScale); diff --git a/Templates/Empty/game/shaders/common/particlesV.hlsl b/Templates/Empty/game/shaders/common/particlesV.hlsl index f09604237..dbeff0cc2 100644 --- a/Templates/Empty/game/shaders/common/particlesV.hlsl +++ b/Templates/Empty/game/shaders/common/particlesV.hlsl @@ -20,16 +20,18 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "shaderModel.hlsl" + struct Vertex { - float4 pos : POSITION; + float3 pos : POSITION; float4 color : COLOR0; float2 uv0 : TEXCOORD0; }; struct Conn { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 color : TEXCOORD0; float2 uv0 : TEXCOORD1; float4 pos : TEXCOORD2; @@ -43,8 +45,8 @@ Conn main( Vertex In ) { Conn Out; - Out.hpos = mul( modelViewProj, In.pos ); - Out.pos = mul( fsModelViewProj, In.pos ); + Out.hpos = mul( modelViewProj, float4(In.pos,1.0) ); + Out.pos = mul(fsModelViewProj, float4(In.pos, 1.0) ); Out.color = In.color; Out.uv0 = In.uv0; diff --git a/Templates/Empty/game/shaders/common/planarReflectBumpP.hlsl b/Templates/Empty/game/shaders/common/planarReflectBumpP.hlsl index a5057db50..d18331fb6 100644 --- a/Templates/Empty/game/shaders/common/planarReflectBumpP.hlsl +++ b/Templates/Empty/game/shaders/common/planarReflectBumpP.hlsl @@ -23,18 +23,26 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- + +#include "shaderModel.hlsl" + struct ConnectData { - float4 texCoord : TEXCOORD0; - float2 tex2 : TEXCOORD1; + float4 hpos : TORQUE_POSITION; + float2 texCoord : TEXCOORD0; + float4 tex2 : TEXCOORD1; }; struct Fragout { - float4 col : COLOR0; + float4 col : TORQUE_TARGET0; }; +TORQUE_UNIFORM_SAMPLER2D(texMap, 0); +TORQUE_UNIFORM_SAMPLER2D(refractMap, 1); +TORQUE_UNIFORM_SAMPLER2D(bumpMap, 2); + //----------------------------------------------------------------------------- // Fade edges of axis for texcoord passed in @@ -54,15 +62,11 @@ float fadeAxis( float val ) //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main( ConnectData IN, - uniform sampler2D refractMap : register(S1), - uniform sampler2D texMap : register(S0), - uniform sampler2D bumpMap : register(S2) -) +Fragout main( ConnectData IN ) { Fragout OUT; - float3 bumpNorm = tex2D( bumpMap, IN.tex2 ) * 2.0 - 1.0; + float3 bumpNorm = TORQUE_TEX2D( bumpMap, IN.tex2 ) * 2.0 - 1.0; float2 offset = float2( bumpNorm.x, bumpNorm.y ); float4 texIndex = IN.texCoord; @@ -74,8 +78,8 @@ Fragout main( ConnectData IN, const float distortion = 0.2; texIndex.xy += offset * distortion * fadeVal; - float4 reflectColor = tex2Dproj( refractMap, texIndex ); - float4 diffuseColor = tex2D( texMap, IN.tex2 ); + float4 reflectColor = TORQUE_TEX2DPROJ( refractMap, texIndex ); + float4 diffuseColor = TORQUE_TEX2D( texMap, IN.tex2 ); OUT.col = diffuseColor + reflectColor * diffuseColor.a; diff --git a/Templates/Empty/game/shaders/common/planarReflectBumpV.hlsl b/Templates/Empty/game/shaders/common/planarReflectBumpV.hlsl index 108f918ce..d45adb574 100644 --- a/Templates/Empty/game/shaders/common/planarReflectBumpV.hlsl +++ b/Templates/Empty/game/shaders/common/planarReflectBumpV.hlsl @@ -22,36 +22,37 @@ #define IN_HLSL #include "shdrConsts.h" +#include "shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- struct VertData { + float3 position : POSITION; + float3 normal : NORMAL; float2 texCoord : TEXCOORD0; float2 lmCoord : TEXCOORD1; float3 T : TEXCOORD2; - float3 B : TEXCOORD3; - float3 normal : NORMAL; - float4 position : POSITION; + float3 B : TEXCOORD3; }; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoord : TEXCOORD0; float2 tex2 : TEXCOORD1; }; +uniform float4x4 modelview; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -ConnectData main( VertData IN, - uniform float4x4 modelview ) +ConnectData main( VertData IN ) { ConnectData OUT; - OUT.hpos = mul(modelview, IN.position); + OUT.hpos = mul(modelview, float4(IN.position,1.0)); float4x4 texGenTest = { 0.5, 0.0, 0.0, 0.5, 0.0, -0.5, 0.0, 0.5, diff --git a/Templates/Empty/game/shaders/common/planarReflectP.hlsl b/Templates/Empty/game/shaders/common/planarReflectP.hlsl index 981cc316d..43b420544 100644 --- a/Templates/Empty/game/shaders/common/planarReflectP.hlsl +++ b/Templates/Empty/game/shaders/common/planarReflectP.hlsl @@ -23,31 +23,34 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- + +#include "shaderModel.hlsl" + struct ConnectData { - float2 texCoord : TEXCOORD0; - float4 tex2 : TEXCOORD1; + float4 hpos : TORQUE_POSITION; + float2 texCoord : TEXCOORD0; + float4 tex2 : TEXCOORD1; }; struct Fragout { - float4 col : COLOR0; + float4 col : TORQUE_TARGET0; }; +TORQUE_UNIFORM_SAMPLER2D(texMap, 0); +TORQUE_UNIFORM_SAMPLER2D(refractMap, 1); //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main( ConnectData IN, - uniform sampler2D texMap : register(S0), - uniform sampler2D refractMap : register(S1) -) +Fragout main( ConnectData IN ) { Fragout OUT; - float4 diffuseColor = tex2D( texMap, IN.texCoord ); - float4 reflectColor = tex2Dproj( refractMap, IN.tex2 ); + float4 diffuseColor = TORQUE_TEX2D( texMap, IN.texCoord ); + float4 reflectColor = TORQUE_TEX2DPROJ(refractMap, IN.tex2); OUT.col = diffuseColor + reflectColor * diffuseColor.a; diff --git a/Templates/Empty/game/shaders/common/planarReflectV.hlsl b/Templates/Empty/game/shaders/common/planarReflectV.hlsl index cd8cb2d96..1f2ca9d4f 100644 --- a/Templates/Empty/game/shaders/common/planarReflectV.hlsl +++ b/Templates/Empty/game/shaders/common/planarReflectV.hlsl @@ -21,7 +21,8 @@ //----------------------------------------------------------------------------- #define IN_HLSL -#include "hlslStructs.h" +#include "hlslStructs.hlsl" +#include "shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures @@ -29,20 +30,20 @@ struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 texCoord : TEXCOORD0; float4 tex2 : TEXCOORD1; }; +uniform float4x4 modelview; + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -ConnectData main( VertexIn_PNTTTB IN, - uniform float4x4 modelview : register(C0) -) +ConnectData main( VertexIn_PNTTTB IN ) { ConnectData OUT; - OUT.hpos = mul(modelview, IN.pos); + OUT.hpos = mul(modelview, float4(IN.pos,1.0)); float4x4 texGenTest = { 0.5, 0.0, 0.0, 0.5, 0.0, -0.5, 0.0, 0.5, diff --git a/Templates/Empty/game/shaders/common/postFx/VolFogGlowP.hlsl b/Templates/Empty/game/shaders/common/postFx/VolFogGlowP.hlsl index 8a61b5928..c3adb3b55 100644 --- a/Templates/Empty/game/shaders/common/postFx/VolFogGlowP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/VolFogGlowP.hlsl @@ -32,12 +32,12 @@ #include "./postFx.hlsl" -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); uniform float strength; struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -50,20 +50,20 @@ struct VertToPix float2 uv7 : TEXCOORD7; }; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { float4 kernel = float4( 0.175, 0.275, 0.375, 0.475 ) * strength; float4 OUT = 0; - OUT += tex2D( diffuseMap, IN.uv0 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv1 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv2 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv3 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv0 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv1 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv2 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv3 ) * kernel.w; - OUT += tex2D( diffuseMap, IN.uv4 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv5 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv6 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv7 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv4 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv5 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv6 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv7 ) * kernel.w; // Calculate a lumenance value in the alpha so we // can use alpha test to save fillrate. diff --git a/Templates/Empty/game/shaders/common/postFx/caustics/causticsP.hlsl b/Templates/Empty/game/shaders/common/postFx/caustics/causticsP.hlsl index c7635027d..d2f4a058a 100644 --- a/Templates/Empty/game/shaders/common/postFx/caustics/causticsP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/caustics/causticsP.hlsl @@ -21,25 +21,26 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" +uniform float accumTime; uniform float3 eyePosWorld; uniform float4 rtParams0; uniform float4 waterFogPlane; -uniform float accumTime; + +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); +TORQUE_UNIFORM_SAMPLER2D(causticsTex0, 1); +TORQUE_UNIFORM_SAMPLER2D(causticsTex1, 2); float distanceToPlane(float4 plane, float3 pos) { return (plane.x * pos.x + plane.y * pos.y + plane.z * pos.z) + plane.w; } -float4 main( PFXVertToPix IN, - uniform sampler2D prepassTex :register(S0), - uniform sampler2D causticsTex0 :register(S1), - uniform sampler2D causticsTex1 :register(S2) ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { //Sample the pre-pass - float4 prePass = prepassUncondition( prepassTex, IN.uv0 ); + float4 prePass = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ); //Get depth float depth = prePass.w; @@ -65,12 +66,12 @@ float4 main( PFXVertToPix IN, causticsUV1.xy -= float2(accumTime*0.15, timeSin*0.15); //Sample caustics texture - float4 caustics = tex2D(causticsTex0, causticsUV0); - caustics *= tex2D(causticsTex1, causticsUV1); + float4 caustics = TORQUE_TEX2D(causticsTex0, causticsUV0); + caustics *= TORQUE_TEX2D(causticsTex1, causticsUV1); //Use normal Z to modulate caustics //float waterDepth = 1 - saturate(pos.z + waterFogPlane.w + 1); - caustics *= saturate(prePass.z) * pow(1-depth, 64) * waterDepth; + caustics *= saturate(prePass.z) * pow(abs(1-depth), 64) * waterDepth; return caustics; } diff --git a/Templates/Empty/game/shaders/common/postFx/chromaticLens.hlsl b/Templates/Empty/game/shaders/common/postFx/chromaticLens.hlsl index 5916e985a..8fdca72b7 100644 --- a/Templates/Empty/game/shaders/common/postFx/chromaticLens.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/chromaticLens.hlsl @@ -26,14 +26,13 @@ #include "./postFx.hlsl" #include "./../torque.hlsl" - -uniform sampler2D backBuffer : register( s0 ); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); uniform float distCoeff; uniform float cubeDistort; uniform float3 colorDistort; -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float2 tex = IN.uv0; @@ -54,7 +53,7 @@ float4 main( PFXVertToPix IN ) : COLOR0 { float x = distort[i] * ( tex.x - 0.5 ) + 0.5; float y = distort[i] * ( tex.y - 0.5 ) + 0.5; - outColor[i] = tex2Dlod( backBuffer, float4(x,y,0,0) )[i]; + outColor[i] = TORQUE_TEX2DLOD( backBuffer, float4(x,y,0,0) )[i]; } return float4( outColor.rgb, 1 ); diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl index bc17a2c04..2f5835fc2 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl @@ -23,21 +23,22 @@ #include "./../postFx.hlsl" // These are set by the game engine. -uniform sampler2D shrunkSampler : register(S0); // Output of DofDownsample() -uniform sampler2D blurredSampler : register(S1); // Blurred version of the shrunk sampler +TORQUE_UNIFORM_SAMPLER2D(shrunkSampler, 0); // Output of DofDownsample() +TORQUE_UNIFORM_SAMPLER2D(blurredSampler, 1); // Blurred version of the shrunk sampler + // This is the pixel shader function that calculates the actual // value used for the near circle of confusion. // "texCoords" are 0 at the bottom left pixel and 1 at the top right. -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float3 color; float coc; half4 blurred; half4 shrunk; - shrunk = tex2D( shrunkSampler, IN.uv0 ); - blurred = tex2D( blurredSampler, IN.uv1 ); + shrunk = half4(TORQUE_TEX2D( shrunkSampler, IN.uv0 )); + blurred = half4(TORQUE_TEX2D( blurredSampler, IN.uv1 )); color = shrunk.rgb; //coc = shrunk.a; //coc = blurred.a; diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl index 40cec49de..8131e45cd 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl @@ -57,7 +57,7 @@ PFXVertToPix main( PFXVert IN ) */ - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); OUT.uv0 = viewportCoordToRenderTarget( IN.uv, rtParams0 ); OUT.uv1 = viewportCoordToRenderTarget( IN.uv, rtParams1 ); OUT.uv2 = viewportCoordToRenderTarget( IN.uv, rtParams2 ); diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_DownSample_P.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_DownSample_P.hlsl index 37e591f25..8c9028654 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_DownSample_P.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_DownSample_P.hlsl @@ -20,22 +20,23 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModel.hlsl" +#include "../../shaderModelAutoGen.hlsl" // These are set by the game engine. // The render target size is one-quarter the scene rendering size. -uniform sampler2D colorSampler : register(S0); -uniform sampler2D depthSampler : register(S1); -uniform float2 dofEqWorld; -uniform float depthOffset; +TORQUE_UNIFORM_SAMPLER2D(colorSampler, 0); +TORQUE_UNIFORM_SAMPLER2D(depthSampler, 1); +uniform float2 dofEqWorld; uniform float2 targetSize; +uniform float depthOffset; uniform float maxWorldCoC; //uniform float2 dofEqWeapon; //uniform float2 dofRowDelta; // float2( 0, 0.25 / renderTargetHeight ) struct Pixel { - float4 position : POSITION; + float4 position : TORQUE_POSITION; float2 tcColor0 : TEXCOORD0; float2 tcColor1 : TEXCOORD1; float2 tcDepth0 : TEXCOORD2; @@ -44,7 +45,7 @@ struct Pixel float2 tcDepth3 : TEXCOORD5; }; -half4 main( Pixel IN ) : COLOR +half4 main( Pixel IN ) : TORQUE_TARGET0 { //return float4( 1.0, 0.0, 1.0, 1.0 ); @@ -69,57 +70,64 @@ half4 main( Pixel IN ) : COLOR // Use bilinear filtering to average 4 color samples for free. color = 0; - color += tex2D( colorSampler, IN.tcColor0.xy + rowOfs[0] ).rgb; - color += tex2D( colorSampler, IN.tcColor1.xy + rowOfs[0] ).rgb; - color += tex2D( colorSampler, IN.tcColor0.xy + rowOfs[2] ).rgb; - color += tex2D( colorSampler, IN.tcColor1.xy + rowOfs[2] ).rgb; + color += half3(TORQUE_TEX2D( colorSampler, IN.tcColor0.xy + rowOfs[0] ).rgb); + color += half3(TORQUE_TEX2D(colorSampler, IN.tcColor1.xy + rowOfs[0]).rgb); + color += half3(TORQUE_TEX2D(colorSampler, IN.tcColor0.xy + rowOfs[2]).rgb); + color += half3(TORQUE_TEX2D(colorSampler, IN.tcColor1.xy + rowOfs[2]).rgb); color /= 4; + //declare thse here to save doing it in each loop below + half4 zero4 = half4(0, 0, 0, 0); + coc = zero4; + half4 dofEqWorld4X = half4(dofEqWorld.xxxx); + half4 dofEqWorld4Y = half4(dofEqWorld.yyyy); + half4 maxWorldCoC4 = half4(maxWorldCoC, maxWorldCoC, maxWorldCoC, maxWorldCoC); // Process 4 samples at a time to use vector hardware efficiently. // The CoC will be 1 if the depth is negative, so use "min" to pick - // between "sceneCoc" and "viewCoc". - - for ( int i = 0; i < 4; i++ ) + // between "sceneCoc" and "viewCoc". + [unroll] // coc[i] causes this anyway + for (int i = 0; i < 4; i++) { - depth[0] = prepassUncondition( depthSampler, float4( IN.tcDepth0.xy + rowOfs[i], 0, 0 ) ).w; - depth[1] = prepassUncondition( depthSampler, float4( IN.tcDepth1.xy + rowOfs[i], 0, 0 ) ).w; - depth[2] = prepassUncondition( depthSampler, float4( IN.tcDepth2.xy + rowOfs[i], 0, 0 ) ).w; - depth[3] = prepassUncondition( depthSampler, float4( IN.tcDepth3.xy + rowOfs[i], 0, 0 ) ).w; - coc[i] = clamp( dofEqWorld.x * depth + dofEqWorld.y, 0.0, maxWorldCoC ); - } + depth[0] = TORQUE_PREPASS_UNCONDITION(depthSampler, (IN.tcDepth0.xy + rowOfs[i])).w; + depth[1] = TORQUE_PREPASS_UNCONDITION(depthSampler, (IN.tcDepth1.xy + rowOfs[i])).w; + depth[2] = TORQUE_PREPASS_UNCONDITION(depthSampler, (IN.tcDepth2.xy + rowOfs[i])).w; + depth[3] = TORQUE_PREPASS_UNCONDITION(depthSampler, (IN.tcDepth3.xy + rowOfs[i])).w; + + coc = max(coc, clamp(dofEqWorld4X * half4(depth)+dofEqWorld4Y, zero4, maxWorldCoC4)); + } /* - depth[0] = tex2D( depthSampler, pixel.tcDepth0.xy + rowOfs[0] ).r; - depth[1] = tex2D( depthSampler, pixel.tcDepth1.xy + rowOfs[0] ).r; - depth[2] = tex2D( depthSampler, pixel.tcDepth2.xy + rowOfs[0] ).r; - depth[3] = tex2D( depthSampler, pixel.tcDepth3.xy + rowOfs[0] ).r; + depth[0] = TORQUE_TEX2D( depthSampler, pixel.tcDepth0.xy + rowOfs[0] ).r; + depth[1] = TORQUE_TEX2D( depthSampler, pixel.tcDepth1.xy + rowOfs[0] ).r; + depth[2] = TORQUE_TEX2D( depthSampler, pixel.tcDepth2.xy + rowOfs[0] ).r; + depth[3] = TORQUE_TEX2D( depthSampler, pixel.tcDepth3.xy + rowOfs[0] ).r; viewCoc = saturate( dofEqWeapon.x * -depth + dofEqWeapon.y ); sceneCoc = saturate( dofEqWorld.x * depth + dofEqWorld.y ); curCoc = min( viewCoc, sceneCoc ); coc = curCoc; - depth[0] = tex2D( depthSampler, pixel.tcDepth0.xy + rowOfs[1] ).r; - depth[1] = tex2D( depthSampler, pixel.tcDepth1.xy + rowOfs[1] ).r; - depth[2] = tex2D( depthSampler, pixel.tcDepth2.xy + rowOfs[1] ).r; - depth[3] = tex2D( depthSampler, pixel.tcDepth3.xy + rowOfs[1] ).r; + depth[0] = TORQUE_TEX2D( depthSampler, pixel.tcDepth0.xy + rowOfs[1] ).r; + depth[1] = TORQUE_TEX2D( depthSampler, pixel.tcDepth1.xy + rowOfs[1] ).r; + depth[2] = TORQUE_TEX2D( depthSampler, pixel.tcDepth2.xy + rowOfs[1] ).r; + depth[3] = TORQUE_TEX2D( depthSampler, pixel.tcDepth3.xy + rowOfs[1] ).r; viewCoc = saturate( dofEqWeapon.x * -depth + dofEqWeapon.y ); sceneCoc = saturate( dofEqWorld.x * depth + dofEqWorld.y ); curCoc = min( viewCoc, sceneCoc ); coc = max( coc, curCoc ); - depth[0] = tex2D( depthSampler, pixel.tcDepth0.xy + rowOfs[2] ).r; - depth[1] = tex2D( depthSampler, pixel.tcDepth1.xy + rowOfs[2] ).r; - depth[2] = tex2D( depthSampler, pixel.tcDepth2.xy + rowOfs[2] ).r; - depth[3] = tex2D( depthSampler, pixel.tcDepth3.xy + rowOfs[2] ).r; + depth[0] = TORQUE_TEX2D( depthSampler, pixel.tcDepth0.xy + rowOfs[2] ).r; + depth[1] = TORQUE_TEX2D( depthSampler, pixel.tcDepth1.xy + rowOfs[2] ).r; + depth[2] = TORQUE_TEX2D( depthSampler, pixel.tcDepth2.xy + rowOfs[2] ).r; + depth[3] = TORQUE_TEX2D( depthSampler, pixel.tcDepth3.xy + rowOfs[2] ).r; viewCoc = saturate( dofEqWeapon.x * -depth + dofEqWeapon.y ); sceneCoc = saturate( dofEqWorld.x * depth + dofEqWorld.y ); curCoc = min( viewCoc, sceneCoc ); coc = max( coc, curCoc ); - depth[0] = tex2D( depthSampler, pixel.tcDepth0.xy + rowOfs[3] ).r; - depth[1] = tex2D( depthSampler, pixel.tcDepth1.xy + rowOfs[3] ).r; - depth[2] = tex2D( depthSampler, pixel.tcDepth2.xy + rowOfs[3] ).r; - depth[3] = tex2D( depthSampler, pixel.tcDepth3.xy + rowOfs[3] ).r; + depth[0] = TORQUE_TEX2D( depthSampler, pixel.tcDepth0.xy + rowOfs[3] ).r; + depth[1] = TORQUE_TEX2D( depthSampler, pixel.tcDepth1.xy + rowOfs[3] ).r; + depth[2] = TORQUE_TEX2D( depthSampler, pixel.tcDepth2.xy + rowOfs[3] ).r; + depth[3] = TORQUE_TEX2D( depthSampler, pixel.tcDepth3.xy + rowOfs[3] ).r; viewCoc = saturate( dofEqWeapon.x * -depth + dofEqWeapon.y ); sceneCoc = saturate( dofEqWorld.x * depth + dofEqWorld.y ); curCoc = min( viewCoc, sceneCoc ); diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_DownSample_V.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_DownSample_V.hlsl index da2a79fb4..0b3ec01e2 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_DownSample_V.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_DownSample_V.hlsl @@ -25,14 +25,14 @@ struct Vert { - float4 pos : POSITION; + float3 pos : POSITION; float2 tc : TEXCOORD0; float3 wsEyeRay : TEXCOORD1; }; struct Pixel { - float4 position : POSITION; + float4 position : TORQUE_POSITION; float2 tcColor0 : TEXCOORD0; float2 tcColor1 : TEXCOORD1; float2 tcDepth0 : TEXCOORD2; @@ -47,7 +47,7 @@ uniform float2 oneOverTargetSize; Pixel main( Vert IN ) { Pixel OUT; - OUT.position = IN.pos; + OUT.position = float4(IN.pos,1.0); float2 uv = viewportCoordToRenderTarget( IN.tc, rtParams0 ); //OUT.position = mul( IN.pos, modelView ); diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Final_P.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Final_P.hlsl index 36622495c..cb7342d40 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Final_P.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Final_P.hlsl @@ -20,13 +20,14 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "./../postFx.hlsl" -uniform sampler2D colorSampler : register(S0); // Original source image -uniform sampler2D smallBlurSampler : register(S1); // Output of SmallBlurPS() -uniform sampler2D largeBlurSampler : register(S2); // Blurred output of DofDownsample() -uniform sampler2D depthSampler : register(S3); // +TORQUE_UNIFORM_SAMPLER2D(colorSampler,0); // Original source image +TORQUE_UNIFORM_SAMPLER2D(smallBlurSampler,1); // Output of SmallBlurPS() +TORQUE_UNIFORM_SAMPLER2D(largeBlurSampler,2); // Blurred output of DofDownsample() +TORQUE_UNIFORM_SAMPLER2D(depthSampler,3); + uniform float2 oneOverTargetSize; uniform float4 dofLerpScale; uniform float4 dofLerpBias; @@ -40,9 +41,9 @@ uniform float maxFarCoC; //static float4 dofLerpBias = float4( 1.0, (1.0 - d2) / d1, 1.0 / d2, (d2 - 1.0) / d2 ); //static float3 dofEqFar = float3( 2.0, 0.0, 1.0 ); -float4 tex2Doffset( sampler2D s, float2 tc, float2 offset ) +float4 tex2Doffset(TORQUE_SAMPLER2D(s), float2 tc, float2 offset) { - return tex2D( s, tc + offset * oneOverTargetSize ); + return TORQUE_TEX2D( s, tc + offset * oneOverTargetSize ); } half3 GetSmallBlurSample( float2 tc ) @@ -51,10 +52,10 @@ half3 GetSmallBlurSample( float2 tc ) const half weight = 4.0 / 17; sum = 0; // Unblurred sample done by alpha blending //sum += weight * tex2Doffset( colorSampler, tc, float2( 0, 0 ) ).rgb; - sum += weight * tex2Doffset( colorSampler, tc, float2( +0.5, -1.5 ) ).rgb; - sum += weight * tex2Doffset( colorSampler, tc, float2( -1.5, -0.5 ) ).rgb; - sum += weight * tex2Doffset( colorSampler, tc, float2( -0.5, +1.5 ) ).rgb; - sum += weight * tex2Doffset( colorSampler, tc, float2( +1.5, +0.5 ) ).rgb; + sum += weight * half3(tex2Doffset(TORQUE_SAMPLER2D_MAKEARG(colorSampler), tc, float2(+0.5, -1.5)).rgb); + sum += weight * half3(tex2Doffset(TORQUE_SAMPLER2D_MAKEARG(colorSampler), tc, float2(-1.5, -0.5)).rgb); + sum += weight * half3(tex2Doffset(TORQUE_SAMPLER2D_MAKEARG(colorSampler), tc, float2(-0.5, +1.5)).rgb); + sum += weight * half3(tex2Doffset(TORQUE_SAMPLER2D_MAKEARG(colorSampler), tc, float2(+1.5, +0.5)).rgb); return sum; } @@ -72,7 +73,7 @@ half4 InterpolateDof( half3 small, half3 med, half3 large, half t ) //float4 dofLerpScale = float4( -1 / d0, -1 / d1, -1 / d2, 1 / d2 ); //float4 dofLerpBias = float4( 1, (1 – d2) / d1, 1 / d2, (d2 – 1) / d2 ); - weights = saturate( t * dofLerpScale + dofLerpBias ); + weights = half4(saturate( t * dofLerpScale + dofLerpBias )); weights.yz = min( weights.yz, 1 - weights.xy ); // Unblurred sample with weight "weights.x" done by alpha blending @@ -84,11 +85,11 @@ half4 InterpolateDof( half3 small, half3 med, half3 large, half t ) return half4( color, alpha ); } -half4 main( PFXVertToPix IN ) : COLOR +half4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { //return half4( 1,0,1,1 ); - //return half4( tex2D( colorSampler, IN.uv0 ).rgb, 1.0 ); - //return half4( tex2D( colorSampler, texCoords ).rgb, 0 ); + //return half4( TORQUE_TEX2D( colorSampler, IN.uv0 ).rgb, 1.0 ); + //return half4( TORQUE_TEX2D( colorSampler, texCoords ).rgb, 0 ); half3 small; half4 med; half3 large; @@ -100,10 +101,10 @@ half4 main( PFXVertToPix IN ) : COLOR small = GetSmallBlurSample( IN.uv0 ); //small = half3( 1,0,0 ); //return half4( small, 1.0 ); - med = tex2D( smallBlurSampler, IN.uv1 ); + med = half4(TORQUE_TEX2D( smallBlurSampler, IN.uv1 )); //med.rgb = half3( 0,1,0 ); //return half4(med.rgb, 0.0); - large = tex2D( largeBlurSampler, IN.uv2 ).rgb; + large = half3(TORQUE_TEX2D(largeBlurSampler, IN.uv2).rgb); //large = half3( 0,0,1 ); //return large; //return half4(large.rgb,1.0); @@ -114,7 +115,7 @@ half4 main( PFXVertToPix IN ) : COLOR //med.rgb = large; //nearCoc = 0; - depth = prepassUncondition( depthSampler, float4( IN.uv3, 0, 0 ) ).w; + depth = half(TORQUE_PREPASS_UNCONDITION( depthSampler, IN.uv3 ).w); //return half4(depth.rrr,1); //return half4(nearCoc.rrr,1.0); @@ -128,8 +129,8 @@ half4 main( PFXVertToPix IN ) : COLOR // dofEqFar.x and dofEqFar.y specify the linear ramp to convert // to depth for the distant out-of-focus region. // dofEqFar.z is the ratio of the far to the near blur radius. - farCoc = clamp( dofEqFar.x * depth + dofEqFar.y, 0.0, maxFarCoC ); - coc = max( nearCoc, farCoc * dofEqFar.z ); + farCoc = half(clamp( dofEqFar.x * depth + dofEqFar.y, 0.0, maxFarCoC )); + coc = half(max( nearCoc, farCoc * dofEqFar.z )); //coc = nearCoc; } diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Final_V.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Final_V.hlsl index 91dfba0a2..86c93701a 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Final_V.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Final_V.hlsl @@ -59,7 +59,7 @@ PFXVertToPix main( PFXVert IN ) */ - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); OUT.uv0 = viewportCoordToRenderTarget( IN.uv, rtParams0 ); OUT.uv1 = viewportCoordToRenderTarget( IN.uv, rtParams1 ); // + float2( -5, 1 ) * oneOverTargetSize; OUT.uv2 = viewportCoordToRenderTarget( IN.uv, rtParams2 ); diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Gausian_P.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Gausian_P.hlsl index 084a2c014..f4d29f3e1 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Gausian_P.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Gausian_P.hlsl @@ -22,11 +22,11 @@ #include "./../postFx.hlsl" -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -39,20 +39,20 @@ struct VertToPix float2 uv7 : TEXCOORD7; }; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { float4 kernel = float4( 0.175, 0.275, 0.375, 0.475 ) * 0.5 / 1.3; //25f; float4 OUT = 0; - OUT += tex2D( diffuseMap, IN.uv0 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv1 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv2 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv3 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv0 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv1 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv2 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv3 ) * kernel.w; - OUT += tex2D( diffuseMap, IN.uv4 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv5 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv6 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv7 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv4 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv5 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv6 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv7 ) * kernel.w; // Calculate a lumenance value in the alpha so we // can use alpha test to save fillrate. diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Gausian_V.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Gausian_V.hlsl index e29746e96..b2d4582e0 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Gausian_V.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Gausian_V.hlsl @@ -24,13 +24,13 @@ #include "./../../torque.hlsl" -uniform float2 texSize0; uniform float4 rtParams0; +uniform float2 texSize0; uniform float2 oneOverTargetSize; struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -47,7 +47,7 @@ VertToPix main( PFXVert IN ) { VertToPix OUT; - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); IN.uv = viewportCoordToRenderTarget( IN.uv, rtParams0 ); diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Passthrough_V.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Passthrough_V.hlsl index 40cec49de..8131e45cd 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_Passthrough_V.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_Passthrough_V.hlsl @@ -57,7 +57,7 @@ PFXVertToPix main( PFXVert IN ) */ - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); OUT.uv0 = viewportCoordToRenderTarget( IN.uv, rtParams0 ); OUT.uv1 = viewportCoordToRenderTarget( IN.uv, rtParams1 ); OUT.uv2 = viewportCoordToRenderTarget( IN.uv, rtParams2 ); diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl index 6d4144576..175525a91 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl @@ -24,22 +24,23 @@ // colorMapSampler, which is the same size as the render target. // The sample weights are 1/16 in the corners, 2/16 on the edges, // and 4/16 in the center. +#include "../../shaderModel.hlsl" -uniform sampler2D colorSampler; // Output of DofNearCoc() +TORQUE_UNIFORM_SAMPLER2D(colorSampler, 0); // Output of DofNearCoc() struct Pixel { - float4 position : POSITION; + float4 position : TORQUE_POSITION; float4 texCoords : TEXCOORD0; }; -float4 main( Pixel IN ) : COLOR +float4 main( Pixel IN ) : TORQUE_TARGET0 { float4 color; color = 0.0; - color += tex2D( colorSampler, IN.texCoords.xz ); - color += tex2D( colorSampler, IN.texCoords.yz ); - color += tex2D( colorSampler, IN.texCoords.xw ); - color += tex2D( colorSampler, IN.texCoords.yw ); + color += TORQUE_TEX2D( colorSampler, IN.texCoords.xz ); + color += TORQUE_TEX2D( colorSampler, IN.texCoords.yz ); + color += TORQUE_TEX2D( colorSampler, IN.texCoords.xw ); + color += TORQUE_TEX2D( colorSampler, IN.texCoords.yw ); return color / 4.0; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl b/Templates/Empty/game/shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl index 204f4639d..3edb1ec2a 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl @@ -30,13 +30,13 @@ struct Vert { - float4 position : POSITION; + float3 position : POSITION; float2 texCoords : TEXCOORD0; }; struct Pixel { - float4 position : POSITION; + float4 position : TORQUE_POSITION; float4 texCoords : TEXCOORD0; }; @@ -47,7 +47,7 @@ Pixel main( Vert IN ) { Pixel OUT; const float4 halfPixel = { -0.5, 0.5, -0.5, 0.5 }; - OUT.position = IN.position; //Transform_ObjectToClip( IN.position ); + OUT.position = float4(IN.position,1.0); //Transform_ObjectToClip( IN.position ); //float2 uv = IN.texCoords + rtParams0.xy; float2 uv = viewportCoordToRenderTarget( IN.texCoords, rtParams0 ); diff --git a/Templates/Empty/game/shaders/common/postFx/dof/gl/DOF_CalcCoC_P.glsl b/Templates/Empty/game/shaders/common/postFx/dof/gl/DOF_CalcCoC_P.glsl index 9bfad955c..38cb099c4 100644 --- a/Templates/Empty/game/shaders/common/postFx/dof/gl/DOF_CalcCoC_P.glsl +++ b/Templates/Empty/game/shaders/common/postFx/dof/gl/DOF_CalcCoC_P.glsl @@ -25,7 +25,7 @@ // These are set by the game engine. uniform sampler2D shrunkSampler; // Output of DofDownsample() -uniform sampler2D blurredSampler; // Blurred version of the shrunk sampler +uniform sampler2D blurredSampler; // Blurred version of the shrunk sampler out vec4 OUT_col; diff --git a/Templates/Empty/game/shaders/common/postFx/edgeaa/dbgEdgeDisplayP.hlsl b/Templates/Empty/game/shaders/common/postFx/edgeaa/dbgEdgeDisplayP.hlsl index 90cf391dc..fbd529031 100644 --- a/Templates/Empty/game/shaders/common/postFx/edgeaa/dbgEdgeDisplayP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/edgeaa/dbgEdgeDisplayP.hlsl @@ -21,10 +21,10 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -float4 main( PFXVertToPix IN, - uniform sampler2D edgeBuffer :register(S0) ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(edgeBuffer); + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - return float4( tex2D( edgeBuffer, IN.uv0 ).rrr, 1.0 ); + return float4( TORQUE_TEX2D( edgeBuffer, IN.uv0 ).rrr, 1.0 ); } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/postFx/edgeaa/edgeAAP.hlsl b/Templates/Empty/game/shaders/common/postFx/edgeaa/edgeAAP.hlsl index e45684199..f5a71687d 100644 --- a/Templates/Empty/game/shaders/common/postFx/edgeaa/edgeAAP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/edgeaa/edgeAAP.hlsl @@ -21,17 +21,17 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -float4 main( PFXVertToPix IN, - uniform sampler2D edgeBuffer : register(S0), - uniform sampler2D backBuffer : register(S1), - uniform float2 targetSize : register(C0) ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(edgeBuffer,0); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 1); +uniform float2 targetSize; + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float2 pixelSize = 1.0 / targetSize; // Sample edge buffer, bail if not on an edge - float edgeSample = tex2D(edgeBuffer, IN.uv0).r; + float edgeSample = TORQUE_TEX2D(edgeBuffer, IN.uv0).r; clip(edgeSample - 1e-6); // Ok we're on an edge, so multi-tap sample, average, and return @@ -58,7 +58,7 @@ float4 main( PFXVertToPix IN, float2 offsetUV = IN.uv1 + edgeSample * ( offsets[i] * 0.5 ) * pixelSize;//rtWidthHeightInvWidthNegHeight.zw; //offsetUV *= 0.999; - accumColor+= tex2D(backBuffer, offsetUV); + accumColor += TORQUE_TEX2D(backBuffer, offsetUV); } accumColor /= 9.0; diff --git a/Templates/Empty/game/shaders/common/postFx/edgeaa/edgeDetectP.hlsl b/Templates/Empty/game/shaders/common/postFx/edgeaa/edgeDetectP.hlsl index bc79516ee..2277126a8 100644 --- a/Templates/Empty/game/shaders/common/postFx/edgeaa/edgeDetectP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/edgeaa/edgeDetectP.hlsl @@ -21,10 +21,12 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(prepassBuffer,0); // GPU Gems 3, pg 443-444 -float GetEdgeWeight(float2 uv0, in sampler2D prepassBuffer, in float2 targetSize) +float GetEdgeWeight(float2 uv0, in float2 targetSize) { float2 offsets[9] = { float2( 0.0, 0.0), @@ -44,10 +46,11 @@ float GetEdgeWeight(float2 uv0, in sampler2D prepassBuffer, in float2 targetSize float Depth[9]; float3 Normal[9]; + [unroll] //no getting around this, may as well save the annoying warning message for(int i = 0; i < 9; i++) { float2 uv = uv0 + offsets[i] * PixelSize; - float4 gbSample = prepassUncondition( prepassBuffer, uv ); + float4 gbSample = TORQUE_PREPASS_UNCONDITION( prepassBuffer, uv ); Depth[i] = gbSample.a; Normal[i] = gbSample.rgb; } @@ -82,9 +85,9 @@ float GetEdgeWeight(float2 uv0, in sampler2D prepassBuffer, in float2 targetSize return dot(normalResults, float4(1.0, 1.0, 1.0, 1.0)) * 0.25; } -float4 main( PFXVertToPix IN, - uniform sampler2D prepassBuffer :register(S0), - uniform float2 targetSize : register(C0) ) : COLOR0 +uniform float2 targetSize; + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - return GetEdgeWeight(IN.uv0, prepassBuffer, targetSize );//rtWidthHeightInvWidthNegHeight.zw); + return GetEdgeWeight(IN.uv0, targetSize);//rtWidthHeightInvWidthNegHeight.zw); } diff --git a/Templates/Empty/game/shaders/common/postFx/flashP.hlsl b/Templates/Empty/game/shaders/common/postFx/flashP.hlsl index 3d9c6c744..93daf3c26 100644 --- a/Templates/Empty/game/shaders/common/postFx/flashP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/flashP.hlsl @@ -25,11 +25,11 @@ uniform float damageFlash; uniform float whiteOut; -uniform sampler2D backBuffer : register(S0); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); -float4 main(PFXVertToPix IN) : COLOR0 +float4 main(PFXVertToPix IN) : TORQUE_TARGET0 { - float4 color1 = tex2D(backBuffer, IN.uv0); + float4 color1 = TORQUE_TEX2D(backBuffer, IN.uv0); float4 color2 = color1 * MUL_COLOR; float4 damage = lerp(color1,color2,damageFlash); return lerp(damage,WHITE_COLOR,whiteOut); diff --git a/Templates/Empty/game/shaders/common/postFx/fogP.hlsl b/Templates/Empty/game/shaders/common/postFx/fogP.hlsl index 0eba9a7b7..b54eea97a 100644 --- a/Templates/Empty/game/shaders/common/postFx/fogP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/fogP.hlsl @@ -20,20 +20,21 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" + #include "./postFx.hlsl" #include "./../torque.hlsl" +#include "./../shaderModelAutoGen.hlsl" -uniform sampler2D prepassTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); uniform float3 eyePosWorld; uniform float4 fogColor; uniform float3 fogData; uniform float4 rtParams0; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { //float2 prepassCoord = ( IN.uv0.xy * rtParams0.zw ) + rtParams0.xy; - float depth = prepassUncondition( prepassTex, IN.uv0 ).w; + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; //return float4( depth, 0, 0, 0.7 ); float factor = computeSceneFog( eyePosWorld, diff --git a/Templates/Empty/game/shaders/common/postFx/fxaa/fxaaP.hlsl b/Templates/Empty/game/shaders/common/postFx/fxaa/fxaaP.hlsl index 357b794e4..269bfea67 100644 --- a/Templates/Empty/game/shaders/common/postFx/fxaa/fxaaP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/fxaa/fxaaP.hlsl @@ -20,38 +20,53 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" + #define FXAA_PC 1 +#if (TORQUE_SM <= 30) #define FXAA_HLSL_3 1 +#elif TORQUE_SM < 49 +#define FXAA_HLSL_4 1 +#elif TORQUE_SM >=50 +#define FXAA_HLSL_5 1 +#endif #define FXAA_QUALITY__PRESET 12 #define FXAA_GREEN_AS_LUMA 1 #include "Fxaa3_11.h" -#include "../postFx.hlsl" struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; }; -uniform sampler2D colorTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(colorTex, 0); uniform float2 oneOverTargetSize; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { +#if (TORQUE_SM >= 10 && TORQUE_SM <=30) + FxaaTex tex = colorTex; +#elif TORQUE_SM >=40 + FxaaTex tex; + tex.smpl = colorTex; + tex.tex = texture_colorTex; +#endif + return FxaaPixelShader( IN.uv0, // vertex position 0, // Unused... console stuff - colorTex, // The color back buffer + tex, // The color back buffer - colorTex, // Used for 360 optimization + tex, // Used for 360 optimization - colorTex, // Used for 360 optimization + tex, // Used for 360 optimization oneOverTargetSize, diff --git a/Templates/Empty/game/shaders/common/postFx/fxaa/fxaaV.hlsl b/Templates/Empty/game/shaders/common/postFx/fxaa/fxaaV.hlsl index ea2c3d106..3bef0a4d3 100644 --- a/Templates/Empty/game/shaders/common/postFx/fxaa/fxaaV.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/fxaa/fxaaV.hlsl @@ -25,7 +25,7 @@ struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; }; @@ -35,7 +35,7 @@ VertToPix main( PFXVert IN ) { VertToPix OUT; - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1); OUT.uv0 = viewportCoordToRenderTarget( IN.uv, rtParams0 ); return OUT; diff --git a/Templates/Empty/game/shaders/common/postFx/gammaP.hlsl b/Templates/Empty/game/shaders/common/postFx/gammaP.hlsl index dedfe8eb5..6e284eb88 100644 --- a/Templates/Empty/game/shaders/common/postFx/gammaP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/gammaP.hlsl @@ -24,23 +24,30 @@ #include "./postFx.hlsl" #include "../torque.hlsl" -uniform sampler2D backBuffer : register(S0); -uniform sampler1D colorCorrectionTex : register( s1 ); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); +TORQUE_UNIFORM_SAMPLER1D(colorCorrectionTex, 1); uniform float OneOverGamma; +uniform float Brightness; +uniform float Contrast; - -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float4 color = tex2D(backBuffer, IN.uv0.xy); + float4 color = TORQUE_TEX2D(backBuffer, IN.uv0.xy); // Apply the color correction. - color.r = tex1D( colorCorrectionTex, color.r ).r; - color.g = tex1D( colorCorrectionTex, color.g ).g; - color.b = tex1D( colorCorrectionTex, color.b ).b; + color.r = TORQUE_TEX1D( colorCorrectionTex, color.r ).r; + color.g = TORQUE_TEX1D( colorCorrectionTex, color.g ).g; + color.b = TORQUE_TEX1D( colorCorrectionTex, color.b ).b; // Apply gamma correction color.rgb = pow( abs(color.rgb), OneOverGamma ); + // Apply contrast + color.rgb = ((color.rgb - 0.5f) * Contrast) + 0.5f; + + // Apply brightness + color.rgb += Brightness; + return color; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/postFx/gl/gammaP.glsl b/Templates/Empty/game/shaders/common/postFx/gl/gammaP.glsl index 414a277d3..1bf5d1b8f 100644 --- a/Templates/Empty/game/shaders/common/postFx/gl/gammaP.glsl +++ b/Templates/Empty/game/shaders/common/postFx/gl/gammaP.glsl @@ -28,6 +28,8 @@ uniform sampler2D backBuffer; uniform sampler1D colorCorrectionTex; uniform float OneOverGamma; +uniform float Brightness; +uniform float Contrast; in vec2 uv0; @@ -45,5 +47,11 @@ void main() // Apply gamma correction color.rgb = pow( abs(color.rgb), vec3(OneOverGamma) ); + // Apply contrast + color.rgb = ((color.rgb - 0.5f) * Contrast) + 0.5f; + + // Apply brightness + color.rgb += Brightness; + OUT_col = color; } \ No newline at end of file diff --git a/Templates/Empty/game/shaders/common/postFx/gl/glowBlurP.glsl b/Templates/Empty/game/shaders/common/postFx/gl/glowBlurP.glsl index d00bee26f..9ebca32fa 100644 --- a/Templates/Empty/game/shaders/common/postFx/gl/glowBlurP.glsl +++ b/Templates/Empty/game/shaders/common/postFx/gl/glowBlurP.glsl @@ -39,7 +39,7 @@ out vec4 OUT_col; void main() { vec4 kernel = vec4( 0.175, 0.275, 0.375, 0.475 ) * 0.5f; - + OUT_col = vec4(0); OUT_col += texture( diffuseMap, uv0 ) * kernel.x; OUT_col += texture( diffuseMap, uv1 ) * kernel.y; @@ -55,5 +55,5 @@ void main() // can use alpha test to save fillrate. vec3 rgb2lum = vec3( 0.30, 0.59, 0.11 ); OUT_col.a = dot( OUT_col.rgb, rgb2lum ); - + } diff --git a/Templates/Empty/game/shaders/common/postFx/glowBlurP.hlsl b/Templates/Empty/game/shaders/common/postFx/glowBlurP.hlsl index 65ae96c6f..80f8ed02d 100644 --- a/Templates/Empty/game/shaders/common/postFx/glowBlurP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/glowBlurP.hlsl @@ -22,11 +22,11 @@ #include "./postFx.hlsl" -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -39,20 +39,20 @@ struct VertToPix float2 uv7 : TEXCOORD7; }; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { float4 kernel = float4( 0.175, 0.275, 0.375, 0.475 ) * 0.5f; float4 OUT = 0; - OUT += tex2D( diffuseMap, IN.uv0 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv1 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv2 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv3 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv0 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv1 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv2 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv3 ) * kernel.w; - OUT += tex2D( diffuseMap, IN.uv4 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv5 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv6 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv7 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv4 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv5 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv6 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv7 ) * kernel.w; // Calculate a lumenance value in the alpha so we // can use alpha test to save fillrate. diff --git a/Templates/Empty/game/shaders/common/postFx/glowBlurV.hlsl b/Templates/Empty/game/shaders/common/postFx/glowBlurV.hlsl index c9c9052ec..b8f5cf9c2 100644 --- a/Templates/Empty/game/shaders/common/postFx/glowBlurV.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/glowBlurV.hlsl @@ -28,7 +28,7 @@ uniform float2 texSize0; struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -45,7 +45,7 @@ VertToPix main( PFXVert IN ) { VertToPix OUT; - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); float2 uv = IN.uv + (0.5f / texSize0); diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl index c28f9eb83..77f4b9915 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl @@ -21,9 +21,8 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -uniform sampler2D inputTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float2 oneOverTargetSize; uniform float gaussMultiplier; uniform float gaussMean; @@ -48,7 +47,7 @@ float computeGaussianValue( float x, float mean, float std_deviation ) return tmp * tmp2; } -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 color = { 0.0f, 0.0f, 0.0f, 0.0f }; float offset = 0; @@ -62,7 +61,7 @@ float4 main( PFXVertToPix IN ) : COLOR offset = (i - 4.0) * oneOverTargetSize.x; x = (i - 4.0) / 4.0; weight = gaussMultiplier * computeGaussianValue( x, gaussMean, gaussStdDev ); - color += (tex2D( inputTex, IN.uv0 + float2( offset, 0.0f ) ) * weight ); + color += (TORQUE_TEX2D( inputTex, IN.uv0 + float2( offset, 0.0f ) ) * weight ); } return float4( color.rgb, 1.0f ); diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl index 93e6b8382..8381f6a5d 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl @@ -21,9 +21,8 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -uniform sampler2D inputTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float2 oneOverTargetSize; uniform float gaussMultiplier; uniform float gaussMean; @@ -47,7 +46,7 @@ float computeGaussianValue( float x, float mean, float std_deviation ) return tmp * tmp2; } -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 color = { 0.0f, 0.0f, 0.0f, 0.0f }; float offset = 0; @@ -61,7 +60,7 @@ float4 main( PFXVertToPix IN ) : COLOR offset = (fI - 4.0) * oneOverTargetSize.y; x = (fI - 4.0) / 4.0; weight = gaussMultiplier * computeGaussianValue( x, gaussMean, gaussStdDev ); - color += (tex2D( inputTex, IN.uv0 + float2( 0.0f, offset ) ) * weight ); + color += (TORQUE_TEX2D( inputTex, IN.uv0 + float2( 0.0f, offset ) ) * weight ); } return float4( color.rgb, 1.0f ); diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/brightPassFilterP.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/brightPassFilterP.hlsl index c438a5153..9a8a93e97 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/brightPassFilterP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/brightPassFilterP.hlsl @@ -21,12 +21,11 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" #include "../../torque.hlsl" -uniform sampler2D inputTex : register(S0); -uniform sampler2D luminanceTex : register(S1); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); +TORQUE_UNIFORM_SAMPLER2D(luminanceTex, 1); uniform float2 oneOverTargetSize; uniform float brightPassThreshold; uniform float g_fMiddleGray; @@ -40,17 +39,17 @@ static float2 gTapOffsets[4] = { -0.5, -0.5 }, { 0.5, 0.5 } }; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 average = { 0.0f, 0.0f, 0.0f, 0.0f }; // Combine and average 4 samples from the source HDR texture. for( int i = 0; i < 4; i++ ) - average += hdrDecode( tex2D( inputTex, IN.uv0 + ( gTapOffsets[i] * oneOverTargetSize ) ) ); + average += hdrDecode( TORQUE_TEX2D( inputTex, IN.uv0 + ( gTapOffsets[i] * oneOverTargetSize ) ) ); average *= 0.25f; // Determine the brightness of this particular pixel. - float adaptedLum = tex2D( luminanceTex, float2( 0.5f, 0.5f ) ).r; + float adaptedLum = TORQUE_TEX2D( luminanceTex, float2( 0.5f, 0.5f ) ).r; float lum = (g_fMiddleGray / (adaptedLum + 0.0001)) * hdrLuminance( average.rgb ); //float lum = hdrLuminance( average.rgb ); diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl index 3f443611c..0f895070a 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl @@ -21,18 +21,17 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -uniform sampler2D currLum : register( S0 ); -uniform sampler2D lastAdaptedLum : register( S1 ); +TORQUE_UNIFORM_SAMPLER2D(currLum, 0); +TORQUE_UNIFORM_SAMPLER2D(lastAdaptedLum, 1); uniform float adaptRate; uniform float deltaTime; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float fAdaptedLum = tex2D( lastAdaptedLum, float2(0.5f, 0.5f) ).r; - float fCurrentLum = tex2D( currLum, float2(0.5f, 0.5f) ).r; + float fAdaptedLum = TORQUE_TEX2D( lastAdaptedLum, float2(0.5f, 0.5f) ).r; + float fCurrentLum = TORQUE_TEX2D( currLum, float2(0.5f, 0.5f) ).r; // The user's adapted luminance level is simulated by closing the gap between // adapted luminance and current luminance by 2% every frame, based on a diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/downScale4x4P.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/downScale4x4P.hlsl index 3ce68452c..01998af0b 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/downScale4x4P.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/downScale4x4P.hlsl @@ -29,23 +29,24 @@ //----------------------------------------------------------------------------- struct VertIn { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoords[8] : TEXCOORD0; }; + +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -float4 main( VertIn IN, - uniform sampler2D inputTex : register(S0) ) : COLOR +float4 main( VertIn IN) : TORQUE_TARGET0 { // We calculate the texture coords // in the vertex shader as an optimization. float4 sample = 0.0f; for ( int i = 0; i < 8; i++ ) { - sample += tex2D( inputTex, IN.texCoords[i].xy ); - sample += tex2D( inputTex, IN.texCoords[i].zw ); + sample += TORQUE_TEX2D( inputTex, IN.texCoords[i].xy ); + sample += TORQUE_TEX2D( inputTex, IN.texCoords[i].zw ); } return sample / 16; diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/downScale4x4V.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/downScale4x4V.hlsl index 88794204e..c9a34b7f4 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/downScale4x4V.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/downScale4x4V.hlsl @@ -29,19 +29,20 @@ struct Conn { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoords[8] : TEXCOORD0; }; +uniform float2 targetSize; + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Conn main( PFXVert In, - uniform float2 targetSize : register(C0) ) +Conn main( PFXVert In ) { Conn Out; - Out.hpos = In.pos; + Out.hpos = float4(In.pos,1.0); // Sample from the 16 surrounding points. Since the center point will be in // the exact center of 16 texels, a 0.5f offset is needed to specify a texel diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/finalPassCombineP.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/finalPassCombineP.hlsl index 7ac71bebd..b786b3f6a 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/finalPassCombineP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/finalPassCombineP.hlsl @@ -22,11 +22,13 @@ #include "../../torque.hlsl" #include "../postFx.hlsl" +#include "../../shaderModelAutoGen.hlsl" -uniform sampler2D sceneTex : register( s0 ); -uniform sampler2D luminanceTex : register( s1 ); -uniform sampler2D bloomTex : register( s2 ); -uniform sampler1D colorCorrectionTex : register( s3 ); +TORQUE_UNIFORM_SAMPLER2D(sceneTex, 0); +TORQUE_UNIFORM_SAMPLER2D(luminanceTex, 1); +TORQUE_UNIFORM_SAMPLER2D(bloomTex, 2); +TORQUE_UNIFORM_SAMPLER1D(colorCorrectionTex, 3); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 4); uniform float2 texSize0; uniform float2 texSize2; @@ -34,20 +36,20 @@ uniform float2 texSize2; uniform float g_fEnableToneMapping; uniform float g_fMiddleGray; uniform float g_fWhiteCutoff; - uniform float g_fEnableBlueShift; -uniform float3 g_fBlueShiftColor; +uniform float3 g_fBlueShiftColor; uniform float g_fBloomScale; uniform float g_fOneOverGamma; +uniform float Brightness; +uniform float Contrast; - -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float4 sample = hdrDecode( tex2D( sceneTex, IN.uv0 ) ); - float adaptedLum = tex2D( luminanceTex, float2( 0.5f, 0.5f ) ).r; - float4 bloom = tex2D( bloomTex, IN.uv0 ); + float4 sample = hdrDecode( TORQUE_TEX2D( sceneTex, IN.uv0 ) ); + float adaptedLum = TORQUE_TEX2D( luminanceTex, float2( 0.5f, 0.5f ) ).r; + float4 bloom = TORQUE_TEX2D( bloomTex, IN.uv0 ); // For very low light conditions, the rods will dominate the perception // of light, and therefore color will be desaturated and shifted @@ -81,15 +83,24 @@ float4 main( PFXVertToPix IN ) : COLOR0 } // Add the bloom effect. - sample += g_fBloomScale * bloom; + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; + if (depth>0.9999) + sample += g_fBloomScale * bloom; // Apply the color correction. - sample.r = tex1D( colorCorrectionTex, sample.r ).r; - sample.g = tex1D( colorCorrectionTex, sample.g ).g; - sample.b = tex1D( colorCorrectionTex, sample.b ).b; + sample.r = TORQUE_TEX1D( colorCorrectionTex, sample.r ).r; + sample.g = TORQUE_TEX1D( colorCorrectionTex, sample.g ).g; + sample.b = TORQUE_TEX1D( colorCorrectionTex, sample.b ).b; + // Apply gamma correction sample.rgb = pow( abs(sample.rgb), g_fOneOverGamma ); + + // Apply contrast + sample.rgb = ((sample.rgb - 0.5f) * Contrast) + 0.5f; + + // Apply brightness + sample.rgb += Brightness; return sample; } diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/gl/finalPassCombineP.glsl b/Templates/Empty/game/shaders/common/postFx/hdr/gl/finalPassCombineP.glsl index f34cff1ef..24a516e79 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/gl/finalPassCombineP.glsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/gl/finalPassCombineP.glsl @@ -23,11 +23,13 @@ #include "../../../gl/torque.glsl" #include "../../../gl/hlslCompat.glsl" #include "../../gl/postFX.glsl" +#include "shadergen:/autogenConditioners.h" uniform sampler2D sceneTex; uniform sampler2D luminanceTex; uniform sampler2D bloomTex; uniform sampler1D colorCorrectionTex; +uniform sampler2D prepassTex; uniform vec2 texSize0; uniform vec2 texSize2; @@ -47,6 +49,7 @@ uniform float Contrast; out vec4 OUT_col; + void main() { vec4 _sample = hdrDecode( texture( sceneTex, IN_uv0 ) ); @@ -85,7 +88,9 @@ void main() } // Add the bloom effect. - _sample += g_fBloomScale * bloom; + float depth = prepassUncondition( prepassTex, IN_uv0 ).w; + if (depth>0.9999) + _sample += g_fBloomScale * bloom; // Apply the color correction. _sample.r = texture( colorCorrectionTex, _sample.r ).r; @@ -94,12 +99,12 @@ void main() // Apply gamma correction _sample.rgb = pow( abs(_sample.rgb), vec3(g_fOneOverGamma) ); - + // Apply contrast _sample.rgb = ((_sample.rgb - 0.5f) * Contrast) + 0.5f; // Apply brightness _sample.rgb += Brightness; - + OUT_col = _sample; } diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/luminanceVisP.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/luminanceVisP.hlsl index 593a24e7b..505d1b825 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/luminanceVisP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/luminanceVisP.hlsl @@ -22,15 +22,14 @@ #include "../postFx.hlsl" #include "../../torque.hlsl" -#include "shadergen:/autogenConditioners.h" -uniform sampler2D inputTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float brightPassThreshold; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float4 sample = hdrDecode( tex2D( inputTex, IN.uv0 ) ); + float4 sample = hdrDecode( TORQUE_TEX2D( inputTex, IN.uv0 ) ); // Determine the brightness of this particular pixel. float lum = hdrLuminance( sample.rgb ); diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/sampleLumInitialP.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/sampleLumInitialP.hlsl index 39fd9dccc..2e23ece1f 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/sampleLumInitialP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/sampleLumInitialP.hlsl @@ -23,7 +23,7 @@ #include "../../torque.hlsl" #include "../postFx.hlsl" -uniform sampler2D inputTex : register( S0 ); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float2 texSize0; uniform float g_fMinLuminace; @@ -36,7 +36,7 @@ static float2 gTapOffsets[9] = }; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float2 tsize = 1.0 / texSize0; @@ -46,7 +46,7 @@ float4 main( PFXVertToPix IN ) : COLOR for ( int i = 0; i < 9; i++ ) { // Decode the hdr value. - sample = hdrDecode( tex2D( inputTex, IN.uv0 + ( gTapOffsets[i] * tsize ) ).rgb ); + sample = hdrDecode( TORQUE_TEX2D( inputTex, IN.uv0 + ( gTapOffsets[i] * tsize ) ).rgb ); // Get the luminance and add it to the average. float lum = max( hdrLuminance( sample ), g_fMinLuminace ); diff --git a/Templates/Empty/game/shaders/common/postFx/hdr/sampleLumIterativeP.hlsl b/Templates/Empty/game/shaders/common/postFx/hdr/sampleLumIterativeP.hlsl index 59e91f0db..46ed6fc70 100644 --- a/Templates/Empty/game/shaders/common/postFx/hdr/sampleLumIterativeP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/hdr/sampleLumIterativeP.hlsl @@ -22,7 +22,7 @@ #include "../postFx.hlsl" -uniform sampler2D inputTex : register( S0 ); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float2 oneOverTargetSize; @@ -34,7 +34,7 @@ static float2 gTapOffsets[16] = { -1.5, 1.5 }, { -0.5, 1.5 }, { 0.5, 1.5 }, { 1.5, 1.5 } }; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float2 pixelSize = oneOverTargetSize; @@ -42,7 +42,7 @@ float4 main( PFXVertToPix IN ) : COLOR for ( int i = 0; i < 16; i++ ) { - float lum = tex2D( inputTex, IN.uv0 + ( gTapOffsets[i] * pixelSize ) ).r; + float lum = TORQUE_TEX2D( inputTex, IN.uv0 + ( gTapOffsets[i] * pixelSize ) ).r; average += lum; } diff --git a/Templates/Empty/game/shaders/common/postFx/lightRay/lightRayOccludeP.hlsl b/Templates/Empty/game/shaders/common/postFx/lightRay/lightRayOccludeP.hlsl index e8870b3c4..b70bafa98 100644 --- a/Templates/Empty/game/shaders/common/postFx/lightRay/lightRayOccludeP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/lightRay/lightRayOccludeP.hlsl @@ -20,29 +20,29 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "../postFx.hlsl" -uniform sampler2D backBuffer : register( s0 ); // The original backbuffer. -uniform sampler2D prepassTex : register( s1 ); // The pre-pass depth and normals. +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 1); uniform float brightScalar; static const float3 LUMINANCE_VECTOR = float3(0.3125f, 0.6154f, 0.0721f); -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 col = float4( 0, 0, 0, 1 ); // Get the depth at this pixel. - float depth = prepassUncondition( prepassTex, IN.uv0 ).w; + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; // If the depth is equal to 1.0, read from the backbuffer // and perform the exposure calculation on the result. if ( depth >= 0.999 ) { - col = tex2D( backBuffer, IN.uv0 ); + col = TORQUE_TEX2D( backBuffer, IN.uv0 ); //col = 1 - exp(-120000 * col); col += dot( col.rgb, LUMINANCE_VECTOR ) + 0.0001f; diff --git a/Templates/Empty/game/shaders/common/postFx/lightRay/lightRayP.hlsl b/Templates/Empty/game/shaders/common/postFx/lightRay/lightRayP.hlsl index ff44abfae..032894710 100644 --- a/Templates/Empty/game/shaders/common/postFx/lightRay/lightRayP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/lightRay/lightRayP.hlsl @@ -22,28 +22,29 @@ #include "../postFx.hlsl" -uniform sampler2D frameSampler : register( s0 ); -uniform sampler2D backBuffer : register( s1 ); +TORQUE_UNIFORM_SAMPLER2D(frameSampler, 0); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 1); + uniform float3 camForward; +uniform int numSamples; uniform float3 lightDirection; +uniform float density; uniform float2 screenSunPos; uniform float2 oneOverTargetSize; -uniform int numSamples; -uniform float density; uniform float weight; uniform float decay; uniform float exposure; -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 texCoord = float4( IN.uv0.xy, 0, 0 ); // Store initial sample. - half3 color = (half3)tex2D( frameSampler, texCoord.xy ).rgb; + half3 color = (half3)TORQUE_TEX2D( frameSampler, texCoord.xy ).rgb; // Store original bb color. - float4 bbCol = tex2D( backBuffer, IN.uv1 ); + float4 bbCol = TORQUE_TEX2D( backBuffer, IN.uv1 ); // Set up illumination decay factor. half illuminationDecay = 1.0; @@ -68,7 +69,7 @@ float4 main( PFXVertToPix IN ) : COLOR0 texCoord.xy -= deltaTexCoord; // Retrieve sample at new location. - half3 sample = (half3)tex2Dlod( frameSampler, texCoord ); + half3 sample = (half3)TORQUE_TEX2DLOD( frameSampler, texCoord ); // Apply sample attenuation scale/decay factors. sample *= half(illuminationDecay * weight); diff --git a/Templates/Empty/game/shaders/common/postFx/motionBlurP.hlsl b/Templates/Empty/game/shaders/common/postFx/motionBlurP.hlsl index 348484f4d..8bc65fbc6 100644 --- a/Templates/Empty/game/shaders/common/postFx/motionBlurP.hlsl +++ b/Templates/Empty/game/shaders/common/postFx/motionBlurP.hlsl @@ -22,23 +22,22 @@ #include "./postFx.hlsl" #include "../torque.hlsl" -#include "shadergen:/autogenConditioners.h" +#include "../shaderModelAutoGen.hlsl" uniform float4x4 matPrevScreenToWorld; uniform float4x4 matWorldToScreen; // Passed in from setShaderConsts() uniform float velocityMultiplier; +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 1); -uniform sampler2D backBuffer : register(S0); -uniform sampler2D prepassTex : register(S1); - -float4 main(PFXVertToPix IN) : COLOR0 +float4 main(PFXVertToPix IN) : TORQUE_TARGET0 { float samples = 5; // First get the prepass texture for uv channel 0 - float4 prepass = prepassUncondition( prepassTex, IN.uv0 ); + float4 prepass = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ); // Next extract the depth float depth = prepass.a; @@ -58,12 +57,12 @@ float4 main(PFXVertToPix IN) : COLOR0 float2 velocity = ((screenPos - previousPos) / velocityMultiplier).xy; // Generate the motion blur - float4 color = tex2D(backBuffer, IN.uv0); + float4 color = TORQUE_TEX2D(backBuffer, IN.uv0); IN.uv0 += velocity; for(int i = 1; i= 10 && TORQUE_SM <=30) + // Semantics + #define TORQUE_POSITION POSITION + #define TORQUE_DEPTH DEPTH + #define TORQUE_TARGET0 COLOR0 + #define TORQUE_TARGET1 COLOR1 + #define TORQUE_TARGET2 COLOR2 + #define TORQUE_TARGET3 COLOR3 + + // Sampler uniforms + #define TORQUE_UNIFORM_SAMPLER1D(tex,regist) uniform sampler1D tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLER2D(tex,regist) uniform sampler2D tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLER3D(tex,regist) uniform sampler3D tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLERCUBE(tex,regist) uniform samplerCUBE tex : register(S##regist) + // Sampling functions + #define TORQUE_TEX1D(tex,coords) tex1D(tex,coords) + #define TORQUE_TEX2D(tex,coords) tex2D(tex,coords) + #define TORQUE_TEX2DPROJ(tex,coords) tex2Dproj(tex,coords) //this really is sm 2 or later + #define TORQUE_TEX3D(tex,coords) tex3D(tex,coords) + #define TORQUE_TEXCUBE(tex,coords) texCUBE(tex,coords) + + //Shader model 3.0 only + #if TORQUE_SM == 30 + #define TORQUE_VPOS VPOS // This is a float2 + // The mipmap LOD is specified in coord.w + #define TORQUE_TEX2DLOD(tex,coords) tex2Dlod(tex,coords) + #endif + + //helper if you want to pass sampler/texture in a function + //2D + #define TORQUE_SAMPLER2D(tex) sampler2D tex + #define TORQUE_SAMPLER2D_MAKEARG(tex) tex + //Cube + #define TORQUE_SAMPLERCUBE(tex) samplerCUBE tex + #define TORQUE_SAMPLERCUBE_MAKEARG(tex) tex +// Shader model 4.0+ +#elif TORQUE_SM >= 40 + #define TORQUE_POSITION SV_Position + #define TORQUE_DEPTH SV_Depth + #define TORQUE_VPOS SV_Position //note float4 compared to SM 3 where it is a float2 + #define TORQUE_TARGET0 SV_Target0 + #define TORQUE_TARGET1 SV_Target1 + #define TORQUE_TARGET2 SV_Target2 + #define TORQUE_TARGET3 SV_Target3 + // Sampler uniforms + //1D is emulated to a 2D for now + #define TORQUE_UNIFORM_SAMPLER1D(tex,regist) uniform Texture2D texture_##tex : register(T##regist); uniform SamplerState tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLER2D(tex,regist) uniform Texture2D texture_##tex : register(T##regist); uniform SamplerState tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLER3D(tex,regist) uniform Texture3D texture_##tex : register(T##regist); uniform SamplerState tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLERCUBE(tex,regist) uniform TextureCube texture_##tex : register(T##regist); uniform SamplerState tex : register(S##regist) + // Sampling functions + #define TORQUE_TEX1D(tex,coords) texture_##tex.Sample(tex,coords) + #define TORQUE_TEX2D(tex,coords) texture_##tex.Sample(tex,coords) + #define TORQUE_TEX2DPROJ(tex,coords) texture_##tex.Sample(tex,coords.xy / coords.w) + #define TORQUE_TEX3D(tex,coords) texture_##tex.Sample(tex,coords) + #define TORQUE_TEXCUBE(tex,coords) texture_##tex.Sample(tex,coords) + // The mipmap LOD is specified in coord.w + #define TORQUE_TEX2DLOD(tex,coords) texture_##tex.SampleLevel(tex,coords.xy,coords.w) + + //helper if you want to pass sampler/texture in a function + //2D + #define TORQUE_SAMPLER2D(tex) Texture2D texture_##tex, SamplerState tex + #define TORQUE_SAMPLER2D_MAKEARG(tex) texture_##tex, tex + //Cube + #define TORQUE_SAMPLERCUBE(tex) TextureCube texture_##tex, SamplerState tex + #define TORQUE_SAMPLERCUBE_MAKEARG(tex) texture_##tex, tex +#endif + +#endif // _TORQUE_SHADERMODEL_ + diff --git a/Templates/Empty/game/shaders/common/shaderModelAutoGen.hlsl b/Templates/Empty/game/shaders/common/shaderModelAutoGen.hlsl new file mode 100644 index 000000000..4f2d8803f --- /dev/null +++ b/Templates/Empty/game/shaders/common/shaderModelAutoGen.hlsl @@ -0,0 +1,35 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _TORQUE_SHADERMODEL_AUTOGEN_ +#define _TORQUE_SHADERMODEL_AUTOGEN_ + +#include "shadergen:/autogenConditioners.h" + +// Portability helpers for autogenConditioners +#if (TORQUE_SM >= 10 && TORQUE_SM <=30) + #define TORQUE_PREPASS_UNCONDITION(tex, coords) prepassUncondition(tex, coords) +#elif TORQUE_SM >= 40 + #define TORQUE_PREPASS_UNCONDITION(tex, coords) prepassUncondition(tex, texture_##tex, coords) +#endif + +#endif //_TORQUE_SHADERMODEL_AUTOGEN_ diff --git a/Templates/Empty/game/shaders/common/terrain/blendP.hlsl b/Templates/Empty/game/shaders/common/terrain/blendP.hlsl index f71088928..aeef9d6e3 100644 --- a/Templates/Empty/game/shaders/common/terrain/blendP.hlsl +++ b/Templates/Empty/game/shaders/common/terrain/blendP.hlsl @@ -21,25 +21,28 @@ //----------------------------------------------------------------------------- #include "terrain.hlsl" +#include "../shaderModel.hlsl" struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 layerCoord : TEXCOORD0; float2 texCoord : TEXCOORD1; }; -float4 main( ConnectData IN, - uniform sampler2D layerTex : register(S0), - uniform sampler2D textureMap : register(S1), - uniform float texId, - uniform float layerSize ) : COLOR +TORQUE_UNIFORM_SAMPLER2D(layerTex, 0); +TORQUE_UNIFORM_SAMPLER2D(textureMap, 1); + +uniform float texId; +uniform float layerSize; + +float4 main( ConnectData IN ) : TORQUE_TARGET0 { - float4 layerSample = round( tex2D( layerTex, IN.layerCoord ) * 255.0f ); + float4 layerSample = round( TORQUE_TEX2D( layerTex, IN.layerCoord ) * 255.0f ); float blend = calcBlend( texId, IN.layerCoord, layerSize, layerSample ); clip( blend - 0.0001 ); - return float4( tex2D( textureMap, IN.texCoord ).rgb, blend ); + return float4( TORQUE_TEX2D(textureMap, IN.texCoord).rgb, blend); } diff --git a/Templates/Empty/game/shaders/common/terrain/blendV.hlsl b/Templates/Empty/game/shaders/common/terrain/blendV.hlsl index 7a79d2de4..9ccd33301 100644 --- a/Templates/Empty/game/shaders/common/terrain/blendV.hlsl +++ b/Templates/Empty/game/shaders/common/terrain/blendV.hlsl @@ -23,6 +23,8 @@ /// The vertex shader used in the generation and caching of the /// base terrain texture. +#include "../shaderModel.hlsl" + struct VertData { float3 position : POSITION; @@ -31,17 +33,18 @@ struct VertData struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 layerCoord : TEXCOORD0; float2 texCoord : TEXCOORD1; }; -ConnectData main( VertData IN, - uniform float2 texScale : register(C0) ) +uniform float2 texScale; + +ConnectData main( VertData IN ) { ConnectData OUT; - OUT.hpos = float4( IN.position.xyz, 1 ); + OUT.hpos = float4( IN.position, 1 ); OUT.layerCoord = IN.texCoord; OUT.texCoord = IN.texCoord * texScale; diff --git a/Templates/Empty/game/shaders/common/terrain/terrain.glsl b/Templates/Empty/game/shaders/common/terrain/terrain.glsl index 79f80888c..756edd553 100644 --- a/Templates/Empty/game/shaders/common/terrain/terrain.glsl +++ b/Templates/Empty/game/shaders/common/terrain/terrain.glsl @@ -32,6 +32,7 @@ float calcBlend( float texId, vec2 layerCoord, float layerSize, vec4 layerSample vec4 diff = clamp( abs( layerSample - texId ), 0.0, 1.0 ); float noBlend = float(any( bvec4(1 - diff) )); + // Check if any of the layer samples // match the current texture id. vec4 factors = vec4(0); for(int i = 0; i < 4; i++) diff --git a/Templates/Empty/game/shaders/common/terrain/terrain.hlsl b/Templates/Empty/game/shaders/common/terrain/terrain.hlsl index 8ce497012..b7c87e618 100644 --- a/Templates/Empty/game/shaders/common/terrain/terrain.hlsl +++ b/Templates/Empty/game/shaders/common/terrain/terrain.hlsl @@ -35,6 +35,7 @@ float calcBlend( float texId, float2 layerCoord, float layerSize, float4 layerSa // Check if any of the layer samples // match the current texture id. float4 factors = 0; + [unroll] for(int i = 0; i < 4; i++) if(layerSample[i] == texId) factors[i] = 1; diff --git a/Templates/Empty/game/shaders/common/torque.hlsl b/Templates/Empty/game/shaders/common/torque.hlsl index 1d253936b..3521042d4 100644 --- a/Templates/Empty/game/shaders/common/torque.hlsl +++ b/Templates/Empty/game/shaders/common/torque.hlsl @@ -23,6 +23,7 @@ #ifndef _TORQUE_HLSL_ #define _TORQUE_HLSL_ +#include "./shaderModel.hlsl" static float M_HALFPI_F = 1.57079632679489661923f; static float M_PI_F = 3.14159265358979323846f; @@ -137,29 +138,29 @@ float3x3 quatToMat( float4 quat ) /// @param negViewTS The negative view vector in tangent space. /// @param depthScale The parallax factor used to scale the depth result. /// -float2 parallaxOffset( sampler2D texMap, float2 texCoord, float3 negViewTS, float depthScale ) +float2 parallaxOffset(TORQUE_SAMPLER2D(texMap), float2 texCoord, float3 negViewTS, float depthScale) { - float depth = tex2D( texMap, texCoord ).a; - float2 offset = negViewTS.xy * ( depth * depthScale ); + float depth = TORQUE_TEX2D(texMap, texCoord).a; + float2 offset = negViewTS.xy * (depth * depthScale); - for ( int i=0; i < PARALLAX_REFINE_STEPS; i++ ) + for (int i = 0; i < PARALLAX_REFINE_STEPS; i++) { - depth = ( depth + tex2D( texMap, texCoord + offset ).a ) * 0.5; - offset = negViewTS.xy * ( depth * depthScale ); + depth = (depth + TORQUE_TEX2D(texMap, texCoord + offset).a) * 0.5; + offset = negViewTS.xy * (depth * depthScale); } return offset; } /// Same as parallaxOffset but for dxtnm where depth is stored in the red channel instead of the alpha -float2 parallaxOffsetDxtnm(sampler2D texMap, float2 texCoord, float3 negViewTS, float depthScale) +float2 parallaxOffsetDxtnm(TORQUE_SAMPLER2D(texMap), float2 texCoord, float3 negViewTS, float depthScale) { - float depth = tex2D(texMap, texCoord).r; + float depth = TORQUE_TEX2D(texMap, texCoord).r; float2 offset = negViewTS.xy * (depth * depthScale); for (int i = 0; i < PARALLAX_REFINE_STEPS; i++) { - depth = (depth + tex2D(texMap, texCoord + offset).r) * 0.5; + depth = (depth + TORQUE_TEX2D(texMap, texCoord + offset).r) * 0.5; offset = negViewTS.xy * (depth * depthScale); } @@ -277,5 +278,37 @@ void fizzle(float2 vpos, float visibility) clip( visibility - frac( determinant( m ) ) ); } +// Deferred Shading: Material Info Flag Check +bool getFlag(float flags, int num) +{ + int process = round(flags * 255); + int squareNum = pow(2, num); + return (fmod(process, pow(2, squareNum)) >= squareNum); +} + +// #define TORQUE_STOCK_GAMMA +#ifdef TORQUE_STOCK_GAMMA +// Sample in linear space. Decodes gamma. +float4 toLinear(float4 tex) +{ + return tex; +} +// Encodes gamma. +float4 toLinear(float4 tex) +{ + return tex; +} +#else +// Sample in linear space. Decodes gamma. +float4 toLinear(float4 tex) +{ + return float4(pow(abs(tex.rgb), 2.2), tex.a); +} +// Encodes gamma. +float4 toGamma(float4 tex) +{ + return float4(pow(abs(tex.rgb), 1.0/2.2), tex.a); +} +#endif // #endif // _TORQUE_HLSL_ diff --git a/Templates/Empty/game/shaders/common/water/gl/waterBasicP.glsl b/Templates/Empty/game/shaders/common/water/gl/waterBasicP.glsl index 82c421031..1d5a07c3f 100644 --- a/Templates/Empty/game/shaders/common/water/gl/waterBasicP.glsl +++ b/Templates/Empty/game/shaders/common/water/gl/waterBasicP.glsl @@ -120,6 +120,7 @@ void main() { // Modulate baseColor by the ambientColor. vec4 waterBaseColor = baseColor * vec4( ambientColor.rgb, 1 ); + waterBaseColor = toLinear(waterBaseColor); // Get the bumpNorm... vec3 bumpNorm = ( texture( bumpMap, IN_rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; diff --git a/Templates/Empty/game/shaders/common/water/gl/waterP.glsl b/Templates/Empty/game/shaders/common/water/gl/waterP.glsl index af151020a..a68ede84e 100644 --- a/Templates/Empty/game/shaders/common/water/gl/waterP.glsl +++ b/Templates/Empty/game/shaders/common/water/gl/waterP.glsl @@ -295,7 +295,7 @@ void main() foamColor.rgb *= FOAM_OPACITY * foamAmt * foamColor.a; // Get reflection map color. - vec4 refMapColor = hdrDecode( texture( reflectMap, reflectCoord ) ); + vec4 refMapColor = texture( reflectMap, reflectCoord ); // If we do not have a reflection texture then we use the cubemap. refMapColor = mix( refMapColor, texture( skyMap, reflectionVec ), NO_REFLECT ); @@ -324,6 +324,7 @@ void main() // Calculate the water "base" color based on depth. vec4 waterBaseColor = baseColor * texture( depthGradMap, saturate( delta / depthGradMax ) ); + waterBaseColor = toLinear(waterBaseColor); // Modulate baseColor by the ambientColor. waterBaseColor *= vec4( ambientColor.rgb, 1 ); diff --git a/Templates/Empty/game/shaders/common/water/waterBasicP.hlsl b/Templates/Empty/game/shaders/common/water/waterBasicP.hlsl index d27b28c67..efb437779 100644 --- a/Templates/Empty/game/shaders/common/water/waterBasicP.hlsl +++ b/Templates/Empty/game/shaders/common/water/waterBasicP.hlsl @@ -57,7 +57,7 @@ struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup float4 rippleTexCoord01 : TEXCOORD0; @@ -92,11 +92,11 @@ float fresnel(float NdotV, float bias, float power) //----------------------------------------------------------------------------- // Uniforms //----------------------------------------------------------------------------- -uniform sampler bumpMap : register( S0 ); +TORQUE_UNIFORM_SAMPLER2D(bumpMap,0); //uniform sampler2D prepassTex : register( S1 ); -uniform sampler2D reflectMap : register( S2 ); -uniform sampler refractBuff : register( S3 ); -uniform samplerCUBE skyMap : register( S4 ); +TORQUE_UNIFORM_SAMPLER2D(reflectMap,2); +TORQUE_UNIFORM_SAMPLER2D(refractBuff,3); +TORQUE_UNIFORM_SAMPLERCUBE(skyMap,4); //uniform sampler foamMap : register( S5 ); uniform float4 baseColor; uniform float4 miscParams; @@ -113,15 +113,16 @@ uniform float4x4 modelMat; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -float4 main( ConnectData IN ) : COLOR +float4 main( ConnectData IN ) : TORQUE_TARGET0 { // Modulate baseColor by the ambientColor. float4 waterBaseColor = baseColor * float4( ambientColor.rgb, 1 ); + waterBaseColor = toLinear(waterBaseColor); // Get the bumpNorm... - float3 bumpNorm = ( tex2D( bumpMap, IN.rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord2 ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; + float3 bumpNorm = ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; + bumpNorm += ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; + bumpNorm += ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord2 ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; bumpNorm = normalize( bumpNorm ); bumpNorm = lerp( bumpNorm, float3(0,0,1), 1.0 - rippleMagnitude.w ); @@ -135,7 +136,7 @@ float4 main( ConnectData IN ) : COLOR distortPos.xy += bumpNorm.xy * distortAmt; #ifdef UNDERWATER - return hdrEncode( tex2Dproj( refractBuff, distortPos ) ); + return hdrEncode( TORQUE_TEX2DPROJ( refractBuff, distortPos ) ); #else float3 eyeVec = IN.objPos.xyz - eyePos; @@ -153,16 +154,16 @@ float4 main( ConnectData IN ) : COLOR float fakeColorAmt = ang; // Get reflection map color - float4 refMapColor = hdrDecode( tex2Dproj( reflectMap, distortPos ) ); + float4 refMapColor = hdrDecode( TORQUE_TEX2DPROJ( reflectMap, distortPos ) ); // If we do not have a reflection texture then we use the cubemap. - refMapColor = lerp( refMapColor, texCUBE( skyMap, reflectionVec ), NO_REFLECT ); + refMapColor = lerp( refMapColor, TORQUE_TEXCUBE( skyMap, reflectionVec ), NO_REFLECT ); // Combine reflection color and fakeColor. float4 reflectColor = lerp( refMapColor, fakeColor, fakeColorAmt ); //return refMapColor; // Get refract color - float4 refractColor = hdrDecode( tex2Dproj( refractBuff, distortPos ) ); + float4 refractColor = hdrDecode( TORQUE_TEX2DPROJ( refractBuff, distortPos ) ); // calc "diffuse" color by lerping from the water color // to refraction image based on the water clarity. @@ -197,7 +198,7 @@ float4 main( ConnectData IN ) : COLOR // Fog it. float factor = computeSceneFog( eyePos, - IN.objPos, + IN.objPos.xyz, WORLD_Z, fogData.x, fogData.y, diff --git a/Templates/Empty/game/shaders/common/water/waterBasicV.hlsl b/Templates/Empty/game/shaders/common/water/waterBasicV.hlsl index 2c201e675..310647c90 100644 --- a/Templates/Empty/game/shaders/common/water/waterBasicV.hlsl +++ b/Templates/Empty/game/shaders/common/water/waterBasicV.hlsl @@ -20,12 +20,13 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- struct VertData { - float4 position : POSITION; + float3 position : POSITION; float3 normal : NORMAL; float2 undulateData : TEXCOORD0; float4 horizonFactor : TEXCOORD1; @@ -33,7 +34,7 @@ struct VertData struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup float4 rippleTexCoord01 : TEXCOORD0; @@ -95,21 +96,21 @@ ConnectData main( VertData IN ) // IN.position.xy += offsetXY; // IN.undulateData += offsetXY; // } - - float4 worldPos = mul( modelMat, IN.position ); + float4 inPos = float4(IN.position, 1.0); + float4 worldPos = mul(modelMat, inPos); IN.position.z = lerp( IN.position.z, eyePos.z, IN.horizonFactor.x ); //OUT.objPos = worldPos; - OUT.objPos.xyz = IN.position.xyz; + OUT.objPos.xyz = IN.position; OUT.objPos.w = worldPos.z; // Send pre-undulation screenspace position - OUT.posPreWave = mul( modelview, IN.position ); + OUT.posPreWave = mul( modelview, inPos ); OUT.posPreWave = mul( texGen, OUT.posPreWave ); // Calculate the undulation amount for this vertex. - float2 undulatePos = mul( modelMat, float4( IN.undulateData.xy, 0, 1 ) ); + float2 undulatePos = mul( modelMat, float4( IN.undulateData.xy, 0, 1 )).xy; //if ( undulatePos.x < 0 ) // undulatePos = IN.position.xy; @@ -128,12 +129,12 @@ ConnectData main( VertData IN ) float undulateFade = 1; // Scale down wave magnitude amount based on distance from the camera. - float dist = distance( IN.position.xyz, eyePos ); + float dist = distance( IN.position, eyePos ); dist = clamp( dist, 1.0, undulateMaxDist ); undulateFade *= ( 1 - dist / undulateMaxDist ); // Also scale down wave magnitude if the camera is very very close. - undulateFade *= saturate( ( distance( IN.position.xyz, eyePos ) - 0.5 ) / 10.0 ); + undulateFade *= saturate( ( distance( IN.position, eyePos ) - 0.5 ) / 10.0 ); undulateAmt *= undulateFade; @@ -141,7 +142,7 @@ ConnectData main( VertData IN ) //undulateAmt = 0; // Apply wave undulation to the vertex. - OUT.posPostWave = IN.position; + OUT.posPostWave = inPos; OUT.posPostWave.xyz += IN.normal.xyz * undulateAmt; // Save worldSpace position of this pixel/vert @@ -210,7 +211,7 @@ ConnectData main( VertData IN ) for ( int i = 0; i < 3; i++ ) { binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * IN.undulateData.x + waveDir[i].y * IN.undulateData.y + elapsedTime * waveData[i].x ); - tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * IN.undulateData.x + waveDir[i].y * IN.undulateData.y + elapsedTime * waveData[i].x ); + tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * IN.undulateData.x + waveDir[i].y * IN.undulateData.y + elapsedTime * waveData[i].x ); } binormal = normalize( binormal ); diff --git a/Templates/Empty/game/shaders/common/water/waterP.hlsl b/Templates/Empty/game/shaders/common/water/waterP.hlsl index 851fb471f..ac66e9b28 100644 --- a/Templates/Empty/game/shaders/common/water/waterP.hlsl +++ b/Templates/Empty/game/shaders/common/water/waterP.hlsl @@ -20,7 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../shaderModelAutoGen.hlsl" #include "../torque.hlsl" //----------------------------------------------------------------------------- @@ -69,7 +69,7 @@ struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup float4 rippleTexCoord01 : TEXCOORD0; @@ -105,13 +105,13 @@ float fresnel(float NdotV, float bias, float power) //----------------------------------------------------------------------------- // Uniforms //----------------------------------------------------------------------------- -uniform sampler bumpMap : register( S0 ); -uniform sampler2D prepassTex : register( S1 ); -uniform sampler2D reflectMap : register( S2 ); -uniform sampler refractBuff : register( S3 ); -uniform samplerCUBE skyMap : register( S4 ); -uniform sampler foamMap : register( S5 ); -uniform sampler1D depthGradMap : register( S6 ); +TORQUE_UNIFORM_SAMPLER2D(bumpMap,0); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 1); +TORQUE_UNIFORM_SAMPLER2D(reflectMap, 2); +TORQUE_UNIFORM_SAMPLER2D(refractBuff, 3); +TORQUE_UNIFORM_SAMPLERCUBE(skyMap, 4); +TORQUE_UNIFORM_SAMPLER2D(foamMap, 5); +TORQUE_UNIFORM_SAMPLER1D(depthGradMap, 6); uniform float4 specularParams; uniform float4 baseColor; uniform float4 miscParams; @@ -138,12 +138,12 @@ uniform float reflectivity; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -float4 main( ConnectData IN ) : COLOR +float4 main( ConnectData IN ) : TORQUE_TARGET0 { // Get the bumpNorm... - float3 bumpNorm = ( tex2D( bumpMap, IN.rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord2.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; + float3 bumpNorm = ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; + bumpNorm += ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; + bumpNorm += ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord2.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; bumpNorm = normalize( bumpNorm ); bumpNorm = lerp( bumpNorm, float3(0,0,1), 1.0 - rippleMagnitude.w ); @@ -155,7 +155,7 @@ float4 main( ConnectData IN ) : COLOR float2 prepassCoord = viewportCoordToRenderTarget( IN.posPostWave, rtParams1 ); - float startDepth = prepassUncondition( prepassTex, prepassCoord ).w; + float startDepth = TORQUE_PREPASS_UNCONDITION( prepassTex, prepassCoord ).w; // The water depth in world units of the undistorted pixel. float startDelta = ( startDepth - pixelDepth ); @@ -180,7 +180,7 @@ float4 main( ConnectData IN ) : COLOR prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); // Get prepass depth at the position of this distorted pixel. - float prepassDepth = prepassUncondition( prepassTex, prepassCoord ).w; + float prepassDepth = TORQUE_PREPASS_UNCONDITION( prepassTex, prepassCoord ).w; if ( prepassDepth > 0.99 ) prepassDepth = 5.0; @@ -212,7 +212,7 @@ float4 main( ConnectData IN ) : COLOR prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); // Get prepass depth at the position of this distorted pixel. - prepassDepth = prepassUncondition( prepassTex, prepassCoord ).w; + prepassDepth = TORQUE_PREPASS_UNCONDITION( prepassTex, prepassCoord ).w; if ( prepassDepth > 0.99 ) prepassDepth = 5.0; delta = ( prepassDepth - pixelDepth ) * farPlaneDist; @@ -260,8 +260,8 @@ float4 main( ConnectData IN ) : COLOR IN.foamTexCoords.xy += foamRippleOffset; IN.foamTexCoords.zw += foamRippleOffset; - float4 foamColor = tex2D( foamMap, IN.foamTexCoords.xy ); - foamColor += tex2D( foamMap, IN.foamTexCoords.zw ); + float4 foamColor = TORQUE_TEX2D( foamMap, IN.foamTexCoords.xy ); + foamColor += TORQUE_TEX2D( foamMap, IN.foamTexCoords.zw ); foamColor = saturate( foamColor ); // Modulate foam color by ambient color @@ -282,18 +282,18 @@ float4 main( ConnectData IN ) : COLOR foamColor.rgb *= FOAM_OPACITY * foamAmt * foamColor.a; // Get reflection map color. - float4 refMapColor = hdrDecode( tex2D( reflectMap, reflectCoord ) ); + float4 refMapColor = TORQUE_TEX2D( reflectMap, reflectCoord ); // If we do not have a reflection texture then we use the cubemap. - refMapColor = lerp( refMapColor, texCUBE( skyMap, reflectionVec ), NO_REFLECT ); + refMapColor = lerp( refMapColor, TORQUE_TEXCUBE( skyMap, reflectionVec ), NO_REFLECT ); - fakeColor = ( texCUBE( skyMap, reflectionVec ) ); + fakeColor = ( TORQUE_TEXCUBE( skyMap, reflectionVec ) ); fakeColor.a = 1; // Combine reflection color and fakeColor. float4 reflectColor = lerp( refMapColor, fakeColor, fakeColorAmt ); // Get refract color - float4 refractColor = hdrDecode( tex2D( refractBuff, refractCoord ) ); + float4 refractColor = hdrDecode( TORQUE_TEX2D( refractBuff, refractCoord ) ); // We darken the refraction color a bit to make underwater // elements look wet. We fade out this darkening near the @@ -310,7 +310,8 @@ float4 main( ConnectData IN ) : COLOR float fogAmt = 1.0 - saturate( exp( -FOG_DENSITY * fogDelta ) ); // Calculate the water "base" color based on depth. - float4 waterBaseColor = baseColor * tex1D( depthGradMap, saturate( delta / depthGradMax ) ); + float4 waterBaseColor = baseColor * TORQUE_TEX1D( depthGradMap, saturate( delta / depthGradMax ) ); + waterBaseColor = toLinear(waterBaseColor); // Modulate baseColor by the ambientColor. waterBaseColor *= float4( ambientColor.rgb, 1 ); @@ -353,7 +354,7 @@ float4 main( ConnectData IN ) : COLOR #else - float4 refractColor = hdrDecode( tex2D( refractBuff, refractCoord ) ); + float4 refractColor = hdrDecode( TORQUE_TEX2D( refractBuff, refractCoord ) ); float4 OUT = refractColor; #endif diff --git a/Templates/Empty/game/shaders/common/water/waterV.hlsl b/Templates/Empty/game/shaders/common/water/waterV.hlsl index d2b097bc5..c869f0e9f 100644 --- a/Templates/Empty/game/shaders/common/water/waterV.hlsl +++ b/Templates/Empty/game/shaders/common/water/waterV.hlsl @@ -20,14 +20,14 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- struct VertData { - float4 position : POSITION; + float3 position : POSITION; float3 normal : NORMAL; float2 undulateData : TEXCOORD0; float4 horizonFactor : TEXCOORD1; @@ -35,7 +35,7 @@ struct VertData struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup float4 rippleTexCoord01 : TEXCOORD0; @@ -94,12 +94,12 @@ ConnectData main( VertData IN ) 0.0, 0.0, 0.0, 1.0 }; IN.position.z = lerp( IN.position.z, eyePos.z, IN.horizonFactor.x ); - - OUT.objPos = IN.position; - OUT.objPos.w = mul( modelMat, IN.position ).z; + float4 inPos = float4( IN.position, 1.0); + OUT.objPos = inPos; + OUT.objPos.w = mul( modelMat, inPos ).z; // Send pre-undulation screenspace position - OUT.posPreWave = mul( modelview, IN.position ); + OUT.posPreWave = mul( modelview, inPos ); OUT.posPreWave = mul( texGen, OUT.posPreWave ); // Calculate the undulation amount for this vertex. @@ -132,7 +132,7 @@ ConnectData main( VertData IN ) OUT.rippleTexCoord2.w = saturate( OUT.rippleTexCoord2.w - 0.2 ) / 0.8; // Apply wave undulation to the vertex. - OUT.posPostWave = IN.position; + OUT.posPostWave = inPos; OUT.posPostWave.xyz += IN.normal.xyz * undulateAmt; // Convert to screen @@ -197,7 +197,7 @@ ConnectData main( VertData IN ) for ( int i = 0; i < 3; i++ ) { binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); - tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); + tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); } binormal = binormal; diff --git a/Templates/Empty/game/shaders/common/wavesP.hlsl b/Templates/Empty/game/shaders/common/wavesP.hlsl index 265842f1f..c51eb4b89 100644 --- a/Templates/Empty/game/shaders/common/wavesP.hlsl +++ b/Templates/Empty/game/shaders/common/wavesP.hlsl @@ -22,13 +22,14 @@ #define IN_HLSL #include "shdrConsts.h" +#include "shaderModel.hlsl" //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- struct v2f { - float4 HPOS : POSITION; + float4 HPOS : TORQUE_POSITION; float2 TEX0 : TEXCOORD0; float4 tangentToCube0 : TEXCOORD1; float4 tangentToCube1 : TEXCOORD2; @@ -42,21 +43,23 @@ struct v2f struct Fragout { - float4 col : COLOR0; + float4 col : TORQUE_TARGET0; }; +// Uniforms +TORQUE_UNIFORM_SAMPLER2D(diffMap,0); +//TORQUE_UNIFORM_SAMPLERCUBE(cubeMap, 1); not used? +TORQUE_UNIFORM_SAMPLER2D(bumpMap,2); + +uniform float4 specularColor : register(PC_MAT_SPECCOLOR); +uniform float4 ambient : register(PC_AMBIENT_COLOR); +uniform float specularPower : register(PC_MAT_SPECPOWER); +uniform float accumTime : register(PC_ACCUM_TIME); + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main(v2f IN, - uniform sampler2D diffMap : register(S0), - uniform sampler2D bumpMap : register(S2), - uniform samplerCUBE cubeMap : register(S1), - uniform float4 specularColor : register(PC_MAT_SPECCOLOR), - uniform float specularPower : register(PC_MAT_SPECPOWER), - uniform float4 ambient : register(PC_AMBIENT_COLOR), - uniform float accumTime : register(PC_ACCUM_TIME) -) +Fragout main(v2f IN) { Fragout OUT; @@ -68,8 +71,8 @@ Fragout main(v2f IN, texOffset.y = IN.TEX0.y + cos( accumTime * 3.0 + IN.TEX0.x * 6.28319 * 2.0 ) * 0.05; - float4 bumpNorm = tex2D( bumpMap, texOffset ) * 2.0 - 1.0; - float4 diffuse = tex2D( diffMap, texOffset ); + float4 bumpNorm = TORQUE_TEX2D( bumpMap, texOffset ) * 2.0 - 1.0; + float4 diffuse = TORQUE_TEX2D( diffMap, texOffset ); OUT.col = diffuse * (saturate( dot( IN.lightVec, bumpNorm.xyz ) ) + ambient); diff --git a/Templates/Empty/game/shaders/common/wavesV.hlsl b/Templates/Empty/game/shaders/common/wavesV.hlsl index 6580daa5b..fccef9d25 100644 --- a/Templates/Empty/game/shaders/common/wavesV.hlsl +++ b/Templates/Empty/game/shaders/common/wavesV.hlsl @@ -22,7 +22,7 @@ #define IN_HLSL #include "shdrConsts.h" -#include "hlslStructs.h" +#include "hlslStructs.hlsl" //----------------------------------------------------------------------------- // Constants @@ -42,21 +42,20 @@ struct Conn }; +uniform float4x4 modelview : register(VC_WORLD_PROJ); +uniform float3x3 cubeTrans : register(VC_CUBE_TRANS); +uniform float3 cubeEyePos : register(VC_CUBE_EYE_POS); +uniform float3 inLightVec : register(VC_LIGHT_DIR1); +uniform float3 eyePos : register(VC_EYE_POS); //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Conn main( VertexIn_PNTTTB In, - uniform float4x4 modelview : register(VC_WORLD_PROJ), - uniform float3x3 cubeTrans : register(VC_CUBE_TRANS), - uniform float3 cubeEyePos : register(VC_CUBE_EYE_POS), - uniform float3 inLightVec : register(VC_LIGHT_DIR1), - uniform float3 eyePos : register(VC_EYE_POS) -) +Conn main( VertexIn_PNTTTB In) { Conn Out; - Out.HPOS = mul(modelview, In.pos); + Out.HPOS = mul(modelview, float4(In.pos,1.0)); Out.TEX0 = In.uv0; diff --git a/Templates/Full/game/core/scripts/client/lighting/advanced/deferredShading.cs b/Templates/Full/game/core/scripts/client/lighting/advanced/deferredShading.cs index 8a1df2c67..d53e6965f 100644 --- a/Templates/Full/game/core/scripts/client/lighting/advanced/deferredShading.cs +++ b/Templates/Full/game/core/scripts/client/lighting/advanced/deferredShading.cs @@ -1,6 +1,6 @@ singleton ShaderData( ClearGBufferShader ) { - DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; + DXVertexShaderFile = "shaders/common/lighting/advanced/deferredClearGBufferV.hlsl"; DXPixelShaderFile = "shaders/common/lighting/advanced/deferredClearGBufferP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; diff --git a/Templates/Full/game/shaders/common/VolumetricFog/VFogP.hlsl b/Templates/Full/game/shaders/common/VolumetricFog/VFogP.hlsl index aaadbf479..e900f7548 100644 --- a/Templates/Full/game/shaders/common/VolumetricFog/VFogP.hlsl +++ b/Templates/Full/game/shaders/common/VolumetricFog/VFogP.hlsl @@ -21,44 +21,44 @@ //----------------------------------------------------------------------------- // Volumetric Fog final pixel shader V2.00 - -#include "shadergen:/autogenConditioners.h" +#include "../shaderModel.hlsl" +#include "../shaderModelAutoGen.hlsl" #include "../torque.hlsl" -uniform sampler2D prepassTex : register(S0); -uniform sampler2D depthBuffer : register(S1); -uniform sampler2D frontBuffer : register(S2); -uniform sampler2D density : register(S3); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); +TORQUE_UNIFORM_SAMPLER2D(depthBuffer, 1); +TORQUE_UNIFORM_SAMPLER2D(frontBuffer, 2); +TORQUE_UNIFORM_SAMPLER2D(density, 3); +uniform float3 ambientColor; uniform float accumTime; uniform float4 fogColor; +uniform float4 modspeed;//xy speed layer 1, zw speed layer 2 +uniform float2 viewpoint; +uniform float2 texscale; uniform float fogDensity; uniform float preBias; uniform float textured; uniform float modstrength; -uniform float4 modspeed;//xy speed layer 1, zw speed layer 2 -uniform float2 viewpoint; -uniform float2 texscale; -uniform float3 ambientColor; uniform float numtiles; uniform float fadesize; uniform float2 PixelSize; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 htpos : TEXCOORD0; float2 uv0 : TEXCOORD1; }; -float4 main( ConnectData IN ) : COLOR0 +float4 main( ConnectData IN ) : TORQUE_TARGET0 { float2 uvscreen=((IN.htpos.xy/IN.htpos.w) + 1.0 ) / 2.0; uvscreen.y = 1.0 - uvscreen.y; - float obj_test = prepassUncondition( prepassTex, uvscreen).w * preBias; - float depth = tex2D(depthBuffer,uvscreen).r; - float front = tex2D(frontBuffer,uvscreen).r; + float obj_test = TORQUE_PREPASS_UNCONDITION(prepassTex, uvscreen).w * preBias; + float depth = TORQUE_TEX2D(depthBuffer, uvscreen).r; + float front = TORQUE_TEX2D(frontBuffer, uvscreen).r; if (depth <= front) return float4(0,0,0,0); @@ -73,8 +73,8 @@ float4 main( ConnectData IN ) : COLOR0 { float2 offset = viewpoint + ((-0.5 + (texscale * uvscreen)) * numtiles); - float2 mod1 = tex2D(density,(offset + (modspeed.xy*accumTime))).rg; - float2 mod2= tex2D(density,(offset + (modspeed.zw*accumTime))).rg; + float2 mod1 = TORQUE_TEX2D(density, (offset + (modspeed.xy*accumTime))).rg; + float2 mod2 = TORQUE_TEX2D(density, (offset + (modspeed.zw*accumTime))).rg; diff = (mod2.r + mod1.r) * modstrength; col *= (2.0 - ((mod1.g + mod2.g) * fadesize))/2.0; } diff --git a/Templates/Full/game/shaders/common/VolumetricFog/VFogPreP.hlsl b/Templates/Full/game/shaders/common/VolumetricFog/VFogPreP.hlsl index bb06f5f7c..fdc839507 100644 --- a/Templates/Full/game/shaders/common/VolumetricFog/VFogPreP.hlsl +++ b/Templates/Full/game/shaders/common/VolumetricFog/VFogPreP.hlsl @@ -21,14 +21,15 @@ //----------------------------------------------------------------------------- // Volumetric Fog prepass pixel shader V1.00 +#include "../shaderModel.hlsl" struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 pos : TEXCOORD0; }; -float4 main( ConnectData IN ) : COLOR0 +float4 main( ConnectData IN ) : TORQUE_TARGET0 { float OUT; diff --git a/Templates/Full/game/shaders/common/VolumetricFog/VFogPreV.hlsl b/Templates/Full/game/shaders/common/VolumetricFog/VFogPreV.hlsl index 2d13cdf01..aba7a745d 100644 --- a/Templates/Full/game/shaders/common/VolumetricFog/VFogPreV.hlsl +++ b/Templates/Full/game/shaders/common/VolumetricFog/VFogPreV.hlsl @@ -22,11 +22,12 @@ // Volumetric Fog prepass vertex shader V1.00 -#include "shaders/common/hlslstructs.h" +#include "../shaderModel.hlsl" +#include "../hlslStructs.hlsl" struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 pos : TEXCOORD0; }; @@ -35,12 +36,9 @@ uniform float4x4 modelView; ConnectData main( VertexIn_P IN) { ConnectData OUT; - - float4 inPos = IN.pos; - inPos.w = 1.0; - OUT.hpos = mul( modelView, inPos ); - OUT.pos = OUT.hpos; + OUT.hpos = mul(modelView, float4(IN.pos, 1.0)); + OUT.pos = OUT.hpos; - return OUT; + return OUT; } diff --git a/Templates/Full/game/shaders/common/VolumetricFog/VFogRefl.hlsl b/Templates/Full/game/shaders/common/VolumetricFog/VFogRefl.hlsl index bd9866cf8..380233b5f 100644 --- a/Templates/Full/game/shaders/common/VolumetricFog/VFogRefl.hlsl +++ b/Templates/Full/game/shaders/common/VolumetricFog/VFogRefl.hlsl @@ -21,17 +21,18 @@ //----------------------------------------------------------------------------- // Volumetric Fog Reflection pixel shader V1.00 +#include "../shaderModel.hlsl" uniform float4 fogColor; uniform float fogDensity; uniform float reflStrength; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 pos : TEXCOORD0; }; -float4 main( ConnectData IN ) : COLOR0 +float4 main( ConnectData IN ) : TORQUE_TARGET0 { return float4(fogColor.rgb,saturate(fogDensity*reflStrength)); } diff --git a/Templates/Full/game/shaders/common/VolumetricFog/VFogV.hlsl b/Templates/Full/game/shaders/common/VolumetricFog/VFogV.hlsl index 7f86802b5..167f83946 100644 --- a/Templates/Full/game/shaders/common/VolumetricFog/VFogV.hlsl +++ b/Templates/Full/game/shaders/common/VolumetricFog/VFogV.hlsl @@ -22,24 +22,25 @@ // Volumetric Fog final vertex shader V1.00 -#include "shaders/common/hlslstructs.h" +#include "../shaderModel.hlsl" +#include "../hlslStructs.hlsl" struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 htpos : TEXCOORD0; float2 uv0 : TEXCOORD1; }; uniform float4x4 modelView; -ConnectData main( VertexIn_PNT IN) +ConnectData main( VertexIn_PNTT IN) { - ConnectData OUT; + ConnectData OUT; - OUT.hpos = mul(modelView, IN.pos); + OUT.hpos = mul(modelView, float4(IN.pos,1.0)); OUT.htpos = OUT.hpos; OUT.uv0 = IN.uv0; - return OUT; + return OUT; } diff --git a/Templates/Full/game/shaders/common/basicCloudsP.hlsl b/Templates/Full/game/shaders/common/basicCloudsP.hlsl index 53b88d8b7..4b40e5e8c 100644 --- a/Templates/Full/game/shaders/common/basicCloudsP.hlsl +++ b/Templates/Full/game/shaders/common/basicCloudsP.hlsl @@ -24,14 +24,14 @@ struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 texCoord : TEXCOORD0; }; -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); -float4 main( ConnectData IN ) : COLOR +float4 main( ConnectData IN ) : TORQUE_TARGET0 { - float4 col = tex2D( diffuseMap, IN.texCoord ); + float4 col = TORQUE_TEX2D(diffuseMap, IN.texCoord); return hdrEncode( col ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/basicCloudsV.hlsl b/Templates/Full/game/shaders/common/basicCloudsV.hlsl index a3d4bb5fe..477f17d50 100644 --- a/Templates/Full/game/shaders/common/basicCloudsV.hlsl +++ b/Templates/Full/game/shaders/common/basicCloudsV.hlsl @@ -20,40 +20,40 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "shaderModel.hlsl" + struct CloudVert { - float4 pos : POSITION; - float3 normal : NORMAL; - float3 binormal : BINORMAL; - float3 tangent : TANGENT; + float3 pos : POSITION; float2 uv0 : TEXCOORD0; }; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 texCoord : TEXCOORD0; }; uniform float4x4 modelview; -uniform float accumTime; -uniform float texScale; uniform float2 texDirection; uniform float2 texOffset; +uniform float accumTime; +uniform float texScale; + ConnectData main( CloudVert IN ) -{ +{ ConnectData OUT; - - OUT.hpos = mul(modelview, IN.pos); + + OUT.hpos = mul(modelview, float4(IN.pos,1.0)); OUT.hpos.w = OUT.hpos.z; - + float2 uv = IN.uv0; uv += texOffset; uv *= texScale; uv += accumTime * texDirection; - OUT.texCoord = uv; - + OUT.texCoord = uv; + return OUT; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/cloudLayerP.hlsl b/Templates/Full/game/shaders/common/cloudLayerP.hlsl index a3c2d06e8..efa8fe0b4 100644 --- a/Templates/Full/game/shaders/common/cloudLayerP.hlsl +++ b/Templates/Full/game/shaders/common/cloudLayerP.hlsl @@ -20,6 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "shaderModel.hlsl" #include "torque.hlsl" //----------------------------------------------------------------------------- @@ -27,7 +28,7 @@ //----------------------------------------------------------------------------- struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoord12 : TEXCOORD0; float4 texCoord34 : TEXCOORD1; float3 vLightTS : TEXCOORD2; // light vector in tangent space, denormalized @@ -38,7 +39,7 @@ struct ConnectData //----------------------------------------------------------------------------- // Uniforms //----------------------------------------------------------------------------- -uniform sampler2D normalHeightMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(normalHeightMap, 0); uniform float3 ambientColor; uniform float3 sunColor; uniform float cloudCoverage; @@ -99,7 +100,7 @@ float3 ComputeIllumination( float2 texCoord, return finalColor; } -float4 main( ConnectData IN ) : COLOR +float4 main( ConnectData IN ) : TORQUE_TARGET0 { // Normalize the interpolated vectors: float3 vViewTS = normalize( IN.vViewTS ); @@ -109,11 +110,11 @@ float4 main( ConnectData IN ) : COLOR float2 texSample = IN.texCoord12.xy; - float4 noise1 = tex2D( normalHeightMap, IN.texCoord12.zw ); + float4 noise1 = TORQUE_TEX2D( normalHeightMap, IN.texCoord12.zw ); noise1 = normalize( ( noise1 - 0.5 ) * 2.0 ); //return noise1; - float4 noise2 = tex2D( normalHeightMap, IN.texCoord34.xy ); + float4 noise2 = TORQUE_TEX2D(normalHeightMap, IN.texCoord34.xy); noise2 = normalize( ( noise2 - 0.5 ) * 2.0 ); //return noise2; @@ -122,7 +123,7 @@ float4 main( ConnectData IN ) : COLOR float noiseHeight = noise1.a * noise2.a * ( cloudCoverage / 2.0 + 0.5 ); - float3 vNormalTS = normalize( tex2D( normalHeightMap, texSample ).xyz * 2.0 - 1.0 ); + float3 vNormalTS = normalize( TORQUE_TEX2D(normalHeightMap, texSample).xyz * 2.0 - 1.0); vNormalTS += noiseNormal; vNormalTS = normalize( vNormalTS ); @@ -130,7 +131,7 @@ float4 main( ConnectData IN ) : COLOR cResultColor.rgb = ComputeIllumination( texSample, vLightTS, vViewTS, vNormalTS ); float coverage = ( cloudCoverage - 0.5 ) * 2.0; - cResultColor.a = tex2D( normalHeightMap, texSample ).a + coverage + noiseHeight; + cResultColor.a = TORQUE_TEX2D(normalHeightMap, texSample).a + coverage + noiseHeight; if ( cloudCoverage > -1.0 ) cResultColor.a /= 1.0 + coverage; diff --git a/Templates/Full/game/shaders/common/cloudLayerV.hlsl b/Templates/Full/game/shaders/common/cloudLayerV.hlsl index c34a57c05..94f8b62cb 100644 --- a/Templates/Full/game/shaders/common/cloudLayerV.hlsl +++ b/Templates/Full/game/shaders/common/cloudLayerV.hlsl @@ -23,10 +23,11 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- +#include "shaderModel.hlsl" struct CloudVert { - float4 pos : POSITION; + float3 pos : POSITION; float3 normal : NORMAL; float3 binormal : BINORMAL; float3 tangent : TANGENT; @@ -35,7 +36,7 @@ struct CloudVert struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoord12 : TEXCOORD0; float4 texCoord34 : TEXCOORD1; float3 vLightTS : TEXCOORD2; // light vector in tangent space, denormalized @@ -60,9 +61,9 @@ uniform float3 texScale; ConnectData main( CloudVert IN ) { ConnectData OUT; - OUT.hpos = mul(modelview, IN.pos); + + OUT.hpos = mul(modelview, float4(IN.pos,1.0)); OUT.hpos.w = OUT.hpos.z; - // Offset the uv so we don't have a seam directly over our head. float2 uv = IN.uv0 + float2( 0.5, 0.5 ); @@ -85,7 +86,7 @@ ConnectData main( CloudVert IN ) float3 vBinormalWS = -IN.binormal; // Compute position in world space: - float4 vPositionWS = IN.pos + float4( eyePosWorld, 1 ); //mul( IN.pos, objTrans ); + float4 vPositionWS = float4(IN.pos, 1.0) + float4(eyePosWorld, 1); //mul( IN.pos, objTrans ); // Compute and output the world view vector (unnormalized): float3 vViewWS = eyePosWorld - vPositionWS.xyz; diff --git a/Templates/Full/game/shaders/common/fixedFunction/addColorTextureP.hlsl b/Templates/Full/game/shaders/common/fixedFunction/addColorTextureP.hlsl index 52ae4e955..d0577428f 100644 --- a/Templates/Full/game/shaders/common/fixedFunction/addColorTextureP.hlsl +++ b/Templates/Full/game/shaders/common/fixedFunction/addColorTextureP.hlsl @@ -20,9 +20,18 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -float4 main( float4 color_in : COLOR0, - float2 texCoord_in : TEXCOORD0, - uniform sampler2D diffuseMap : register(S0) ) : COLOR0 +#include "../shaderModel.hlsl" + +struct Conn { - return float4(color_in.rgb, color_in.a * tex2D(diffuseMap, texCoord_in).a); + float4 HPOS : TORQUE_POSITION; + float4 color : COLOR; + float2 texCoord : TEXCOORD0; +}; + +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); + +float4 main( Conn IN ) : TORQUE_TARGET0 +{ + return float4(IN.color.rgb, IN.color.a * TORQUE_TEX2D(diffuseMap, IN.texCoord).a); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/fixedFunction/addColorTextureV.hlsl b/Templates/Full/game/shaders/common/fixedFunction/addColorTextureV.hlsl index 43a82dca6..8bf4e88d8 100644 --- a/Templates/Full/game/shaders/common/fixedFunction/addColorTextureV.hlsl +++ b/Templates/Full/game/shaders/common/fixedFunction/addColorTextureV.hlsl @@ -20,22 +20,28 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../shaderModel.hlsl" + struct Appdata { - float4 position : POSITION; + float3 position : POSITION; float4 color : COLOR; float2 texCoord : TEXCOORD0; }; + struct Conn { - float4 HPOS : POSITION; + float4 HPOS : TORQUE_POSITION; float4 color : COLOR; float2 texCoord : TEXCOORD0; }; -Conn main( Appdata In, uniform float4x4 modelview : register(C0) ) + +uniform float4x4 modelview; + +Conn main( Appdata In ) { Conn Out; - Out.HPOS = mul(modelview, In.position); + Out.HPOS = mul(modelview, float4(In.position,1.0)); Out.color = In.color; Out.texCoord = In.texCoord; return Out; diff --git a/Templates/Full/game/shaders/common/fixedFunction/colorP.hlsl b/Templates/Full/game/shaders/common/fixedFunction/colorP.hlsl index 90bb08112..dd9990e07 100644 --- a/Templates/Full/game/shaders/common/fixedFunction/colorP.hlsl +++ b/Templates/Full/game/shaders/common/fixedFunction/colorP.hlsl @@ -20,7 +20,15 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -float4 main( float4 color_in : COLOR0, uniform sampler2D diffuseMap : register(S0) ) : COLOR0 +#include "../shaderModel.hlsl" + +struct Conn { - return color_in; + float4 HPOS : TORQUE_POSITION; + float4 color : COLOR; +}; + +float4 main(Conn IN) : TORQUE_TARGET0 +{ + return IN.color; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/fixedFunction/colorV.hlsl b/Templates/Full/game/shaders/common/fixedFunction/colorV.hlsl index f0efe1493..d16dfb863 100644 --- a/Templates/Full/game/shaders/common/fixedFunction/colorV.hlsl +++ b/Templates/Full/game/shaders/common/fixedFunction/colorV.hlsl @@ -20,20 +20,26 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../shaderModel.hlsl" + struct Appdata { - float4 position : POSITION; + float3 position : POSITION; float4 color : COLOR; }; + struct Conn { - float4 HPOS : POSITION; + float4 HPOS : TORQUE_POSITION; float4 color : COLOR; }; -Conn main( Appdata In, uniform float4x4 modelview : register(C0) ) + +uniform float4x4 modelview; + +Conn main( Appdata In ) { Conn Out; - Out.HPOS = mul(modelview, In.position); + Out.HPOS = mul(modelview, float4(In.position,1.0)); Out.color = In.color; return Out; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/fixedFunction/modColorTextureP.hlsl b/Templates/Full/game/shaders/common/fixedFunction/modColorTextureP.hlsl index ccf22845c..63afec2a4 100644 --- a/Templates/Full/game/shaders/common/fixedFunction/modColorTextureP.hlsl +++ b/Templates/Full/game/shaders/common/fixedFunction/modColorTextureP.hlsl @@ -20,9 +20,18 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -float4 main( float4 color_in : COLOR0, - float2 texCoord_in : TEXCOORD0, - uniform sampler2D diffuseMap : register(S0) ) : COLOR0 +#include "../shaderModel.hlsl" + +struct Conn { - return tex2D(diffuseMap, texCoord_in) * color_in; + float4 HPOS : TORQUE_POSITION; + float4 color : COLOR; + float2 texCoord : TEXCOORD0; +}; + +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); + +float4 main( Conn IN ) : TORQUE_TARGET0 +{ + return TORQUE_TEX2D(diffuseMap, IN.texCoord) * IN.color; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/fixedFunction/modColorTextureV.hlsl b/Templates/Full/game/shaders/common/fixedFunction/modColorTextureV.hlsl index 43a82dca6..8bf4e88d8 100644 --- a/Templates/Full/game/shaders/common/fixedFunction/modColorTextureV.hlsl +++ b/Templates/Full/game/shaders/common/fixedFunction/modColorTextureV.hlsl @@ -20,22 +20,28 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../shaderModel.hlsl" + struct Appdata { - float4 position : POSITION; + float3 position : POSITION; float4 color : COLOR; float2 texCoord : TEXCOORD0; }; + struct Conn { - float4 HPOS : POSITION; + float4 HPOS : TORQUE_POSITION; float4 color : COLOR; float2 texCoord : TEXCOORD0; }; -Conn main( Appdata In, uniform float4x4 modelview : register(C0) ) + +uniform float4x4 modelview; + +Conn main( Appdata In ) { Conn Out; - Out.HPOS = mul(modelview, In.position); + Out.HPOS = mul(modelview, float4(In.position,1.0)); Out.color = In.color; Out.texCoord = In.texCoord; return Out; diff --git a/Templates/Full/game/shaders/common/fixedFunction/textureP.hlsl b/Templates/Full/game/shaders/common/fixedFunction/textureP.hlsl new file mode 100644 index 000000000..82dbd4ce9 --- /dev/null +++ b/Templates/Full/game/shaders/common/fixedFunction/textureP.hlsl @@ -0,0 +1,36 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../shaderModel.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); + +struct Conn +{ + float4 hpos : TORQUE_POSITION; + float2 texCoord : TEXCOORD0; +}; + +float4 main(Conn IN) : TORQUE_TARGET0 +{ + return TORQUE_TEX2D(diffuseMap, IN.texCoord); +} \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/fixedFunction/textureV.hlsl b/Templates/Full/game/shaders/common/fixedFunction/textureV.hlsl new file mode 100644 index 000000000..204cf9514 --- /dev/null +++ b/Templates/Full/game/shaders/common/fixedFunction/textureV.hlsl @@ -0,0 +1,46 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../shaderModel.hlsl" + +struct Appdata +{ + float3 position : POSITION; + float4 color : COLOR; + float2 texCoord : TEXCOORD0; +}; + +struct Conn +{ + float4 hpos : TORQUE_POSITION; + float2 texCoord : TEXCOORD0; +}; + +uniform float4x4 modelview; + +Conn main( Appdata In ) +{ + Conn Out; + Out.hpos = mul(modelview, float4(In.position, 1.0)); + Out.texCoord = In.texCoord; + return Out; +} \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/foliage.hlsl b/Templates/Full/game/shaders/common/foliage.hlsl index e875bb23f..9952c29d6 100644 --- a/Templates/Full/game/shaders/common/foliage.hlsl +++ b/Templates/Full/game/shaders/common/foliage.hlsl @@ -30,11 +30,11 @@ #define MAX_COVERTYPES 8 +uniform float2 gc_fadeParams; +uniform float2 gc_windDir; uniform float3 gc_camRight; uniform float3 gc_camUp; uniform float4 gc_typeRects[MAX_COVERTYPES]; -uniform float2 gc_fadeParams; -uniform float2 gc_windDir; // .x = gust length // .y = premultiplied simulation time and gust frequency diff --git a/Templates/Full/game/shaders/common/fxFoliageReplicatorP.hlsl b/Templates/Full/game/shaders/common/fxFoliageReplicatorP.hlsl index dfa2e4de0..a8bb68e28 100644 --- a/Templates/Full/game/shaders/common/fxFoliageReplicatorP.hlsl +++ b/Templates/Full/game/shaders/common/fxFoliageReplicatorP.hlsl @@ -21,36 +21,39 @@ //----------------------------------------------------------------------------- #include "shdrConsts.h" - +#include "shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- struct ConnectData { - float2 texCoord : TEXCOORD0; - float4 lum : COLOR0; + float4 hpos : TORQUE_POSITION; + float2 outTexCoord : TEXCOORD0; + float4 color : COLOR0; float4 groundAlphaCoeff : COLOR1; float2 alphaLookup : TEXCOORD1; }; struct Fragout { - float4 col : COLOR0; + float4 col : TORQUE_TARGET0; }; +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); +TORQUE_UNIFORM_SAMPLER2D(alphaMap, 1); + +uniform float4 groundAlpha; +uniform float4 ambient; + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main( ConnectData IN, - uniform sampler2D diffuseMap : register(S0), - uniform sampler2D alphaMap : register(S1), - uniform float4 groundAlpha, - uniform float4 ambient ) +Fragout main( ConnectData IN ) { Fragout OUT; - float4 alpha = tex2D(alphaMap, IN.alphaLookup); - OUT.col = float4( ambient.rgb * IN.lum.rgb, 1.0 ) * tex2D(diffuseMap, IN.texCoord); + float4 alpha = TORQUE_TEX2D(alphaMap, IN.alphaLookup); + OUT.col = float4( ambient.rgb * IN.lum.rgb, 1.0 ) * TORQUE_TEX2D(diffuseMap, IN.texCoord); OUT.col.a = OUT.col.a * min(alpha, groundAlpha + IN.groundAlphaCoeff.x).x; return OUT; diff --git a/Templates/Full/game/shaders/common/fxFoliageReplicatorV.hlsl b/Templates/Full/game/shaders/common/fxFoliageReplicatorV.hlsl index 06a9cf5e5..70ec9ff4c 100644 --- a/Templates/Full/game/shaders/common/fxFoliageReplicatorV.hlsl +++ b/Templates/Full/game/shaders/common/fxFoliageReplicatorV.hlsl @@ -23,39 +23,42 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- + +#include "shaderModel.hlsl" + struct VertData { - float2 texCoord : TEXCOORD0; - float2 waveScale : TEXCOORD1; + float3 position : POSITION; float3 normal : NORMAL; - float4 position : POSITION; + float2 texCoord : TEXCOORD0; + float2 waveScale : TEXCOORD1; }; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 outTexCoord : TEXCOORD0; float4 color : COLOR0; float4 groundAlphaCoeff : COLOR1; float2 alphaLookup : TEXCOORD1; }; +uniform float4x4 projection : register(C0); +uniform float4x4 world : register(C4); +uniform float GlobalSwayPhase : register(C8); +uniform float SwayMagnitudeSide : register(C9); +uniform float SwayMagnitudeFront : register(C10); +uniform float GlobalLightPhase : register(C11); +uniform float LuminanceMagnitude : register(C12); +uniform float LuminanceMidpoint : register(C13); +uniform float DistanceRange : register(C14); +uniform float3 CameraPos : register(C15); +uniform float TrueBillboard : register(C16); + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -ConnectData main( VertData IN, - uniform float4x4 projection : register(C0), - uniform float4x4 world : register(C4), - uniform float GlobalSwayPhase : register(C8), - uniform float SwayMagnitudeSide : register(C9), - uniform float SwayMagnitudeFront : register(C10), - uniform float GlobalLightPhase : register(C11), - uniform float LuminanceMagnitude : register(C12), - uniform float LuminanceMidpoint : register(C13), - uniform float DistanceRange : register(C14), - uniform float3 CameraPos : register(C15), - uniform float TrueBillboard : register(C16) -) +ConnectData main( VertData IN ) { ConnectData OUT; @@ -113,7 +116,7 @@ ConnectData main( VertData IN, float Luminance = LuminanceMidpoint + LuminanceMagnitude * cos(GlobalLightPhase + IN.normal.y); // Alpha - float3 worldPos = float3(IN.position.x, IN.position.y, IN.position.z); + float3 worldPos = IN.position; float alpha = abs(distance(worldPos, CameraPos)) / DistanceRange; alpha = clamp(alpha, 0.0f, 1.0f); //pass it through diff --git a/Templates/Full/game/shaders/common/guiMaterialV.hlsl b/Templates/Full/game/shaders/common/guiMaterialV.hlsl index 425da5da4..5d725338f 100644 --- a/Templates/Full/game/shaders/common/guiMaterialV.hlsl +++ b/Templates/Full/game/shaders/common/guiMaterialV.hlsl @@ -20,23 +20,25 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "hlslStructs.h" +#include "hlslStructs.hlsl" +#include "shaderModel.hlsl" struct MaterialDecoratorConnectV { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; }; +uniform float4x4 modelview : register(C0); + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -MaterialDecoratorConnectV main( VertexIn_PCT IN, - uniform float4x4 modelview : register(C0) ) +MaterialDecoratorConnectV main( VertexIn_PCT IN ) { MaterialDecoratorConnectV OUT; - OUT.hpos = mul(modelview, IN.pos); + OUT.hpos = mul(modelview, float4(IN.pos,1.0)); OUT.uv0 = IN.uv0; return OUT; diff --git a/Templates/Full/game/shaders/common/hlslStructs.hlsl b/Templates/Full/game/shaders/common/hlslStructs.hlsl new file mode 100644 index 000000000..ce0ca305c --- /dev/null +++ b/Templates/Full/game/shaders/common/hlslStructs.hlsl @@ -0,0 +1,114 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +// The purpose of this file is to get all of our HLSL structures into one place. +// Please use the structures here instead of redefining input and output structures +// in each shader file. If structures are added, please adhere to the naming convention. + +//------------------------------------------------------------------------------ +// Vertex Input Structures +// +// These structures map to FVFs/Vertex Declarations in Torque. See gfxStructs.h +//------------------------------------------------------------------------------ + +// Notes +// +// Position should be specified as a float3 as our vertex structures in +// the engine output float3s for position. + +struct VertexIn_P +{ + float3 pos : POSITION; +}; + +struct VertexIn_PT +{ + float3 pos : POSITION; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PTTT +{ + float3 pos : POSITION; + float2 uv0 : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float2 uv2 : TEXCOORD2; +}; + +struct VertexIn_PC +{ + float3 pos : POSITION; + float4 color : DIFFUSE; +}; + +struct VertexIn_PNC +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float4 color : DIFFUSE; +}; + +struct VertexIn_PCT +{ + float3 pos : POSITION; + float4 color : DIFFUSE; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PN +{ + float3 pos : POSITION; + float3 normal : NORMAL; +}; + +struct VertexIn_PNT +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PNTT +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float3 tangent : TANGENT; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PNCT +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float4 color : DIFFUSE; + float2 uv0 : TEXCOORD0; +}; + +struct VertexIn_PNTTTB +{ + float3 pos : POSITION; + float3 normal : NORMAL; + float2 uv0 : TEXCOORD0; + float2 uv1 : TEXCOORD1; + float3 T : TEXCOORD2; + float3 B : TEXCOORD3; +}; \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting.hlsl b/Templates/Full/game/shaders/common/lighting.hlsl index a2c753618..a41b8a873 100644 --- a/Templates/Full/game/shaders/common/lighting.hlsl +++ b/Templates/Full/game/shaders/common/lighting.hlsl @@ -241,7 +241,7 @@ float4 AL_DeferredOutput( } //specular = color * map * spec^gloss - float specularOut = (specularColor * matInfo.b * min(pow(specular, max(( matInfo.a/ AL_ConstantSpecularPower),1.0f)),matInfo.a)).r; + float specularOut = (specularColor * matInfo.b * min(pow(abs(specular), max(( matInfo.a/ AL_ConstantSpecularPower),1.0f)),matInfo.a)).r; lightColor *= shadowAttenuation; lightColor += ambient.rgb; diff --git a/Templates/Full/game/shaders/common/lighting/advanced/convexGeometryV.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/convexGeometryV.hlsl index c86cd4e89..064fcffa6 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/convexGeometryV.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/convexGeometryV.hlsl @@ -20,17 +20,24 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "../../hlslStructs.h" +#include "../../hlslStructs.hlsl" +#include "../../shaderModel.hlsl" + +struct VertData +{ + float3 pos : POSITION; + float4 color : COLOR; +}; struct ConvexConnectV { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 wsEyeDir : TEXCOORD0; float4 ssPos : TEXCOORD1; float4 vsEyeDir : TEXCOORD2; }; -ConvexConnectV main( VertexIn_P IN, +ConvexConnectV main( VertData IN, uniform float4x4 modelview, uniform float4x4 objTrans, uniform float4x4 worldViewOnly, @@ -38,9 +45,9 @@ ConvexConnectV main( VertexIn_P IN, { ConvexConnectV OUT; - OUT.hpos = mul( modelview, IN.pos ); - OUT.wsEyeDir = mul( objTrans, IN.pos ) - float4( eyePosWorld, 0.0 ); - OUT.vsEyeDir = mul( worldViewOnly, IN.pos ); + OUT.hpos = mul( modelview, float4(IN.pos,1.0) ); + OUT.wsEyeDir = mul(objTrans, float4(IN.pos, 1.0)) - float4(eyePosWorld, 0.0); + OUT.vsEyeDir = mul(worldViewOnly, float4(IN.pos, 1.0)); OUT.ssPos = OUT.hpos; return OUT; diff --git a/Templates/Full/game/shaders/common/lighting/advanced/dbgColorBufferP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/dbgColorBufferP.hlsl index 349c943f9..ad3debbaf 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/dbgColorBufferP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/dbgColorBufferP.hlsl @@ -20,12 +20,11 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" +TORQUE_UNIFORM_SAMPLER2D(colorBufferTex,0); -float4 main( PFXVertToPix IN, - uniform sampler2D colorBufferTex : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - return float4(tex2D( colorBufferTex, IN.uv0 ).rgb, 1.0); + return float4(TORQUE_TEX2D( colorBufferTex, IN.uv0 ).rgb, 1.0); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl index a2b2b5d7d..68df09a78 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/dbgDepthVisualizeP.hlsl @@ -20,14 +20,14 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" +#include "../../shaderModelAutoGen.hlsl" +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); +TORQUE_UNIFORM_SAMPLER1D(depthViz, 1); -float4 main( PFXVertToPix IN, - uniform sampler2D prepassTex : register(S0), - uniform sampler1D depthViz : register(S1) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float depth = prepassUncondition( prepassTex, IN.uv0 ).w; - return float4( tex1D( depthViz, depth ).rgb, 1.0 ); + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; + return float4( TORQUE_TEX1D( depthViz, depth ).rgb, 1.0 ); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl index 3c31c897e..257383659 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/dbgGlowVisualizeP.hlsl @@ -20,12 +20,11 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" +TORQUE_UNIFORM_SAMPLER2D(glowBuffer, 0); -float4 main( PFXVertToPix IN, - uniform sampler2D glowBuffer : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - return tex2D(glowBuffer, IN.uv0); + return TORQUE_TEX2D(glowBuffer, IN.uv0); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl index e037ad8b9..ca6d8d677 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/dbgLightColorVisualizeP.hlsl @@ -20,13 +20,13 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "../../postfx/postFx.hlsl" +TORQUE_UNIFORM_SAMPLER2D(lightPrePassTex,0); -float4 main( PFXVertToPix IN, - uniform sampler2D lightPrePassTex : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float4 lightColor = tex2D( lightPrePassTex, IN.uv0 ); + float4 lightColor = TORQUE_TEX2D( lightPrePassTex, IN.uv0 ); return float4( lightColor.rgb, 1.0 ); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl index 8e1074add..072f07e00 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/dbgLightSpecularVisualizeP.hlsl @@ -20,13 +20,12 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(lightPrePassTex,0); - -float4 main( PFXVertToPix IN, - uniform sampler2D lightPrePassTex : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float specular = tex2D( lightPrePassTex, IN.uv0 ).a; + float specular = TORQUE_TEX2D( lightPrePassTex, IN.uv0 ).a; return float4( specular, specular, specular, 1.0 ); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl index c160045b4..4f31d2c53 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/dbgNormalVisualizeP.hlsl @@ -20,13 +20,13 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" +#include "../../shaderModelAutoGen.hlsl" +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); -float4 main( PFXVertToPix IN, - uniform sampler2D prepassTex : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float3 normal = prepassUncondition( prepassTex, IN.uv0 ).xyz; + float3 normal = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).xyz; return float4( ( normal + 1.0 ) * 0.5, 1.0 ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/dbgShadowVisualizeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/dbgShadowVisualizeP.hlsl index b1f2bca29..b54833499 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/dbgShadowVisualizeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/dbgShadowVisualizeP.hlsl @@ -20,15 +20,19 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" + struct MaterialDecoratorConnectV { + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; }; -float4 main( MaterialDecoratorConnectV IN, - uniform sampler2D shadowMap : register(S0), - uniform sampler1D depthViz : register(S1) ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(shadowMap, 0); +TORQUE_UNIFORM_SAMPLER1D(depthViz, 1); + +float4 main( MaterialDecoratorConnectV IN ) : TORQUE_TARGET0 { - float depth = saturate( tex2D( shadowMap, IN.uv0 ).r ); - return float4( tex1D( depthViz, depth ).rgb, 1 ); + float depth = saturate( TORQUE_TEX2D( shadowMap, IN.uv0 ).r ); + return float4( TORQUE_TEX1D( depthViz, depth ).rgb, 1 ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/dbgSpecMapVisualizeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/dbgSpecMapVisualizeP.hlsl index ba5f2c0e1..eba38a879 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/dbgSpecMapVisualizeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/dbgSpecMapVisualizeP.hlsl @@ -20,13 +20,12 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../postfx/postFx.hlsl" +TORQUE_UNIFORM_SAMPLER2D(matinfoTex,0); -float4 main( PFXVertToPix IN, - uniform sampler2D matinfoTex : register(S0) ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float specular = tex2D( matinfoTex, IN.uv0 ).b; + float specular = TORQUE_TEX2D( matinfoTex, IN.uv0 ).b; return float4( specular, specular, specular, 1.0 ); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/deferredClearGBufferP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/deferredClearGBufferP.hlsl index df9870248..cefebe8c7 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/deferredClearGBufferP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/deferredClearGBufferP.hlsl @@ -20,17 +20,24 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" + +struct Conn +{ + float4 hpos : TORQUE_POSITION; +}; + struct Fragout { - float4 col : COLOR0; - float4 col1 : COLOR1; - float4 col2 : COLOR2; + float4 col : TORQUE_TARGET0; + float4 col1 : TORQUE_TARGET1; + float4 col2 : TORQUE_TARGET2; }; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main( ) +Fragout main( Conn IN ) { Fragout OUT; diff --git a/Templates/Full/game/shaders/common/lighting/advanced/deferredClearGBufferV.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/deferredClearGBufferV.hlsl new file mode 100644 index 000000000..20ba4d509 --- /dev/null +++ b/Templates/Full/game/shaders/common/lighting/advanced/deferredClearGBufferV.hlsl @@ -0,0 +1,43 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2012 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#include "../../shaderModel.hlsl" + +struct Appdata +{ + float3 pos : POSITION; + float4 color : COLOR; +}; + +struct Conn +{ + float4 hpos : TORQUE_POSITION; +}; + +uniform float4x4 modelview; + +Conn main( Appdata In ) +{ + Conn Out; + Out.hpos = float4(In.pos,1.0); + return Out; +} diff --git a/Templates/Full/game/shaders/common/lighting/advanced/deferredColorShaderP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/deferredColorShaderP.hlsl index 5e6d0a984..d91d2eb38 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/deferredColorShaderP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/deferredColorShaderP.hlsl @@ -20,11 +20,13 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" + struct Fragout { - float4 col : COLOR0; - float4 col1 : COLOR1; - float4 col2 : COLOR2; + float4 col : TORQUE_TARGET0; + float4 col1 : TORQUE_TARGET1; + float4 col2 : TORQUE_TARGET2; }; //----------------------------------------------------------------------------- diff --git a/Templates/Full/game/shaders/common/lighting/advanced/deferredShadingP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/deferredShadingP.hlsl index 80e6acde0..c710656f8 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/deferredShadingP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/deferredShadingP.hlsl @@ -20,22 +20,22 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "../../postfx/postFx.hlsl" #include "shaders/common/torque.hlsl" +TORQUE_UNIFORM_SAMPLER2D(colorBufferTex,0); +TORQUE_UNIFORM_SAMPLER2D(lightPrePassTex,1); +TORQUE_UNIFORM_SAMPLER2D(matInfoTex,2); +TORQUE_UNIFORM_SAMPLER2D(prepassTex,3); -float4 main( PFXVertToPix IN, - uniform sampler2D colorBufferTex : register(S0), - uniform sampler2D lightPrePassTex : register(S1), - uniform sampler2D matInfoTex : register(S2), - uniform sampler2D prepassTex : register(S3)) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float4 lightBuffer = tex2D( lightPrePassTex, IN.uv0 ); - float4 colorBuffer = tex2D( colorBufferTex, IN.uv0 ); - float4 matInfo = tex2D( matInfoTex, IN.uv0 ); + float4 lightBuffer = TORQUE_TEX2D( lightPrePassTex, IN.uv0 ); + float4 colorBuffer = TORQUE_TEX2D( colorBufferTex, IN.uv0 ); + float4 matInfo = TORQUE_TEX2D( matInfoTex, IN.uv0 ); float specular = saturate(lightBuffer.a); - float depth = prepassUncondition( prepassTex, IN.uv0 ).w; + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; if (depth>0.9999) return float4(0,0,0,0); diff --git a/Templates/Full/game/shaders/common/lighting/advanced/farFrustumQuad.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/farFrustumQuad.hlsl index 567dd11ce..543e21677 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/farFrustumQuad.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/farFrustumQuad.hlsl @@ -19,10 +19,11 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" struct FarFrustumQuadConnectV { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float3 wsEyeRay : TEXCOORD1; float3 vsEyeRay : TEXCOORD2; @@ -30,6 +31,7 @@ struct FarFrustumQuadConnectV struct FarFrustumQuadConnectP { + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float3 wsEyeRay : TEXCOORD1; float3 vsEyeRay : TEXCOORD2; diff --git a/Templates/Full/game/shaders/common/lighting/advanced/farFrustumQuadV.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/farFrustumQuadV.hlsl index 08cf61285..0167d901a 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/farFrustumQuadV.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/farFrustumQuadV.hlsl @@ -20,7 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "../../hlslStructs.h" +#include "../../hlslStructs.hlsl" #include "farFrustumQuad.hlsl" @@ -36,8 +36,8 @@ FarFrustumQuadConnectV main( VertexIn_PNTT IN, // Interpolators will generate eye rays the // from far-frustum corners. - OUT.wsEyeRay = IN.tangent.xyz; - OUT.vsEyeRay = IN.normal.xyz; + OUT.wsEyeRay = IN.tangent; + OUT.vsEyeRay = IN.normal; return OUT; } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/particlePointLightP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/particlePointLightP.hlsl index bc4784980..7ff5d50d2 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/particlePointLightP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/particlePointLightP.hlsl @@ -20,35 +20,36 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" - #include "farFrustumQuad.hlsl" #include "lightingUtils.hlsl" #include "../../lighting.hlsl" +#include "../../shaderModel.hlsl" +#include "../../shaderModelAutoGen.hlsl" struct ConvexConnectP { + float4 pos : TORQUE_POSITION; float4 ssPos : TEXCOORD0; float3 vsEyeDir : TEXCOORD1; }; -float4 main( ConvexConnectP IN, - uniform sampler2D prePassBuffer : register(S0), - - uniform float4 lightPosition, - uniform float4 lightColor, - uniform float lightRange, - - uniform float4 vsFarPlane, - uniform float4 rtParams0 ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(prePassBuffer, 0); + +uniform float4 lightPosition; +uniform float4 lightColor; +uniform float lightRange; +uniform float4 vsFarPlane; +uniform float4 rtParams0; + +float4 main( ConvexConnectP IN ) : TORQUE_TARGET0 { // Compute scene UV float3 ssPos = IN.ssPos.xyz / IN.ssPos.w; float2 uvScene = getUVFromSSPos(ssPos, rtParams0); // Sample/unpack the normal/z data - float4 prepassSample = prepassUncondition(prePassBuffer, uvScene); + float4 prepassSample = TORQUE_PREPASS_UNCONDITION(prePassBuffer, uvScene); float3 normal = prepassSample.rgb; float depth = prepassSample.a; diff --git a/Templates/Full/game/shaders/common/lighting/advanced/particlePointLightV.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/particlePointLightV.hlsl index f5dc9e444..faa2ec115 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/particlePointLightV.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/particlePointLightV.hlsl @@ -20,24 +20,26 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "../../hlslStructs.h" +#include "../../hlslStructs.hlsl" +#include "../../shaderModel.hlsl" struct ConvexConnectV { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 ssPos : TEXCOORD0; float3 vsEyeDir : TEXCOORD1; }; -ConvexConnectV main( VertexIn_P IN, - uniform float4x4 viewProj, - uniform float4x4 view, - uniform float3 particlePosWorld, - uniform float lightRange ) +uniform float4x4 viewProj; +uniform float4x4 view; +uniform float3 particlePosWorld; +uniform float lightRange; + +ConvexConnectV main( VertexIn_P IN ) { ConvexConnectV OUT; - - float4 vPosWorld = IN.pos + float4(particlePosWorld, 0.0) + float4(IN.pos.xyz, 0.0) * lightRange; + float4 pos = float4(IN.pos, 0.0); + float4 vPosWorld = pos + float4(particlePosWorld, 0.0) + pos * lightRange; OUT.hpos = mul(viewProj, vPosWorld); OUT.vsEyeDir = mul(view, vPosWorld); OUT.ssPos = OUT.hpos; diff --git a/Templates/Full/game/shaders/common/lighting/advanced/pointLightP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/pointLightP.hlsl index 9051ff09d..540fd65c7 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/pointLightP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/pointLightP.hlsl @@ -20,7 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "farFrustumQuad.hlsl" #include "lightingUtils.hlsl" @@ -31,17 +31,17 @@ struct ConvexConnectP { + float4 pos : TORQUE_POSITION; float4 wsEyeDir : TEXCOORD0; float4 ssPos : TEXCOORD1; float4 vsEyeDir : TEXCOORD2; - float4 color : COLOR0; }; #ifdef USE_COOKIE_TEX /// The texture for cookie rendering. -uniform samplerCUBE cookieMap : register(S3); +TORQUE_UNIFORM_SAMPLERCUBE(cookieMap, 3); #endif @@ -53,9 +53,9 @@ uniform samplerCUBE cookieMap : register(S3); return shadowCoord; } - float4 shadowSample( samplerCUBE shadowMap, float3 shadowCoord ) + float4 shadowSample( TORQUE_SAMPLERCUBE(shadowMap), float3 shadowCoord ) { - return texCUBE( shadowMap, shadowCoord ); + return TORQUE_TEXCUBE( shadowMap, shadowCoord ); } #else @@ -106,44 +106,44 @@ uniform samplerCUBE cookieMap : register(S3); #endif +TORQUE_UNIFORM_SAMPLER2D(prePassBuffer, 0); -float4 main( ConvexConnectP IN, +#ifdef SHADOW_CUBE +TORQUE_UNIFORM_SAMPLERCUBE(shadowMap, 1); +#else +TORQUE_UNIFORM_SAMPLER2D(shadowMap, 1); +TORQUE_UNIFORM_SAMPLER2D(dynamicShadowMap, 2); +#endif - uniform sampler2D prePassBuffer : register(S0), +TORQUE_UNIFORM_SAMPLER2D(lightBuffer, 5); +TORQUE_UNIFORM_SAMPLER2D(colorBuffer, 6); +TORQUE_UNIFORM_SAMPLER2D(matInfoBuffer, 7); - #ifdef SHADOW_CUBE - uniform samplerCUBE shadowMap : register(S1), - #else - uniform sampler2D shadowMap : register(S1), - uniform sampler2D dynamicShadowMap : register(S2), - #endif +uniform float4 rtParams0; +uniform float4 lightColor; - uniform sampler2D lightBuffer : register(S5), - uniform sampler2D colorBuffer : register(S6), - uniform sampler2D matInfoBuffer : register(S7), +uniform float lightBrightness; +uniform float3 lightPosition; - uniform float4 rtParams0, +uniform float4 lightMapParams; +uniform float4 vsFarPlane; +uniform float4 lightParams; - uniform float3 lightPosition, - uniform float4 lightColor, - uniform float lightBrightness, - uniform float lightRange, - uniform float2 lightAttenuation, - uniform float4 lightMapParams, +uniform float lightRange; +uniform float shadowSoftness; +uniform float2 lightAttenuation; - uniform float4 vsFarPlane, - uniform float3x3 viewToLightProj, - uniform float3x3 dynamicViewToLightProj, +uniform float3x3 viewToLightProj; +uniform float3x3 dynamicViewToLightProj; - uniform float4 lightParams, - uniform float shadowSoftness ) : COLOR0 +float4 main( ConvexConnectP IN ) : TORQUE_TARGET0 { // Compute scene UV float3 ssPos = IN.ssPos.xyz / IN.ssPos.w; float2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); // Emissive. - float4 matInfo = tex2D( matInfoBuffer, uvScene ); + float4 matInfo = TORQUE_TEX2D( matInfoBuffer, uvScene ); bool emissive = getFlag( matInfo.r, 0 ); if ( emissive ) { @@ -151,7 +151,7 @@ float4 main( ConvexConnectP IN, } // Sample/unpack the normal/z data - float4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); + float4 prepassSample = TORQUE_PREPASS_UNCONDITION( prePassBuffer, uvScene ); float3 normal = prepassSample.rgb; float depth = prepassSample.a; @@ -188,14 +188,14 @@ float4 main( ConvexConnectP IN, #ifdef SHADOW_CUBE // TODO: We need to fix shadow cube to handle soft shadows! - float occ = texCUBE( shadowMap, mul( viewToLightProj, -lightVec ) ).r; + float occ = TORQUE_TEXCUBE( shadowMap, mul( viewToLightProj, -lightVec ) ).r; float shadowed = saturate( exp( lightParams.y * ( occ - distToLight ) ) ); #else // Static float2 shadowCoord = decodeShadowCoord( mul( viewToLightProj, -lightVec ) ).xy; - float static_shadowed = softShadow_filter( shadowMap, + float static_shadowed = softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(shadowMap), ssPos.xy, shadowCoord, shadowSoftness, @@ -205,7 +205,7 @@ float4 main( ConvexConnectP IN, // Dynamic float2 dynamicShadowCoord = decodeShadowCoord( mul( dynamicViewToLightProj, -lightVec ) ).xy; - float dynamic_shadowed = softShadow_filter( dynamicShadowMap, + float dynamic_shadowed = softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), ssPos.xy, dynamicShadowCoord, shadowSoftness, @@ -223,7 +223,7 @@ float4 main( ConvexConnectP IN, #ifdef USE_COOKIE_TEX // Lookup the cookie sample. - float4 cookie = texCUBE( cookieMap, mul( viewToLightProj, -lightVec ) ); + float4 cookie = TORQUE_TEXCUBE( cookieMap, mul( viewToLightProj, -lightVec ) ); // Multiply the light with the cookie tex. lightcol *= cookie.rgb; @@ -263,6 +263,6 @@ float4 main( ConvexConnectP IN, addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); } - float4 colorSample = tex2D( colorBuffer, uvScene ); + float4 colorSample = TORQUE_TEX2D( colorBuffer, uvScene ); return AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/softShadow.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/softShadow.hlsl index 36bffbfd9..0faf3e1fb 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/softShadow.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/softShadow.hlsl @@ -20,6 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" #if defined( SOFTSHADOW ) && defined( SOFTSHADOW_HIGH_QUALITY ) @@ -69,10 +70,9 @@ static float2 sNonUniformTaps[NUM_PRE_TAPS] = /// The texture used to do per-pixel pseudorandom /// rotations of the filter taps. -uniform sampler2D gTapRotationTex : register(S4); +TORQUE_UNIFORM_SAMPLER2D(gTapRotationTex, 4); - -float softShadow_sampleTaps( sampler2D shadowMap, +float softShadow_sampleTaps( TORQUE_SAMPLER2D(shadowMap1), float2 sinCos, float2 shadowPos, float filterRadius, @@ -88,7 +88,7 @@ float softShadow_sampleTaps( sampler2D shadowMap, { tap.x = ( sNonUniformTaps[t].x * sinCos.y - sNonUniformTaps[t].y * sinCos.x ) * filterRadius; tap.y = ( sNonUniformTaps[t].y * sinCos.y + sNonUniformTaps[t].x * sinCos.x ) * filterRadius; - float occluder = tex2Dlod( shadowMap, float4( shadowPos + tap, 0, 0 ) ).r; + float occluder = TORQUE_TEX2DLOD( shadowMap1, float4( shadowPos + tap, 0, 0 ) ).r; float esm = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); shadow += esm / float( endTap - startTap ); @@ -98,7 +98,7 @@ float softShadow_sampleTaps( sampler2D shadowMap, } -float softShadow_filter( sampler2D shadowMap, +float softShadow_filter( TORQUE_SAMPLER2D(shadowMap), float2 vpos, float2 shadowPos, float filterRadius, @@ -111,16 +111,15 @@ float softShadow_filter( sampler2D shadowMap, // If softshadow is undefined then we skip any complex // filtering... just do a single sample ESM. - float occluder = tex2Dlod( shadowMap, float4( shadowPos, 0, 0 ) ).r; + float occluder = TORQUE_TEX2DLOD(shadowMap, float4(shadowPos, 0, 0)).r; float shadow = saturate( exp( esmFactor * ( occluder - distToLight ) ) ); #else - // Lookup the random rotation for this screen pixel. - float2 sinCos = ( tex2Dlod( gTapRotationTex, float4( vpos * 16, 0, 0 ) ).rg - 0.5 ) * 2; + float2 sinCos = ( TORQUE_TEX2DLOD(gTapRotationTex, float4(vpos * 16, 0, 0)).rg - 0.5) * 2; // Do the prediction taps first. - float shadow = softShadow_sampleTaps( shadowMap, + float shadow = softShadow_sampleTaps( TORQUE_SAMPLER2D_MAKEARG(shadowMap), sinCos, shadowPos, filterRadius, @@ -137,7 +136,7 @@ float softShadow_filter( sampler2D shadowMap, // in a partially shadowed area. if ( shadow * ( 1.0 - shadow ) * max( dotNL, 0 ) > 0.06 ) { - shadow += softShadow_sampleTaps( shadowMap, + shadow += softShadow_sampleTaps( TORQUE_SAMPLER2D_MAKEARG(shadowMap), sinCos, shadowPos, filterRadius, diff --git a/Templates/Full/game/shaders/common/lighting/advanced/spotLightP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/spotLightP.hlsl index 226b9cfea..e1f3baf93 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/spotLightP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/spotLightP.hlsl @@ -20,7 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModel.hlsl" +#include "../../shaderModelAutoGen.hlsl" #include "farFrustumQuad.hlsl" #include "lightingUtils.hlsl" @@ -31,54 +32,55 @@ struct ConvexConnectP { + float4 pos : TORQUE_POSITION; float4 wsEyeDir : TEXCOORD0; float4 ssPos : TEXCOORD1; float4 vsEyeDir : TEXCOORD2; - float4 color : COLOR0; }; +TORQUE_UNIFORM_SAMPLER2D(prePassBuffer, 0); +TORQUE_UNIFORM_SAMPLER2D(shadowMap, 1); +TORQUE_UNIFORM_SAMPLER2D(dynamicShadowMap,2); + #ifdef USE_COOKIE_TEX /// The texture for cookie rendering. -uniform sampler2D cookieMap : register(S3); +TORQUE_UNIFORM_SAMPLER2D(cookieMap, 3); #endif +TORQUE_UNIFORM_SAMPLER2D(lightBuffer, 5); +TORQUE_UNIFORM_SAMPLER2D(colorBuffer, 6); +TORQUE_UNIFORM_SAMPLER2D(matInfoBuffer, 7); -float4 main( ConvexConnectP IN, +uniform float4 rtParams0; - uniform sampler2D prePassBuffer : register(S0), - uniform sampler2D shadowMap : register(S1), - uniform sampler2D dynamicShadowMap : register(S2), +uniform float lightBrightness; +uniform float3 lightPosition; - uniform sampler2D lightBuffer : register(S5), - uniform sampler2D colorBuffer : register(S6), - uniform sampler2D matInfoBuffer : register(S7), +uniform float4 lightColor; - uniform float4 rtParams0, +uniform float lightRange; +uniform float3 lightDirection; - uniform float3 lightPosition, - uniform float4 lightColor, - uniform float lightBrightness, - uniform float lightRange, - uniform float2 lightAttenuation, - uniform float3 lightDirection, - uniform float4 lightSpotParams, - uniform float4 lightMapParams, +uniform float4 lightSpotParams; +uniform float4 lightMapParams; +uniform float4 vsFarPlane; +uniform float4x4 viewToLightProj; +uniform float4 lightParams; +uniform float4x4 dynamicViewToLightProj; - uniform float4 vsFarPlane, - uniform float4x4 viewToLightProj, - uniform float4x4 dynamicViewToLightProj, +uniform float2 lightAttenuation; +uniform float shadowSoftness; - uniform float4 lightParams, - uniform float shadowSoftness ) : COLOR0 +float4 main( ConvexConnectP IN ) : TORQUE_TARGET0 { // Compute scene UV float3 ssPos = IN.ssPos.xyz / IN.ssPos.w; float2 uvScene = getUVFromSSPos( ssPos, rtParams0 ); // Emissive. - float4 matInfo = tex2D( matInfoBuffer, uvScene ); + float4 matInfo = TORQUE_TEX2D( matInfoBuffer, uvScene ); bool emissive = getFlag( matInfo.r, 0 ); if ( emissive ) { @@ -86,7 +88,7 @@ float4 main( ConvexConnectP IN, } // Sample/unpack the normal/z data - float4 prepassSample = prepassUncondition( prePassBuffer, uvScene ); + float4 prepassSample = TORQUE_PREPASS_UNCONDITION( prePassBuffer, uvScene ); float3 normal = prepassSample.rgb; float depth = prepassSample.a; @@ -130,7 +132,7 @@ float4 main( ConvexConnectP IN, // Get a linear depth from the light source. float distToLight = pxlPosLightProj.z / lightRange; - float static_shadowed = softShadow_filter( shadowMap, + float static_shadowed = softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(shadowMap), ssPos.xy, shadowCoord, shadowSoftness, @@ -138,7 +140,7 @@ float4 main( ConvexConnectP IN, nDotL, lightParams.y ); - float dynamic_shadowed = softShadow_filter( dynamicShadowMap, + float dynamic_shadowed = softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), ssPos.xy, dynshadowCoord, shadowSoftness, @@ -152,7 +154,7 @@ float4 main( ConvexConnectP IN, #ifdef USE_COOKIE_TEX // Lookup the cookie sample. - float4 cookie = tex2D( cookieMap, shadowCoord ); + float4 cookie = TORQUE_TEX2D( cookieMap, shadowCoord ); // Multiply the light with the cookie tex. lightcol *= cookie.rgb; @@ -192,6 +194,6 @@ float4 main( ConvexConnectP IN, addToResult = ( 1.0 - shadowed ) * abs(lightMapParams); } - float4 colorSample = tex2D( colorBuffer, uvScene ); + float4 colorSample = TORQUE_TEX2D( colorBuffer, uvScene ); return AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/vectorLightP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/vectorLightP.hlsl index 896576564..1a9726171 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/vectorLightP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/vectorLightP.hlsl @@ -20,7 +20,8 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModel.hlsl" +#include "../../shaderModelAutoGen.hlsl" #include "farFrustumQuad.hlsl" #include "../../torque.hlsl" @@ -29,16 +30,55 @@ #include "../shadowMap/shadowMapIO_HLSL.h" #include "softShadow.hlsl" - -uniform sampler2D shadowMap : register(S1); -uniform sampler2D dynamicShadowMap : register(S2); +TORQUE_UNIFORM_SAMPLER2D(prePassBuffer, 0); +TORQUE_UNIFORM_SAMPLER2D(shadowMap, 1); +TORQUE_UNIFORM_SAMPLER2D(dynamicShadowMap, 2); #ifdef USE_SSAO_MASK -uniform sampler2D ssaoMask : register(S3); +TORQUE_UNIFORM_SAMPLER2D(ssaoMask, 3); uniform float4 rtParams3; #endif +//register 4? +TORQUE_UNIFORM_SAMPLER2D(lightBuffer, 5); +TORQUE_UNIFORM_SAMPLER2D(colorBuffer, 6); +TORQUE_UNIFORM_SAMPLER2D(matInfoBuffer, 7); -float4 AL_VectorLightShadowCast( sampler2D sourceShadowMap, +uniform float lightBrightness; +uniform float3 lightDirection; + +uniform float4 lightColor; +uniform float4 lightAmbient; + +uniform float shadowSoftness; +uniform float3 eyePosWorld; + +uniform float4 atlasXOffset; +uniform float4 atlasYOffset; +uniform float4 zNearFarInvNearFar; +uniform float4 lightMapParams; +uniform float4 farPlaneScalePSSM; +uniform float4 overDarkPSSM; + +uniform float2 fadeStartLength; +uniform float2 atlasScale; + +uniform float4x4 eyeMat; + +// Static Shadows +uniform float4x4 worldToLightProj; +uniform float4 scaleX; +uniform float4 scaleY; +uniform float4 offsetX; +uniform float4 offsetY; +// Dynamic Shadows +uniform float4x4 dynamicWorldToLightProj; +uniform float4 dynamicScaleX; +uniform float4 dynamicScaleY; +uniform float4 dynamicOffsetX; +uniform float4 dynamicOffsetY; +uniform float4 dynamicFarPlaneScalePSSM; + +float4 AL_VectorLightShadowCast( TORQUE_SAMPLER2D(sourceShadowMap), float2 texCoord, float4x4 worldToLightProj, float4 worldPos, @@ -52,8 +92,7 @@ float4 AL_VectorLightShadowCast( sampler2D sourceShadowMap, float2 atlasScale, float shadowSoftness, float dotNL , - float4 overDarkPSSM -) + float4 overDarkPSSM) { // Compute shadow map coordinate float4 pxlPosLightProj = mul(worldToLightProj, worldPos); @@ -144,7 +183,7 @@ float4 AL_VectorLightShadowCast( sampler2D sourceShadowMap, distToLight *= farPlaneScale; return float4(debugColor, - softShadow_filter( sourceShadowMap, + softShadow_filter( TORQUE_SAMPLER2D_MAKEARG(sourceShadowMap), texCoord, shadowCoord, farPlaneScale * shadowSoftness, @@ -153,50 +192,10 @@ float4 AL_VectorLightShadowCast( sampler2D sourceShadowMap, dot( finalMask, overDarkPSSM ) ) ); }; -float4 main( FarFrustumQuadConnectP IN, - - uniform sampler2D prePassBuffer : register(S0), - - uniform sampler2D lightBuffer : register(S5), - uniform sampler2D colorBuffer : register(S6), - uniform sampler2D matInfoBuffer : register(S7), - - uniform float3 lightDirection, - uniform float4 lightColor, - uniform float lightBrightness, - uniform float4 lightAmbient, - uniform float4x4 eyeMat, - - uniform float3 eyePosWorld, - uniform float4 atlasXOffset, - uniform float4 atlasYOffset, - uniform float2 atlasScale, - uniform float4 zNearFarInvNearFar, - uniform float4 lightMapParams, - uniform float2 fadeStartLength, - uniform float4 overDarkPSSM, - uniform float shadowSoftness, - - // Static Shadows - uniform float4x4 worldToLightProj, - uniform float4 scaleX, - uniform float4 scaleY, - uniform float4 offsetX, - uniform float4 offsetY, - uniform float4 farPlaneScalePSSM, - - // Dynamic Shadows - uniform float4x4 dynamicWorldToLightProj, - uniform float4 dynamicScaleX, - uniform float4 dynamicScaleY, - uniform float4 dynamicOffsetX, - uniform float4 dynamicOffsetY, - uniform float4 dynamicFarPlaneScalePSSM - - ) : COLOR0 +float4 main( FarFrustumQuadConnectP IN ) : TORQUE_TARGET0 { // Emissive. - float4 matInfo = tex2D( matInfoBuffer, IN.uv0 ); + float4 matInfo = TORQUE_TEX2D( matInfoBuffer, IN.uv0 ); bool emissive = getFlag( matInfo.r, 0 ); if ( emissive ) { @@ -204,7 +203,7 @@ float4 main( FarFrustumQuadConnectP IN, } // Sample/unpack the normal/z data - float4 prepassSample = prepassUncondition( prePassBuffer, IN.uv0 ); + float4 prepassSample = TORQUE_PREPASS_UNCONDITION( prePassBuffer, IN.uv0 ); float3 normal = prepassSample.rgb; float depth = prepassSample.a; @@ -229,7 +228,7 @@ float4 main( FarFrustumQuadConnectP IN, #else - float4 static_shadowed_colors = AL_VectorLightShadowCast( shadowMap, + float4 static_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(shadowMap), IN.uv0.xy, worldToLightProj, worldPos, @@ -241,7 +240,7 @@ float4 main( FarFrustumQuadConnectP IN, shadowSoftness, dotNL, overDarkPSSM); - float4 dynamic_shadowed_colors = AL_VectorLightShadowCast( dynamicShadowMap, + float4 dynamic_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), IN.uv0.xy, dynamicWorldToLightProj, worldPos, @@ -307,7 +306,7 @@ float4 main( FarFrustumQuadConnectP IN, // Sample the AO texture. #ifdef USE_SSAO_MASK - float ao = 1.0 - tex2D( ssaoMask, viewportCoordToRenderTarget( IN.uv0.xy, rtParams3 ) ).r; + float ao = 1.0 - TORQUE_TEX2D( ssaoMask, viewportCoordToRenderTarget( IN.uv0.xy, rtParams3 ) ).r; addToResult *= ao; #endif @@ -315,6 +314,6 @@ float4 main( FarFrustumQuadConnectP IN, lightColorOut = debugColor; #endif - float4 colorSample = tex2D( colorBuffer, IN.uv0 ); + float4 colorSample = TORQUE_TEX2D( colorBuffer, IN.uv0 ); return AL_DeferredOutput(lightColorOut, colorSample.rgb, matInfo, addToResult, specular, Sat_NL_Att); } diff --git a/Templates/Full/game/shaders/common/lighting/basic/shadowFilterP.hlsl b/Templates/Full/game/shaders/common/lighting/basic/shadowFilterP.hlsl index f161fb5d3..b56aade8d 100644 --- a/Templates/Full/game/shaders/common/lighting/basic/shadowFilterP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/basic/shadowFilterP.hlsl @@ -22,11 +22,11 @@ #include "shaders/common/postFx/postFx.hlsl" -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv : TEXCOORD0; }; @@ -35,15 +35,15 @@ static float weight[3] = { 0.2270270270, 0.3162162162, 0.0702702703 }; uniform float2 oneOverTargetSize; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { - float4 OUT = tex2D( diffuseMap, IN.uv ) * weight[0]; + float4 OUT = TORQUE_TEX2D( diffuseMap, IN.uv ) * weight[0]; for ( int i=1; i < 3; i++ ) { float2 sample = (BLUR_DIR * offset[i]) * oneOverTargetSize; - OUT += tex2D( diffuseMap, IN.uv + sample ) * weight[i]; - OUT += tex2D( diffuseMap, IN.uv - sample ) * weight[i]; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv + sample ) * weight[i]; + OUT += TORQUE_TEX2D(diffuseMap, IN.uv - sample) * weight[i]; } return OUT; diff --git a/Templates/Full/game/shaders/common/lighting/basic/shadowFilterV.hlsl b/Templates/Full/game/shaders/common/lighting/basic/shadowFilterV.hlsl index bf6a36249..c89af7357 100644 --- a/Templates/Full/game/shaders/common/lighting/basic/shadowFilterV.hlsl +++ b/Templates/Full/game/shaders/common/lighting/basic/shadowFilterV.hlsl @@ -27,7 +27,7 @@ float4 rtParams0; struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv : TEXCOORD0; }; @@ -35,7 +35,7 @@ VertToPix main( PFXVert IN ) { VertToPix OUT; - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); OUT.uv = viewportCoordToRenderTarget( IN.uv, rtParams0 ); return OUT; diff --git a/Templates/Full/game/shaders/common/lighting/shadowMap/boxFilterP.hlsl b/Templates/Full/game/shaders/common/lighting/shadowMap/boxFilterP.hlsl index dd691de23..a187c3c63 100644 --- a/Templates/Full/game/shaders/common/lighting/shadowMap/boxFilterP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/shadowMap/boxFilterP.hlsl @@ -23,10 +23,12 @@ //***************************************************************************** // Box Filter //***************************************************************************** +#include "../ShaderModel.hlsl" struct ConnectData { - float2 tex0 : TEXCOORD0; + float4 hpos : TORQUE_POSITION; + float2 tex0 : TEXCOORD0; }; // If not defined from ShaderData then define @@ -40,12 +42,12 @@ float log_conv ( float x0, float X, float y0, float Y ) return (X + log(x0 + (y0 * exp(Y - X)))); } -float4 main( ConnectData IN, - uniform sampler2D diffuseMap0 : register(S0), - uniform float texSize : register(C0), - uniform float2 blurDimension : register(C2), - uniform float2 blurBoundaries : register(C3) - ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(diffuseMap0, 0); +uniform float texSize : register(C0); +uniform float2 blurDimension : register(C2); +uniform float2 blurBoundaries : register(C3); + +float4 main( ConnectData IN ) : TORQUE_TARGET0 { // 5x5 if (IN.tex0.x <= blurBoundaries.x) @@ -56,8 +58,8 @@ float4 main( ConnectData IN, float2 texCoord = IN.tex0; - float accum = log_conv(0.3125, tex2D(diffuseMap0, texCoord - sampleOffset), 0.375, tex2D(diffuseMap0, texCoord)); - accum = log_conv(1, accum, 0.3125, tex2D(diffuseMap0, texCoord + sampleOffset)); + float accum = log_conv(0.3125, TORQUE_TEX2D(diffuseMap0, texCoord - sampleOffset), 0.375, tex2D(diffuseMap0, texCoord)); + accum = log_conv(1, accum, 0.3125, TORQUE_TEX2D(diffuseMap0, texCoord + sampleOffset)); return accum; } else { @@ -73,7 +75,7 @@ float4 main( ConnectData IN, return accum; } else { - return tex2D(diffuseMap0, IN.tex0); + return TORQUE_TEX2D(diffuseMap0, IN.tex0); } } } diff --git a/Templates/Full/game/shaders/common/lighting/shadowMap/boxFilterV.hlsl b/Templates/Full/game/shaders/common/lighting/shadowMap/boxFilterV.hlsl index 75d9af000..3679e41bb 100644 --- a/Templates/Full/game/shaders/common/lighting/shadowMap/boxFilterV.hlsl +++ b/Templates/Full/game/shaders/common/lighting/shadowMap/boxFilterV.hlsl @@ -26,15 +26,18 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- + +#include "../ShaderModel.hlsl" + struct VertData { - float2 texCoord : TEXCOORD0; - float4 position : POSITION; + float3 position : POSITION; + float2 texCoord : TEXCOORD0; }; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 tex0 : TEXCOORD0; }; @@ -47,7 +50,7 @@ ConnectData main( VertData IN, { ConnectData OUT; - OUT.hpos = mul(modelview, IN.position); + OUT.hpos = mul(modelview, float4(IN.position,1.0)); OUT.tex0 = IN.texCoord; return OUT; diff --git a/Templates/Full/game/shaders/common/particleCompositeP.hlsl b/Templates/Full/game/shaders/common/particleCompositeP.hlsl index 35c2cb4c5..6e26ddbdb 100644 --- a/Templates/Full/game/shaders/common/particleCompositeP.hlsl +++ b/Templates/Full/game/shaders/common/particleCompositeP.hlsl @@ -20,22 +20,30 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "torque.hlsl" +#include "shaderModel.hlsl" -uniform sampler2D colorSource : register(S0); +TORQUE_UNIFORM_SAMPLER2D(colorSource, 0); uniform float4 offscreenTargetParams; #ifdef TORQUE_LINEAR_DEPTH #define REJECT_EDGES -uniform sampler2D edgeSource : register(S1); +TORQUE_UNIFORM_SAMPLER2D(edgeSource, 1); uniform float4 edgeTargetParams; #endif +struct Conn +{ + float4 hpos : TORQUE_POSITION; + float4 offscreenPos : TEXCOORD0; + float4 backbufferPos : TEXCOORD1; +}; -float4 main( float4 offscreenPos : TEXCOORD0, float4 backbufferPos : TEXCOORD1 ) : COLOR + +float4 main(Conn IN) : TORQUE_TARGET0 { // Off-screen particle source screenspace position in XY // Back-buffer screenspace position in ZW - float4 ssPos = float4(offscreenPos.xy / offscreenPos.w, backbufferPos.xy / backbufferPos.w); + float4 ssPos = float4(IN.offscreenPos.xy / IN.offscreenPos.w, IN.backbufferPos.xy / IN.backbufferPos.w); float4 uvScene = ( ssPos + 1.0 ) / 2.0; uvScene.yw = 1.0 - uvScene.yw; @@ -44,10 +52,10 @@ float4 main( float4 offscreenPos : TEXCOORD0, float4 backbufferPos : TEXCOORD1 ) #ifdef REJECT_EDGES // Cut out particles along the edges, this will create the stencil mask uvScene.zw = viewportCoordToRenderTarget(uvScene.zw, edgeTargetParams); - float edge = tex2D( edgeSource, uvScene.zw ).r; + float edge = TORQUE_TEX2D( edgeSource, uvScene.zw ).r; clip( -edge ); #endif // Sample offscreen target and return - return tex2D( colorSource, uvScene.xy ); + return TORQUE_TEX2D( colorSource, uvScene.xy ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/particleCompositeV.hlsl b/Templates/Full/game/shaders/common/particleCompositeV.hlsl index 87fac0d94..c4c51204a 100644 --- a/Templates/Full/game/shaders/common/particleCompositeV.hlsl +++ b/Templates/Full/game/shaders/common/particleCompositeV.hlsl @@ -20,22 +20,28 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "hlslStructs.h" +#include "shaderModel.hlsl" -struct VertOut +struct Vertex { - float4 hpos : POSITION; + float3 pos : POSITION; + float4 uvCoord : COLOR0; +}; + +struct Conn +{ + float4 hpos : TORQUE_POSITION; float4 offscreenPos : TEXCOORD0; float4 backbufferPos : TEXCOORD1; }; uniform float4 screenRect; // point, extent -VertOut main( float4 uvCoord : COLOR ) +Conn main(Vertex IN) { - VertOut OUT; + Conn OUT; - OUT.hpos = float4(uvCoord.xy, 1.0, 1.0); + OUT.hpos = float4(IN.uvCoord.xy, 1.0, 1.0); OUT.hpos.xy *= screenRect.zw; OUT.hpos.xy += screenRect.xy; diff --git a/Templates/Full/game/shaders/common/particlesP.hlsl b/Templates/Full/game/shaders/common/particlesP.hlsl index 80e3c7105..37439c59a 100644 --- a/Templates/Full/game/shaders/common/particlesP.hlsl +++ b/Templates/Full/game/shaders/common/particlesP.hlsl @@ -21,7 +21,7 @@ //----------------------------------------------------------------------------- #include "torque.hlsl" - +#include "shaderModel.hlsl" // With advanced lighting we get soft particles. #ifdef TORQUE_LINEAR_DEPTH #define SOFTPARTICLES @@ -29,11 +29,11 @@ #ifdef SOFTPARTICLES - #include "shadergen:/autogenConditioners.h" + #include "shaderModelAutoGen.hlsl" uniform float oneOverSoftness; uniform float oneOverFar; - uniform sampler2D prepassTex : register(S1); + TORQUE_UNIFORM_SAMPLER2D(prepassTex, 1); //uniform float3 vEye; uniform float4 prePassTargetParams; #endif @@ -42,14 +42,14 @@ struct Conn { + float4 hpos : TORQUE_POSITION; float4 color : TEXCOORD0; float2 uv0 : TEXCOORD1; - float4 pos : TEXCOORD2; + float4 pos : TEXCOORD2; }; -uniform sampler2D diffuseMap : register(S0); - -uniform sampler2D paraboloidLightMap : register(S2); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); +TORQUE_UNIFORM_SAMPLER2D(paraboloidLightMap, 2); float4 lmSample( float3 nrm ) { @@ -69,14 +69,14 @@ float4 lmSample( float3 nrm ) // Atlasing front and back maps, so scale lmCoord.x *= 0.5; - return tex2D(paraboloidLightMap, lmCoord); + return TORQUE_TEX2D(paraboloidLightMap, lmCoord); } uniform float alphaFactor; uniform float alphaScale; -float4 main( Conn IN ) : COLOR +float4 main( Conn IN ) : TORQUE_TARGET0 { float softBlend = 1; @@ -84,7 +84,7 @@ float4 main( Conn IN ) : COLOR float2 tc = IN.pos.xy * float2(1.0, -1.0) / IN.pos.w; tc = viewportCoordToRenderTarget(saturate( ( tc + 1.0 ) * 0.5 ), prePassTargetParams); - float sceneDepth = prepassUncondition( prepassTex, tc ).w; + float sceneDepth = TORQUE_PREPASS_UNCONDITION(prepassTex, tc).w; float depth = IN.pos.w * oneOverFar; float diff = sceneDepth - depth; #ifdef CLIP_Z @@ -96,7 +96,7 @@ float4 main( Conn IN ) : COLOR softBlend = saturate( diff * oneOverSoftness ); #endif - float4 diffuse = tex2D( diffuseMap, IN.uv0 ); + float4 diffuse = TORQUE_TEX2D( diffuseMap, IN.uv0 ); //return float4( lmSample(float3(0, 0, -1)).rgb, IN.color.a * diffuse.a * softBlend * alphaScale); diff --git a/Templates/Full/game/shaders/common/particlesV.hlsl b/Templates/Full/game/shaders/common/particlesV.hlsl index f09604237..dbeff0cc2 100644 --- a/Templates/Full/game/shaders/common/particlesV.hlsl +++ b/Templates/Full/game/shaders/common/particlesV.hlsl @@ -20,16 +20,18 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "shaderModel.hlsl" + struct Vertex { - float4 pos : POSITION; + float3 pos : POSITION; float4 color : COLOR0; float2 uv0 : TEXCOORD0; }; struct Conn { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 color : TEXCOORD0; float2 uv0 : TEXCOORD1; float4 pos : TEXCOORD2; @@ -43,8 +45,8 @@ Conn main( Vertex In ) { Conn Out; - Out.hpos = mul( modelViewProj, In.pos ); - Out.pos = mul( fsModelViewProj, In.pos ); + Out.hpos = mul( modelViewProj, float4(In.pos,1.0) ); + Out.pos = mul(fsModelViewProj, float4(In.pos, 1.0) ); Out.color = In.color; Out.uv0 = In.uv0; diff --git a/Templates/Full/game/shaders/common/planarReflectBumpP.hlsl b/Templates/Full/game/shaders/common/planarReflectBumpP.hlsl index a5057db50..d18331fb6 100644 --- a/Templates/Full/game/shaders/common/planarReflectBumpP.hlsl +++ b/Templates/Full/game/shaders/common/planarReflectBumpP.hlsl @@ -23,18 +23,26 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- + +#include "shaderModel.hlsl" + struct ConnectData { - float4 texCoord : TEXCOORD0; - float2 tex2 : TEXCOORD1; + float4 hpos : TORQUE_POSITION; + float2 texCoord : TEXCOORD0; + float4 tex2 : TEXCOORD1; }; struct Fragout { - float4 col : COLOR0; + float4 col : TORQUE_TARGET0; }; +TORQUE_UNIFORM_SAMPLER2D(texMap, 0); +TORQUE_UNIFORM_SAMPLER2D(refractMap, 1); +TORQUE_UNIFORM_SAMPLER2D(bumpMap, 2); + //----------------------------------------------------------------------------- // Fade edges of axis for texcoord passed in @@ -54,15 +62,11 @@ float fadeAxis( float val ) //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main( ConnectData IN, - uniform sampler2D refractMap : register(S1), - uniform sampler2D texMap : register(S0), - uniform sampler2D bumpMap : register(S2) -) +Fragout main( ConnectData IN ) { Fragout OUT; - float3 bumpNorm = tex2D( bumpMap, IN.tex2 ) * 2.0 - 1.0; + float3 bumpNorm = TORQUE_TEX2D( bumpMap, IN.tex2 ) * 2.0 - 1.0; float2 offset = float2( bumpNorm.x, bumpNorm.y ); float4 texIndex = IN.texCoord; @@ -74,8 +78,8 @@ Fragout main( ConnectData IN, const float distortion = 0.2; texIndex.xy += offset * distortion * fadeVal; - float4 reflectColor = tex2Dproj( refractMap, texIndex ); - float4 diffuseColor = tex2D( texMap, IN.tex2 ); + float4 reflectColor = TORQUE_TEX2DPROJ( refractMap, texIndex ); + float4 diffuseColor = TORQUE_TEX2D( texMap, IN.tex2 ); OUT.col = diffuseColor + reflectColor * diffuseColor.a; diff --git a/Templates/Full/game/shaders/common/planarReflectBumpV.hlsl b/Templates/Full/game/shaders/common/planarReflectBumpV.hlsl index 108f918ce..d45adb574 100644 --- a/Templates/Full/game/shaders/common/planarReflectBumpV.hlsl +++ b/Templates/Full/game/shaders/common/planarReflectBumpV.hlsl @@ -22,36 +22,37 @@ #define IN_HLSL #include "shdrConsts.h" +#include "shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- struct VertData { + float3 position : POSITION; + float3 normal : NORMAL; float2 texCoord : TEXCOORD0; float2 lmCoord : TEXCOORD1; float3 T : TEXCOORD2; - float3 B : TEXCOORD3; - float3 normal : NORMAL; - float4 position : POSITION; + float3 B : TEXCOORD3; }; struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoord : TEXCOORD0; float2 tex2 : TEXCOORD1; }; +uniform float4x4 modelview; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -ConnectData main( VertData IN, - uniform float4x4 modelview ) +ConnectData main( VertData IN ) { ConnectData OUT; - OUT.hpos = mul(modelview, IN.position); + OUT.hpos = mul(modelview, float4(IN.position,1.0)); float4x4 texGenTest = { 0.5, 0.0, 0.0, 0.5, 0.0, -0.5, 0.0, 0.5, diff --git a/Templates/Full/game/shaders/common/planarReflectP.hlsl b/Templates/Full/game/shaders/common/planarReflectP.hlsl index 981cc316d..43b420544 100644 --- a/Templates/Full/game/shaders/common/planarReflectP.hlsl +++ b/Templates/Full/game/shaders/common/planarReflectP.hlsl @@ -23,31 +23,34 @@ //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- + +#include "shaderModel.hlsl" + struct ConnectData { - float2 texCoord : TEXCOORD0; - float4 tex2 : TEXCOORD1; + float4 hpos : TORQUE_POSITION; + float2 texCoord : TEXCOORD0; + float4 tex2 : TEXCOORD1; }; struct Fragout { - float4 col : COLOR0; + float4 col : TORQUE_TARGET0; }; +TORQUE_UNIFORM_SAMPLER2D(texMap, 0); +TORQUE_UNIFORM_SAMPLER2D(refractMap, 1); //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main( ConnectData IN, - uniform sampler2D texMap : register(S0), - uniform sampler2D refractMap : register(S1) -) +Fragout main( ConnectData IN ) { Fragout OUT; - float4 diffuseColor = tex2D( texMap, IN.texCoord ); - float4 reflectColor = tex2Dproj( refractMap, IN.tex2 ); + float4 diffuseColor = TORQUE_TEX2D( texMap, IN.texCoord ); + float4 reflectColor = TORQUE_TEX2DPROJ(refractMap, IN.tex2); OUT.col = diffuseColor + reflectColor * diffuseColor.a; diff --git a/Templates/Full/game/shaders/common/planarReflectV.hlsl b/Templates/Full/game/shaders/common/planarReflectV.hlsl index cd8cb2d96..1f2ca9d4f 100644 --- a/Templates/Full/game/shaders/common/planarReflectV.hlsl +++ b/Templates/Full/game/shaders/common/planarReflectV.hlsl @@ -21,7 +21,8 @@ //----------------------------------------------------------------------------- #define IN_HLSL -#include "hlslStructs.h" +#include "hlslStructs.hlsl" +#include "shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures @@ -29,20 +30,20 @@ struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 texCoord : TEXCOORD0; float4 tex2 : TEXCOORD1; }; +uniform float4x4 modelview; + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -ConnectData main( VertexIn_PNTTTB IN, - uniform float4x4 modelview : register(C0) -) +ConnectData main( VertexIn_PNTTTB IN ) { ConnectData OUT; - OUT.hpos = mul(modelview, IN.pos); + OUT.hpos = mul(modelview, float4(IN.pos,1.0)); float4x4 texGenTest = { 0.5, 0.0, 0.0, 0.5, 0.0, -0.5, 0.0, 0.5, diff --git a/Templates/Full/game/shaders/common/postFx/VolFogGlowP.hlsl b/Templates/Full/game/shaders/common/postFx/VolFogGlowP.hlsl index 8a61b5928..c3adb3b55 100644 --- a/Templates/Full/game/shaders/common/postFx/VolFogGlowP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/VolFogGlowP.hlsl @@ -32,12 +32,12 @@ #include "./postFx.hlsl" -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); uniform float strength; struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -50,20 +50,20 @@ struct VertToPix float2 uv7 : TEXCOORD7; }; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { float4 kernel = float4( 0.175, 0.275, 0.375, 0.475 ) * strength; float4 OUT = 0; - OUT += tex2D( diffuseMap, IN.uv0 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv1 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv2 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv3 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv0 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv1 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv2 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv3 ) * kernel.w; - OUT += tex2D( diffuseMap, IN.uv4 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv5 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv6 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv7 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv4 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv5 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv6 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv7 ) * kernel.w; // Calculate a lumenance value in the alpha so we // can use alpha test to save fillrate. diff --git a/Templates/Full/game/shaders/common/postFx/caustics/causticsP.hlsl b/Templates/Full/game/shaders/common/postFx/caustics/causticsP.hlsl index c7635027d..d2f4a058a 100644 --- a/Templates/Full/game/shaders/common/postFx/caustics/causticsP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/caustics/causticsP.hlsl @@ -21,25 +21,26 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" +uniform float accumTime; uniform float3 eyePosWorld; uniform float4 rtParams0; uniform float4 waterFogPlane; -uniform float accumTime; + +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); +TORQUE_UNIFORM_SAMPLER2D(causticsTex0, 1); +TORQUE_UNIFORM_SAMPLER2D(causticsTex1, 2); float distanceToPlane(float4 plane, float3 pos) { return (plane.x * pos.x + plane.y * pos.y + plane.z * pos.z) + plane.w; } -float4 main( PFXVertToPix IN, - uniform sampler2D prepassTex :register(S0), - uniform sampler2D causticsTex0 :register(S1), - uniform sampler2D causticsTex1 :register(S2) ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { //Sample the pre-pass - float4 prePass = prepassUncondition( prepassTex, IN.uv0 ); + float4 prePass = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ); //Get depth float depth = prePass.w; @@ -65,12 +66,12 @@ float4 main( PFXVertToPix IN, causticsUV1.xy -= float2(accumTime*0.15, timeSin*0.15); //Sample caustics texture - float4 caustics = tex2D(causticsTex0, causticsUV0); - caustics *= tex2D(causticsTex1, causticsUV1); + float4 caustics = TORQUE_TEX2D(causticsTex0, causticsUV0); + caustics *= TORQUE_TEX2D(causticsTex1, causticsUV1); //Use normal Z to modulate caustics //float waterDepth = 1 - saturate(pos.z + waterFogPlane.w + 1); - caustics *= saturate(prePass.z) * pow(1-depth, 64) * waterDepth; + caustics *= saturate(prePass.z) * pow(abs(1-depth), 64) * waterDepth; return caustics; } diff --git a/Templates/Full/game/shaders/common/postFx/chromaticLens.hlsl b/Templates/Full/game/shaders/common/postFx/chromaticLens.hlsl index 5916e985a..8fdca72b7 100644 --- a/Templates/Full/game/shaders/common/postFx/chromaticLens.hlsl +++ b/Templates/Full/game/shaders/common/postFx/chromaticLens.hlsl @@ -26,14 +26,13 @@ #include "./postFx.hlsl" #include "./../torque.hlsl" - -uniform sampler2D backBuffer : register( s0 ); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); uniform float distCoeff; uniform float cubeDistort; uniform float3 colorDistort; -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float2 tex = IN.uv0; @@ -54,7 +53,7 @@ float4 main( PFXVertToPix IN ) : COLOR0 { float x = distort[i] * ( tex.x - 0.5 ) + 0.5; float y = distort[i] * ( tex.y - 0.5 ) + 0.5; - outColor[i] = tex2Dlod( backBuffer, float4(x,y,0,0) )[i]; + outColor[i] = TORQUE_TEX2DLOD( backBuffer, float4(x,y,0,0) )[i]; } return float4( outColor.rgb, 1 ); diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl index bc17a2c04..2f5835fc2 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_CalcCoC_P.hlsl @@ -23,21 +23,22 @@ #include "./../postFx.hlsl" // These are set by the game engine. -uniform sampler2D shrunkSampler : register(S0); // Output of DofDownsample() -uniform sampler2D blurredSampler : register(S1); // Blurred version of the shrunk sampler +TORQUE_UNIFORM_SAMPLER2D(shrunkSampler, 0); // Output of DofDownsample() +TORQUE_UNIFORM_SAMPLER2D(blurredSampler, 1); // Blurred version of the shrunk sampler + // This is the pixel shader function that calculates the actual // value used for the near circle of confusion. // "texCoords" are 0 at the bottom left pixel and 1 at the top right. -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float3 color; float coc; half4 blurred; half4 shrunk; - shrunk = tex2D( shrunkSampler, IN.uv0 ); - blurred = tex2D( blurredSampler, IN.uv1 ); + shrunk = half4(TORQUE_TEX2D( shrunkSampler, IN.uv0 )); + blurred = half4(TORQUE_TEX2D( blurredSampler, IN.uv1 )); color = shrunk.rgb; //coc = shrunk.a; //coc = blurred.a; diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl index 40cec49de..8131e45cd 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_CalcCoC_V.hlsl @@ -57,7 +57,7 @@ PFXVertToPix main( PFXVert IN ) */ - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); OUT.uv0 = viewportCoordToRenderTarget( IN.uv, rtParams0 ); OUT.uv1 = viewportCoordToRenderTarget( IN.uv, rtParams1 ); OUT.uv2 = viewportCoordToRenderTarget( IN.uv, rtParams2 ); diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_DownSample_P.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_DownSample_P.hlsl index 37e591f25..8c9028654 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_DownSample_P.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_DownSample_P.hlsl @@ -20,22 +20,23 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModel.hlsl" +#include "../../shaderModelAutoGen.hlsl" // These are set by the game engine. // The render target size is one-quarter the scene rendering size. -uniform sampler2D colorSampler : register(S0); -uniform sampler2D depthSampler : register(S1); -uniform float2 dofEqWorld; -uniform float depthOffset; +TORQUE_UNIFORM_SAMPLER2D(colorSampler, 0); +TORQUE_UNIFORM_SAMPLER2D(depthSampler, 1); +uniform float2 dofEqWorld; uniform float2 targetSize; +uniform float depthOffset; uniform float maxWorldCoC; //uniform float2 dofEqWeapon; //uniform float2 dofRowDelta; // float2( 0, 0.25 / renderTargetHeight ) struct Pixel { - float4 position : POSITION; + float4 position : TORQUE_POSITION; float2 tcColor0 : TEXCOORD0; float2 tcColor1 : TEXCOORD1; float2 tcDepth0 : TEXCOORD2; @@ -44,7 +45,7 @@ struct Pixel float2 tcDepth3 : TEXCOORD5; }; -half4 main( Pixel IN ) : COLOR +half4 main( Pixel IN ) : TORQUE_TARGET0 { //return float4( 1.0, 0.0, 1.0, 1.0 ); @@ -69,57 +70,64 @@ half4 main( Pixel IN ) : COLOR // Use bilinear filtering to average 4 color samples for free. color = 0; - color += tex2D( colorSampler, IN.tcColor0.xy + rowOfs[0] ).rgb; - color += tex2D( colorSampler, IN.tcColor1.xy + rowOfs[0] ).rgb; - color += tex2D( colorSampler, IN.tcColor0.xy + rowOfs[2] ).rgb; - color += tex2D( colorSampler, IN.tcColor1.xy + rowOfs[2] ).rgb; + color += half3(TORQUE_TEX2D( colorSampler, IN.tcColor0.xy + rowOfs[0] ).rgb); + color += half3(TORQUE_TEX2D(colorSampler, IN.tcColor1.xy + rowOfs[0]).rgb); + color += half3(TORQUE_TEX2D(colorSampler, IN.tcColor0.xy + rowOfs[2]).rgb); + color += half3(TORQUE_TEX2D(colorSampler, IN.tcColor1.xy + rowOfs[2]).rgb); color /= 4; + //declare thse here to save doing it in each loop below + half4 zero4 = half4(0, 0, 0, 0); + coc = zero4; + half4 dofEqWorld4X = half4(dofEqWorld.xxxx); + half4 dofEqWorld4Y = half4(dofEqWorld.yyyy); + half4 maxWorldCoC4 = half4(maxWorldCoC, maxWorldCoC, maxWorldCoC, maxWorldCoC); // Process 4 samples at a time to use vector hardware efficiently. // The CoC will be 1 if the depth is negative, so use "min" to pick - // between "sceneCoc" and "viewCoc". - - for ( int i = 0; i < 4; i++ ) + // between "sceneCoc" and "viewCoc". + [unroll] // coc[i] causes this anyway + for (int i = 0; i < 4; i++) { - depth[0] = prepassUncondition( depthSampler, float4( IN.tcDepth0.xy + rowOfs[i], 0, 0 ) ).w; - depth[1] = prepassUncondition( depthSampler, float4( IN.tcDepth1.xy + rowOfs[i], 0, 0 ) ).w; - depth[2] = prepassUncondition( depthSampler, float4( IN.tcDepth2.xy + rowOfs[i], 0, 0 ) ).w; - depth[3] = prepassUncondition( depthSampler, float4( IN.tcDepth3.xy + rowOfs[i], 0, 0 ) ).w; - coc[i] = clamp( dofEqWorld.x * depth + dofEqWorld.y, 0.0, maxWorldCoC ); - } + depth[0] = TORQUE_PREPASS_UNCONDITION(depthSampler, (IN.tcDepth0.xy + rowOfs[i])).w; + depth[1] = TORQUE_PREPASS_UNCONDITION(depthSampler, (IN.tcDepth1.xy + rowOfs[i])).w; + depth[2] = TORQUE_PREPASS_UNCONDITION(depthSampler, (IN.tcDepth2.xy + rowOfs[i])).w; + depth[3] = TORQUE_PREPASS_UNCONDITION(depthSampler, (IN.tcDepth3.xy + rowOfs[i])).w; + + coc = max(coc, clamp(dofEqWorld4X * half4(depth)+dofEqWorld4Y, zero4, maxWorldCoC4)); + } /* - depth[0] = tex2D( depthSampler, pixel.tcDepth0.xy + rowOfs[0] ).r; - depth[1] = tex2D( depthSampler, pixel.tcDepth1.xy + rowOfs[0] ).r; - depth[2] = tex2D( depthSampler, pixel.tcDepth2.xy + rowOfs[0] ).r; - depth[3] = tex2D( depthSampler, pixel.tcDepth3.xy + rowOfs[0] ).r; + depth[0] = TORQUE_TEX2D( depthSampler, pixel.tcDepth0.xy + rowOfs[0] ).r; + depth[1] = TORQUE_TEX2D( depthSampler, pixel.tcDepth1.xy + rowOfs[0] ).r; + depth[2] = TORQUE_TEX2D( depthSampler, pixel.tcDepth2.xy + rowOfs[0] ).r; + depth[3] = TORQUE_TEX2D( depthSampler, pixel.tcDepth3.xy + rowOfs[0] ).r; viewCoc = saturate( dofEqWeapon.x * -depth + dofEqWeapon.y ); sceneCoc = saturate( dofEqWorld.x * depth + dofEqWorld.y ); curCoc = min( viewCoc, sceneCoc ); coc = curCoc; - depth[0] = tex2D( depthSampler, pixel.tcDepth0.xy + rowOfs[1] ).r; - depth[1] = tex2D( depthSampler, pixel.tcDepth1.xy + rowOfs[1] ).r; - depth[2] = tex2D( depthSampler, pixel.tcDepth2.xy + rowOfs[1] ).r; - depth[3] = tex2D( depthSampler, pixel.tcDepth3.xy + rowOfs[1] ).r; + depth[0] = TORQUE_TEX2D( depthSampler, pixel.tcDepth0.xy + rowOfs[1] ).r; + depth[1] = TORQUE_TEX2D( depthSampler, pixel.tcDepth1.xy + rowOfs[1] ).r; + depth[2] = TORQUE_TEX2D( depthSampler, pixel.tcDepth2.xy + rowOfs[1] ).r; + depth[3] = TORQUE_TEX2D( depthSampler, pixel.tcDepth3.xy + rowOfs[1] ).r; viewCoc = saturate( dofEqWeapon.x * -depth + dofEqWeapon.y ); sceneCoc = saturate( dofEqWorld.x * depth + dofEqWorld.y ); curCoc = min( viewCoc, sceneCoc ); coc = max( coc, curCoc ); - depth[0] = tex2D( depthSampler, pixel.tcDepth0.xy + rowOfs[2] ).r; - depth[1] = tex2D( depthSampler, pixel.tcDepth1.xy + rowOfs[2] ).r; - depth[2] = tex2D( depthSampler, pixel.tcDepth2.xy + rowOfs[2] ).r; - depth[3] = tex2D( depthSampler, pixel.tcDepth3.xy + rowOfs[2] ).r; + depth[0] = TORQUE_TEX2D( depthSampler, pixel.tcDepth0.xy + rowOfs[2] ).r; + depth[1] = TORQUE_TEX2D( depthSampler, pixel.tcDepth1.xy + rowOfs[2] ).r; + depth[2] = TORQUE_TEX2D( depthSampler, pixel.tcDepth2.xy + rowOfs[2] ).r; + depth[3] = TORQUE_TEX2D( depthSampler, pixel.tcDepth3.xy + rowOfs[2] ).r; viewCoc = saturate( dofEqWeapon.x * -depth + dofEqWeapon.y ); sceneCoc = saturate( dofEqWorld.x * depth + dofEqWorld.y ); curCoc = min( viewCoc, sceneCoc ); coc = max( coc, curCoc ); - depth[0] = tex2D( depthSampler, pixel.tcDepth0.xy + rowOfs[3] ).r; - depth[1] = tex2D( depthSampler, pixel.tcDepth1.xy + rowOfs[3] ).r; - depth[2] = tex2D( depthSampler, pixel.tcDepth2.xy + rowOfs[3] ).r; - depth[3] = tex2D( depthSampler, pixel.tcDepth3.xy + rowOfs[3] ).r; + depth[0] = TORQUE_TEX2D( depthSampler, pixel.tcDepth0.xy + rowOfs[3] ).r; + depth[1] = TORQUE_TEX2D( depthSampler, pixel.tcDepth1.xy + rowOfs[3] ).r; + depth[2] = TORQUE_TEX2D( depthSampler, pixel.tcDepth2.xy + rowOfs[3] ).r; + depth[3] = TORQUE_TEX2D( depthSampler, pixel.tcDepth3.xy + rowOfs[3] ).r; viewCoc = saturate( dofEqWeapon.x * -depth + dofEqWeapon.y ); sceneCoc = saturate( dofEqWorld.x * depth + dofEqWorld.y ); curCoc = min( viewCoc, sceneCoc ); diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_DownSample_V.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_DownSample_V.hlsl index da2a79fb4..0b3ec01e2 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_DownSample_V.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_DownSample_V.hlsl @@ -25,14 +25,14 @@ struct Vert { - float4 pos : POSITION; + float3 pos : POSITION; float2 tc : TEXCOORD0; float3 wsEyeRay : TEXCOORD1; }; struct Pixel { - float4 position : POSITION; + float4 position : TORQUE_POSITION; float2 tcColor0 : TEXCOORD0; float2 tcColor1 : TEXCOORD1; float2 tcDepth0 : TEXCOORD2; @@ -47,7 +47,7 @@ uniform float2 oneOverTargetSize; Pixel main( Vert IN ) { Pixel OUT; - OUT.position = IN.pos; + OUT.position = float4(IN.pos,1.0); float2 uv = viewportCoordToRenderTarget( IN.tc, rtParams0 ); //OUT.position = mul( IN.pos, modelView ); diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_Final_P.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_Final_P.hlsl index 36622495c..cb7342d40 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_Final_P.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_Final_P.hlsl @@ -20,13 +20,14 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "./../postFx.hlsl" -uniform sampler2D colorSampler : register(S0); // Original source image -uniform sampler2D smallBlurSampler : register(S1); // Output of SmallBlurPS() -uniform sampler2D largeBlurSampler : register(S2); // Blurred output of DofDownsample() -uniform sampler2D depthSampler : register(S3); // +TORQUE_UNIFORM_SAMPLER2D(colorSampler,0); // Original source image +TORQUE_UNIFORM_SAMPLER2D(smallBlurSampler,1); // Output of SmallBlurPS() +TORQUE_UNIFORM_SAMPLER2D(largeBlurSampler,2); // Blurred output of DofDownsample() +TORQUE_UNIFORM_SAMPLER2D(depthSampler,3); + uniform float2 oneOverTargetSize; uniform float4 dofLerpScale; uniform float4 dofLerpBias; @@ -40,9 +41,9 @@ uniform float maxFarCoC; //static float4 dofLerpBias = float4( 1.0, (1.0 - d2) / d1, 1.0 / d2, (d2 - 1.0) / d2 ); //static float3 dofEqFar = float3( 2.0, 0.0, 1.0 ); -float4 tex2Doffset( sampler2D s, float2 tc, float2 offset ) +float4 tex2Doffset(TORQUE_SAMPLER2D(s), float2 tc, float2 offset) { - return tex2D( s, tc + offset * oneOverTargetSize ); + return TORQUE_TEX2D( s, tc + offset * oneOverTargetSize ); } half3 GetSmallBlurSample( float2 tc ) @@ -51,10 +52,10 @@ half3 GetSmallBlurSample( float2 tc ) const half weight = 4.0 / 17; sum = 0; // Unblurred sample done by alpha blending //sum += weight * tex2Doffset( colorSampler, tc, float2( 0, 0 ) ).rgb; - sum += weight * tex2Doffset( colorSampler, tc, float2( +0.5, -1.5 ) ).rgb; - sum += weight * tex2Doffset( colorSampler, tc, float2( -1.5, -0.5 ) ).rgb; - sum += weight * tex2Doffset( colorSampler, tc, float2( -0.5, +1.5 ) ).rgb; - sum += weight * tex2Doffset( colorSampler, tc, float2( +1.5, +0.5 ) ).rgb; + sum += weight * half3(tex2Doffset(TORQUE_SAMPLER2D_MAKEARG(colorSampler), tc, float2(+0.5, -1.5)).rgb); + sum += weight * half3(tex2Doffset(TORQUE_SAMPLER2D_MAKEARG(colorSampler), tc, float2(-1.5, -0.5)).rgb); + sum += weight * half3(tex2Doffset(TORQUE_SAMPLER2D_MAKEARG(colorSampler), tc, float2(-0.5, +1.5)).rgb); + sum += weight * half3(tex2Doffset(TORQUE_SAMPLER2D_MAKEARG(colorSampler), tc, float2(+1.5, +0.5)).rgb); return sum; } @@ -72,7 +73,7 @@ half4 InterpolateDof( half3 small, half3 med, half3 large, half t ) //float4 dofLerpScale = float4( -1 / d0, -1 / d1, -1 / d2, 1 / d2 ); //float4 dofLerpBias = float4( 1, (1 – d2) / d1, 1 / d2, (d2 – 1) / d2 ); - weights = saturate( t * dofLerpScale + dofLerpBias ); + weights = half4(saturate( t * dofLerpScale + dofLerpBias )); weights.yz = min( weights.yz, 1 - weights.xy ); // Unblurred sample with weight "weights.x" done by alpha blending @@ -84,11 +85,11 @@ half4 InterpolateDof( half3 small, half3 med, half3 large, half t ) return half4( color, alpha ); } -half4 main( PFXVertToPix IN ) : COLOR +half4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { //return half4( 1,0,1,1 ); - //return half4( tex2D( colorSampler, IN.uv0 ).rgb, 1.0 ); - //return half4( tex2D( colorSampler, texCoords ).rgb, 0 ); + //return half4( TORQUE_TEX2D( colorSampler, IN.uv0 ).rgb, 1.0 ); + //return half4( TORQUE_TEX2D( colorSampler, texCoords ).rgb, 0 ); half3 small; half4 med; half3 large; @@ -100,10 +101,10 @@ half4 main( PFXVertToPix IN ) : COLOR small = GetSmallBlurSample( IN.uv0 ); //small = half3( 1,0,0 ); //return half4( small, 1.0 ); - med = tex2D( smallBlurSampler, IN.uv1 ); + med = half4(TORQUE_TEX2D( smallBlurSampler, IN.uv1 )); //med.rgb = half3( 0,1,0 ); //return half4(med.rgb, 0.0); - large = tex2D( largeBlurSampler, IN.uv2 ).rgb; + large = half3(TORQUE_TEX2D(largeBlurSampler, IN.uv2).rgb); //large = half3( 0,0,1 ); //return large; //return half4(large.rgb,1.0); @@ -114,7 +115,7 @@ half4 main( PFXVertToPix IN ) : COLOR //med.rgb = large; //nearCoc = 0; - depth = prepassUncondition( depthSampler, float4( IN.uv3, 0, 0 ) ).w; + depth = half(TORQUE_PREPASS_UNCONDITION( depthSampler, IN.uv3 ).w); //return half4(depth.rrr,1); //return half4(nearCoc.rrr,1.0); @@ -128,8 +129,8 @@ half4 main( PFXVertToPix IN ) : COLOR // dofEqFar.x and dofEqFar.y specify the linear ramp to convert // to depth for the distant out-of-focus region. // dofEqFar.z is the ratio of the far to the near blur radius. - farCoc = clamp( dofEqFar.x * depth + dofEqFar.y, 0.0, maxFarCoC ); - coc = max( nearCoc, farCoc * dofEqFar.z ); + farCoc = half(clamp( dofEqFar.x * depth + dofEqFar.y, 0.0, maxFarCoC )); + coc = half(max( nearCoc, farCoc * dofEqFar.z )); //coc = nearCoc; } diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_Final_V.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_Final_V.hlsl index 91dfba0a2..86c93701a 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_Final_V.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_Final_V.hlsl @@ -59,7 +59,7 @@ PFXVertToPix main( PFXVert IN ) */ - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); OUT.uv0 = viewportCoordToRenderTarget( IN.uv, rtParams0 ); OUT.uv1 = viewportCoordToRenderTarget( IN.uv, rtParams1 ); // + float2( -5, 1 ) * oneOverTargetSize; OUT.uv2 = viewportCoordToRenderTarget( IN.uv, rtParams2 ); diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_Gausian_P.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_Gausian_P.hlsl index 084a2c014..f4d29f3e1 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_Gausian_P.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_Gausian_P.hlsl @@ -22,11 +22,11 @@ #include "./../postFx.hlsl" -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -39,20 +39,20 @@ struct VertToPix float2 uv7 : TEXCOORD7; }; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { float4 kernel = float4( 0.175, 0.275, 0.375, 0.475 ) * 0.5 / 1.3; //25f; float4 OUT = 0; - OUT += tex2D( diffuseMap, IN.uv0 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv1 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv2 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv3 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv0 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv1 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv2 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv3 ) * kernel.w; - OUT += tex2D( diffuseMap, IN.uv4 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv5 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv6 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv7 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv4 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv5 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv6 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv7 ) * kernel.w; // Calculate a lumenance value in the alpha so we // can use alpha test to save fillrate. diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_Gausian_V.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_Gausian_V.hlsl index e29746e96..b2d4582e0 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_Gausian_V.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_Gausian_V.hlsl @@ -24,13 +24,13 @@ #include "./../../torque.hlsl" -uniform float2 texSize0; uniform float4 rtParams0; +uniform float2 texSize0; uniform float2 oneOverTargetSize; struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -47,7 +47,7 @@ VertToPix main( PFXVert IN ) { VertToPix OUT; - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); IN.uv = viewportCoordToRenderTarget( IN.uv, rtParams0 ); diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_Passthrough_V.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_Passthrough_V.hlsl index 40cec49de..8131e45cd 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_Passthrough_V.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_Passthrough_V.hlsl @@ -57,7 +57,7 @@ PFXVertToPix main( PFXVert IN ) */ - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); OUT.uv0 = viewportCoordToRenderTarget( IN.uv, rtParams0 ); OUT.uv1 = viewportCoordToRenderTarget( IN.uv, rtParams1 ); OUT.uv2 = viewportCoordToRenderTarget( IN.uv, rtParams2 ); diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl index 6d4144576..175525a91 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_SmallBlur_P.hlsl @@ -24,22 +24,23 @@ // colorMapSampler, which is the same size as the render target. // The sample weights are 1/16 in the corners, 2/16 on the edges, // and 4/16 in the center. +#include "../../shaderModel.hlsl" -uniform sampler2D colorSampler; // Output of DofNearCoc() +TORQUE_UNIFORM_SAMPLER2D(colorSampler, 0); // Output of DofNearCoc() struct Pixel { - float4 position : POSITION; + float4 position : TORQUE_POSITION; float4 texCoords : TEXCOORD0; }; -float4 main( Pixel IN ) : COLOR +float4 main( Pixel IN ) : TORQUE_TARGET0 { float4 color; color = 0.0; - color += tex2D( colorSampler, IN.texCoords.xz ); - color += tex2D( colorSampler, IN.texCoords.yz ); - color += tex2D( colorSampler, IN.texCoords.xw ); - color += tex2D( colorSampler, IN.texCoords.yw ); + color += TORQUE_TEX2D( colorSampler, IN.texCoords.xz ); + color += TORQUE_TEX2D( colorSampler, IN.texCoords.yz ); + color += TORQUE_TEX2D( colorSampler, IN.texCoords.xw ); + color += TORQUE_TEX2D( colorSampler, IN.texCoords.yw ); return color / 4.0; } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl b/Templates/Full/game/shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl index 204f4639d..3edb1ec2a 100644 --- a/Templates/Full/game/shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl +++ b/Templates/Full/game/shaders/common/postFx/dof/DOF_SmallBlur_V.hlsl @@ -30,13 +30,13 @@ struct Vert { - float4 position : POSITION; + float3 position : POSITION; float2 texCoords : TEXCOORD0; }; struct Pixel { - float4 position : POSITION; + float4 position : TORQUE_POSITION; float4 texCoords : TEXCOORD0; }; @@ -47,7 +47,7 @@ Pixel main( Vert IN ) { Pixel OUT; const float4 halfPixel = { -0.5, 0.5, -0.5, 0.5 }; - OUT.position = IN.position; //Transform_ObjectToClip( IN.position ); + OUT.position = float4(IN.position,1.0); //Transform_ObjectToClip( IN.position ); //float2 uv = IN.texCoords + rtParams0.xy; float2 uv = viewportCoordToRenderTarget( IN.texCoords, rtParams0 ); diff --git a/Templates/Full/game/shaders/common/postFx/edgeaa/dbgEdgeDisplayP.hlsl b/Templates/Full/game/shaders/common/postFx/edgeaa/dbgEdgeDisplayP.hlsl index 90cf391dc..fbd529031 100644 --- a/Templates/Full/game/shaders/common/postFx/edgeaa/dbgEdgeDisplayP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/edgeaa/dbgEdgeDisplayP.hlsl @@ -21,10 +21,10 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -float4 main( PFXVertToPix IN, - uniform sampler2D edgeBuffer :register(S0) ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(edgeBuffer); + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - return float4( tex2D( edgeBuffer, IN.uv0 ).rrr, 1.0 ); + return float4( TORQUE_TEX2D( edgeBuffer, IN.uv0 ).rrr, 1.0 ); } \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/postFx/edgeaa/edgeAAP.hlsl b/Templates/Full/game/shaders/common/postFx/edgeaa/edgeAAP.hlsl index e45684199..f5a71687d 100644 --- a/Templates/Full/game/shaders/common/postFx/edgeaa/edgeAAP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/edgeaa/edgeAAP.hlsl @@ -21,17 +21,17 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -float4 main( PFXVertToPix IN, - uniform sampler2D edgeBuffer : register(S0), - uniform sampler2D backBuffer : register(S1), - uniform float2 targetSize : register(C0) ) : COLOR0 +TORQUE_UNIFORM_SAMPLER2D(edgeBuffer,0); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 1); +uniform float2 targetSize; + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float2 pixelSize = 1.0 / targetSize; // Sample edge buffer, bail if not on an edge - float edgeSample = tex2D(edgeBuffer, IN.uv0).r; + float edgeSample = TORQUE_TEX2D(edgeBuffer, IN.uv0).r; clip(edgeSample - 1e-6); // Ok we're on an edge, so multi-tap sample, average, and return @@ -58,7 +58,7 @@ float4 main( PFXVertToPix IN, float2 offsetUV = IN.uv1 + edgeSample * ( offsets[i] * 0.5 ) * pixelSize;//rtWidthHeightInvWidthNegHeight.zw; //offsetUV *= 0.999; - accumColor+= tex2D(backBuffer, offsetUV); + accumColor += TORQUE_TEX2D(backBuffer, offsetUV); } accumColor /= 9.0; diff --git a/Templates/Full/game/shaders/common/postFx/edgeaa/edgeDetectP.hlsl b/Templates/Full/game/shaders/common/postFx/edgeaa/edgeDetectP.hlsl index bc79516ee..2277126a8 100644 --- a/Templates/Full/game/shaders/common/postFx/edgeaa/edgeDetectP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/edgeaa/edgeDetectP.hlsl @@ -21,10 +21,12 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" + +TORQUE_UNIFORM_SAMPLER2D(prepassBuffer,0); // GPU Gems 3, pg 443-444 -float GetEdgeWeight(float2 uv0, in sampler2D prepassBuffer, in float2 targetSize) +float GetEdgeWeight(float2 uv0, in float2 targetSize) { float2 offsets[9] = { float2( 0.0, 0.0), @@ -44,10 +46,11 @@ float GetEdgeWeight(float2 uv0, in sampler2D prepassBuffer, in float2 targetSize float Depth[9]; float3 Normal[9]; + [unroll] //no getting around this, may as well save the annoying warning message for(int i = 0; i < 9; i++) { float2 uv = uv0 + offsets[i] * PixelSize; - float4 gbSample = prepassUncondition( prepassBuffer, uv ); + float4 gbSample = TORQUE_PREPASS_UNCONDITION( prepassBuffer, uv ); Depth[i] = gbSample.a; Normal[i] = gbSample.rgb; } @@ -82,9 +85,9 @@ float GetEdgeWeight(float2 uv0, in sampler2D prepassBuffer, in float2 targetSize return dot(normalResults, float4(1.0, 1.0, 1.0, 1.0)) * 0.25; } -float4 main( PFXVertToPix IN, - uniform sampler2D prepassBuffer :register(S0), - uniform float2 targetSize : register(C0) ) : COLOR0 +uniform float2 targetSize; + +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - return GetEdgeWeight(IN.uv0, prepassBuffer, targetSize );//rtWidthHeightInvWidthNegHeight.zw); + return GetEdgeWeight(IN.uv0, targetSize);//rtWidthHeightInvWidthNegHeight.zw); } diff --git a/Templates/Full/game/shaders/common/postFx/flashP.hlsl b/Templates/Full/game/shaders/common/postFx/flashP.hlsl index 3d9c6c744..93daf3c26 100644 --- a/Templates/Full/game/shaders/common/postFx/flashP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/flashP.hlsl @@ -25,11 +25,11 @@ uniform float damageFlash; uniform float whiteOut; -uniform sampler2D backBuffer : register(S0); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); -float4 main(PFXVertToPix IN) : COLOR0 +float4 main(PFXVertToPix IN) : TORQUE_TARGET0 { - float4 color1 = tex2D(backBuffer, IN.uv0); + float4 color1 = TORQUE_TEX2D(backBuffer, IN.uv0); float4 color2 = color1 * MUL_COLOR; float4 damage = lerp(color1,color2,damageFlash); return lerp(damage,WHITE_COLOR,whiteOut); diff --git a/Templates/Full/game/shaders/common/postFx/fogP.hlsl b/Templates/Full/game/shaders/common/postFx/fogP.hlsl index 0eba9a7b7..b54eea97a 100644 --- a/Templates/Full/game/shaders/common/postFx/fogP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/fogP.hlsl @@ -20,20 +20,21 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" + #include "./postFx.hlsl" #include "./../torque.hlsl" +#include "./../shaderModelAutoGen.hlsl" -uniform sampler2D prepassTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 0); uniform float3 eyePosWorld; uniform float4 fogColor; uniform float3 fogData; uniform float4 rtParams0; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { //float2 prepassCoord = ( IN.uv0.xy * rtParams0.zw ) + rtParams0.xy; - float depth = prepassUncondition( prepassTex, IN.uv0 ).w; + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; //return float4( depth, 0, 0, 0.7 ); float factor = computeSceneFog( eyePosWorld, diff --git a/Templates/Full/game/shaders/common/postFx/fxaa/fxaaP.hlsl b/Templates/Full/game/shaders/common/postFx/fxaa/fxaaP.hlsl index 357b794e4..269bfea67 100644 --- a/Templates/Full/game/shaders/common/postFx/fxaa/fxaaP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/fxaa/fxaaP.hlsl @@ -20,38 +20,53 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../../shaderModel.hlsl" + #define FXAA_PC 1 +#if (TORQUE_SM <= 30) #define FXAA_HLSL_3 1 +#elif TORQUE_SM < 49 +#define FXAA_HLSL_4 1 +#elif TORQUE_SM >=50 +#define FXAA_HLSL_5 1 +#endif #define FXAA_QUALITY__PRESET 12 #define FXAA_GREEN_AS_LUMA 1 #include "Fxaa3_11.h" -#include "../postFx.hlsl" struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; }; -uniform sampler2D colorTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(colorTex, 0); uniform float2 oneOverTargetSize; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { +#if (TORQUE_SM >= 10 && TORQUE_SM <=30) + FxaaTex tex = colorTex; +#elif TORQUE_SM >=40 + FxaaTex tex; + tex.smpl = colorTex; + tex.tex = texture_colorTex; +#endif + return FxaaPixelShader( IN.uv0, // vertex position 0, // Unused... console stuff - colorTex, // The color back buffer + tex, // The color back buffer - colorTex, // Used for 360 optimization + tex, // Used for 360 optimization - colorTex, // Used for 360 optimization + tex, // Used for 360 optimization oneOverTargetSize, diff --git a/Templates/Full/game/shaders/common/postFx/fxaa/fxaaV.hlsl b/Templates/Full/game/shaders/common/postFx/fxaa/fxaaV.hlsl index ea2c3d106..3bef0a4d3 100644 --- a/Templates/Full/game/shaders/common/postFx/fxaa/fxaaV.hlsl +++ b/Templates/Full/game/shaders/common/postFx/fxaa/fxaaV.hlsl @@ -25,7 +25,7 @@ struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; }; @@ -35,7 +35,7 @@ VertToPix main( PFXVert IN ) { VertToPix OUT; - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1); OUT.uv0 = viewportCoordToRenderTarget( IN.uv, rtParams0 ); return OUT; diff --git a/Templates/Full/game/shaders/common/postFx/gammaP.hlsl b/Templates/Full/game/shaders/common/postFx/gammaP.hlsl index 20196548b..6e284eb88 100644 --- a/Templates/Full/game/shaders/common/postFx/gammaP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/gammaP.hlsl @@ -24,21 +24,21 @@ #include "./postFx.hlsl" #include "../torque.hlsl" -uniform sampler2D backBuffer : register(S0); -uniform sampler1D colorCorrectionTex : register( s1 ); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); +TORQUE_UNIFORM_SAMPLER1D(colorCorrectionTex, 1); uniform float OneOverGamma; uniform float Brightness; uniform float Contrast; -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float4 color = tex2D(backBuffer, IN.uv0.xy); + float4 color = TORQUE_TEX2D(backBuffer, IN.uv0.xy); // Apply the color correction. - color.r = tex1D( colorCorrectionTex, color.r ).r; - color.g = tex1D( colorCorrectionTex, color.g ).g; - color.b = tex1D( colorCorrectionTex, color.b ).b; + color.r = TORQUE_TEX1D( colorCorrectionTex, color.r ).r; + color.g = TORQUE_TEX1D( colorCorrectionTex, color.g ).g; + color.b = TORQUE_TEX1D( colorCorrectionTex, color.b ).b; // Apply gamma correction color.rgb = pow( abs(color.rgb), OneOverGamma ); diff --git a/Templates/Full/game/shaders/common/postFx/glowBlurP.hlsl b/Templates/Full/game/shaders/common/postFx/glowBlurP.hlsl index 65ae96c6f..80f8ed02d 100644 --- a/Templates/Full/game/shaders/common/postFx/glowBlurP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/glowBlurP.hlsl @@ -22,11 +22,11 @@ #include "./postFx.hlsl" -uniform sampler2D diffuseMap : register(S0); +TORQUE_UNIFORM_SAMPLER2D(diffuseMap, 0); struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -39,20 +39,20 @@ struct VertToPix float2 uv7 : TEXCOORD7; }; -float4 main( VertToPix IN ) : COLOR +float4 main( VertToPix IN ) : TORQUE_TARGET0 { float4 kernel = float4( 0.175, 0.275, 0.375, 0.475 ) * 0.5f; float4 OUT = 0; - OUT += tex2D( diffuseMap, IN.uv0 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv1 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv2 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv3 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv0 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv1 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv2 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv3 ) * kernel.w; - OUT += tex2D( diffuseMap, IN.uv4 ) * kernel.x; - OUT += tex2D( diffuseMap, IN.uv5 ) * kernel.y; - OUT += tex2D( diffuseMap, IN.uv6 ) * kernel.z; - OUT += tex2D( diffuseMap, IN.uv7 ) * kernel.w; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv4 ) * kernel.x; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv5 ) * kernel.y; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv6 ) * kernel.z; + OUT += TORQUE_TEX2D( diffuseMap, IN.uv7 ) * kernel.w; // Calculate a lumenance value in the alpha so we // can use alpha test to save fillrate. diff --git a/Templates/Full/game/shaders/common/postFx/glowBlurV.hlsl b/Templates/Full/game/shaders/common/postFx/glowBlurV.hlsl index c9c9052ec..b8f5cf9c2 100644 --- a/Templates/Full/game/shaders/common/postFx/glowBlurV.hlsl +++ b/Templates/Full/game/shaders/common/postFx/glowBlurV.hlsl @@ -28,7 +28,7 @@ uniform float2 texSize0; struct VertToPix { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 uv0 : TEXCOORD0; float2 uv1 : TEXCOORD1; @@ -45,7 +45,7 @@ VertToPix main( PFXVert IN ) { VertToPix OUT; - OUT.hpos = IN.pos; + OUT.hpos = float4(IN.pos,1.0); float2 uv = IN.uv + (0.5f / texSize0); diff --git a/Templates/Full/game/shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl index c28f9eb83..77f4b9915 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl @@ -21,9 +21,8 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -uniform sampler2D inputTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float2 oneOverTargetSize; uniform float gaussMultiplier; uniform float gaussMean; @@ -48,7 +47,7 @@ float computeGaussianValue( float x, float mean, float std_deviation ) return tmp * tmp2; } -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 color = { 0.0f, 0.0f, 0.0f, 0.0f }; float offset = 0; @@ -62,7 +61,7 @@ float4 main( PFXVertToPix IN ) : COLOR offset = (i - 4.0) * oneOverTargetSize.x; x = (i - 4.0) / 4.0; weight = gaussMultiplier * computeGaussianValue( x, gaussMean, gaussStdDev ); - color += (tex2D( inputTex, IN.uv0 + float2( offset, 0.0f ) ) * weight ); + color += (TORQUE_TEX2D( inputTex, IN.uv0 + float2( offset, 0.0f ) ) * weight ); } return float4( color.rgb, 1.0f ); diff --git a/Templates/Full/game/shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl index 93e6b8382..8381f6a5d 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl @@ -21,9 +21,8 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -uniform sampler2D inputTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float2 oneOverTargetSize; uniform float gaussMultiplier; uniform float gaussMean; @@ -47,7 +46,7 @@ float computeGaussianValue( float x, float mean, float std_deviation ) return tmp * tmp2; } -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 color = { 0.0f, 0.0f, 0.0f, 0.0f }; float offset = 0; @@ -61,7 +60,7 @@ float4 main( PFXVertToPix IN ) : COLOR offset = (fI - 4.0) * oneOverTargetSize.y; x = (fI - 4.0) / 4.0; weight = gaussMultiplier * computeGaussianValue( x, gaussMean, gaussStdDev ); - color += (tex2D( inputTex, IN.uv0 + float2( 0.0f, offset ) ) * weight ); + color += (TORQUE_TEX2D( inputTex, IN.uv0 + float2( 0.0f, offset ) ) * weight ); } return float4( color.rgb, 1.0f ); diff --git a/Templates/Full/game/shaders/common/postFx/hdr/brightPassFilterP.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/brightPassFilterP.hlsl index c438a5153..9a8a93e97 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/brightPassFilterP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/brightPassFilterP.hlsl @@ -21,12 +21,11 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" #include "../../torque.hlsl" -uniform sampler2D inputTex : register(S0); -uniform sampler2D luminanceTex : register(S1); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); +TORQUE_UNIFORM_SAMPLER2D(luminanceTex, 1); uniform float2 oneOverTargetSize; uniform float brightPassThreshold; uniform float g_fMiddleGray; @@ -40,17 +39,17 @@ static float2 gTapOffsets[4] = { -0.5, -0.5 }, { 0.5, 0.5 } }; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 average = { 0.0f, 0.0f, 0.0f, 0.0f }; // Combine and average 4 samples from the source HDR texture. for( int i = 0; i < 4; i++ ) - average += hdrDecode( tex2D( inputTex, IN.uv0 + ( gTapOffsets[i] * oneOverTargetSize ) ) ); + average += hdrDecode( TORQUE_TEX2D( inputTex, IN.uv0 + ( gTapOffsets[i] * oneOverTargetSize ) ) ); average *= 0.25f; // Determine the brightness of this particular pixel. - float adaptedLum = tex2D( luminanceTex, float2( 0.5f, 0.5f ) ).r; + float adaptedLum = TORQUE_TEX2D( luminanceTex, float2( 0.5f, 0.5f ) ).r; float lum = (g_fMiddleGray / (adaptedLum + 0.0001)) * hdrLuminance( average.rgb ); //float lum = hdrLuminance( average.rgb ); diff --git a/Templates/Full/game/shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl index 3f443611c..0f895070a 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl @@ -21,18 +21,17 @@ //----------------------------------------------------------------------------- #include "../postFx.hlsl" -#include "shadergen:/autogenConditioners.h" -uniform sampler2D currLum : register( S0 ); -uniform sampler2D lastAdaptedLum : register( S1 ); +TORQUE_UNIFORM_SAMPLER2D(currLum, 0); +TORQUE_UNIFORM_SAMPLER2D(lastAdaptedLum, 1); uniform float adaptRate; uniform float deltaTime; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float fAdaptedLum = tex2D( lastAdaptedLum, float2(0.5f, 0.5f) ).r; - float fCurrentLum = tex2D( currLum, float2(0.5f, 0.5f) ).r; + float fAdaptedLum = TORQUE_TEX2D( lastAdaptedLum, float2(0.5f, 0.5f) ).r; + float fCurrentLum = TORQUE_TEX2D( currLum, float2(0.5f, 0.5f) ).r; // The user's adapted luminance level is simulated by closing the gap between // adapted luminance and current luminance by 2% every frame, based on a diff --git a/Templates/Full/game/shaders/common/postFx/hdr/downScale4x4P.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/downScale4x4P.hlsl index 3ce68452c..01998af0b 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/downScale4x4P.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/downScale4x4P.hlsl @@ -29,23 +29,24 @@ //----------------------------------------------------------------------------- struct VertIn { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoords[8] : TEXCOORD0; }; + +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -float4 main( VertIn IN, - uniform sampler2D inputTex : register(S0) ) : COLOR +float4 main( VertIn IN) : TORQUE_TARGET0 { // We calculate the texture coords // in the vertex shader as an optimization. float4 sample = 0.0f; for ( int i = 0; i < 8; i++ ) { - sample += tex2D( inputTex, IN.texCoords[i].xy ); - sample += tex2D( inputTex, IN.texCoords[i].zw ); + sample += TORQUE_TEX2D( inputTex, IN.texCoords[i].xy ); + sample += TORQUE_TEX2D( inputTex, IN.texCoords[i].zw ); } return sample / 16; diff --git a/Templates/Full/game/shaders/common/postFx/hdr/downScale4x4V.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/downScale4x4V.hlsl index 88794204e..c9a34b7f4 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/downScale4x4V.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/downScale4x4V.hlsl @@ -29,19 +29,20 @@ struct Conn { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float4 texCoords[8] : TEXCOORD0; }; +uniform float2 targetSize; + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Conn main( PFXVert In, - uniform float2 targetSize : register(C0) ) +Conn main( PFXVert In ) { Conn Out; - Out.hpos = In.pos; + Out.hpos = float4(In.pos,1.0); // Sample from the 16 surrounding points. Since the center point will be in // the exact center of 16 texels, a 0.5f offset is needed to specify a texel diff --git a/Templates/Full/game/shaders/common/postFx/hdr/finalPassCombineP.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/finalPassCombineP.hlsl index cb71f01c2..b786b3f6a 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/finalPassCombineP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/finalPassCombineP.hlsl @@ -20,15 +20,15 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" #include "../../torque.hlsl" #include "../postFx.hlsl" +#include "../../shaderModelAutoGen.hlsl" -uniform sampler2D sceneTex : register( s0 ); -uniform sampler2D luminanceTex : register( s1 ); -uniform sampler2D bloomTex : register( s2 ); -uniform sampler1D colorCorrectionTex : register( s3 ); -uniform sampler2D prepassTex : register(S4); +TORQUE_UNIFORM_SAMPLER2D(sceneTex, 0); +TORQUE_UNIFORM_SAMPLER2D(luminanceTex, 1); +TORQUE_UNIFORM_SAMPLER2D(bloomTex, 2); +TORQUE_UNIFORM_SAMPLER1D(colorCorrectionTex, 3); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 4); uniform float2 texSize0; uniform float2 texSize2; @@ -36,22 +36,20 @@ uniform float2 texSize2; uniform float g_fEnableToneMapping; uniform float g_fMiddleGray; uniform float g_fWhiteCutoff; - uniform float g_fEnableBlueShift; -uniform float3 g_fBlueShiftColor; +uniform float3 g_fBlueShiftColor; uniform float g_fBloomScale; uniform float g_fOneOverGamma; uniform float Brightness; uniform float Contrast; - -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float4 sample = hdrDecode( tex2D( sceneTex, IN.uv0 ) ); - float adaptedLum = tex2D( luminanceTex, float2( 0.5f, 0.5f ) ).r; - float4 bloom = tex2D( bloomTex, IN.uv0 ); + float4 sample = hdrDecode( TORQUE_TEX2D( sceneTex, IN.uv0 ) ); + float adaptedLum = TORQUE_TEX2D( luminanceTex, float2( 0.5f, 0.5f ) ).r; + float4 bloom = TORQUE_TEX2D( bloomTex, IN.uv0 ); // For very low light conditions, the rods will dominate the perception // of light, and therefore color will be desaturated and shifted @@ -85,14 +83,14 @@ float4 main( PFXVertToPix IN ) : COLOR0 } // Add the bloom effect. - float depth = prepassUncondition( prepassTex, IN.uv0 ).w; + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; if (depth>0.9999) sample += g_fBloomScale * bloom; // Apply the color correction. - sample.r = tex1D( colorCorrectionTex, sample.r ).r; - sample.g = tex1D( colorCorrectionTex, sample.g ).g; - sample.b = tex1D( colorCorrectionTex, sample.b ).b; + sample.r = TORQUE_TEX1D( colorCorrectionTex, sample.r ).r; + sample.g = TORQUE_TEX1D( colorCorrectionTex, sample.g ).g; + sample.b = TORQUE_TEX1D( colorCorrectionTex, sample.b ).b; // Apply gamma correction diff --git a/Templates/Full/game/shaders/common/postFx/hdr/luminanceVisP.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/luminanceVisP.hlsl index 593a24e7b..505d1b825 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/luminanceVisP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/luminanceVisP.hlsl @@ -22,15 +22,14 @@ #include "../postFx.hlsl" #include "../../torque.hlsl" -#include "shadergen:/autogenConditioners.h" -uniform sampler2D inputTex : register(S0); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float brightPassThreshold; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { - float4 sample = hdrDecode( tex2D( inputTex, IN.uv0 ) ); + float4 sample = hdrDecode( TORQUE_TEX2D( inputTex, IN.uv0 ) ); // Determine the brightness of this particular pixel. float lum = hdrLuminance( sample.rgb ); diff --git a/Templates/Full/game/shaders/common/postFx/hdr/sampleLumInitialP.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/sampleLumInitialP.hlsl index 39fd9dccc..2e23ece1f 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/sampleLumInitialP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/sampleLumInitialP.hlsl @@ -23,7 +23,7 @@ #include "../../torque.hlsl" #include "../postFx.hlsl" -uniform sampler2D inputTex : register( S0 ); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float2 texSize0; uniform float g_fMinLuminace; @@ -36,7 +36,7 @@ static float2 gTapOffsets[9] = }; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float2 tsize = 1.0 / texSize0; @@ -46,7 +46,7 @@ float4 main( PFXVertToPix IN ) : COLOR for ( int i = 0; i < 9; i++ ) { // Decode the hdr value. - sample = hdrDecode( tex2D( inputTex, IN.uv0 + ( gTapOffsets[i] * tsize ) ).rgb ); + sample = hdrDecode( TORQUE_TEX2D( inputTex, IN.uv0 + ( gTapOffsets[i] * tsize ) ).rgb ); // Get the luminance and add it to the average. float lum = max( hdrLuminance( sample ), g_fMinLuminace ); diff --git a/Templates/Full/game/shaders/common/postFx/hdr/sampleLumIterativeP.hlsl b/Templates/Full/game/shaders/common/postFx/hdr/sampleLumIterativeP.hlsl index 59e91f0db..46ed6fc70 100644 --- a/Templates/Full/game/shaders/common/postFx/hdr/sampleLumIterativeP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/hdr/sampleLumIterativeP.hlsl @@ -22,7 +22,7 @@ #include "../postFx.hlsl" -uniform sampler2D inputTex : register( S0 ); +TORQUE_UNIFORM_SAMPLER2D(inputTex, 0); uniform float2 oneOverTargetSize; @@ -34,7 +34,7 @@ static float2 gTapOffsets[16] = { -1.5, 1.5 }, { -0.5, 1.5 }, { 0.5, 1.5 }, { 1.5, 1.5 } }; -float4 main( PFXVertToPix IN ) : COLOR +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float2 pixelSize = oneOverTargetSize; @@ -42,7 +42,7 @@ float4 main( PFXVertToPix IN ) : COLOR for ( int i = 0; i < 16; i++ ) { - float lum = tex2D( inputTex, IN.uv0 + ( gTapOffsets[i] * pixelSize ) ).r; + float lum = TORQUE_TEX2D( inputTex, IN.uv0 + ( gTapOffsets[i] * pixelSize ) ).r; average += lum; } diff --git a/Templates/Full/game/shaders/common/postFx/lightRay/lightRayOccludeP.hlsl b/Templates/Full/game/shaders/common/postFx/lightRay/lightRayOccludeP.hlsl index e8870b3c4..b70bafa98 100644 --- a/Templates/Full/game/shaders/common/postFx/lightRay/lightRayOccludeP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/lightRay/lightRayOccludeP.hlsl @@ -20,29 +20,29 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../../shaderModelAutoGen.hlsl" #include "../postFx.hlsl" -uniform sampler2D backBuffer : register( s0 ); // The original backbuffer. -uniform sampler2D prepassTex : register( s1 ); // The pre-pass depth and normals. +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 1); uniform float brightScalar; static const float3 LUMINANCE_VECTOR = float3(0.3125f, 0.6154f, 0.0721f); -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 col = float4( 0, 0, 0, 1 ); // Get the depth at this pixel. - float depth = prepassUncondition( prepassTex, IN.uv0 ).w; + float depth = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ).w; // If the depth is equal to 1.0, read from the backbuffer // and perform the exposure calculation on the result. if ( depth >= 0.999 ) { - col = tex2D( backBuffer, IN.uv0 ); + col = TORQUE_TEX2D( backBuffer, IN.uv0 ); //col = 1 - exp(-120000 * col); col += dot( col.rgb, LUMINANCE_VECTOR ) + 0.0001f; diff --git a/Templates/Full/game/shaders/common/postFx/lightRay/lightRayP.hlsl b/Templates/Full/game/shaders/common/postFx/lightRay/lightRayP.hlsl index ff44abfae..032894710 100644 --- a/Templates/Full/game/shaders/common/postFx/lightRay/lightRayP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/lightRay/lightRayP.hlsl @@ -22,28 +22,29 @@ #include "../postFx.hlsl" -uniform sampler2D frameSampler : register( s0 ); -uniform sampler2D backBuffer : register( s1 ); +TORQUE_UNIFORM_SAMPLER2D(frameSampler, 0); +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 1); + uniform float3 camForward; +uniform int numSamples; uniform float3 lightDirection; +uniform float density; uniform float2 screenSunPos; uniform float2 oneOverTargetSize; -uniform int numSamples; -uniform float density; uniform float weight; uniform float decay; uniform float exposure; -float4 main( PFXVertToPix IN ) : COLOR0 +float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 { float4 texCoord = float4( IN.uv0.xy, 0, 0 ); // Store initial sample. - half3 color = (half3)tex2D( frameSampler, texCoord.xy ).rgb; + half3 color = (half3)TORQUE_TEX2D( frameSampler, texCoord.xy ).rgb; // Store original bb color. - float4 bbCol = tex2D( backBuffer, IN.uv1 ); + float4 bbCol = TORQUE_TEX2D( backBuffer, IN.uv1 ); // Set up illumination decay factor. half illuminationDecay = 1.0; @@ -68,7 +69,7 @@ float4 main( PFXVertToPix IN ) : COLOR0 texCoord.xy -= deltaTexCoord; // Retrieve sample at new location. - half3 sample = (half3)tex2Dlod( frameSampler, texCoord ); + half3 sample = (half3)TORQUE_TEX2DLOD( frameSampler, texCoord ); // Apply sample attenuation scale/decay factors. sample *= half(illuminationDecay * weight); diff --git a/Templates/Full/game/shaders/common/postFx/motionBlurP.hlsl b/Templates/Full/game/shaders/common/postFx/motionBlurP.hlsl index 348484f4d..8bc65fbc6 100644 --- a/Templates/Full/game/shaders/common/postFx/motionBlurP.hlsl +++ b/Templates/Full/game/shaders/common/postFx/motionBlurP.hlsl @@ -22,23 +22,22 @@ #include "./postFx.hlsl" #include "../torque.hlsl" -#include "shadergen:/autogenConditioners.h" +#include "../shaderModelAutoGen.hlsl" uniform float4x4 matPrevScreenToWorld; uniform float4x4 matWorldToScreen; // Passed in from setShaderConsts() uniform float velocityMultiplier; +TORQUE_UNIFORM_SAMPLER2D(backBuffer, 0); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 1); -uniform sampler2D backBuffer : register(S0); -uniform sampler2D prepassTex : register(S1); - -float4 main(PFXVertToPix IN) : COLOR0 +float4 main(PFXVertToPix IN) : TORQUE_TARGET0 { float samples = 5; // First get the prepass texture for uv channel 0 - float4 prepass = prepassUncondition( prepassTex, IN.uv0 ); + float4 prepass = TORQUE_PREPASS_UNCONDITION( prepassTex, IN.uv0 ); // Next extract the depth float depth = prepass.a; @@ -58,12 +57,12 @@ float4 main(PFXVertToPix IN) : COLOR0 float2 velocity = ((screenPos - previousPos) / velocityMultiplier).xy; // Generate the motion blur - float4 color = tex2D(backBuffer, IN.uv0); + float4 color = TORQUE_TEX2D(backBuffer, IN.uv0); IN.uv0 += velocity; for(int i = 1; i= 10 && TORQUE_SM <=30) + // Semantics + #define TORQUE_POSITION POSITION + #define TORQUE_DEPTH DEPTH + #define TORQUE_TARGET0 COLOR0 + #define TORQUE_TARGET1 COLOR1 + #define TORQUE_TARGET2 COLOR2 + #define TORQUE_TARGET3 COLOR3 + + // Sampler uniforms + #define TORQUE_UNIFORM_SAMPLER1D(tex,regist) uniform sampler1D tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLER2D(tex,regist) uniform sampler2D tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLER3D(tex,regist) uniform sampler3D tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLERCUBE(tex,regist) uniform samplerCUBE tex : register(S##regist) + // Sampling functions + #define TORQUE_TEX1D(tex,coords) tex1D(tex,coords) + #define TORQUE_TEX2D(tex,coords) tex2D(tex,coords) + #define TORQUE_TEX2DPROJ(tex,coords) tex2Dproj(tex,coords) //this really is sm 2 or later + #define TORQUE_TEX3D(tex,coords) tex3D(tex,coords) + #define TORQUE_TEXCUBE(tex,coords) texCUBE(tex,coords) + + //Shader model 3.0 only + #if TORQUE_SM == 30 + #define TORQUE_VPOS VPOS // This is a float2 + // The mipmap LOD is specified in coord.w + #define TORQUE_TEX2DLOD(tex,coords) tex2Dlod(tex,coords) + #endif + + //helper if you want to pass sampler/texture in a function + //2D + #define TORQUE_SAMPLER2D(tex) sampler2D tex + #define TORQUE_SAMPLER2D_MAKEARG(tex) tex + //Cube + #define TORQUE_SAMPLERCUBE(tex) samplerCUBE tex + #define TORQUE_SAMPLERCUBE_MAKEARG(tex) tex +// Shader model 4.0+ +#elif TORQUE_SM >= 40 + #define TORQUE_POSITION SV_Position + #define TORQUE_DEPTH SV_Depth + #define TORQUE_VPOS SV_Position //note float4 compared to SM 3 where it is a float2 + #define TORQUE_TARGET0 SV_Target0 + #define TORQUE_TARGET1 SV_Target1 + #define TORQUE_TARGET2 SV_Target2 + #define TORQUE_TARGET3 SV_Target3 + // Sampler uniforms + //1D is emulated to a 2D for now + #define TORQUE_UNIFORM_SAMPLER1D(tex,regist) uniform Texture2D texture_##tex : register(T##regist); uniform SamplerState tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLER2D(tex,regist) uniform Texture2D texture_##tex : register(T##regist); uniform SamplerState tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLER3D(tex,regist) uniform Texture3D texture_##tex : register(T##regist); uniform SamplerState tex : register(S##regist) + #define TORQUE_UNIFORM_SAMPLERCUBE(tex,regist) uniform TextureCube texture_##tex : register(T##regist); uniform SamplerState tex : register(S##regist) + // Sampling functions + #define TORQUE_TEX1D(tex,coords) texture_##tex.Sample(tex,coords) + #define TORQUE_TEX2D(tex,coords) texture_##tex.Sample(tex,coords) + #define TORQUE_TEX2DPROJ(tex,coords) texture_##tex.Sample(tex,coords.xy / coords.w) + #define TORQUE_TEX3D(tex,coords) texture_##tex.Sample(tex,coords) + #define TORQUE_TEXCUBE(tex,coords) texture_##tex.Sample(tex,coords) + // The mipmap LOD is specified in coord.w + #define TORQUE_TEX2DLOD(tex,coords) texture_##tex.SampleLevel(tex,coords.xy,coords.w) + + //helper if you want to pass sampler/texture in a function + //2D + #define TORQUE_SAMPLER2D(tex) Texture2D texture_##tex, SamplerState tex + #define TORQUE_SAMPLER2D_MAKEARG(tex) texture_##tex, tex + //Cube + #define TORQUE_SAMPLERCUBE(tex) TextureCube texture_##tex, SamplerState tex + #define TORQUE_SAMPLERCUBE_MAKEARG(tex) texture_##tex, tex +#endif + +#endif // _TORQUE_SHADERMODEL_ + diff --git a/Templates/Full/game/shaders/common/shaderModelAutoGen.hlsl b/Templates/Full/game/shaders/common/shaderModelAutoGen.hlsl new file mode 100644 index 000000000..4f2d8803f --- /dev/null +++ b/Templates/Full/game/shaders/common/shaderModelAutoGen.hlsl @@ -0,0 +1,35 @@ +//----------------------------------------------------------------------------- +// Copyright (c) 2015 GarageGames, LLC +// +// 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: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// 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. +//----------------------------------------------------------------------------- + +#ifndef _TORQUE_SHADERMODEL_AUTOGEN_ +#define _TORQUE_SHADERMODEL_AUTOGEN_ + +#include "shadergen:/autogenConditioners.h" + +// Portability helpers for autogenConditioners +#if (TORQUE_SM >= 10 && TORQUE_SM <=30) + #define TORQUE_PREPASS_UNCONDITION(tex, coords) prepassUncondition(tex, coords) +#elif TORQUE_SM >= 40 + #define TORQUE_PREPASS_UNCONDITION(tex, coords) prepassUncondition(tex, texture_##tex, coords) +#endif + +#endif //_TORQUE_SHADERMODEL_AUTOGEN_ diff --git a/Templates/Full/game/shaders/common/terrain/blendP.hlsl b/Templates/Full/game/shaders/common/terrain/blendP.hlsl index f71088928..aeef9d6e3 100644 --- a/Templates/Full/game/shaders/common/terrain/blendP.hlsl +++ b/Templates/Full/game/shaders/common/terrain/blendP.hlsl @@ -21,25 +21,28 @@ //----------------------------------------------------------------------------- #include "terrain.hlsl" +#include "../shaderModel.hlsl" struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 layerCoord : TEXCOORD0; float2 texCoord : TEXCOORD1; }; -float4 main( ConnectData IN, - uniform sampler2D layerTex : register(S0), - uniform sampler2D textureMap : register(S1), - uniform float texId, - uniform float layerSize ) : COLOR +TORQUE_UNIFORM_SAMPLER2D(layerTex, 0); +TORQUE_UNIFORM_SAMPLER2D(textureMap, 1); + +uniform float texId; +uniform float layerSize; + +float4 main( ConnectData IN ) : TORQUE_TARGET0 { - float4 layerSample = round( tex2D( layerTex, IN.layerCoord ) * 255.0f ); + float4 layerSample = round( TORQUE_TEX2D( layerTex, IN.layerCoord ) * 255.0f ); float blend = calcBlend( texId, IN.layerCoord, layerSize, layerSample ); clip( blend - 0.0001 ); - return float4( tex2D( textureMap, IN.texCoord ).rgb, blend ); + return float4( TORQUE_TEX2D(textureMap, IN.texCoord).rgb, blend); } diff --git a/Templates/Full/game/shaders/common/terrain/blendV.hlsl b/Templates/Full/game/shaders/common/terrain/blendV.hlsl index 7a79d2de4..9ccd33301 100644 --- a/Templates/Full/game/shaders/common/terrain/blendV.hlsl +++ b/Templates/Full/game/shaders/common/terrain/blendV.hlsl @@ -23,6 +23,8 @@ /// The vertex shader used in the generation and caching of the /// base terrain texture. +#include "../shaderModel.hlsl" + struct VertData { float3 position : POSITION; @@ -31,17 +33,18 @@ struct VertData struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; float2 layerCoord : TEXCOORD0; float2 texCoord : TEXCOORD1; }; -ConnectData main( VertData IN, - uniform float2 texScale : register(C0) ) +uniform float2 texScale; + +ConnectData main( VertData IN ) { ConnectData OUT; - OUT.hpos = float4( IN.position.xyz, 1 ); + OUT.hpos = float4( IN.position, 1 ); OUT.layerCoord = IN.texCoord; OUT.texCoord = IN.texCoord * texScale; diff --git a/Templates/Full/game/shaders/common/terrain/terrain.hlsl b/Templates/Full/game/shaders/common/terrain/terrain.hlsl index 8ce497012..b7c87e618 100644 --- a/Templates/Full/game/shaders/common/terrain/terrain.hlsl +++ b/Templates/Full/game/shaders/common/terrain/terrain.hlsl @@ -35,6 +35,7 @@ float calcBlend( float texId, float2 layerCoord, float layerSize, float4 layerSa // Check if any of the layer samples // match the current texture id. float4 factors = 0; + [unroll] for(int i = 0; i < 4; i++) if(layerSample[i] == texId) factors[i] = 1; diff --git a/Templates/Full/game/shaders/common/torque.hlsl b/Templates/Full/game/shaders/common/torque.hlsl index f50832cb8..3521042d4 100644 --- a/Templates/Full/game/shaders/common/torque.hlsl +++ b/Templates/Full/game/shaders/common/torque.hlsl @@ -23,6 +23,7 @@ #ifndef _TORQUE_HLSL_ #define _TORQUE_HLSL_ +#include "./shaderModel.hlsl" static float M_HALFPI_F = 1.57079632679489661923f; static float M_PI_F = 3.14159265358979323846f; @@ -137,29 +138,29 @@ float3x3 quatToMat( float4 quat ) /// @param negViewTS The negative view vector in tangent space. /// @param depthScale The parallax factor used to scale the depth result. /// -float2 parallaxOffset( sampler2D texMap, float2 texCoord, float3 negViewTS, float depthScale ) +float2 parallaxOffset(TORQUE_SAMPLER2D(texMap), float2 texCoord, float3 negViewTS, float depthScale) { - float depth = tex2D( texMap, texCoord ).a; - float2 offset = negViewTS.xy * ( depth * depthScale ); + float depth = TORQUE_TEX2D(texMap, texCoord).a; + float2 offset = negViewTS.xy * (depth * depthScale); - for ( int i=0; i < PARALLAX_REFINE_STEPS; i++ ) + for (int i = 0; i < PARALLAX_REFINE_STEPS; i++) { - depth = ( depth + tex2D( texMap, texCoord + offset ).a ) * 0.5; - offset = negViewTS.xy * ( depth * depthScale ); + depth = (depth + TORQUE_TEX2D(texMap, texCoord + offset).a) * 0.5; + offset = negViewTS.xy * (depth * depthScale); } return offset; } /// Same as parallaxOffset but for dxtnm where depth is stored in the red channel instead of the alpha -float2 parallaxOffsetDxtnm(sampler2D texMap, float2 texCoord, float3 negViewTS, float depthScale) +float2 parallaxOffsetDxtnm(TORQUE_SAMPLER2D(texMap), float2 texCoord, float3 negViewTS, float depthScale) { - float depth = tex2D(texMap, texCoord).r; + float depth = TORQUE_TEX2D(texMap, texCoord).r; float2 offset = negViewTS.xy * (depth * depthScale); for (int i = 0; i < PARALLAX_REFINE_STEPS; i++) { - depth = (depth + tex2D(texMap, texCoord + offset).r) * 0.5; + depth = (depth + TORQUE_TEX2D(texMap, texCoord + offset).r) * 0.5; offset = negViewTS.xy * (depth * depthScale); } diff --git a/Templates/Full/game/shaders/common/water/waterBasicP.hlsl b/Templates/Full/game/shaders/common/water/waterBasicP.hlsl index 7ae933f6f..efb437779 100644 --- a/Templates/Full/game/shaders/common/water/waterBasicP.hlsl +++ b/Templates/Full/game/shaders/common/water/waterBasicP.hlsl @@ -57,7 +57,7 @@ struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup float4 rippleTexCoord01 : TEXCOORD0; @@ -92,11 +92,11 @@ float fresnel(float NdotV, float bias, float power) //----------------------------------------------------------------------------- // Uniforms //----------------------------------------------------------------------------- -uniform sampler bumpMap : register( S0 ); +TORQUE_UNIFORM_SAMPLER2D(bumpMap,0); //uniform sampler2D prepassTex : register( S1 ); -uniform sampler2D reflectMap : register( S2 ); -uniform sampler refractBuff : register( S3 ); -uniform samplerCUBE skyMap : register( S4 ); +TORQUE_UNIFORM_SAMPLER2D(reflectMap,2); +TORQUE_UNIFORM_SAMPLER2D(refractBuff,3); +TORQUE_UNIFORM_SAMPLERCUBE(skyMap,4); //uniform sampler foamMap : register( S5 ); uniform float4 baseColor; uniform float4 miscParams; @@ -113,16 +113,16 @@ uniform float4x4 modelMat; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -float4 main( ConnectData IN ) : COLOR +float4 main( ConnectData IN ) : TORQUE_TARGET0 { // Modulate baseColor by the ambientColor. float4 waterBaseColor = baseColor * float4( ambientColor.rgb, 1 ); waterBaseColor = toLinear(waterBaseColor); // Get the bumpNorm... - float3 bumpNorm = ( tex2D( bumpMap, IN.rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord2 ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; + float3 bumpNorm = ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; + bumpNorm += ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; + bumpNorm += ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord2 ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; bumpNorm = normalize( bumpNorm ); bumpNorm = lerp( bumpNorm, float3(0,0,1), 1.0 - rippleMagnitude.w ); @@ -136,7 +136,7 @@ float4 main( ConnectData IN ) : COLOR distortPos.xy += bumpNorm.xy * distortAmt; #ifdef UNDERWATER - return hdrEncode( tex2Dproj( refractBuff, distortPos ) ); + return hdrEncode( TORQUE_TEX2DPROJ( refractBuff, distortPos ) ); #else float3 eyeVec = IN.objPos.xyz - eyePos; @@ -154,16 +154,16 @@ float4 main( ConnectData IN ) : COLOR float fakeColorAmt = ang; // Get reflection map color - float4 refMapColor = hdrDecode( tex2Dproj( reflectMap, distortPos ) ); + float4 refMapColor = hdrDecode( TORQUE_TEX2DPROJ( reflectMap, distortPos ) ); // If we do not have a reflection texture then we use the cubemap. - refMapColor = lerp( refMapColor, texCUBE( skyMap, reflectionVec ), NO_REFLECT ); + refMapColor = lerp( refMapColor, TORQUE_TEXCUBE( skyMap, reflectionVec ), NO_REFLECT ); // Combine reflection color and fakeColor. float4 reflectColor = lerp( refMapColor, fakeColor, fakeColorAmt ); //return refMapColor; // Get refract color - float4 refractColor = hdrDecode( tex2Dproj( refractBuff, distortPos ) ); + float4 refractColor = hdrDecode( TORQUE_TEX2DPROJ( refractBuff, distortPos ) ); // calc "diffuse" color by lerping from the water color // to refraction image based on the water clarity. @@ -198,7 +198,7 @@ float4 main( ConnectData IN ) : COLOR // Fog it. float factor = computeSceneFog( eyePos, - IN.objPos, + IN.objPos.xyz, WORLD_Z, fogData.x, fogData.y, diff --git a/Templates/Full/game/shaders/common/water/waterBasicV.hlsl b/Templates/Full/game/shaders/common/water/waterBasicV.hlsl index 2c201e675..310647c90 100644 --- a/Templates/Full/game/shaders/common/water/waterBasicV.hlsl +++ b/Templates/Full/game/shaders/common/water/waterBasicV.hlsl @@ -20,12 +20,13 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- +#include "../shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- struct VertData { - float4 position : POSITION; + float3 position : POSITION; float3 normal : NORMAL; float2 undulateData : TEXCOORD0; float4 horizonFactor : TEXCOORD1; @@ -33,7 +34,7 @@ struct VertData struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup float4 rippleTexCoord01 : TEXCOORD0; @@ -95,21 +96,21 @@ ConnectData main( VertData IN ) // IN.position.xy += offsetXY; // IN.undulateData += offsetXY; // } - - float4 worldPos = mul( modelMat, IN.position ); + float4 inPos = float4(IN.position, 1.0); + float4 worldPos = mul(modelMat, inPos); IN.position.z = lerp( IN.position.z, eyePos.z, IN.horizonFactor.x ); //OUT.objPos = worldPos; - OUT.objPos.xyz = IN.position.xyz; + OUT.objPos.xyz = IN.position; OUT.objPos.w = worldPos.z; // Send pre-undulation screenspace position - OUT.posPreWave = mul( modelview, IN.position ); + OUT.posPreWave = mul( modelview, inPos ); OUT.posPreWave = mul( texGen, OUT.posPreWave ); // Calculate the undulation amount for this vertex. - float2 undulatePos = mul( modelMat, float4( IN.undulateData.xy, 0, 1 ) ); + float2 undulatePos = mul( modelMat, float4( IN.undulateData.xy, 0, 1 )).xy; //if ( undulatePos.x < 0 ) // undulatePos = IN.position.xy; @@ -128,12 +129,12 @@ ConnectData main( VertData IN ) float undulateFade = 1; // Scale down wave magnitude amount based on distance from the camera. - float dist = distance( IN.position.xyz, eyePos ); + float dist = distance( IN.position, eyePos ); dist = clamp( dist, 1.0, undulateMaxDist ); undulateFade *= ( 1 - dist / undulateMaxDist ); // Also scale down wave magnitude if the camera is very very close. - undulateFade *= saturate( ( distance( IN.position.xyz, eyePos ) - 0.5 ) / 10.0 ); + undulateFade *= saturate( ( distance( IN.position, eyePos ) - 0.5 ) / 10.0 ); undulateAmt *= undulateFade; @@ -141,7 +142,7 @@ ConnectData main( VertData IN ) //undulateAmt = 0; // Apply wave undulation to the vertex. - OUT.posPostWave = IN.position; + OUT.posPostWave = inPos; OUT.posPostWave.xyz += IN.normal.xyz * undulateAmt; // Save worldSpace position of this pixel/vert @@ -210,7 +211,7 @@ ConnectData main( VertData IN ) for ( int i = 0; i < 3; i++ ) { binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * IN.undulateData.x + waveDir[i].y * IN.undulateData.y + elapsedTime * waveData[i].x ); - tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * IN.undulateData.x + waveDir[i].y * IN.undulateData.y + elapsedTime * waveData[i].x ); + tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * IN.undulateData.x + waveDir[i].y * IN.undulateData.y + elapsedTime * waveData[i].x ); } binormal = normalize( binormal ); diff --git a/Templates/Full/game/shaders/common/water/waterP.hlsl b/Templates/Full/game/shaders/common/water/waterP.hlsl index c4edff0d7..ac66e9b28 100644 --- a/Templates/Full/game/shaders/common/water/waterP.hlsl +++ b/Templates/Full/game/shaders/common/water/waterP.hlsl @@ -20,7 +20,7 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../shaderModelAutoGen.hlsl" #include "../torque.hlsl" //----------------------------------------------------------------------------- @@ -69,7 +69,7 @@ struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup float4 rippleTexCoord01 : TEXCOORD0; @@ -105,13 +105,13 @@ float fresnel(float NdotV, float bias, float power) //----------------------------------------------------------------------------- // Uniforms //----------------------------------------------------------------------------- -uniform sampler bumpMap : register( S0 ); -uniform sampler2D prepassTex : register( S1 ); -uniform sampler2D reflectMap : register( S2 ); -uniform sampler refractBuff : register( S3 ); -uniform samplerCUBE skyMap : register( S4 ); -uniform sampler foamMap : register( S5 ); -uniform sampler1D depthGradMap : register( S6 ); +TORQUE_UNIFORM_SAMPLER2D(bumpMap,0); +TORQUE_UNIFORM_SAMPLER2D(prepassTex, 1); +TORQUE_UNIFORM_SAMPLER2D(reflectMap, 2); +TORQUE_UNIFORM_SAMPLER2D(refractBuff, 3); +TORQUE_UNIFORM_SAMPLERCUBE(skyMap, 4); +TORQUE_UNIFORM_SAMPLER2D(foamMap, 5); +TORQUE_UNIFORM_SAMPLER1D(depthGradMap, 6); uniform float4 specularParams; uniform float4 baseColor; uniform float4 miscParams; @@ -138,12 +138,12 @@ uniform float reflectivity; //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -float4 main( ConnectData IN ) : COLOR +float4 main( ConnectData IN ) : TORQUE_TARGET0 { // Get the bumpNorm... - float3 bumpNorm = ( tex2D( bumpMap, IN.rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; - bumpNorm += ( tex2D( bumpMap, IN.rippleTexCoord2.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; + float3 bumpNorm = ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord01.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.x; + bumpNorm += ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord01.zw ).rgb * 2.0 - 1.0 ) * rippleMagnitude.y; + bumpNorm += ( TORQUE_TEX2D( bumpMap, IN.rippleTexCoord2.xy ).rgb * 2.0 - 1.0 ) * rippleMagnitude.z; bumpNorm = normalize( bumpNorm ); bumpNorm = lerp( bumpNorm, float3(0,0,1), 1.0 - rippleMagnitude.w ); @@ -155,7 +155,7 @@ float4 main( ConnectData IN ) : COLOR float2 prepassCoord = viewportCoordToRenderTarget( IN.posPostWave, rtParams1 ); - float startDepth = prepassUncondition( prepassTex, prepassCoord ).w; + float startDepth = TORQUE_PREPASS_UNCONDITION( prepassTex, prepassCoord ).w; // The water depth in world units of the undistorted pixel. float startDelta = ( startDepth - pixelDepth ); @@ -180,7 +180,7 @@ float4 main( ConnectData IN ) : COLOR prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); // Get prepass depth at the position of this distorted pixel. - float prepassDepth = prepassUncondition( prepassTex, prepassCoord ).w; + float prepassDepth = TORQUE_PREPASS_UNCONDITION( prepassTex, prepassCoord ).w; if ( prepassDepth > 0.99 ) prepassDepth = 5.0; @@ -212,7 +212,7 @@ float4 main( ConnectData IN ) : COLOR prepassCoord = viewportCoordToRenderTarget( distortPos, rtParams1 ); // Get prepass depth at the position of this distorted pixel. - prepassDepth = prepassUncondition( prepassTex, prepassCoord ).w; + prepassDepth = TORQUE_PREPASS_UNCONDITION( prepassTex, prepassCoord ).w; if ( prepassDepth > 0.99 ) prepassDepth = 5.0; delta = ( prepassDepth - pixelDepth ) * farPlaneDist; @@ -260,8 +260,8 @@ float4 main( ConnectData IN ) : COLOR IN.foamTexCoords.xy += foamRippleOffset; IN.foamTexCoords.zw += foamRippleOffset; - float4 foamColor = tex2D( foamMap, IN.foamTexCoords.xy ); - foamColor += tex2D( foamMap, IN.foamTexCoords.zw ); + float4 foamColor = TORQUE_TEX2D( foamMap, IN.foamTexCoords.xy ); + foamColor += TORQUE_TEX2D( foamMap, IN.foamTexCoords.zw ); foamColor = saturate( foamColor ); // Modulate foam color by ambient color @@ -282,18 +282,18 @@ float4 main( ConnectData IN ) : COLOR foamColor.rgb *= FOAM_OPACITY * foamAmt * foamColor.a; // Get reflection map color. - float4 refMapColor = tex2D( reflectMap, reflectCoord ); + float4 refMapColor = TORQUE_TEX2D( reflectMap, reflectCoord ); // If we do not have a reflection texture then we use the cubemap. - refMapColor = lerp( refMapColor, texCUBE( skyMap, reflectionVec ), NO_REFLECT ); + refMapColor = lerp( refMapColor, TORQUE_TEXCUBE( skyMap, reflectionVec ), NO_REFLECT ); - fakeColor = ( texCUBE( skyMap, reflectionVec ) ); + fakeColor = ( TORQUE_TEXCUBE( skyMap, reflectionVec ) ); fakeColor.a = 1; // Combine reflection color and fakeColor. float4 reflectColor = lerp( refMapColor, fakeColor, fakeColorAmt ); // Get refract color - float4 refractColor = hdrDecode( tex2D( refractBuff, refractCoord ) ); + float4 refractColor = hdrDecode( TORQUE_TEX2D( refractBuff, refractCoord ) ); // We darken the refraction color a bit to make underwater // elements look wet. We fade out this darkening near the @@ -310,7 +310,7 @@ float4 main( ConnectData IN ) : COLOR float fogAmt = 1.0 - saturate( exp( -FOG_DENSITY * fogDelta ) ); // Calculate the water "base" color based on depth. - float4 waterBaseColor = baseColor * tex1D( depthGradMap, saturate( delta / depthGradMax ) ); + float4 waterBaseColor = baseColor * TORQUE_TEX1D( depthGradMap, saturate( delta / depthGradMax ) ); waterBaseColor = toLinear(waterBaseColor); // Modulate baseColor by the ambientColor. @@ -354,7 +354,7 @@ float4 main( ConnectData IN ) : COLOR #else - float4 refractColor = hdrDecode( tex2D( refractBuff, refractCoord ) ); + float4 refractColor = hdrDecode( TORQUE_TEX2D( refractBuff, refractCoord ) ); float4 OUT = refractColor; #endif diff --git a/Templates/Full/game/shaders/common/water/waterV.hlsl b/Templates/Full/game/shaders/common/water/waterV.hlsl index d2b097bc5..c869f0e9f 100644 --- a/Templates/Full/game/shaders/common/water/waterV.hlsl +++ b/Templates/Full/game/shaders/common/water/waterV.hlsl @@ -20,14 +20,14 @@ // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#include "shadergen:/autogenConditioners.h" +#include "../shaderModel.hlsl" //----------------------------------------------------------------------------- // Structures //----------------------------------------------------------------------------- struct VertData { - float4 position : POSITION; + float3 position : POSITION; float3 normal : NORMAL; float2 undulateData : TEXCOORD0; float4 horizonFactor : TEXCOORD1; @@ -35,7 +35,7 @@ struct VertData struct ConnectData { - float4 hpos : POSITION; + float4 hpos : TORQUE_POSITION; // TexCoord 0 and 1 (xy,zw) for ripple texture lookup float4 rippleTexCoord01 : TEXCOORD0; @@ -94,12 +94,12 @@ ConnectData main( VertData IN ) 0.0, 0.0, 0.0, 1.0 }; IN.position.z = lerp( IN.position.z, eyePos.z, IN.horizonFactor.x ); - - OUT.objPos = IN.position; - OUT.objPos.w = mul( modelMat, IN.position ).z; + float4 inPos = float4( IN.position, 1.0); + OUT.objPos = inPos; + OUT.objPos.w = mul( modelMat, inPos ).z; // Send pre-undulation screenspace position - OUT.posPreWave = mul( modelview, IN.position ); + OUT.posPreWave = mul( modelview, inPos ); OUT.posPreWave = mul( texGen, OUT.posPreWave ); // Calculate the undulation amount for this vertex. @@ -132,7 +132,7 @@ ConnectData main( VertData IN ) OUT.rippleTexCoord2.w = saturate( OUT.rippleTexCoord2.w - 0.2 ) / 0.8; // Apply wave undulation to the vertex. - OUT.posPostWave = IN.position; + OUT.posPostWave = inPos; OUT.posPostWave.xyz += IN.normal.xyz * undulateAmt; // Convert to screen @@ -197,7 +197,7 @@ ConnectData main( VertData IN ) for ( int i = 0; i < 3; i++ ) { binormal.z += undulateFade * waveDir[i].x * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); - tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); + tangent.z += undulateFade * waveDir[i].y * waveData[i].y * cos( waveDir[i].x * undulatePos.x + waveDir[i].y * undulatePos.y + elapsedTime * waveData[i].x ); } binormal = binormal; diff --git a/Templates/Full/game/shaders/common/wavesP.hlsl b/Templates/Full/game/shaders/common/wavesP.hlsl index 265842f1f..c51eb4b89 100644 --- a/Templates/Full/game/shaders/common/wavesP.hlsl +++ b/Templates/Full/game/shaders/common/wavesP.hlsl @@ -22,13 +22,14 @@ #define IN_HLSL #include "shdrConsts.h" +#include "shaderModel.hlsl" //----------------------------------------------------------------------------- // Data //----------------------------------------------------------------------------- struct v2f { - float4 HPOS : POSITION; + float4 HPOS : TORQUE_POSITION; float2 TEX0 : TEXCOORD0; float4 tangentToCube0 : TEXCOORD1; float4 tangentToCube1 : TEXCOORD2; @@ -42,21 +43,23 @@ struct v2f struct Fragout { - float4 col : COLOR0; + float4 col : TORQUE_TARGET0; }; +// Uniforms +TORQUE_UNIFORM_SAMPLER2D(diffMap,0); +//TORQUE_UNIFORM_SAMPLERCUBE(cubeMap, 1); not used? +TORQUE_UNIFORM_SAMPLER2D(bumpMap,2); + +uniform float4 specularColor : register(PC_MAT_SPECCOLOR); +uniform float4 ambient : register(PC_AMBIENT_COLOR); +uniform float specularPower : register(PC_MAT_SPECPOWER); +uniform float accumTime : register(PC_ACCUM_TIME); + //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Fragout main(v2f IN, - uniform sampler2D diffMap : register(S0), - uniform sampler2D bumpMap : register(S2), - uniform samplerCUBE cubeMap : register(S1), - uniform float4 specularColor : register(PC_MAT_SPECCOLOR), - uniform float specularPower : register(PC_MAT_SPECPOWER), - uniform float4 ambient : register(PC_AMBIENT_COLOR), - uniform float accumTime : register(PC_ACCUM_TIME) -) +Fragout main(v2f IN) { Fragout OUT; @@ -68,8 +71,8 @@ Fragout main(v2f IN, texOffset.y = IN.TEX0.y + cos( accumTime * 3.0 + IN.TEX0.x * 6.28319 * 2.0 ) * 0.05; - float4 bumpNorm = tex2D( bumpMap, texOffset ) * 2.0 - 1.0; - float4 diffuse = tex2D( diffMap, texOffset ); + float4 bumpNorm = TORQUE_TEX2D( bumpMap, texOffset ) * 2.0 - 1.0; + float4 diffuse = TORQUE_TEX2D( diffMap, texOffset ); OUT.col = diffuse * (saturate( dot( IN.lightVec, bumpNorm.xyz ) ) + ambient); diff --git a/Templates/Full/game/shaders/common/wavesV.hlsl b/Templates/Full/game/shaders/common/wavesV.hlsl index 6580daa5b..fccef9d25 100644 --- a/Templates/Full/game/shaders/common/wavesV.hlsl +++ b/Templates/Full/game/shaders/common/wavesV.hlsl @@ -22,7 +22,7 @@ #define IN_HLSL #include "shdrConsts.h" -#include "hlslStructs.h" +#include "hlslStructs.hlsl" //----------------------------------------------------------------------------- // Constants @@ -42,21 +42,20 @@ struct Conn }; +uniform float4x4 modelview : register(VC_WORLD_PROJ); +uniform float3x3 cubeTrans : register(VC_CUBE_TRANS); +uniform float3 cubeEyePos : register(VC_CUBE_EYE_POS); +uniform float3 inLightVec : register(VC_LIGHT_DIR1); +uniform float3 eyePos : register(VC_EYE_POS); //----------------------------------------------------------------------------- // Main //----------------------------------------------------------------------------- -Conn main( VertexIn_PNTTTB In, - uniform float4x4 modelview : register(VC_WORLD_PROJ), - uniform float3x3 cubeTrans : register(VC_CUBE_TRANS), - uniform float3 cubeEyePos : register(VC_CUBE_EYE_POS), - uniform float3 inLightVec : register(VC_LIGHT_DIR1), - uniform float3 eyePos : register(VC_EYE_POS) -) +Conn main( VertexIn_PNTTTB In) { Conn Out; - Out.HPOS = mul(modelview, In.pos); + Out.HPOS = mul(modelview, float4(In.pos,1.0)); Out.TEX0 = In.uv0; From 41e5caf22b6332c96197e8a83c0ac2e279a1af4c Mon Sep 17 00:00:00 2001 From: rextimmy Date: Sun, 20 Mar 2016 21:52:11 +1000 Subject: [PATCH 3/5] Direct3D11 Engine/source changes --- Engine/source/T3D/cameraSpline.cpp | 2 +- Engine/source/T3D/fx/precipitation.cpp | 2 +- Engine/source/T3D/fx/precipitation.h | 2 +- Engine/source/environment/VolumetricFog.cpp | 12 +- .../environment/VolumetricFogRTManager.cpp | 34 +-- .../environment/VolumetricFogRTManager.h | 1 - Engine/source/environment/scatterSky.cpp | 12 +- Engine/source/environment/sun.cpp | 10 +- Engine/source/environment/waterObject.cpp | 14 +- Engine/source/gfx/D3D9/gfxD3D9Device.cpp | 1 + Engine/source/gfx/D3D9/gfxD3D9Shader.cpp | 13 +- .../source/gfx/D3D9/gfxD3D9VertexBuffer.cpp | 3 +- .../gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp | 1 - Engine/source/gfx/D3D9/pc/gfxPCD3D9Device.cpp | 2 +- Engine/source/gfx/D3D9/screenshotD3D9.cpp | 2 +- Engine/source/gfx/D3D9/screenshotD3D9.h | 8 +- Engine/source/gfx/genericConstBuffer.h | 12 +- Engine/source/gfx/gfxAPI.cpp | 2 +- Engine/source/gfx/gfxDevice.cpp | 2 + Engine/source/gfx/gfxDrawUtil.cpp | 153 +++++++--- Engine/source/gfx/gfxEnums.h | 3 +- Engine/source/gfx/gfxInit.cpp | 49 ++-- Engine/source/gfx/gfxShader.cpp | 15 +- Engine/source/gfx/gfxShader.h | 13 +- Engine/source/gfx/gfxStringEnumTranslate.cpp | 1 - Engine/source/gfx/gfxVertexFormat.cpp | 15 + Engine/source/gfx/gfxVertexFormat.h | 11 +- Engine/source/gfx/gl/gfxGLDevice.cpp | 13 +- Engine/source/gfx/gl/gfxGLEnumTranslate.cpp | 1 - Engine/source/gfx/gl/gfxGLShader.cpp | 12 +- Engine/source/gfx/primBuilder.cpp | 2 - Engine/source/gui/3d/guiTSControl.cpp | 2 +- .../source/gui/controls/guiGradientCtrl.cpp | 120 ++++---- .../gui/controls/guiTextEditSliderCtrl.cpp | 2 +- Engine/source/gui/editor/guiEditCtrl.h | 2 +- Engine/source/gui/editor/guiFilterCtrl.cpp | 2 +- Engine/source/gui/editor/guiGraphCtrl.cpp | 2 +- Engine/source/gui/worldEditor/editTSCtrl.cpp | 2 +- Engine/source/gui/worldEditor/gizmo.cpp | 6 +- .../gui/worldEditor/guiTerrPreviewCtrl.cpp | 20 +- .../source/gui/worldEditor/terrainEditor.cpp | 26 +- Engine/source/gui/worldEditor/terrainEditor.h | 2 +- Engine/source/gui/worldEditor/worldEditor.cpp | 4 +- .../advanced/advancedLightBinManager.cpp | 32 +- .../glsl/deferredShadingFeaturesGLSL.cpp | 1 - .../advanced/glsl/gBufferConditionerGLSL.cpp | 2 +- .../hlsl/advancedLightingFeaturesHLSL.cpp | 131 +++++++-- .../hlsl/deferredShadingFeaturesHLSL.cpp | 29 +- .../advanced/hlsl/gBufferConditionerHLSL.cpp | 35 ++- Engine/source/lighting/common/blobShadow.cpp | 2 +- Engine/source/materials/miscShdrDat.h | 7 +- .../materials/processedShaderMaterial.cpp | 2 +- .../materials/processedShaderMaterial.h | 2 + Engine/source/materials/shaderData.cpp | 1 + .../platformWin32/videoInfo/wmiVideoInfo.cpp | 120 ++++---- .../platformWin32/videoInfo/wmiVideoInfo.h | 5 +- Engine/source/postFx/postEffect.cpp | 24 +- .../renderInstance/renderPrePassMgr.cpp | 1 - Engine/source/scene/reflectionManager.cpp | 14 +- Engine/source/scene/simPath.cpp | 4 +- Engine/source/scene/simPath.h | 2 +- .../source/shaderGen/HLSL/accuFeatureHLSL.cpp | 31 +- Engine/source/shaderGen/HLSL/bumpHLSL.cpp | 61 +++- .../source/shaderGen/HLSL/paraboloidHLSL.cpp | 10 +- .../source/shaderGen/HLSL/pixSpecularHLSL.cpp | 34 ++- .../source/shaderGen/HLSL/shaderCompHLSL.cpp | 110 +++---- Engine/source/shaderGen/HLSL/shaderCompHLSL.h | 2 + .../shaderGen/HLSL/shaderFeatureHLSL.cpp | 274 +++++++++++++++--- .../source/shaderGen/HLSL/shaderFeatureHLSL.h | 5 + .../source/shaderGen/HLSL/shaderGenHLSL.cpp | 36 ++- .../shaderGen/HLSL/shaderGenHLSLInit.cpp | 1 + Engine/source/shaderGen/langElement.cpp | 4 + Engine/source/shaderGen/langElement.h | 2 + Engine/source/shaderGen/shaderFeature.cpp | 5 + Engine/source/shaderGen/shaderFeature.h | 7 +- Engine/source/shaderGen/shaderGen.cpp | 7 +- .../source/terrain/glsl/terrFeatureGLSL.cpp | 4 - .../source/terrain/hlsl/terrFeatureHLSL.cpp | 254 +++++++++++++--- Engine/source/terrain/terrRender.cpp | 18 +- Engine/source/ts/tsMesh.cpp | 14 +- .../windowManager/win32/win32Window.cpp | 2 + 81 files changed, 1291 insertions(+), 617 deletions(-) diff --git a/Engine/source/T3D/cameraSpline.cpp b/Engine/source/T3D/cameraSpline.cpp index 144415015..9b0f93d5b 100644 --- a/Engine/source/T3D/cameraSpline.cpp +++ b/Engine/source/T3D/cameraSpline.cpp @@ -188,7 +188,7 @@ void CameraSpline::renderTimeMap() gBuilding = true; // Build vertex buffer - GFXVertexBufferHandle vb; + GFXVertexBufferHandle vb; vb.set(GFX, mTimeMap.size(), GFXBufferTypeVolatile); void *ptr = vb.lock(); if(!ptr) return; diff --git a/Engine/source/T3D/fx/precipitation.cpp b/Engine/source/T3D/fx/precipitation.cpp index d7067c063..0cbcf7c7f 100644 --- a/Engine/source/T3D/fx/precipitation.cpp +++ b/Engine/source/T3D/fx/precipitation.cpp @@ -1557,7 +1557,7 @@ void Precipitation::renderObject(ObjectRenderInst *ri, SceneRenderState *state, Point3F pos; VectorF orthoDir, velocity, right, up, rightUp(0.0f, 0.0f, 0.0f), leftUp(0.0f, 0.0f, 0.0f); F32 distance = 0; - GFXVertexPT* vertPtr = NULL; + GFXVertexPCT* vertPtr = NULL; const Point2F *tc; // Do this here and we won't have to in the loop! diff --git a/Engine/source/T3D/fx/precipitation.h b/Engine/source/T3D/fx/precipitation.h index 908d7005f..80f76f2bb 100644 --- a/Engine/source/T3D/fx/precipitation.h +++ b/Engine/source/T3D/fx/precipitation.h @@ -239,7 +239,7 @@ class Precipitation : public GameBase void destroySplash(Raindrop *drop); ///< Removes a drop from the splash list GFXPrimitiveBufferHandle mRainIB; - GFXVertexBufferHandle mRainVB; + GFXVertexBufferHandle mRainVB; bool onAdd(); void onRemove(); diff --git a/Engine/source/environment/VolumetricFog.cpp b/Engine/source/environment/VolumetricFog.cpp index e6be112dc..9087effee 100644 --- a/Engine/source/environment/VolumetricFog.cpp +++ b/Engine/source/environment/VolumetricFog.cpp @@ -317,8 +317,7 @@ void VolumetricFog::handleResize(VolumetricFogRTManager *RTM, bool resize) { F32 width = (F32)mPlatformWindow->getClientExtent().x; F32 height = (F32)mPlatformWindow->getClientExtent().y; - if (!mPlatformWindow->isFullscreen()) - height -= 20;//subtract caption bar from rendertarget size. + mTexScale.x = 2.0f - ((F32)mTexture.getWidth() / width); mTexScale.y = 2.0f - ((F32)mTexture.getHeight() / height); } @@ -1075,7 +1074,6 @@ void VolumetricFog::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMa mPPShaderConsts->setSafe(mPPModelViewProjSC, xform); - LightInfo *lightinfo = LIGHTMGR->getSpecialLight(LightManager::slSunLightType); const ColorF &sunlight = state->getAmbientLightColor(); Point3F ambientColor(sunlight.red, sunlight.green, sunlight.blue); @@ -1160,6 +1158,11 @@ void VolumetricFog::render(ObjectRenderInst *ri, SceneRenderState *state, BaseMa GFX->setStateBlock(mStateblockF); GFX->drawPrimitive(0); + + // Ensure these two textures are bound to the pixel shader input on the second run as they are used as pixel shader outputs (render targets). + GFX->setTexture(1, NULL); //mDepthBuffer + GFX->setTexture(2, NULL); //mFrontBuffer + GFX->updateStates(); //update the dirty texture state we set above } void VolumetricFog::reflect_render(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance *overrideMat) @@ -1210,9 +1213,6 @@ void VolumetricFog::InitTexture() F32 width = (F32)mPlatformWindow->getClientExtent().x; F32 height = (F32)mPlatformWindow->getClientExtent().y; - if (!mPlatformWindow->isFullscreen()) - height -= 20;//subtract caption bar from rendertarget size. - mTexScale.x = 2.0f - ((F32)mTexture.getWidth() / width); mTexScale.y = 2.0f - ((F32)mTexture.getHeight() / height); } diff --git a/Engine/source/environment/VolumetricFogRTManager.cpp b/Engine/source/environment/VolumetricFogRTManager.cpp index 2a927cc09..8c98983b2 100644 --- a/Engine/source/environment/VolumetricFogRTManager.cpp +++ b/Engine/source/environment/VolumetricFogRTManager.cpp @@ -36,6 +36,7 @@ #include "windowManager/platformWindowMgr.h" #include "console/engineAPI.h" #include "gui/core/guiCanvas.h" +#include "gfx/gfxDevice.h" MODULE_BEGIN(VolumetricFogRTManager) @@ -127,10 +128,10 @@ void VolumetricFogRTManager::consoleInit() bool VolumetricFogRTManager::Init() { if (mIsInitialized) - { + { Con::errorf("VolumetricFogRTManager allready initialized!!"); return true; - } + } GuiCanvas* cv = dynamic_cast(Sim::findObject("Canvas")); if (cv == NULL) @@ -142,15 +143,11 @@ bool VolumetricFogRTManager::Init() mPlatformWindow = cv->getPlatformWindow(); mPlatformWindow->getScreenResChangeSignal().notify(this,&VolumetricFogRTManager::ResizeRT); - if (mTargetScale < 1) + if (mTargetScale < 1 || GFX->getAdapterType() == Direct3D11) mTargetScale = 1; mWidth = mFloor(mPlatformWindow->getClientExtent().x / mTargetScale); - mHeight = mPlatformWindow->getClientExtent().y; - mFullScreen = mPlatformWindow->isFullscreen(); - if (!mFullScreen) - mHeight -= 20;//subtract caption bar from rendertarget size. - mHeight = mFloor(mHeight / mTargetScale); + mHeight = mFloor(mPlatformWindow->getClientExtent().y / mTargetScale); mDepthBuffer = GFXTexHandle(mWidth, mHeight, GFXFormatR32F, &GFXDefaultRenderTargetProfile, avar("%s() - mDepthBuffer (line %d)", __FUNCTION__, __LINE__)); @@ -221,14 +218,11 @@ void VolumetricFogRTManager::FogAnswered() bool VolumetricFogRTManager::Resize() { - if (mTargetScale < 1) + if (mTargetScale < 1 || GFX->getAdapterType() == Direct3D11) mTargetScale = 1; + mWidth = mFloor(mPlatformWindow->getClientExtent().x / mTargetScale); - mHeight = mPlatformWindow->getClientExtent().y; - - if (!mPlatformWindow->isFullscreen()) - mHeight -= 20;//subtract caption bar from rendertarget size. - mHeight = mFloor(mHeight / mTargetScale); + mHeight = mFloor(mPlatformWindow->getClientExtent().y / mTargetScale); if (mWidth < 16 || mHeight < 16) return false; @@ -248,19 +242,19 @@ bool VolumetricFogRTManager::Resize() mFrontBuffer = GFXTexHandle(mWidth, mHeight, GFXFormatR32F, &GFXDefaultRenderTargetProfile, avar("%s() - mFrontBuffer (line %d)", __FUNCTION__, __LINE__)); if (!mFrontBuffer.isValid()) - { + { Con::errorf("VolumetricFogRTManager::Resize() Fatal Error: Unable to create front buffer"); return false; - } + } mFrontTarget.setTexture(mFrontBuffer); mDepthBuffer = GFXTexHandle(mWidth, mHeight, GFXFormatR32F, &GFXDefaultRenderTargetProfile, avar("%s() - mDepthBuffer (line %d)", __FUNCTION__, __LINE__)); if (!mDepthBuffer.isValid()) - { - Con::errorf("VolumetricFogRTManager::Resize() Fatal Error: Unable to create Depthbuffer"); - return false; - } + { + Con::errorf("VolumetricFogRTManager::Resize() Fatal Error: Unable to create Depthbuffer"); + return false; + } mDepthTarget.setTexture(mDepthBuffer); return true; } diff --git a/Engine/source/environment/VolumetricFogRTManager.h b/Engine/source/environment/VolumetricFogRTManager.h index d69bed6bd..8000a4447 100644 --- a/Engine/source/environment/VolumetricFogRTManager.h +++ b/Engine/source/environment/VolumetricFogRTManager.h @@ -62,7 +62,6 @@ class VolumetricFogRTManager : public SceneObject U32 mFogHasAnswered; U32 mWidth; U32 mHeight; - bool mFullScreen; void onRemove(); void onSceneRemove(); diff --git a/Engine/source/environment/scatterSky.cpp b/Engine/source/environment/scatterSky.cpp index dbdeef48b..7607246f4 100644 --- a/Engine/source/environment/scatterSky.cpp +++ b/Engine/source/environment/scatterSky.cpp @@ -1067,17 +1067,17 @@ void ScatterSky::_renderMoon( ObjectRenderInst *ri, SceneRenderState *state, Bas // Initialize points with basic info Point3F points[4]; - points[0] = Point3F(-BBRadius, 0.0, -BBRadius); + points[0] = Point3F( -BBRadius, 0.0, -BBRadius); points[1] = Point3F( -BBRadius, 0.0, BBRadius); - points[2] = Point3F( BBRadius, 0.0, BBRadius); - points[3] = Point3F( BBRadius, 0.0, -BBRadius); + points[2] = Point3F( BBRadius, 0.0, -BBRadius); + points[3] = Point3F( BBRadius, 0.0, BBRadius); static const Point2F sCoords[4] = { Point2F( 0.0f, 0.0f ), Point2F( 0.0f, 1.0f ), - Point2F( 1.0f, 1.0f ), - Point2F( 1.0f, 0.0f ) + Point2F( 1.0f, 0.0f ), + Point2F( 1.0f, 1.0f ) }; // Get info we need to adjust points @@ -1126,7 +1126,7 @@ void ScatterSky::_renderMoon( ObjectRenderInst *ri, SceneRenderState *state, Bas mMoonMatInst->setSceneInfo( state, sgData ); GFX->setVertexBuffer( vb ); - GFX->drawPrimitive( GFXTriangleFan, 0, 2 ); + GFX->drawPrimitive( GFXTriangleStrip, 0, 2 ); } } diff --git a/Engine/source/environment/sun.cpp b/Engine/source/environment/sun.cpp index d79d923d6..729e3b57b 100644 --- a/Engine/source/environment/sun.cpp +++ b/Engine/source/environment/sun.cpp @@ -467,15 +467,15 @@ void Sun::_renderCorona( ObjectRenderInst *ri, SceneRenderState *state, BaseMatI Point3F points[4]; points[0] = Point3F(-BBRadius, 0.0, -BBRadius); points[1] = Point3F( -BBRadius, 0.0, BBRadius); - points[2] = Point3F( BBRadius, 0.0, BBRadius); - points[3] = Point3F( BBRadius, 0.0, -BBRadius); + points[2] = Point3F( BBRadius, 0.0, -BBRadius); + points[3] = Point3F(BBRadius, 0.0, BBRadius); static const Point2F sCoords[4] = { Point2F( 0.0f, 0.0f ), Point2F( 0.0f, 1.0f ), - Point2F( 1.0f, 1.0f ), - Point2F( 1.0f, 0.0f ) + Point2F( 1.0f, 0.0f ), + Point2F(1.0f, 1.0f) }; // Get info we need to adjust points @@ -525,7 +525,7 @@ void Sun::_renderCorona( ObjectRenderInst *ri, SceneRenderState *state, BaseMatI mCoronaMatInst->setSceneInfo( state, sgData ); GFX->setVertexBuffer( vb ); - GFX->drawPrimitive( GFXTriangleFan, 0, 2 ); + GFX->drawPrimitive( GFXTriangleStrip, 0, 2 ); } } diff --git a/Engine/source/environment/waterObject.cpp b/Engine/source/environment/waterObject.cpp index 9b527e4c8..1dab7ca74 100644 --- a/Engine/source/environment/waterObject.cpp +++ b/Engine/source/environment/waterObject.cpp @@ -826,25 +826,25 @@ void WaterObject::drawUnderwaterFilter( SceneRenderState *state ) // draw quad - GFXVertexBufferHandle verts( GFX, 4, GFXBufferTypeVolatile ); + GFXVertexBufferHandle verts( GFX, 4, GFXBufferTypeVolatile ); verts.lock(); - verts[0].point.set( -1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 ); + verts[0].point.set(1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0); verts[0].color = mUnderwaterColor; - verts[1].point.set( -1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 ); + verts[1].point.set(1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0); verts[1].color = mUnderwaterColor; - verts[2].point.set( 1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 ); + verts[2].point.set(-1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0); verts[2].color = mUnderwaterColor; - verts[3].point.set( 1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 ); + verts[3].point.set(-1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0); verts[3].color = mUnderwaterColor; verts.unlock(); GFX->setVertexBuffer( verts ); - GFX->drawPrimitive( GFXTriangleFan, 0, 2 ); + GFX->drawPrimitive( GFXTriangleStrip, 0, 2 ); // reset states / transforms GFX->setProjectionMatrix( proj ); @@ -1141,7 +1141,7 @@ bool WaterObject::initMaterial( S32 idx ) else mat = MATMGR->createMatInstance( mSurfMatName[idx] ); - const GFXVertexFormat *flags = getGFXVertexFormat(); + const GFXVertexFormat *flags = getGFXVertexFormat(); if ( mat && mat->init( MATMGR->getDefaultFeatures(), flags ) ) { diff --git a/Engine/source/gfx/D3D9/gfxD3D9Device.cpp b/Engine/source/gfx/D3D9/gfxD3D9Device.cpp index d3eb8ed8a..c6610ed14 100644 --- a/Engine/source/gfx/D3D9/gfxD3D9Device.cpp +++ b/Engine/source/gfx/D3D9/gfxD3D9Device.cpp @@ -826,6 +826,7 @@ GFXVertexBuffer * GFXD3D9Device::allocVertexBuffer( U32 numVerts, switch(bufferType) { + case GFXBufferTypeImmutable: case GFXBufferTypeStatic: pool = isD3D9Ex() ? D3DPOOL_DEFAULT : D3DPOOL_MANAGED; break; diff --git a/Engine/source/gfx/D3D9/gfxD3D9Shader.cpp b/Engine/source/gfx/D3D9/gfxD3D9Shader.cpp index 2af7a9abd..657797319 100644 --- a/Engine/source/gfx/D3D9/gfxD3D9Shader.cpp +++ b/Engine/source/gfx/D3D9/gfxD3D9Shader.cpp @@ -1307,10 +1307,15 @@ void GFXD3D9Shader::_buildSamplerShaderConstantHandles( VectorgetElementCount(); i++ ) { - const GFXVertexElement &element = mInstancingFormat.getElement( i ); + const GFXVertexElement &element = mInstancingFormat->getElement( i ); String constName = String::ToString( "$%s", element.getSemantic().c_str() ); @@ -1347,9 +1352,9 @@ void GFXD3D9Shader::_buildInstancingShaderConstantHandles() // If this is a matrix we will have 2 or 3 more of these // semantics with the same name after it. - for ( ; i < mInstancingFormat.getElementCount(); i++ ) + for ( ; i < mInstancingFormat->getElementCount(); i++ ) { - const GFXVertexElement &nextElement = mInstancingFormat.getElement( i ); + const GFXVertexElement &nextElement = mInstancingFormat->getElement( i ); if ( nextElement.getSemantic() != element.getSemantic() ) { i--; diff --git a/Engine/source/gfx/D3D9/gfxD3D9VertexBuffer.cpp b/Engine/source/gfx/D3D9/gfxD3D9VertexBuffer.cpp index d31e93870..0da7a3895 100644 --- a/Engine/source/gfx/D3D9/gfxD3D9VertexBuffer.cpp +++ b/Engine/source/gfx/D3D9/gfxD3D9VertexBuffer.cpp @@ -55,6 +55,7 @@ void GFXD3D9VertexBuffer::lock(U32 vertexStart, U32 vertexEnd, void **vertexPtr) switch( mBufferType ) { + case GFXBufferTypeImmutable: case GFXBufferTypeStatic: break; @@ -203,7 +204,7 @@ void GFXD3D9VertexBuffer::zombify() { AssertFatal(lockedVertexStart == 0 && lockedVertexEnd == 0, "GFXD3D9VertexBuffer::zombify - Cannot zombify a locked buffer!"); // Static buffers are managed by D3D9 so we don't deal with them. - if(mBufferType == GFXBufferTypeDynamic) + if(mBufferType == GFXBufferTypeDynamic || mBufferType == GFXBufferTypeImmutable) { SAFE_RELEASE(vb); } diff --git a/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp b/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp index 29063f4e4..77ea67041 100644 --- a/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp +++ b/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp @@ -302,7 +302,6 @@ void GFXD3D9EnumTranslate::init() GFXD3D9PrimType[GFXLineStrip] = D3DPT_LINESTRIP; GFXD3D9PrimType[GFXTriangleList] = D3DPT_TRIANGLELIST; GFXD3D9PrimType[GFXTriangleStrip] = D3DPT_TRIANGLESTRIP; - GFXD3D9PrimType[GFXTriangleFan] = D3DPT_TRIANGLEFAN; VALIDATE_LOOKUPTABLE( GFXD3D9PrimType, GFXPT ); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ diff --git a/Engine/source/gfx/D3D9/pc/gfxPCD3D9Device.cpp b/Engine/source/gfx/D3D9/pc/gfxPCD3D9Device.cpp index 3dfcfe1d4..d113bf70b 100644 --- a/Engine/source/gfx/D3D9/pc/gfxPCD3D9Device.cpp +++ b/Engine/source/gfx/D3D9/pc/gfxPCD3D9Device.cpp @@ -514,7 +514,7 @@ void GFXPCD3D9Device::init( const GFXVideoMode &mode, PlatformWindow *window /* mCardProfiler = new GFXD3D9CardProfiler(mAdapterIndex); mCardProfiler->init(); - gScreenShot = new ScreenShotD3D; + gScreenShot = new ScreenShotD3D9; // Set the video capture frame grabber. mVideoFrameGrabber = new VideoFrameGrabberD3D9(); diff --git a/Engine/source/gfx/D3D9/screenshotD3D9.cpp b/Engine/source/gfx/D3D9/screenshotD3D9.cpp index b6b5e0500..c7d3ff3cb 100644 --- a/Engine/source/gfx/D3D9/screenshotD3D9.cpp +++ b/Engine/source/gfx/D3D9/screenshotD3D9.cpp @@ -30,7 +30,7 @@ #include -GBitmap* ScreenShotD3D::_captureBackBuffer() +GBitmap* ScreenShotD3D9::_captureBackBuffer() { #ifdef TORQUE_OS_XENON return NULL; diff --git a/Engine/source/gfx/D3D9/screenshotD3D9.h b/Engine/source/gfx/D3D9/screenshotD3D9.h index d017591d6..023fa1562 100644 --- a/Engine/source/gfx/D3D9/screenshotD3D9.h +++ b/Engine/source/gfx/D3D9/screenshotD3D9.h @@ -19,15 +19,15 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- -#ifndef _SCREENSHOTD3D_H_ -#define _SCREENSHOTD3D_H_ +#ifndef _SCREENSHOTD3D9_H_ +#define _SCREENSHOTD3D9_H_ #include "gfx/screenshot.h" //************************************************************************** // D3D implementation of screenshot //************************************************************************** -class ScreenShotD3D : public ScreenShot +class ScreenShotD3D9 : public ScreenShot { protected: @@ -36,4 +36,4 @@ protected: }; -#endif // _SCREENSHOTD3D_H_ +#endif // _SCREENSHOTD3D9_H_ diff --git a/Engine/source/gfx/genericConstBuffer.h b/Engine/source/gfx/genericConstBuffer.h index b8a012159..c38947541 100644 --- a/Engine/source/gfx/genericConstBuffer.h +++ b/Engine/source/gfx/genericConstBuffer.h @@ -106,7 +106,7 @@ public: virtual ~GenericConstBufferLayout() {} /// Add a parameter to the buffer - void addParameter(const String& name, const GFXShaderConstType constType, const U32 offset, const U32 size, const U32 arraySize, const U32 alignValue); + virtual void addParameter(const String& name, const GFXShaderConstType constType, const U32 offset, const U32 size, const U32 arraySize, const U32 alignValue); /// Get the size of the buffer inline U32 getBufferSize() const { return mBufferSize; } @@ -210,6 +210,9 @@ public: /// state at the same time. inline const U8* getDirtyBuffer( U32 *start, U32 *size ); + /// Gets the entire buffer ignoring dirty range + inline const U8* getEntireBuffer(); + /// Sets the entire buffer as dirty or clears the dirty state. inline void setDirty( bool dirty ); @@ -348,6 +351,13 @@ inline const U8* GenericConstBuffer::getDirtyBuffer( U32 *start, U32 *size ) return buffer; } +inline const U8* GenericConstBuffer::getEntireBuffer() +{ + AssertFatal(mBuffer, "GenericConstBuffer::getDirtyBuffer() - Buffer is empty!"); + + return mBuffer; +} + inline bool GenericConstBuffer::isEqual( const GenericConstBuffer *buffer ) const { U32 bsize = mLayout->getBufferSize(); diff --git a/Engine/source/gfx/gfxAPI.cpp b/Engine/source/gfx/gfxAPI.cpp index 91a9974df..b41b1297b 100644 --- a/Engine/source/gfx/gfxAPI.cpp +++ b/Engine/source/gfx/gfxAPI.cpp @@ -41,7 +41,7 @@ ImplementEnumType( GFXAdapterType, "Back-end graphics API used by the GFX subsystem.\n\n" "@ingroup GFX" ) { OpenGL, "OpenGL", "OpenGL." }, - { Direct3D8, "D3D8", "Direct3D 8." }, + { Direct3D11, "D3D11", "Direct3D 11." }, { Direct3D9, "D3D9", "Direct3D 9." }, { NullDevice, "NullDevice", "Null device for dedicated servers." }, { Direct3D9_360, "Xenon", "Direct3D 9 on Xbox 360." } diff --git a/Engine/source/gfx/gfxDevice.cpp b/Engine/source/gfx/gfxDevice.cpp index 3f63fb884..5158f2992 100644 --- a/Engine/source/gfx/gfxDevice.cpp +++ b/Engine/source/gfx/gfxDevice.cpp @@ -514,6 +514,8 @@ void GFXDevice::updateStates(bool forceSetAll /*=false*/) mStateBlockDirty = false; } + _updateRenderTargets(); + if( mTexturesDirty ) { mTexturesDirty = false; diff --git a/Engine/source/gfx/gfxDrawUtil.cpp b/Engine/source/gfx/gfxDrawUtil.cpp index 34b1c8872..3adbfb7b7 100644 --- a/Engine/source/gfx/gfxDrawUtil.cpp +++ b/Engine/source/gfx/gfxDrawUtil.cpp @@ -458,7 +458,7 @@ void GFXDrawUtil::drawRect( const Point2F &upperLeft, const Point2F &lowerRight, Point2F nw(-0.5f,-0.5f); /* \ */ Point2F ne(0.5f,-0.5f); /* / */ - GFXVertexBufferHandle verts (mDevice, 10, GFXBufferTypeVolatile ); + GFXVertexBufferHandle verts (mDevice, 10, GFXBufferTypeVolatile ); verts.lock(); F32 ulOffset = 0.5f - mDevice->getFillConventionOffset(); @@ -521,12 +521,12 @@ void GFXDrawUtil::drawRectFill( const Point2F &upperLeft, const Point2F &lowerRi Point2F nw(-0.5,-0.5); /* \ */ Point2F ne(0.5,-0.5); /* / */ - GFXVertexBufferHandle verts(mDevice, 4, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, 4, GFXBufferTypeVolatile); verts.lock(); F32 ulOffset = 0.5f - mDevice->getFillConventionOffset(); - verts[0].point.set( upperLeft.x + nw.x + ulOffset, upperLeft.y + nw.y + ulOffset, 0.0f); + verts[0].point.set( upperLeft.x+nw.x + ulOffset, upperLeft.y+nw.y + ulOffset, 0.0f ); verts[1].point.set( lowerRight.x + ne.x + ulOffset, upperLeft.y + ne.y + ulOffset, 0.0f); verts[2].point.set( upperLeft.x - ne.x + ulOffset, lowerRight.y - ne.y + ulOffset, 0.0f); verts[3].point.set( lowerRight.x - nw.x + ulOffset, lowerRight.y - nw.y + ulOffset, 0.0f); @@ -548,7 +548,7 @@ void GFXDrawUtil::draw2DSquare( const Point2F &screenPoint, F32 width, F32 spinA Point3F offset( screenPoint.x, screenPoint.y, 0.0 ); - GFXVertexBufferHandle verts( mDevice, 4, GFXBufferTypeVolatile ); + GFXVertexBufferHandle verts( mDevice, 4, GFXBufferTypeVolatile ); verts.lock(); verts[0].point.set( -width, -width, 0.0f ); @@ -608,7 +608,7 @@ void GFXDrawUtil::drawLine( F32 x1, F32 y1, F32 x2, F32 y2, const ColorI &color void GFXDrawUtil::drawLine( F32 x1, F32 y1, F32 z1, F32 x2, F32 y2, F32 z2, const ColorI &color ) { - GFXVertexBufferHandle verts( mDevice, 2, GFXBufferTypeVolatile ); + GFXVertexBufferHandle verts( mDevice, 2, GFXBufferTypeVolatile ); verts.lock(); verts[0].point.set( x1, y1, z1 ); @@ -647,7 +647,7 @@ void GFXDrawUtil::drawSphere( const GFXStateBlockDesc &desc, F32 radius, const P const SphereMesh::TriangleMesh * sphereMesh = gSphere.getMesh(2); S32 numPoly = sphereMesh->numPoly; S32 totalPoly = 0; - GFXVertexBufferHandle verts(mDevice, numPoly*3, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, numPoly*3, GFXBufferTypeVolatile); verts.lock(); S32 vertexIndex = 0; for (S32 i=0; i verts(mDevice, 4, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, 4, GFXBufferTypeVolatile); verts.lock(); // Set up the line strip @@ -745,7 +745,7 @@ void GFXDrawUtil::_drawWireTriangle( const GFXStateBlockDesc &desc, const Point3 void GFXDrawUtil::_drawSolidTriangle( const GFXStateBlockDesc &desc, const Point3F &p0, const Point3F &p1, const Point3F &p2, const ColorI &color, const MatrixF *xfm ) { - GFXVertexBufferHandle verts(mDevice, 3, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, 3, GFXBufferTypeVolatile); verts.lock(); // Set up the line strip @@ -778,7 +778,7 @@ void GFXDrawUtil::drawPolygon( const GFXStateBlockDesc& desc, const Point3F* poi { const bool isWireframe = ( desc.fillMode == GFXFillWireframe ); const U32 numVerts = isWireframe ? numPoints + 1 : numPoints; - GFXVertexBufferHandle< GFXVertexPC > verts( mDevice, numVerts, GFXBufferTypeVolatile ); + GFXVertexBufferHandle< GFXVertexPCT > verts( mDevice, numVerts, GFXBufferTypeVolatile ); verts.lock(); for( U32 i = 0; i < numPoints; ++ i ) @@ -809,7 +809,7 @@ void GFXDrawUtil::drawPolygon( const GFXStateBlockDesc& desc, const Point3F* poi if( desc.fillMode == GFXFillWireframe ) mDevice->drawPrimitive( GFXLineStrip, 0, numPoints ); else - mDevice->drawPrimitive( GFXTriangleFan, 0, numPoints - 2 ); + mDevice->drawPrimitive( GFXTriangleStrip, 0, numPoints - 2 ); } void GFXDrawUtil::drawCube( const GFXStateBlockDesc &desc, const Box3F &box, const ColorI &color, const MatrixF *xfm ) @@ -827,7 +827,7 @@ void GFXDrawUtil::drawCube( const GFXStateBlockDesc &desc, const Point3F &size, void GFXDrawUtil::_drawWireCube( const GFXStateBlockDesc &desc, const Point3F &size, const Point3F &pos, const ColorI &color, const MatrixF *xfm ) { - GFXVertexBufferHandle verts(mDevice, 30, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, 30, GFXBufferTypeVolatile); verts.lock(); Point3F halfSize = size * 0.5f; @@ -870,7 +870,7 @@ void GFXDrawUtil::_drawWireCube( const GFXStateBlockDesc &desc, const Point3F &s void GFXDrawUtil::_drawSolidCube( const GFXStateBlockDesc &desc, const Point3F &size, const Point3F &pos, const ColorI &color, const MatrixF *xfm ) { - GFXVertexBufferHandle verts(mDevice, 36, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, 36, GFXBufferTypeVolatile); verts.lock(); Point3F halfSize = size * 0.5f; @@ -950,7 +950,7 @@ void GFXDrawUtil::_drawWirePolyhedron( const GFXStateBlockDesc &desc, const AnyP // Allocate a temporary vertex buffer. - GFXVertexBufferHandle< GFXVertexPC > verts( mDevice, numEdges * 2, GFXBufferTypeVolatile); + GFXVertexBufferHandle< GFXVertexPCT > verts( mDevice, numEdges * 2, GFXBufferTypeVolatile); // Fill it with the vertices for the edges. @@ -997,7 +997,7 @@ void GFXDrawUtil::_drawSolidPolyhedron( const GFXStateBlockDesc &desc, const Any // Create a temp buffer for the vertices and // put all the polyhedron's points in there. - GFXVertexBufferHandle< GFXVertexPC > verts( mDevice, numPoints, GFXBufferTypeVolatile ); + GFXVertexBufferHandle< GFXVertexPCT > verts( mDevice, numPoints, GFXBufferTypeVolatile ); verts.lock(); for( U32 i = 0; i < numPoints; ++ i ) @@ -1071,7 +1071,7 @@ void GFXDrawUtil::_drawSolidPolyhedron( const GFXStateBlockDesc &desc, const Any for( U32 i = 0; i < numPolys; ++ i ) { U32 numVerts = numIndicesForPoly[ i ]; - mDevice->drawIndexedPrimitive( GFXTriangleFan, 0, 0, numPoints, startIndex, numVerts - 2 ); + mDevice->drawIndexedPrimitive( GFXTriangleStrip, 0, 0, numPoints, startIndex, numVerts - 2 ); startIndex += numVerts; } } @@ -1119,7 +1119,7 @@ void GFXDrawUtil::drawObjectBox( const GFXStateBlockDesc &desc, const Point3F &s PrimBuild::end(); } -static const Point2F circlePoints[] = +static const Point2F circlePoints[] = { Point2F(0.707107f, 0.707107f), Point2F(0.923880f, 0.382683f), @@ -1156,7 +1156,7 @@ void GFXDrawUtil::_drawSolidCapsule( const GFXStateBlockDesc &desc, const Point3 mat = MatrixF::Identity; S32 numPoints = sizeof(circlePoints)/sizeof(Point2F); - GFXVertexBufferHandle verts(mDevice, numPoints * 2 + 2, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, numPoints * 2 + 2, GFXBufferTypeVolatile); verts.lock(); for (S32 i=0; imultWorld(mat); S32 numPoints = sizeof(circlePoints)/sizeof(Point2F); - GFXVertexBufferHandle verts(mDevice, numPoints, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, numPoints, GFXBufferTypeVolatile); verts.lock(); for (S32 i=0; i< numPoints; i++) { @@ -1268,27 +1268,57 @@ void GFXDrawUtil::drawCone( const GFXStateBlockDesc &desc, const Point3F &basePn mDevice->multWorld(mat); S32 numPoints = sizeof(circlePoints)/sizeof(Point2F); - GFXVertexBufferHandle verts(mDevice, numPoints + 2, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, numPoints * 3 + 2, GFXBufferTypeVolatile); verts.lock(); - verts[0].point = Point3F(0.0f,0.0f,1.0f); - verts[0].color = color; - for (S32 i=0; isetStateBlockByDesc( desc ); mDevice->setVertexBuffer( verts ); - mDevice->setupGenericShaders( GFXDevice::GSModColorTexture ); + mDevice->setupGenericShaders(); - mDevice->drawPrimitive( GFXTriangleFan, 0, numPoints ); - mDevice->drawPrimitive( GFXTriangleFan, 1, numPoints-1 ); + mDevice->drawPrimitive(GFXTriangleStrip, 0, numPoints - 2); + mDevice->drawPrimitive(GFXTriangleStrip, numPoints, numPoints * 2); mDevice->popWorldMatrix(); + } void GFXDrawUtil::drawCylinder( const GFXStateBlockDesc &desc, const Point3F &basePnt, const Point3F &tipPnt, F32 radius, const ColorI &color ) @@ -1307,32 +1337,59 @@ void GFXDrawUtil::drawCylinder( const GFXStateBlockDesc &desc, const Point3F &ba mDevice->pushWorldMatrix(); mDevice->multWorld(mat); - S32 numPoints = sizeof(circlePoints)/sizeof(Point2F); - GFXVertexBufferHandle verts(mDevice, numPoints * 4 + 4, GFXBufferTypeVolatile); + S32 numPoints = sizeof(circlePoints) / sizeof(Point2F); + GFXVertexBufferHandle verts(mDevice, numPoints *4 + 2, GFXBufferTypeVolatile); verts.lock(); - for (S32 i=0; isetStateBlockByDesc( desc ); mDevice->setVertexBuffer( verts ); - mDevice->setupGenericShaders( GFXDevice::GSModColorTexture ); + mDevice->setupGenericShaders(); - mDevice->drawPrimitive( GFXTriangleFan, 0, numPoints ); - mDevice->drawPrimitive( GFXTriangleFan, numPoints + 1, numPoints ); - mDevice->drawPrimitive( GFXTriangleStrip, 2 * numPoints + 2, 2 * numPoints); + mDevice->drawPrimitive( GFXTriangleStrip, 0, numPoints-2 ); + mDevice->drawPrimitive( GFXTriangleStrip, numPoints, numPoints - 2); + mDevice->drawPrimitive( GFXTriangleStrip, numPoints*2, numPoints * 2); mDevice->popWorldMatrix(); } @@ -1393,7 +1450,7 @@ void GFXDrawUtil::drawFrustum( const Frustum &f, const ColorI &color ) void GFXDrawUtil::drawSolidPlane( const GFXStateBlockDesc &desc, const Point3F &pos, const Point2F &size, const ColorI &color ) { - GFXVertexBufferHandle verts(mDevice, 4, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(mDevice, 4, GFXBufferTypeVolatile); verts.lock(); verts[0].point = pos + Point3F( -size.x / 2.0f, -size.y / 2.0f, 0 ); @@ -1412,7 +1469,7 @@ void GFXDrawUtil::drawSolidPlane( const GFXStateBlockDesc &desc, const Point3F & mDevice->setVertexBuffer( verts ); mDevice->setupGenericShaders(); - mDevice->drawPrimitive( GFXTriangleFan, 0, 2 ); + mDevice->drawPrimitive( GFXTriangleStrip, 0, 2 ); } void GFXDrawUtil::drawPlaneGrid( const GFXStateBlockDesc &desc, const Point3F &pos, const Point2F &size, const Point2F &step, const ColorI &color, Plane plane ) @@ -1449,7 +1506,7 @@ void GFXDrawUtil::drawPlaneGrid( const GFXStateBlockDesc &desc, const Point3F &p break; } - GFXVertexBufferHandle verts( mDevice, numVertices, GFXBufferTypeVolatile ); + GFXVertexBufferHandle verts( mDevice, numVertices, GFXBufferTypeVolatile ); verts.lock(); U32 vertCount = 0; @@ -1541,7 +1598,7 @@ void GFXDrawUtil::drawTransform( const GFXStateBlockDesc &desc, const MatrixF &m GFX->multWorld( mat ); - GFXVertexBufferHandle verts( mDevice, 6, GFXBufferTypeVolatile ); + GFXVertexBufferHandle verts( mDevice, 6, GFXBufferTypeVolatile ); verts.lock(); const static ColorI defColors[3] = diff --git a/Engine/source/gfx/gfxEnums.h b/Engine/source/gfx/gfxEnums.h index e0c560ac8..0e3878154 100644 --- a/Engine/source/gfx/gfxEnums.h +++ b/Engine/source/gfx/gfxEnums.h @@ -68,7 +68,6 @@ enum GFXPrimitiveType GFXLineStrip, GFXTriangleList, GFXTriangleStrip, - GFXTriangleFan, GFXPT_COUNT }; @@ -277,8 +276,8 @@ enum GFXBlend enum GFXAdapterType { OpenGL = 0, + Direct3D11, Direct3D9, - Direct3D8, NullDevice, Direct3D9_360, GFXAdapterType_Count diff --git a/Engine/source/gfx/gfxInit.cpp b/Engine/source/gfx/gfxInit.cpp index 3b0ef44e1..09d503d10 100644 --- a/Engine/source/gfx/gfxInit.cpp +++ b/Engine/source/gfx/gfxInit.cpp @@ -77,8 +77,8 @@ inline static void _GFXInitReportAdapters(Vector &adapters) case NullDevice: Con::printf(" Null device found"); break; - case Direct3D8: - Con::printf(" Direct 3D (version 8.1) device found"); + case Direct3D11: + Con::printf(" Direct 3D (version 11.x) device found"); break; default : Con::printf(" Unknown device found"); @@ -221,7 +221,8 @@ GFXAdapter* GFXInit::chooseAdapter( GFXAdapterType type, const char* outputDevic const char* GFXInit::getAdapterNameFromType(GFXAdapterType type) { - static const char* _names[] = { "OpenGL", "D3D9", "D3D8", "NullDevice", "Xenon" }; + // must match GFXAdapterType order + static const char* _names[] = { "OpenGL", "D3D11", "D3D9", "NullDevice", "Xenon" }; if( type < 0 || type >= GFXAdapterType_Count ) { @@ -268,51 +269,53 @@ GFXAdapter *GFXInit::getBestAdapterChoice() // // If D3D is unavailable, we're not on windows, so GL is de facto the // best choice! - F32 highestSM9 = 0.f, highestSMGL = 0.f; - GFXAdapter *foundAdapter8 = NULL, *foundAdapter9 = NULL, - *foundAdapterGL = NULL; + F32 highestSMDX = 0.f, highestSMGL = 0.f; + GFXAdapter *foundAdapter9 = NULL, *foundAdapterGL = NULL, *foundAdapter11 = NULL; - for(S32 i=0; imType) + switch (currAdapter->mType) { - case Direct3D9: - if(currAdapter->mShaderModel > highestSM9) + case Direct3D11: + if (currAdapter->mShaderModel > highestSMDX) { - highestSM9 = currAdapter->mShaderModel; + highestSMDX = currAdapter->mShaderModel; + foundAdapter11 = currAdapter; + } + break; + + case Direct3D9: + if (currAdapter->mShaderModel > highestSMDX) + { + highestSMDX = currAdapter->mShaderModel; foundAdapter9 = currAdapter; } break; case OpenGL: - if(currAdapter->mShaderModel > highestSMGL) + if (currAdapter->mShaderModel > highestSMGL) { highestSMGL = currAdapter->mShaderModel; foundAdapterGL = currAdapter; } break; - case Direct3D8: - if(!foundAdapter8) - foundAdapter8 = currAdapter; - break; - default: break; } } - // Return best found in order DX9, GL, DX8. - if(foundAdapter9) + // Return best found in order DX11,DX9, GL + if (foundAdapter11) + return foundAdapter11; + + if (foundAdapter9) return foundAdapter9; - if(foundAdapterGL) + if (foundAdapterGL) return foundAdapterGL; - if(foundAdapter8) - return foundAdapter8; - // Uh oh - we didn't find anything. Grab whatever we can that's not Null... for(S32 i=0; imType != NullDevice) diff --git a/Engine/source/gfx/gfxShader.cpp b/Engine/source/gfx/gfxShader.cpp index 5e81d8a10..54f1893e6 100644 --- a/Engine/source/gfx/gfxShader.cpp +++ b/Engine/source/gfx/gfxShader.cpp @@ -35,7 +35,8 @@ bool GFXShader::smLogWarnings = true; GFXShader::GFXShader() : mPixVersion( 0.0f ), - mReloadKey( 0 ) + mReloadKey( 0 ), + mInstancingFormat( NULL ) { } @@ -43,6 +44,8 @@ GFXShader::~GFXShader() { Torque::FS::RemoveChangeNotification( mVertexFile, this, &GFXShader::_onFileChanged ); Torque::FS::RemoveChangeNotification( mPixelFile, this, &GFXShader::_onFileChanged ); + + SAFE_DELETE(mInstancingFormat); } #ifndef TORQUE_OPENGL @@ -60,8 +63,16 @@ bool GFXShader::init( const Torque::Path &vertFile, const Torque::Path &pixFile, F32 pixVersion, const Vector ¯os, - const Vector &samplerNames) + const Vector &samplerNames, + GFXVertexFormat *instanceFormat) { + // Take care of instancing + if (instanceFormat) + { + mInstancingFormat = new GFXVertexFormat; + mInstancingFormat->copy(*instanceFormat); + } + // Store the inputs for use in reloading. mVertexFile = vertFile; mPixelFile = pixFile; diff --git a/Engine/source/gfx/gfxShader.h b/Engine/source/gfx/gfxShader.h index 318ab5ec0..f9059fbc0 100644 --- a/Engine/source/gfx/gfxShader.h +++ b/Engine/source/gfx/gfxShader.h @@ -262,13 +262,12 @@ protected: /// their destructor. Vector mActiveBuffers; + GFXVertexFormat *mInstancingFormat; + /// A protected constructor so it cannot be instantiated. GFXShader(); -public: - - // TODO: Add this into init(). - GFXVertexFormat mInstancingFormat; +public: /// Adds a global shader macro which will be merged with /// the script defined macros on every shader reload. @@ -312,7 +311,8 @@ public: const Torque::Path &pixFile, F32 pixVersion, const Vector ¯os, - const Vector &samplerNames); + const Vector &samplerNames, + GFXVertexFormat *instanceFormat = NULL ); /// Reloads the shader from disk. bool reload(); @@ -358,6 +358,9 @@ public: // GFXResource const String describeSelf() const { return mDescription; } + // Get instancing vertex format + GFXVertexFormat *getInstancingFormat() { return mInstancingFormat; } + protected: /// Called when the shader files change on disk. diff --git a/Engine/source/gfx/gfxStringEnumTranslate.cpp b/Engine/source/gfx/gfxStringEnumTranslate.cpp index 38fe29c7a..c564fbb29 100644 --- a/Engine/source/gfx/gfxStringEnumTranslate.cpp +++ b/Engine/source/gfx/gfxStringEnumTranslate.cpp @@ -347,7 +347,6 @@ void GFXStringEnumTranslate::init() GFX_STRING_ASSIGN_MACRO( GFXStringPrimType, GFXLineStrip ); GFX_STRING_ASSIGN_MACRO( GFXStringPrimType, GFXTriangleList ); GFX_STRING_ASSIGN_MACRO( GFXStringPrimType, GFXTriangleStrip ); - GFX_STRING_ASSIGN_MACRO( GFXStringPrimType, GFXTriangleFan ); VALIDATE_LOOKUPTABLE( GFXStringPrimType, GFXPT ); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ diff --git a/Engine/source/gfx/gfxVertexFormat.cpp b/Engine/source/gfx/gfxVertexFormat.cpp index fe1a2cf46..15f16a4d4 100644 --- a/Engine/source/gfx/gfxVertexFormat.cpp +++ b/Engine/source/gfx/gfxVertexFormat.cpp @@ -70,6 +70,7 @@ GFXVertexFormat::GFXVertexFormat() mHasColor( false ), mHasNormal( false ), mHasTangent( false ), + mHasInstancing( false ), mTexCoordCount( 0 ), mSizeInBytes( 0 ), mDecl( NULL ) @@ -83,6 +84,7 @@ void GFXVertexFormat::copy( const GFXVertexFormat &format ) mHasNormal = format.mHasNormal; mHasTangent = format.mHasTangent; mHasColor = format.mHasColor; + mHasInstancing = format.mHasInstancing; mTexCoordCount = format.mTexCoordCount; mSizeInBytes = format.mSizeInBytes; mDescription = format.mDescription; @@ -161,6 +163,14 @@ bool GFXVertexFormat::hasColor() const return mHasColor; } +bool GFXVertexFormat::hasInstancing() const +{ + if (mDirty) + const_cast(this)->_updateDirty(); + + return mHasInstancing; +} + U32 GFXVertexFormat::getTexCoordCount() const { if ( mDirty ) @@ -177,6 +187,11 @@ U32 GFXVertexFormat::getSizeInBytes() const return mSizeInBytes; } +void GFXVertexFormat::enableInstancing() +{ + mHasInstancing = true; +} + void GFXVertexFormat::_updateDirty() { PROFILE_SCOPE( GFXVertexFormat_updateDirty ); diff --git a/Engine/source/gfx/gfxVertexFormat.h b/Engine/source/gfx/gfxVertexFormat.h index 0f32e085e..09934e0df 100644 --- a/Engine/source/gfx/gfxVertexFormat.h +++ b/Engine/source/gfx/gfxVertexFormat.h @@ -153,6 +153,9 @@ public: /// The copy constructor. GFXVertexFormat( const GFXVertexFormat &format ) { copy( format ); } + /// Tell this format it has instancing + void enableInstancing(); + /// Copy the other vertex format. void copy( const GFXVertexFormat &format ); @@ -163,7 +166,7 @@ public: const String& getDescription() const; /// Clears all the vertex elements. - void clear(); + void clear(); /// Adds a vertex element to the format. /// @@ -182,6 +185,9 @@ public: /// Returns true if there is a COLOR semantic in this vertex format. bool hasColor() const; + /// Return true if instancing is used with this vertex format. + bool hasInstancing() const; + /// Returns the texture coordinate count by /// counting the number of TEXCOORD semantics. U32 getTexCoordCount() const; @@ -225,6 +231,9 @@ protected: /// Is true if there is a COLOR semantic in this vertex format. bool mHasColor; + /// Is instaning used with this vertex format. + bool mHasInstancing; + /// The texture coordinate count by counting the /// number of "TEXCOORD" semantics. U32 mTexCoordCount; diff --git a/Engine/source/gfx/gl/gfxGLDevice.cpp b/Engine/source/gfx/gl/gfxGLDevice.cpp index 01bbd02ea..8d3b8e93a 100644 --- a/Engine/source/gfx/gl/gfxGLDevice.cpp +++ b/Engine/source/gfx/gl/gfxGLDevice.cpp @@ -513,9 +513,6 @@ inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32 case GFXTriangleStrip : return 2 + primitiveCount; break; - case GFXTriangleFan : - return 2 + primitiveCount; - break; default: AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type"); break; @@ -789,7 +786,8 @@ void GFXGLDevice::setupGenericShaders( GenericShaderType type ) shaderData->registerObject(); mGenericShader[GSColor] = shaderData->getShader(); mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer(); - mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" ); + mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" ); + Sim::getRootGroup()->addObject(shaderData); shaderData = new ShaderData(); shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/modColorTextureV.glsl"); @@ -799,7 +797,8 @@ void GFXGLDevice::setupGenericShaders( GenericShaderType type ) shaderData->registerObject(); mGenericShader[GSModColorTexture] = shaderData->getShader(); mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer(); - mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" ); + mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" ); + Sim::getRootGroup()->addObject(shaderData); shaderData = new ShaderData(); shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/addColorTextureV.glsl"); @@ -809,7 +808,8 @@ void GFXGLDevice::setupGenericShaders( GenericShaderType type ) shaderData->registerObject(); mGenericShader[GSAddColorTexture] = shaderData->getShader(); mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer(); - mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" ); + mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" ); + Sim::getRootGroup()->addObject(shaderData); shaderData = new ShaderData(); shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/textureV.glsl"); @@ -820,6 +820,7 @@ void GFXGLDevice::setupGenericShaders( GenericShaderType type ) mGenericShader[GSTexture] = shaderData->getShader(); mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer(); mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" ); + Sim::getRootGroup()->addObject(shaderData); } MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize]; diff --git a/Engine/source/gfx/gl/gfxGLEnumTranslate.cpp b/Engine/source/gfx/gl/gfxGLEnumTranslate.cpp index e78d807c1..7955590e1 100644 --- a/Engine/source/gfx/gl/gfxGLEnumTranslate.cpp +++ b/Engine/source/gfx/gl/gfxGLEnumTranslate.cpp @@ -53,7 +53,6 @@ void GFXGLEnumTranslate::init() GFXGLPrimType[GFXLineStrip] = GL_LINE_STRIP; GFXGLPrimType[GFXTriangleList] = GL_TRIANGLES; GFXGLPrimType[GFXTriangleStrip] = GL_TRIANGLE_STRIP; - GFXGLPrimType[GFXTriangleFan] = GL_TRIANGLE_FAN; // Blend GFXGLBlend[GFXBlendZero] = GL_ZERO; diff --git a/Engine/source/gfx/gl/gfxGLShader.cpp b/Engine/source/gfx/gl/gfxGLShader.cpp index 8de562d9d..2e63c61fe 100644 --- a/Engine/source/gfx/gl/gfxGLShader.cpp +++ b/Engine/source/gfx/gl/gfxGLShader.cpp @@ -664,10 +664,14 @@ void GFXGLShader::initHandles() glUseProgram(0); //instancing + if (!mInstancingFormat) + return; + U32 offset = 0; - for ( U32 i=0; i < mInstancingFormat.getElementCount(); i++ ) + + for ( U32 i=0; i < mInstancingFormat->getElementCount(); i++ ) { - const GFXVertexElement &element = mInstancingFormat.getElement( i ); + const GFXVertexElement &element = mInstancingFormat->getElement( i ); String constName = String::ToString( "$%s", element.getSemantic().c_str() ); @@ -702,9 +706,9 @@ void GFXGLShader::initHandles() // If this is a matrix we will have 2 or 3 more of these // semantics with the same name after it. - for ( ; i < mInstancingFormat.getElementCount(); i++ ) + for ( ; i < mInstancingFormat->getElementCount(); i++ ) { - const GFXVertexElement &nextElement = mInstancingFormat.getElement( i ); + const GFXVertexElement &nextElement = mInstancingFormat->getElement( i ); if ( nextElement.getSemantic() != element.getSemantic() ) { i--; diff --git a/Engine/source/gfx/primBuilder.cpp b/Engine/source/gfx/primBuilder.cpp index af33d3a41..0c661a8e8 100644 --- a/Engine/source/gfx/primBuilder.cpp +++ b/Engine/source/gfx/primBuilder.cpp @@ -117,7 +117,6 @@ GFXVertexBuffer * endToBuffer( U32 &numPrims ) } case GFXTriangleStrip: - case GFXTriangleFan: { numPrims = mCurVertIndex - 2; break; @@ -171,7 +170,6 @@ void end( bool useGenericShaders ) } case GFXTriangleStrip: - case GFXTriangleFan: { stripStart = 2; vertStride = 1; diff --git a/Engine/source/gui/3d/guiTSControl.cpp b/Engine/source/gui/3d/guiTSControl.cpp index cbb520433..02d93690f 100644 --- a/Engine/source/gui/3d/guiTSControl.cpp +++ b/Engine/source/gui/3d/guiTSControl.cpp @@ -110,7 +110,7 @@ namespace start -= lineVec; end += lineVec; - GFXVertexBufferHandle verts(GFX, 4, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(GFX, 4, GFXBufferTypeVolatile); verts.lock(); verts[0].point.set( start.x+perp.x, start.y+perp.y, z1 ); diff --git a/Engine/source/gui/controls/guiGradientCtrl.cpp b/Engine/source/gui/controls/guiGradientCtrl.cpp index e137fabd9..cf29e3996 100644 --- a/Engine/source/gui/controls/guiGradientCtrl.cpp +++ b/Engine/source/gui/controls/guiGradientCtrl.cpp @@ -319,81 +319,79 @@ void GuiGradientCtrl::renderColorBox(RectI &bounds) void GuiGradientCtrl::drawBlendRangeBox(RectI &bounds, bool vertical, Vector colorRange) { GFX->setStateBlock(mStateBlock); - - // Create new global dimensions + + // Create new global dimensions S32 l = bounds.point.x + mSwatchFactor, r = bounds.point.x + bounds.extent.x - mSwatchFactor; S32 t = bounds.point.y, b = bounds.point.y + bounds.extent.y - mSwatchFactor; - - // Draw border using new global dimensions - if (mProfile->mBorder) - GFX->getDrawUtil()->drawRect( RectI( Point2I(l,t),Point2I(r,b) ), mProfile->mBorderColor); - - // Update local dimensions - mBlendRangeBox.point = globalToLocalCoord(Point2I(l, t)); - mBlendRangeBox.extent = globalToLocalCoord(Point2I(r, b)); - ColorRange& firstColorRange = colorRange.first(); - - if(colorRange.size() == 1) // Only one color to draw - { - PrimBuild::begin( GFXTriangleFan, 4 ); + // Draw border using new global dimensions + if (mProfile->mBorder) + GFX->getDrawUtil()->drawRect(RectI(Point2I(l, t), Point2I(r, b)), mProfile->mBorderColor); - PrimBuild::color(firstColorRange.swatch->getColor()); - PrimBuild::vertex2i( l, t ); - PrimBuild::vertex2i( l, b ); + // Update local dimensions + mBlendRangeBox.point = globalToLocalCoord(Point2I(l, t)); + mBlendRangeBox.extent = globalToLocalCoord(Point2I(r, b)); - PrimBuild::color(firstColorRange.swatch->getColor()); - PrimBuild::vertex2i( r, b ); - PrimBuild::vertex2i( r, t ); + if (colorRange.size() == 1) // Only one color to draw + { + PrimBuild::begin(GFXTriangleStrip, 4); - PrimBuild::end(); - } - else - { - PrimBuild::begin( GFXTriangleFan, 4 ); + PrimBuild::color(colorRange.first().swatch->getColor()); + PrimBuild::vertex2i(l, t); + PrimBuild::vertex2i(r, t); - PrimBuild::color(firstColorRange.swatch->getColor()); - PrimBuild::vertex2i( l, t ); - PrimBuild::vertex2i( l, b ); + PrimBuild::color(colorRange.first().swatch->getColor()); + PrimBuild::vertex2i(l, b); + PrimBuild::vertex2i(r, b); - PrimBuild::color(firstColorRange.swatch->getColor()); - PrimBuild::vertex2i(l + firstColorRange.swatch->getPosition().x, b); - PrimBuild::vertex2i(l + firstColorRange.swatch->getPosition().x, t); + PrimBuild::end(); + } + else + { + PrimBuild::begin(GFXTriangleStrip, 4); - PrimBuild::end(); + PrimBuild::color(colorRange.first().swatch->getColor()); + PrimBuild::vertex2i(l, t); + PrimBuild::vertex2i(l + colorRange.first().swatch->getPosition().x, t); - for( U16 i = 0;i < colorRange.size() - 1; i++ ) - { - PrimBuild::begin( GFXTriangleFan, 4 ); - if (!vertical) // Horizontal (+x) - { - // First color - PrimBuild::color( colorRange[i].swatch->getColor() ); - PrimBuild::vertex2i( l + colorRange[i].swatch->getPosition().x, t ); - PrimBuild::vertex2i( l + colorRange[i].swatch->getPosition().x, b ); - - // First color - PrimBuild::color( colorRange[i+1].swatch->getColor() ); - PrimBuild::vertex2i( l + colorRange[i+1].swatch->getPosition().x, b ); - PrimBuild::vertex2i( l + colorRange[i+1].swatch->getPosition().x, t ); - } - PrimBuild::end(); - } + PrimBuild::color(colorRange.first().swatch->getColor()); + PrimBuild::vertex2i(l, b); + PrimBuild::vertex2i(l + colorRange.first().swatch->getPosition().x, b); - ColorRange& lastColorRange = colorRange.last(); + PrimBuild::end(); - PrimBuild::begin( GFXTriangleFan, 4 ); + for (U16 i = 0; i < colorRange.size() - 1; i++) + { + PrimBuild::begin(GFXTriangleStrip, 4); + if (!vertical) // Horizontal (+x) + { + // First color + PrimBuild::color(colorRange[i].swatch->getColor()); + PrimBuild::vertex2i(l + colorRange[i].swatch->getPosition().x, t); + PrimBuild::color(colorRange[i + 1].swatch->getColor()); + PrimBuild::vertex2i(l + colorRange[i + 1].swatch->getPosition().x, t); - PrimBuild::color(lastColorRange.swatch->getColor()); - PrimBuild::vertex2i(l + lastColorRange.swatch->getPosition().x, t); - PrimBuild::vertex2i(l + lastColorRange.swatch->getPosition().x, b); - - PrimBuild::color(lastColorRange.swatch->getColor()); - PrimBuild::vertex2i( r, b ); - PrimBuild::vertex2i( r, t ); + // First color + PrimBuild::color(colorRange[i].swatch->getColor()); + PrimBuild::vertex2i(l + colorRange[i].swatch->getPosition().x, b); + PrimBuild::color(colorRange[i + 1].swatch->getColor()); + PrimBuild::vertex2i(l + colorRange[i + 1].swatch->getPosition().x, b); + } + PrimBuild::end(); + } - PrimBuild::end(); - } + PrimBuild::begin(GFXTriangleStrip, 4); + + PrimBuild::color(colorRange.last().swatch->getColor()); + PrimBuild::vertex2i(l + colorRange.last().swatch->getPosition().x, t); + PrimBuild::vertex2i(r, t); + + PrimBuild::color(colorRange.last().swatch->getColor()); + PrimBuild::vertex2i(l + colorRange.last().swatch->getPosition().x, b); + PrimBuild::vertex2i(r, b); + + PrimBuild::end(); + } } void GuiGradientCtrl::onMouseDown(const GuiEvent &event) diff --git a/Engine/source/gui/controls/guiTextEditSliderCtrl.cpp b/Engine/source/gui/controls/guiTextEditSliderCtrl.cpp index 5d89ec0e2..a3e9c884f 100644 --- a/Engine/source/gui/controls/guiTextEditSliderCtrl.cpp +++ b/Engine/source/gui/controls/guiTextEditSliderCtrl.cpp @@ -355,7 +355,7 @@ void GuiTextEditSliderCtrl::onRender(Point2I offset, const RectI &updateRect) Point2I(start.x+14,midPoint.y), mProfile->mFontColor); - GFXVertexBufferHandle verts(GFX, 6, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(GFX, 6, GFXBufferTypeVolatile); verts.lock(); verts[0].color.set( 0, 0, 0 ); diff --git a/Engine/source/gui/editor/guiEditCtrl.h b/Engine/source/gui/editor/guiEditCtrl.h index 7731545f1..38a1ddf34 100644 --- a/Engine/source/gui/editor/guiEditCtrl.h +++ b/Engine/source/gui/editor/guiEditCtrl.h @@ -114,7 +114,7 @@ class GuiEditCtrl : public GuiControl SimSet* mSelectedSet; // grid drawing - GFXVertexBufferHandle mDots; + GFXVertexBufferHandle mDots; GFXStateBlockRef mDotSB; mouseModes mMouseDownMode; diff --git a/Engine/source/gui/editor/guiFilterCtrl.cpp b/Engine/source/gui/editor/guiFilterCtrl.cpp index a3ea707e8..39f16a99b 100644 --- a/Engine/source/gui/editor/guiFilterCtrl.cpp +++ b/Engine/source/gui/editor/guiFilterCtrl.cpp @@ -196,7 +196,7 @@ void GuiFilterCtrl::onRender(Point2I offset, const RectI &updateRect) } // draw the curv - GFXVertexBufferHandle verts(GFX, ext.x, GFXBufferTypeVolatile); + GFXVertexBufferHandle verts(GFX, ext.x, GFXBufferTypeVolatile); verts.lock(); diff --git a/Engine/source/gui/editor/guiGraphCtrl.cpp b/Engine/source/gui/editor/guiGraphCtrl.cpp index e00998b0b..6dc224365 100644 --- a/Engine/source/gui/editor/guiGraphCtrl.cpp +++ b/Engine/source/gui/editor/guiGraphCtrl.cpp @@ -177,7 +177,7 @@ void GuiGraphCtrl::onRender(Point2I offset, const RectI &updateRect) for( S32 sample = 0; sample < numSamples; ++ sample ) { - PrimBuild::begin( GFXTriangleFan, 4 ); + PrimBuild::begin( GFXTriangleStrip, 4 ); PrimBuild::color( mGraphColor[ k ] ); F32 offset = F32( getExtent().x ) / F32( MaxDataPoints ) * F32( sample + 1 ); diff --git a/Engine/source/gui/worldEditor/editTSCtrl.cpp b/Engine/source/gui/worldEditor/editTSCtrl.cpp index 7781525c6..928cbfbf1 100644 --- a/Engine/source/gui/worldEditor/editTSCtrl.cpp +++ b/Engine/source/gui/worldEditor/editTSCtrl.cpp @@ -1315,7 +1315,7 @@ DefineEngineMethod( EditTSCtrl, renderCircle, void, ( Point3F pos, Point3F norma { PrimBuild::color( object->mConsoleFillColor ); - PrimBuild::begin( GFXTriangleFan, points.size() + 2 ); + PrimBuild::begin( GFXTriangleStrip, points.size() + 2 ); // Center point PrimBuild::vertex3fv( pos ); diff --git a/Engine/source/gui/worldEditor/gizmo.cpp b/Engine/source/gui/worldEditor/gizmo.cpp index 7ae32519c..c95533bd6 100644 --- a/Engine/source/gui/worldEditor/gizmo.cpp +++ b/Engine/source/gui/worldEditor/gizmo.cpp @@ -1403,7 +1403,7 @@ void Gizmo::renderGizmo(const MatrixF &cameraTransform, F32 cameraFOV ) for(U32 j = 0; j < 6; j++) { - PrimBuild::begin( GFXTriangleFan, 4 ); + PrimBuild::begin( GFXTriangleStrip, 4 ); PrimBuild::vertex3fv( sgCenterBoxPnts[sgBoxVerts[j][0]] * tipScale); PrimBuild::vertex3fv( sgCenterBoxPnts[sgBoxVerts[j][1]] * tipScale); @@ -1599,7 +1599,7 @@ void Gizmo::_renderAxisBoxes() for(U32 j = 0; j < 6; j++) { - PrimBuild::begin( GFXTriangleFan, 4 ); + PrimBuild::begin( GFXTriangleStrip, 4 ); PrimBuild::vertex3fv( sgCenterBoxPnts[sgBoxVerts[j][0]] * tipScale + sgAxisVectors[axisIdx] * pos ); PrimBuild::vertex3fv( sgCenterBoxPnts[sgBoxVerts[j][1]] * tipScale + sgAxisVectors[axisIdx] * pos ); @@ -1663,7 +1663,7 @@ void Gizmo::_renderAxisCircles() ColorI color = mProfile->inActiveColor; color.alpha = 100; PrimBuild::color( color ); - PrimBuild::begin( GFXTriangleFan, segments+2 ); + PrimBuild::begin( GFXTriangleStrip, segments+2 ); PrimBuild::vertex3fv( Point3F(0,0,0) ); diff --git a/Engine/source/gui/worldEditor/guiTerrPreviewCtrl.cpp b/Engine/source/gui/worldEditor/guiTerrPreviewCtrl.cpp index b5d5d2524..37dd68952 100644 --- a/Engine/source/gui/worldEditor/guiTerrPreviewCtrl.cpp +++ b/Engine/source/gui/worldEditor/guiTerrPreviewCtrl.cpp @@ -265,18 +265,18 @@ void GuiTerrPreviewCtrl::onRender(Point2I offset, const RectI &updateRect) // the texture if flipped horz to reflect how the terrain is really drawn PrimBuild::color3f(1.0f, 1.0f, 1.0f); - PrimBuild::begin(GFXTriangleFan, 4); - PrimBuild::texCoord2f(textureP1.x, textureP2.y); - PrimBuild::vertex2f(screenP1.x, screenP2.y); // left bottom + PrimBuild::begin(GFXTriangleStrip, 4); + PrimBuild::texCoord2f(textureP1.x, textureP1.y); + PrimBuild::vertex2f(screenP1.x, screenP1.y); // left top - - PrimBuild::texCoord2f(textureP2.x, textureP2.y); - PrimBuild::vertex2f(screenP2.x, screenP2.y); // right bottom - PrimBuild::texCoord2f(textureP2.x, textureP1.y); - PrimBuild::vertex2f(screenP2.x, screenP1.y); // right top + PrimBuild::texCoord2f(textureP2.x, textureP1.y); + PrimBuild::vertex2f(screenP2.x, screenP1.y); // right top - PrimBuild::texCoord2f(textureP1.x, textureP1.y); - PrimBuild::vertex2f(screenP1.x, screenP1.y); // left top + PrimBuild::texCoord2f(textureP1.x, textureP2.y); + PrimBuild::vertex2f(screenP1.x, screenP2.y); // left bottom + + PrimBuild::texCoord2f(textureP2.x, textureP2.y); + PrimBuild::vertex2f(screenP2.x, screenP2.y); // right bottom PrimBuild::end(); } } diff --git a/Engine/source/gui/worldEditor/terrainEditor.cpp b/Engine/source/gui/worldEditor/terrainEditor.cpp index 0ff51f37a..cf80218e3 100644 --- a/Engine/source/gui/worldEditor/terrainEditor.cpp +++ b/Engine/source/gui/worldEditor/terrainEditor.cpp @@ -658,7 +658,7 @@ void SelectionBrush::rebuild() //... move the selection } -void SelectionBrush::render(Vector & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const +void SelectionBrush::render(Vector & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const { //... render the selection } @@ -1342,8 +1342,8 @@ void TerrainEditor::renderPoints( const Vector &pointList ) U32 vertsThisDrawCall = getMin( (U32)vertsLeft, (U32)MAX_DYNAMIC_VERTS ); vertsLeft -= vertsThisDrawCall; - GFXVertexBufferHandle vbuff( GFX, vertsThisDrawCall, GFXBufferTypeVolatile ); - GFXVertexPC *vert = vbuff.lock(); + GFXVertexBufferHandle vbuff( GFX, vertsThisDrawCall, GFXBufferTypeVolatile ); + GFXVertexPCT *vert = vbuff.lock(); const U32 loops = vertsThisDrawCall / 6; @@ -1394,7 +1394,7 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol if(sel.size() == 0) return; - Vector vertexBuffer; + Vector vertexBuffer; ColorF color; ColorI iColor; @@ -1430,15 +1430,15 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol // iColor = color; - GFXVertexPC *verts = &(vertexBuffer[i * 5]); + GFXVertexPCT *verts = &(vertexBuffer[i * 5]); - verts[0].point = wPos + Point3F(-squareSize, -squareSize, 0); + verts[0].point = wPos + Point3F(-squareSize, squareSize, 0); verts[0].color = iColor; - verts[1].point = wPos + Point3F( squareSize, -squareSize, 0); + verts[1].point = wPos + Point3F( squareSize, squareSize, 0); verts[1].color = iColor; - verts[2].point = wPos + Point3F( squareSize, squareSize, 0); + verts[2].point = wPos + Point3F( -squareSize, -squareSize, 0); verts[2].color = iColor; - verts[3].point = wPos + Point3F(-squareSize, squareSize, 0); + verts[3].point = wPos + Point3F( squareSize, -squareSize, 0); verts[3].color = iColor; verts[4].point = verts[0].point; verts[4].color = iColor; @@ -1452,7 +1452,7 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol GridPoint selectedGridPoint = sel[i].mGridPoint; Point2I gPos = selectedGridPoint.gridPos; - GFXVertexPC *verts = &(vertexBuffer[i * 5]); + GFXVertexPCT *verts = &(vertexBuffer[i * 5]); bool center = gridToWorld(selectedGridPoint, verts[0].point); gridToWorld(Point2I(gPos.x + 1, gPos.y), verts[1].point, selectedGridPoint.terrainBlock); @@ -1503,12 +1503,12 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol // Render this bad boy, by stuffing everything into a volatile buffer // and rendering... - GFXVertexBufferHandle selectionVB(GFX, vertexBuffer.size(), GFXBufferTypeStatic); + GFXVertexBufferHandle selectionVB(GFX, vertexBuffer.size(), GFXBufferTypeStatic); selectionVB.lock(0, vertexBuffer.size()); // Copy stuff - dMemcpy((void*)&selectionVB[0], (void*)&vertexBuffer[0], sizeof(GFXVertexPC) * vertexBuffer.size()); + dMemcpy((void*)&selectionVB[0], (void*)&vertexBuffer[0], sizeof(GFXVertexPCT) * vertexBuffer.size()); selectionVB.unlock(); @@ -1518,7 +1518,7 @@ void TerrainEditor::renderSelection( const Selection & sel, const ColorF & inCol if(renderFill) for(U32 i=0; i < sel.size(); i++) - GFX->drawPrimitive( GFXTriangleFan, i*5, 4); + GFX->drawPrimitive( GFXTriangleStrip, i*5, 4); if(renderFrame) for(U32 i=0; i < sel.size(); i++) diff --git a/Engine/source/gui/worldEditor/terrainEditor.h b/Engine/source/gui/worldEditor/terrainEditor.h index 1b5d7cc15..53c2aa79d 100644 --- a/Engine/source/gui/worldEditor/terrainEditor.h +++ b/Engine/source/gui/worldEditor/terrainEditor.h @@ -173,7 +173,7 @@ public: const char *getType() const { return "selection"; } void rebuild(); - void render(Vector & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const; + void render(Vector & vertexBuffer, S32 & verts, S32 & elems, S32 & prims, const ColorF & inColorFull, const ColorF & inColorNone, const ColorF & outColorFull, const ColorF & outColorNone) const; void setSize(const Point2I &){} protected: diff --git a/Engine/source/gui/worldEditor/worldEditor.cpp b/Engine/source/gui/worldEditor/worldEditor.cpp index 6065b233e..7f39a598b 100644 --- a/Engine/source/gui/worldEditor/worldEditor.cpp +++ b/Engine/source/gui/worldEditor/worldEditor.cpp @@ -1303,7 +1303,7 @@ void WorldEditor::renderObjectFace(SceneObject * obj, const VectorF & normal, co PrimBuild::color( col ); - PrimBuild::begin( GFXTriangleFan, 4 ); + PrimBuild::begin( GFXTriangleStrip, 4 ); for(U32 k = 0; k < 4; k++) { PrimBuild::vertex3f(projPnts[k].x, projPnts[k].y, projPnts[k].z); @@ -1503,7 +1503,7 @@ void WorldEditor::renderSplinePath(SimPath::Path *path) if(vCount > 4000) batchSize = 4000; - GFXVertexBufferHandle vb; + GFXVertexBufferHandle vb; vb.set(GFX, 3*batchSize, GFXBufferTypeVolatile); void *lockPtr = vb.lock(); if(!lockPtr) return; diff --git a/Engine/source/lighting/advanced/advancedLightBinManager.cpp b/Engine/source/lighting/advanced/advancedLightBinManager.cpp index 98330a5de..bec9afb8a 100644 --- a/Engine/source/lighting/advanced/advancedLightBinManager.cpp +++ b/Engine/source/lighting/advanced/advancedLightBinManager.cpp @@ -305,7 +305,7 @@ void AdvancedLightBinManager::render( SceneRenderState *state ) { vectorMatInfo->matInstance->setSceneInfo( state, sgData ); vectorMatInfo->matInstance->setTransforms( matrixSet, state ); - GFX->drawPrimitive( GFXTriangleFan, 0, 2 ); + GFX->drawPrimitive( GFXTriangleStrip, 0, 2 ); } } @@ -482,24 +482,24 @@ void AdvancedLightBinManager::_setupPerFrameParameters( const SceneRenderState * // passes.... this is a volatile VB and updates every frame. FarFrustumQuadVert verts[4]; { - verts[0].point.set( wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos ); - invCam.mulP( wsFrustumPoints[Frustum::FarBottomLeft], &verts[0].normal ); - verts[0].texCoord.set( -1.0, -1.0 ); - verts[0].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos); + verts[0].point.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraPos); + invCam.mulP(wsFrustumPoints[Frustum::FarTopLeft], &verts[0].normal); + verts[0].texCoord.set(-1.0, 1.0); + verts[0].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos); - verts[1].point.set( wsFrustumPoints[Frustum::FarTopLeft] - cameraPos ); - invCam.mulP( wsFrustumPoints[Frustum::FarTopLeft], &verts[1].normal ); - verts[1].texCoord.set( -1.0, 1.0 ); - verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos); + verts[1].point.set(wsFrustumPoints[Frustum::FarTopRight] - cameraPos); + invCam.mulP(wsFrustumPoints[Frustum::FarTopRight], &verts[1].normal); + verts[1].texCoord.set(1.0, 1.0); + verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos); - verts[2].point.set( wsFrustumPoints[Frustum::FarTopRight] - cameraPos ); - invCam.mulP( wsFrustumPoints[Frustum::FarTopRight], &verts[2].normal ); - verts[2].texCoord.set( 1.0, 1.0 ); - verts[2].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos); + verts[2].point.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos); + invCam.mulP(wsFrustumPoints[Frustum::FarBottomLeft], &verts[2].normal); + verts[2].texCoord.set(-1.0, -1.0); + verts[2].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos); - verts[3].point.set( wsFrustumPoints[Frustum::FarBottomRight] - cameraPos ); - invCam.mulP( wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal ); - verts[3].texCoord.set( 1.0, -1.0 ); + verts[3].point.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraPos); + invCam.mulP(wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal); + verts[3].texCoord.set(1.0, -1.0); verts[3].tangent.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraOffsetPos); } mFarFrustumQuadVerts.set( GFX, 4 ); diff --git a/Engine/source/lighting/advanced/glsl/deferredShadingFeaturesGLSL.cpp b/Engine/source/lighting/advanced/glsl/deferredShadingFeaturesGLSL.cpp index 1dc906989..bfa39779e 100644 --- a/Engine/source/lighting/advanced/glsl/deferredShadingFeaturesGLSL.cpp +++ b/Engine/source/lighting/advanced/glsl/deferredShadingFeaturesGLSL.cpp @@ -62,7 +62,6 @@ void DeferredSpecMapGLSL::processPix( Vector &componentList, c specularMap->uniform = true; specularMap->sampler = true; specularMap->constNum = Var::getTexUnitNum(); - LangElement *texOp = new GenOp( "tex2D(@, @)", specularMap, texCoord ); //matinfo.g slot reserved for AO later meta->addStatement(new GenOp(" @.g = 1.0;\r\n", material)); meta->addStatement(new GenOp(" @.b = dot(tex2D(@, @).rgb, vec3(0.3, 0.59, 0.11));\r\n", material, specularMap, texCoord)); diff --git a/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.cpp b/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.cpp index d2d383148..095f4ea9e 100644 --- a/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.cpp +++ b/Engine/source/lighting/advanced/glsl/gBufferConditionerGLSL.cpp @@ -114,7 +114,7 @@ void GBufferConditionerGLSL::processVert( Vector &componentLis // TODO: Total hack because Conditioner is directly derived // from ShaderFeature and not from ShaderFeatureGLSL. NamedFeatureGLSL dummy( String::EmptyString ); - dummy.mInstancingFormat = mInstancingFormat; + dummy.setInstancingFormat( mInstancingFormat ); Var *worldViewOnly = dummy.getWorldView( componentList, fd.features[MFT_UseInstancing], meta ); meta->addStatement( new GenOp(" @ = tMul(@, float4( normalize(@), 0.0 ) ).xyz;\r\n", diff --git a/Engine/source/lighting/advanced/hlsl/advancedLightingFeaturesHLSL.cpp b/Engine/source/lighting/advanced/hlsl/advancedLightingFeaturesHLSL.cpp index 0bfbed42a..172eb65c8 100644 --- a/Engine/source/lighting/advanced/hlsl/advancedLightingFeaturesHLSL.cpp +++ b/Engine/source/lighting/advanced/hlsl/advancedLightingFeaturesHLSL.cpp @@ -126,6 +126,18 @@ void DeferredRTLightingFeatHLSL::processPix( Vector &component lightInfoBuffer->sampler = true; lightInfoBuffer->constNum = Var::getTexUnitNum(); // used as texture unit num here + Var* lightBufferTex = NULL; + if (mIsDirect3D11) + { + lightInfoBuffer->setType("SamplerState"); + lightBufferTex = new Var; + lightBufferTex->setName("lightInfoBufferTex"); + lightBufferTex->setType("Texture2D"); + lightBufferTex->uniform = true; + lightBufferTex->texture = true; + lightBufferTex->constNum = lightInfoBuffer->constNum; + } + // Declare the RTLighting variables in this feature, they will either be assigned // in this feature, or in the tonemap/lightmap feature Var *d_lightcolor = new Var( "d_lightcolor", "float3" ); @@ -140,8 +152,12 @@ void DeferredRTLightingFeatHLSL::processPix( Vector &component // Perform the uncondition here. String unconditionLightInfo = String::ToLower( AdvancedLightBinManager::smBufferName ) + "Uncondition"; - meta->addStatement( new GenOp( avar( " %s(tex2D(@, @), @, @, @);\r\n", - unconditionLightInfo.c_str() ), lightInfoBuffer, uvScene, d_lightcolor, d_NL_Att, d_specular ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(avar(" %s(@.Sample(@, @), @, @, @);\r\n", + unconditionLightInfo.c_str()), lightBufferTex, lightInfoBuffer, uvScene, d_lightcolor, d_NL_Att, d_specular)); + else + meta->addStatement(new GenOp(avar(" %s(tex2D(@, @), @, @, @);\r\n", + unconditionLightInfo.c_str()), lightInfoBuffer, uvScene, d_lightcolor, d_NL_Att, d_specular)); // If this has an interlaced pre-pass, do averaging here if( fd.features[MFT_InterlacedPrePass] ) @@ -157,8 +173,12 @@ void DeferredRTLightingFeatHLSL::processPix( Vector &component } meta->addStatement( new GenOp( " float id_NL_Att, id_specular;\r\n float3 id_lightcolor;\r\n" ) ); - meta->addStatement( new GenOp( avar( " %s(tex2D(@, @ + float2(0.0, @.y)), id_lightcolor, id_NL_Att, id_specular);\r\n", - unconditionLightInfo.c_str() ), lightInfoBuffer, uvScene, oneOverTargetSize ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(avar(" %s(@.Sample(@, @ + float2(0.0, @.y)), id_lightcolor, id_NL_Att, id_specular);\r\n", + unconditionLightInfo.c_str()), lightBufferTex, lightInfoBuffer, uvScene, oneOverTargetSize)); + else + meta->addStatement(new GenOp(avar(" %s(tex2D(@, @ + float2(0.0, @.y)), id_lightcolor, id_NL_Att, id_specular);\r\n", + unconditionLightInfo.c_str()), lightInfoBuffer, uvScene, oneOverTargetSize)); meta->addStatement( new GenOp(" @ = lerp(@, id_lightcolor, 0.5);\r\n", d_lightcolor, d_lightcolor ) ); meta->addStatement( new GenOp(" @ = lerp(@, id_NL_Att, 0.5);\r\n", d_NL_Att, d_NL_Att ) ); @@ -272,8 +292,17 @@ void DeferredBumpFeatHLSL::processPix( Vector &componentList, // create texture var Var *bumpMap = getNormalMapTex(); - Var *texCoord = getInTexCoord( "texCoord", "float2", true, componentList ); - LangElement *texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); + Var *texCoord = getInTexCoord("texCoord", "float2", true, componentList); + + LangElement *texOp = NULL; + + if (mIsDirect3D11) + { + Var *bumpMapTex = (Var*)LangElement::find("bumpMapTex"); + texOp = new GenOp("@.Sample(@, @)", bumpMapTex, bumpMap, texCoord); + } + else + texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord); // create bump normal Var *bumpNorm = new Var; @@ -295,8 +324,25 @@ void DeferredBumpFeatHLSL::processPix( Vector &componentList, bumpMap->sampler = true; bumpMap->constNum = Var::getTexUnitNum(); - texCoord = getInTexCoord( "detCoord", "float2", true, componentList ); - texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); + Var* detailNormalTex = NULL; + if (mIsDirect3D11) + { + bumpMap->setType("SamplerState"); + detailNormalTex = new Var; + detailNormalTex->setName("detailBumpMapTex"); + detailNormalTex->setType("Texture2D"); + detailNormalTex->uniform = true; + detailNormalTex->texture = true; + detailNormalTex->constNum = bumpMap->constNum; + } + + + texCoord = getInTexCoord("detCoord", "float2", true, componentList); + + if (mIsDirect3D11) + texOp = new GenOp("@.Sample(@, @)", detailNormalTex, bumpMap, texCoord); + else + texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord); Var *detailBump = new Var; detailBump->setName( "detailBump" ); @@ -333,25 +379,32 @@ void DeferredBumpFeatHLSL::processPix( Vector &componentList, else if (fd.features[MFT_AccuMap]) { Var *bumpSample = (Var *)LangElement::find( "bumpSample" ); - if( bumpSample == NULL ) + if (bumpSample == NULL) { MultiLine *meta = new MultiLine; - Var *texCoord = getInTexCoord( "texCoord", "float2", true, componentList ); + Var *texCoord = getInTexCoord("texCoord", "float2", true, componentList); Var *bumpMap = getNormalMapTex(); bumpSample = new Var; - bumpSample->setType( "float4" ); - bumpSample->setName( "bumpSample" ); - LangElement *bumpSampleDecl = new DecOp( bumpSample ); + bumpSample->setType("float4"); + bumpSample->setName("bumpSample"); + LangElement *bumpSampleDecl = new DecOp(bumpSample); - meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord ) ); + if (mIsDirect3D11) + { + Var *bumpMapTex = (Var *)LangElement::find("bumpMapTex"); + output = new GenOp(" @ = @.Sample(@, @);\r\n", bumpSampleDecl, bumpMapTex, bumpMap, texCoord); + } + else + output = new GenOp(" @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord); if ( fd.features.hasFeature( MFT_DetailNormalMap ) ) { Var *bumpMap = (Var*)LangElement::find( "detailBumpMap" ); - if ( !bumpMap ) { + if ( !bumpMap ) + { bumpMap = new Var; bumpMap->setType( "sampler2D" ); bumpMap->setName( "detailBumpMap" ); @@ -360,8 +413,24 @@ void DeferredBumpFeatHLSL::processPix( Vector &componentList, bumpMap->constNum = Var::getTexUnitNum(); } + Var* bumpMapTex = (Var*)LangElement::find("detailBumpMap"); + if (mIsDirect3D11 && !bumpMapTex) + { + bumpMap->setType("SamplerState"); + bumpMapTex = new Var; + bumpMapTex->setName("detailBumpMapTex"); + bumpMapTex->setType("Texture2D"); + bumpMapTex->uniform = true; + bumpMapTex->texture = true; + bumpMapTex->constNum = bumpMap->constNum; + } + texCoord = getInTexCoord( "detCoord", "float2", true, componentList ); - LangElement *texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); + LangElement *texOp = NULL; + if (mIsDirect3D11) + texOp = new GenOp("@.Sample(@, @)", bumpMap, bumpMapTex, texCoord); + else + texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); Var *detailBump = new Var; detailBump->setName( "detailBump" ); @@ -402,7 +471,14 @@ void DeferredBumpFeatHLSL::processPix( Vector &componentList, bumpSample->setName( "bumpSample" ); LangElement *bumpSampleDecl = new DecOp( bumpSample ); - output = new GenOp( " @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord ); + if (mIsDirect3D11) + { + Var *bumpMapTex = (Var *)LangElement::find("bumpMapTex"); + output = new GenOp(" @ = @.Sample(@, @);\r\n", bumpSampleDecl, bumpMapTex, bumpMap, texCoord); + } + else + output = new GenOp(" @ = tex2D(@, @);\r\n", bumpSampleDecl, bumpMap, texCoord); + return; } } @@ -547,7 +623,8 @@ void DeferredPixelSpecularHLSL::processPix( Vector &component AssertFatal( lightInfoSamp && d_specular && d_NL_Att, "DeferredPixelSpecularHLSL::processPix - Something hosed the deferred features!" ); - if (fd.features[ MFT_AccuMap ]) { + if (fd.features[ MFT_AccuMap ]) + { // change specularity where the accu texture is applied Var *accuPlc = (Var*) LangElement::find( "plc" ); Var *accuSpecular = (Var*)LangElement::find( "accuSpecular" ); @@ -671,6 +748,18 @@ void DeferredMinnaertHLSL::processPix( Vector &componentList, prepassBuffer->sampler = true; prepassBuffer->constNum = Var::getTexUnitNum(); // used as texture unit num here + Var* prePassTex = NULL; + if (mIsDirect3D11) + { + prepassBuffer->setType("SamplerState"); + prePassTex = new Var; + prePassTex->setName("prePassTex"); + prePassTex->setType("Texture2D"); + prePassTex->uniform = true; + prePassTex->texture = true; + prePassTex->constNum = prepassBuffer->constNum; + } + // Texture coord Var *uvScene = (Var*) LangElement::find( "uvScene" ); AssertFatal(uvScene != NULL, "Unable to find UVScene, no RTLighting feature?"); @@ -684,7 +773,11 @@ void DeferredMinnaertHLSL::processPix( Vector &componentList, Var *d_NL_Att = (Var*)LangElement::find( "d_NL_Att" ); - meta->addStatement( new GenOp( avar( " float4 normalDepth = %s(@, @);\r\n", unconditionPrePassMethod.c_str() ), prepassBuffer, uvScene ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(avar(" float4 normalDepth = %s(@, ,@, @);\r\n", unconditionPrePassMethod.c_str()), prepassBuffer, prePassTex, uvScene)); + else + meta->addStatement(new GenOp(avar(" float4 normalDepth = %s(@, @);\r\n", unconditionPrePassMethod.c_str()), prepassBuffer, uvScene)); + meta->addStatement( new GenOp( " float vDotN = dot(normalDepth.xyz, @);\r\n", wsViewVec ) ); meta->addStatement( new GenOp( " float Minnaert = pow( @, @) * pow(vDotN, 1.0 - @);\r\n", d_NL_Att, minnaertConstant, minnaertConstant ) ); meta->addStatement( new GenOp( " @;\r\n", assignColor( new GenOp( "float4(Minnaert, Minnaert, Minnaert, 1.0)" ), Material::Mul ) ) ); diff --git a/Engine/source/lighting/advanced/hlsl/deferredShadingFeaturesHLSL.cpp b/Engine/source/lighting/advanced/hlsl/deferredShadingFeaturesHLSL.cpp index 3e42af953..25c86b7bc 100644 --- a/Engine/source/lighting/advanced/hlsl/deferredShadingFeaturesHLSL.cpp +++ b/Engine/source/lighting/advanced/hlsl/deferredShadingFeaturesHLSL.cpp @@ -62,12 +62,35 @@ void DeferredSpecMapHLSL::processPix( Vector &componentList, c specularMap->uniform = true; specularMap->sampler = true; specularMap->constNum = Var::getTexUnitNum(); - LangElement *texOp = new GenOp( "tex2D(@, @)", specularMap, texCoord ); + + Var* specularMapTex = NULL; + if (mIsDirect3D11) + { + specularMap->setType("SamplerState"); + specularMapTex = new Var; + specularMapTex->setName("specularMapTex"); + specularMapTex->setType("Texture2D"); + specularMapTex->uniform = true; + specularMapTex->texture = true; + specularMapTex->constNum = specularMap->constNum; + } //matinfo.g slot reserved for AO later + Var* specColor = new Var; + specColor->setName("specColor"); + specColor->setType("float4"); + LangElement *specColorElem = new DecOp(specColor); + meta->addStatement(new GenOp(" @.g = 1.0;\r\n", material)); - meta->addStatement(new GenOp(" @.b = dot(tex2D(@, @).rgb, float3(0.3, 0.59, 0.11));\r\n", material, specularMap, texCoord)); - meta->addStatement(new GenOp(" @.a = tex2D(@, @).a;\r\n", material, specularMap, texCoord)); + //sample specular map + if (mIsDirect3D11) + meta->addStatement(new GenOp(" @ = @.Sample(@, @);\r\n", specColorElem, specularMapTex, specularMap, texCoord)); + else + meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", specColorElem, specularMap, texCoord)); + + meta->addStatement(new GenOp(" @.b = dot(@.rgb, float3(0.3, 0.59, 0.11));\r\n", material, specColor)); + meta->addStatement(new GenOp(" @.a = @.a;\r\n", material, specColor)); + output = meta; } diff --git a/Engine/source/lighting/advanced/hlsl/gBufferConditionerHLSL.cpp b/Engine/source/lighting/advanced/hlsl/gBufferConditionerHLSL.cpp index 6f99d035c..d03a40ecd 100644 --- a/Engine/source/lighting/advanced/hlsl/gBufferConditionerHLSL.cpp +++ b/Engine/source/lighting/advanced/hlsl/gBufferConditionerHLSL.cpp @@ -28,7 +28,7 @@ #include "materials/materialFeatureTypes.h" #include "materials/materialFeatureData.h" #include "shaderGen/hlsl/shaderFeatureHLSL.h" - +#include "gfx/gfxDevice.h" GBufferConditionerHLSL::GBufferConditionerHLSL( const GFXFormat bufferFormat, const NormalSpace nrmSpace ) : Parent( bufferFormat ) @@ -114,7 +114,7 @@ void GBufferConditionerHLSL::processVert( Vector &componentLis // TODO: Total hack because Conditioner is directly derived // from ShaderFeature and not from ShaderFeatureHLSL. NamedFeatureHLSL dummy( String::EmptyString ); - dummy.mInstancingFormat = mInstancingFormat; + dummy.setInstancingFormat( mInstancingFormat ); Var *worldViewOnly = dummy.getWorldView( componentList, fd.features[MFT_UseInstancing], meta ); meta->addStatement( new GenOp(" @ = mul(@, float4( normalize(@), 0.0 ) ).xyz;\r\n", @@ -222,6 +222,7 @@ Var* GBufferConditionerHLSL::printMethodHeader( MethodType methodType, const Str retVal = Parent::printMethodHeader( methodType, methodName, stream, meta ); else { + const bool isDirect3D11 = GFX->getAdapterType() == Direct3D11; Var *methodVar = new Var; methodVar->setName(methodName); methodVar->setType("inline float4"); @@ -237,12 +238,28 @@ Var* GBufferConditionerHLSL::printMethodHeader( MethodType methodType, const Str screenUV->setType("float2"); DecOp *screenUVDecl = new DecOp(screenUV); + Var *prepassTex = NULL; + DecOp *prepassTexDecl = NULL; + if (isDirect3D11) + { + prepassSampler->setType("SamplerState"); + prepassTex = new Var; + prepassTex->setName("prepassTexVar"); + prepassTex->setType("Texture2D"); + prepassTex->texture = true; + prepassTex->constNum = prepassSampler->constNum; + prepassTexDecl = new DecOp(prepassTex); + } + Var *bufferSample = new Var; bufferSample->setName("bufferSample"); bufferSample->setType("float4"); DecOp *bufferSampleDecl = new DecOp(bufferSample); - meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) ); + if (isDirect3D11) + meta->addStatement(new GenOp("@(@, @, @)\r\n", methodDecl, prepassSamplerDecl, prepassTexDecl, screenUVDecl)); + else + meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) ); meta->addStatement( new GenOp( "{\r\n" ) ); @@ -255,10 +272,14 @@ Var* GBufferConditionerHLSL::printMethodHeader( MethodType methodType, const Str // The gbuffer has no mipmaps, so use tex2dlod when // possible so that the shader compiler can optimize. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) ); - meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) ); - meta->addStatement( new GenOp( " #else\r\n" ) ); - meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) ); - meta->addStatement( new GenOp( " #endif\r\n\r\n" ) ); + if (isDirect3D11) + meta->addStatement(new GenOp(" @ = @.SampleLevel(@, @,0);\r\n", bufferSampleDecl, prepassTex, prepassSampler, screenUV)); + else + meta->addStatement(new GenOp(" @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV)); + + meta->addStatement(new GenOp(" #else\r\n")); + meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV)); + meta->addStatement(new GenOp(" #endif\r\n\r\n")); #endif // We don't use this way of passing var's around, so this should cause a crash diff --git a/Engine/source/lighting/common/blobShadow.cpp b/Engine/source/lighting/common/blobShadow.cpp index 9756757e9..48bfb1e52 100644 --- a/Engine/source/lighting/common/blobShadow.cpp +++ b/Engine/source/lighting/common/blobShadow.cpp @@ -338,7 +338,7 @@ void BlobShadow::render( F32 camDist, const TSRenderState &rdata ) GFX->setVertexBuffer(mShadowBuffer); for(U32 p=0; pdrawPrimitive(GFXTriangleFan, mPartition[p].vertexStart, (mPartition[p].vertexCount - 2)); + GFX->drawPrimitive(GFXTriangleStrip, mPartition[p].vertexStart, (mPartition[p].vertexCount - 2)); // This is a bad nasty hack which forces the shadow to reconstruct itself every frame. mPartition.clear(); diff --git a/Engine/source/materials/miscShdrDat.h b/Engine/source/materials/miscShdrDat.h index 25422008d..9ebaa6f46 100644 --- a/Engine/source/materials/miscShdrDat.h +++ b/Engine/source/materials/miscShdrDat.h @@ -22,10 +22,6 @@ #ifndef _MISCSHDRDAT_H_ #define _MISCSHDRDAT_H_ -#ifndef _PLATFORM_H_ -#include "platform/platform.h" -#endif - //************************************************************************** // This file is an attempt to keep certain classes from having to know about // the ShaderGen class @@ -45,6 +41,7 @@ enum RegisterType RT_COLOR, RT_TEXCOORD, RT_VPOS, + RT_SVPOSITION }; enum Components @@ -52,7 +49,7 @@ enum Components C_VERT_STRUCT = 0, C_CONNECTOR, C_VERT_MAIN, - C_PIX_MAIN, + C_PIX_MAIN }; #endif // _MISCSHDRDAT_H_ diff --git a/Engine/source/materials/processedShaderMaterial.cpp b/Engine/source/materials/processedShaderMaterial.cpp index 37f745253..185c9f0b9 100644 --- a/Engine/source/materials/processedShaderMaterial.cpp +++ b/Engine/source/materials/processedShaderMaterial.cpp @@ -209,7 +209,7 @@ bool ProcessedShaderMaterial::init( const FeatureSet &features, if ( mFeatures.hasFeature( MFT_UseInstancing ) ) { mInstancingState = new InstancingState(); - mInstancingState->setFormat( &_getRPD( 0 )->shader->mInstancingFormat, mVertexFormat ); + mInstancingState->setFormat( _getRPD( 0 )->shader->getInstancingFormat(), mVertexFormat ); } return true; } diff --git a/Engine/source/materials/processedShaderMaterial.h b/Engine/source/materials/processedShaderMaterial.h index 9bcc0eec7..4f7c67023 100644 --- a/Engine/source/materials/processedShaderMaterial.h +++ b/Engine/source/materials/processedShaderMaterial.h @@ -167,6 +167,8 @@ protected: mInstFormat = instFormat; mDeclFormat.copy( *vertexFormat ); mDeclFormat.append( *mInstFormat, 1 ); + // Let the declaration know we have instancing. + mDeclFormat.enableInstancing(); mDeclFormat.getDecl(); delete [] mBuffer; diff --git a/Engine/source/materials/shaderData.cpp b/Engine/source/materials/shaderData.cpp index 36e0a3994..e8c1dbb3b 100644 --- a/Engine/source/materials/shaderData.cpp +++ b/Engine/source/materials/shaderData.cpp @@ -236,6 +236,7 @@ GFXShader* ShaderData::_createShader( const Vector ¯os ) { case Direct3D9_360: case Direct3D9: + case Direct3D11: { success = shader->init( mDXVertexShaderName, mDXPixelShaderName, diff --git a/Engine/source/platformWin32/videoInfo/wmiVideoInfo.cpp b/Engine/source/platformWin32/videoInfo/wmiVideoInfo.cpp index 23f63635d..b4fecbba3 100644 --- a/Engine/source/platformWin32/videoInfo/wmiVideoInfo.cpp +++ b/Engine/source/platformWin32/videoInfo/wmiVideoInfo.cpp @@ -25,6 +25,7 @@ //#include #include //#include +#include #pragma comment(lib, "comsuppw.lib") #pragma comment(lib, "wbemuuid.lib") @@ -53,58 +54,6 @@ struct MYGUID : public GUID } }; -//------------------------------------------------------------------------------ -// DXGI decls for retrieving device info on Vista. We manually declare that -// stuff here, so we don't depend on headers and compile on any setup. At -// run-time, it depends on whether we can successfully load the DXGI DLL; if -// not, nothing of this here will be used. - -struct IDXGIObject; -struct IDXGIFactory; -struct IDXGIAdapter; -struct IDXGIOutput; - -struct DXGI_SWAP_CHAIN_DESC; -struct DXGI_ADAPTER_DESC; - -struct IDXGIObject : public IUnknown -{ - virtual HRESULT STDMETHODCALLTYPE SetPrivateData( REFGUID, UINT, const void* ) = 0; - virtual HRESULT STDMETHODCALLTYPE SetPrivateDataInterface( REFGUID, const IUnknown* ) = 0; - virtual HRESULT STDMETHODCALLTYPE GetPrivateData( REFGUID, UINT*, void* ) = 0; - virtual HRESULT STDMETHODCALLTYPE GetParent( REFIID, void** ) = 0; -}; - -struct IDXGIFactory : public IDXGIObject -{ - virtual HRESULT STDMETHODCALLTYPE EnumAdapters( UINT, IDXGIAdapter** ) = 0; - virtual HRESULT STDMETHODCALLTYPE MakeWindowAssociation( HWND, UINT ) = 0; - virtual HRESULT STDMETHODCALLTYPE GetWindowAssociation( HWND ) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateSwapChain( IUnknown*, DXGI_SWAP_CHAIN_DESC* ) = 0; - virtual HRESULT STDMETHODCALLTYPE CreateSoftwareAdapter( HMODULE, IDXGIAdapter** ) = 0; -}; - -struct IDXGIAdapter : public IDXGIObject -{ - virtual HRESULT STDMETHODCALLTYPE EnumOutputs( UINT, IDXGIOutput** ) = 0; - virtual HRESULT STDMETHODCALLTYPE GetDesc( DXGI_ADAPTER_DESC* ) = 0; - virtual HRESULT STDMETHODCALLTYPE CheckInterfaceSupport( REFGUID, LARGE_INTEGER* ) = 0; -}; - -struct DXGI_ADAPTER_DESC -{ - WCHAR Description[ 128 ]; - UINT VendorId; - UINT DeviceId; - UINT SubSysId; - UINT Revision; - SIZE_T DedicatedVideoMemory; - SIZE_T DedicatedSystemMemory; - SIZE_T SharedSystemMemory; - LUID AdapterLuid; -}; - -static MYGUID IID_IDXGIFactory( 0x7b7166ec, 0x21c7, 0x44ae, 0xb2, 0x1a, 0xc9, 0xae, 0x32, 0x1a, 0xe3, 0x69 ); //------------------------------------------------------------------------------ // DXDIAG declarations. @@ -184,6 +133,26 @@ WMIVideoInfo::~WMIVideoInfo() //------------------------------------------------------------------------------ +String WMIVideoInfo::_lookUpVendorId(U32 vendorId) +{ + String vendor; + switch (vendorId) + { + case 0x10DE: + vendor = "NVIDIA"; + break; + case 0x1002: + vendor = "AMD"; + break; + case 0x8086: + vendor = "INTEL"; + break; + } + return vendor; +} + +//------------------------------------------------------------------------------ + bool WMIVideoInfo::_initialize() { // Init COM @@ -282,16 +251,15 @@ bool WMIVideoInfo::_initializeWMI() bool WMIVideoInfo::_initializeDXGI() { - // Try going for DXGI. Will only succeed on Vista. -#if 0 + // Try using for DXGI 1.1, will only succeed on Windows 7+. mDXGIModule = ( HMODULE ) LoadLibrary( L"dxgi.dll" ); if( mDXGIModule != 0 ) { - typedef HRESULT (* CreateDXGIFactoryFuncType )( REFIID, void** ); + typedef HRESULT (WINAPI* CreateDXGIFactoryFuncType )( REFIID, void** ); CreateDXGIFactoryFuncType factoryFunction = - ( CreateDXGIFactoryFuncType ) GetProcAddress( ( HMODULE ) mDXGIModule, "CreateDXGIFactory" ); + ( CreateDXGIFactoryFuncType ) GetProcAddress( ( HMODULE ) mDXGIModule, "CreateDXGIFactory1" ); - if( factoryFunction && factoryFunction( IID_IDXGIFactory, ( void** ) &mDXGIFactory ) == S_OK ) + if( factoryFunction && factoryFunction( IID_IDXGIFactory1, ( void** ) &mDXGIFactory ) == S_OK ) return true; else { @@ -299,7 +267,7 @@ bool WMIVideoInfo::_initializeDXGI() mDXGIModule = 0; } } -#endif + return false; } @@ -483,20 +451,36 @@ bool WMIVideoInfo::_queryPropertyDxDiag( const PVIQueryType queryType, const U32 bool WMIVideoInfo::_queryPropertyDXGI( const PVIQueryType queryType, const U32 adapterId, String *outValue ) { -#if 0 + if( mDXGIFactory ) { - IDXGIAdapter* adapter; - if( mDXGIFactory->EnumAdapters( adapterId, &adapter ) != S_OK ) + // Special case to deal with PVI_NumAdapters + if (queryType == PVI_NumAdapters) + { + U32 count = 0; + IDXGIAdapter1 *adapter; + while (mDXGIFactory->EnumAdapters1(count, &adapter) != DXGI_ERROR_NOT_FOUND) + { + ++count; + adapter->Release(); + } + + String value = String::ToString("%d", count); + *outValue = value; + return true; + } + + IDXGIAdapter1* adapter; + if( mDXGIFactory->EnumAdapters1( adapterId, &adapter ) != S_OK ) return false; - DXGI_ADAPTER_DESC desc; - if( adapter->GetDesc( &desc ) != S_OK ) + DXGI_ADAPTER_DESC1 desc; + if( adapter->GetDesc1( &desc ) != S_OK ) { adapter->Release(); return false; } - + String value; switch( queryType ) { @@ -511,15 +495,17 @@ bool WMIVideoInfo::_queryPropertyDXGI( const PVIQueryType queryType, const U32 a case PVI_VRAM: value = String( avar( "%i", desc.DedicatedVideoMemory / 1048576 ) ); break; - - //RDTODO + case PVI_ChipSet: + value = _lookUpVendorId(desc.VendorId); + break; + //TODO PVI_DriverVersion } adapter->Release(); *outValue = value; return true; } -#endif + return false; } diff --git a/Engine/source/platformWin32/videoInfo/wmiVideoInfo.h b/Engine/source/platformWin32/videoInfo/wmiVideoInfo.h index 6d5457039..3b71d97fc 100644 --- a/Engine/source/platformWin32/videoInfo/wmiVideoInfo.h +++ b/Engine/source/platformWin32/videoInfo/wmiVideoInfo.h @@ -28,7 +28,7 @@ struct IWbemLocator; struct IWbemServices; -struct IDXGIFactory; +struct IDXGIFactory1; struct IDxDiagProvider; class WMIVideoInfo : public PlatformVideoInfo @@ -39,7 +39,7 @@ private: bool mComInitialized; void* mDXGIModule; - IDXGIFactory* mDXGIFactory; + IDXGIFactory1* mDXGIFactory; IDxDiagProvider* mDxDiagProvider; bool _initializeDXGI(); @@ -54,6 +54,7 @@ protected: static WCHAR *smPVIQueryTypeToWMIString []; bool _queryProperty( const PVIQueryType queryType, const U32 adapterId, String *outValue ); bool _initialize(); + String _lookUpVendorId(U32 vendorId); public: WMIVideoInfo(); diff --git a/Engine/source/postFx/postEffect.cpp b/Engine/source/postFx/postEffect.cpp index 62c35baf6..c388e0abe 100644 --- a/Engine/source/postFx/postEffect.cpp +++ b/Engine/source/postFx/postEffect.cpp @@ -510,23 +510,23 @@ void PostEffect::_updateScreenGeometry( const Frustum &frustum, PFXVertex *vert = outVB->lock(); - vert->point.set( -1.0, -1.0, 0.0 ); - vert->texCoord.set( 0.0f, 1.0f ); - vert->wsEyeRay = frustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos; - vert++; - - vert->point.set( -1.0, 1.0, 0.0 ); - vert->texCoord.set( 0.0f, 0.0f ); + vert->point.set(-1.0, 1.0, 0.0); + vert->texCoord.set(0.0f, 0.0f); vert->wsEyeRay = frustumPoints[Frustum::FarTopLeft] - cameraOffsetPos; vert++; - vert->point.set( 1.0, 1.0, 0.0 ); - vert->texCoord.set( 1.0f, 0.0f ); + vert->point.set(1.0, 1.0, 0.0); + vert->texCoord.set(1.0f, 0.0f); vert->wsEyeRay = frustumPoints[Frustum::FarTopRight] - cameraOffsetPos; vert++; - vert->point.set( 1.0, -1.0, 0.0 ); - vert->texCoord.set( 1.0f, 1.0f ); + vert->point.set(-1.0, -1.0, 0.0); + vert->texCoord.set(0.0f, 1.0f); + vert->wsEyeRay = frustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos; + vert++; + + vert->point.set(1.0, -1.0, 0.0); + vert->texCoord.set(1.0f, 1.0f); vert->wsEyeRay = frustumPoints[Frustum::FarBottomRight] - cameraOffsetPos; vert++; @@ -1275,7 +1275,7 @@ void PostEffect::process( const SceneRenderState *state, // Draw it. GFX->setVertexBuffer( vb ); - GFX->drawPrimitive( GFXTriangleFan, 0, 2 ); + GFX->drawPrimitive( GFXTriangleStrip, 0, 2 ); // Allow PostEffecVis to hook in. PFXVIS->onPFXProcessed( this ); diff --git a/Engine/source/renderInstance/renderPrePassMgr.cpp b/Engine/source/renderInstance/renderPrePassMgr.cpp index 4f08dc6ea..6e7a8f3ef 100644 --- a/Engine/source/renderInstance/renderPrePassMgr.cpp +++ b/Engine/source/renderInstance/renderPrePassMgr.cpp @@ -385,7 +385,6 @@ void RenderPrePassMgr::render( SceneRenderState *state ) GFXTextureObject *lastLM = NULL; GFXCubemap *lastCubemap = NULL; GFXTextureObject *lastReflectTex = NULL; - GFXTextureObject *lastMiscTex = NULL; GFXTextureObject *lastAccuTex = NULL; // Next render all the meshes. diff --git a/Engine/source/scene/reflectionManager.cpp b/Engine/source/scene/reflectionManager.cpp index 323e11c8a..5536b4fa5 100644 --- a/Engine/source/scene/reflectionManager.cpp +++ b/Engine/source/scene/reflectionManager.cpp @@ -248,8 +248,18 @@ GFXTextureObject* ReflectionManager::getRefractTex( bool forceUpdate ) const U32 desWidth = targetSize.x; const U32 desHeight = targetSize.y; #else - const U32 desWidth = mFloor( (F32)targetSize.x * smRefractTexScale ); - const U32 desHeight = mFloor( ( F32)targetSize.y * smRefractTexScale ); + U32 desWidth, desHeight; + // D3D11 needs to be the same size as the active target + if (GFX->getAdapterType() == Direct3D11) + { + desWidth = targetSize.x; + desHeight = targetSize.y; + } + else + { + desWidth = mFloor((F32)targetSize.x * smRefractTexScale); + desHeight = mFloor((F32)targetSize.y * smRefractTexScale); + } #endif if ( mRefractTex.isNull() || diff --git a/Engine/source/scene/simPath.cpp b/Engine/source/scene/simPath.cpp index c25764ad1..d38ea914f 100644 --- a/Engine/source/scene/simPath.cpp +++ b/Engine/source/scene/simPath.cpp @@ -273,7 +273,7 @@ DefineEngineMethod( Path, getPathId, S32, (),, //-------------------------------------------------------------------------- GFXStateBlockRef Marker::smStateBlock; -GFXVertexBufferHandle Marker::smVertexBuffer; +GFXVertexBufferHandle Marker::smVertexBuffer; GFXPrimitiveBufferHandle Marker::smPrimitiveBuffer; static Point3F wedgePoints[4] = { @@ -295,7 +295,7 @@ void Marker::initGFXResources() smStateBlock = GFX->createStateBlock(d); smVertexBuffer.set(GFX, 4, GFXBufferTypeStatic); - GFXVertexPC* verts = smVertexBuffer.lock(); + GFXVertexPCT* verts = smVertexBuffer.lock(); verts[0].point = wedgePoints[0] * 0.25f; verts[1].point = wedgePoints[1] * 0.25f; verts[2].point = wedgePoints[2] * 0.25f; diff --git a/Engine/source/scene/simPath.h b/Engine/source/scene/simPath.h index 9e172bdf4..4633e0a10 100644 --- a/Engine/source/scene/simPath.h +++ b/Engine/source/scene/simPath.h @@ -132,7 +132,7 @@ class Marker : public SceneObject static void initGFXResources(); static GFXStateBlockRef smStateBlock; - static GFXVertexBufferHandle smVertexBuffer; + static GFXVertexBufferHandle smVertexBuffer; static GFXPrimitiveBufferHandle smPrimitiveBuffer; public: diff --git a/Engine/source/shaderGen/HLSL/accuFeatureHLSL.cpp b/Engine/source/shaderGen/HLSL/accuFeatureHLSL.cpp index 2bafc06f4..6010c8283 100644 --- a/Engine/source/shaderGen/HLSL/accuFeatureHLSL.cpp +++ b/Engine/source/shaderGen/HLSL/accuFeatureHLSL.cpp @@ -85,7 +85,8 @@ void AccuTexFeatHLSL::processPix( Vector &componentList, // accu constants Var *accuScale = (Var*)LangElement::find( "accuScale" ); - if ( !accuScale ) { + if ( !accuScale ) + { accuScale = new Var; accuScale->setType( "float" ); accuScale->setName( "accuScale" ); @@ -94,7 +95,8 @@ void AccuTexFeatHLSL::processPix( Vector &componentList, accuScale->constSortPos = cspPotentialPrimitive; } Var *accuDirection = (Var*)LangElement::find( "accuDirection" ); - if ( !accuDirection ) { + if ( !accuDirection ) + { accuDirection = new Var; accuDirection->setType( "float" ); accuDirection->setName( "accuDirection" ); @@ -103,7 +105,8 @@ void AccuTexFeatHLSL::processPix( Vector &componentList, accuDirection->constSortPos = cspPotentialPrimitive; } Var *accuStrength = (Var*)LangElement::find( "accuStrength" ); - if ( !accuStrength ) { + if ( !accuStrength ) + { accuStrength = new Var; accuStrength->setType( "float" ); accuStrength->setName( "accuStrength" ); @@ -112,7 +115,8 @@ void AccuTexFeatHLSL::processPix( Vector &componentList, accuStrength->constSortPos = cspPotentialPrimitive; } Var *accuCoverage = (Var*)LangElement::find( "accuCoverage" ); - if ( !accuCoverage ) { + if ( !accuCoverage ) + { accuCoverage = new Var; accuCoverage->setType( "float" ); accuCoverage->setName( "accuCoverage" ); @@ -121,7 +125,8 @@ void AccuTexFeatHLSL::processPix( Vector &componentList, accuCoverage->constSortPos = cspPotentialPrimitive; } Var *accuSpecular = (Var*)LangElement::find( "accuSpecular" ); - if ( !accuSpecular ) { + if ( !accuSpecular ) + { accuSpecular = new Var; accuSpecular->setType( "float" ); accuSpecular->setName( "accuSpecular" ); @@ -133,14 +138,26 @@ void AccuTexFeatHLSL::processPix( Vector &componentList, Var *inTex = getInTexCoord( "texCoord", "float2", true, componentList ); Var *accuVec = getInTexCoord( "accuVec", "float3", true, componentList ); Var *bumpNorm = (Var *)LangElement::find( "bumpSample" ); - if( bumpNorm == NULL ) { + if( bumpNorm == NULL ) + { bumpNorm = (Var *)LangElement::find( "bumpNormal" ); if (!bumpNorm) return; } // get the accu pixel color - meta->addStatement( new GenOp( " @ = tex2D(@, @ * @);\r\n", colorAccuDecl, accuMap, inTex, accuScale ) ); + if (mIsDirect3D11) + { + Var *accuMapTex = new Var; + accuMapTex->setType("Texture2D"); + accuMapTex->setName("accuMapTex"); + accuMapTex->uniform = true; + accuMapTex->texture = true; + accuMapTex->constNum = accuMap->constNum; + meta->addStatement(new GenOp(" @ = @.Sample(@, @ * @);\r\n", colorAccuDecl, accuMapTex, accuMap, inTex, accuScale)); + } + else + meta->addStatement(new GenOp(" @ = tex2D(@, @ * @);\r\n", colorAccuDecl, accuMap, inTex, accuScale)); // scale up normals meta->addStatement( new GenOp( " @.xyz = @.xyz * 2.0 - 0.5;\r\n", bumpNorm, bumpNorm ) ); diff --git a/Engine/source/shaderGen/HLSL/bumpHLSL.cpp b/Engine/source/shaderGen/HLSL/bumpHLSL.cpp index 327e7ad6f..ee34f3e66 100644 --- a/Engine/source/shaderGen/HLSL/bumpHLSL.cpp +++ b/Engine/source/shaderGen/HLSL/bumpHLSL.cpp @@ -70,6 +70,13 @@ void BumpFeatHLSL::processPix( Vector &componentList, Var *bumpMap = getNormalMapTex(); LangElement *texOp = NULL; + //if it's D3D11 let's create the texture object + Var* bumpMapTex = NULL; + if (mIsDirect3D11) + { + bumpMapTex = (Var*)LangElement::find("bumpMapTex"); + } + // Handle atlased textures // http://www.infinity-universe.com/Infinity/index.php?option=com_content&task=view&id=65&Itemid=47 if(fd.features[MFT_NormalMapAtlas]) @@ -127,18 +134,25 @@ void BumpFeatHLSL::processPix( Vector &componentList, // Add a newline meta->addStatement( new GenOp( "\r\n" ) ); - if(is_sm3) + if (mIsDirect3D11) { - texOp = new GenOp( "tex2Dlod(@, float4(@, 0.0, mipLod_bump))", bumpMap, texCoord ); + texOp = new GenOp("@.SampleLevel(@, @, mipLod_bump)", bumpMapTex, bumpMap, texCoord); + } + else if (is_sm3) + { + texOp = new GenOp("tex2Dlod(@, float4(@, 0.0, mipLod_bump))", bumpMap, texCoord); } else { - texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); + texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord); } } else { - texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); + if (mIsDirect3D11) + texOp = new GenOp("@.Sample(@, @)", bumpMapTex, bumpMap, texCoord); + else + texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord); } Var *bumpNorm = new Var( "bumpNormal", "float4" ); @@ -156,8 +170,26 @@ void BumpFeatHLSL::processPix( Vector &componentList, bumpMap->sampler = true; bumpMap->constNum = Var::getTexUnitNum(); + Var* detailBumpTex = NULL; + if (mIsDirect3D11) + { + bumpMap->setType("SamplerState"); + detailBumpTex = new Var; + detailBumpTex->setName("detailBumpTex"); + detailBumpTex->setType("Texture2D"); + detailBumpTex->uniform = true; + detailBumpTex->texture = true; + detailBumpTex->constNum = bumpMap->constNum; + } + else + bumpMap->setType("sampler2D"); + texCoord = getInTexCoord( "detCoord", "float2", true, componentList ); - texOp = new GenOp( "tex2D(@, @)", bumpMap, texCoord ); + + if (mIsDirect3D11) + texOp = new GenOp("@.Sample(@, @)", detailBumpTex, bumpMap, texCoord); + else + texOp = new GenOp("tex2D(@, @)", bumpMap, texCoord); Var *detailBump = new Var; detailBump->setName( "detailBump" ); @@ -345,17 +377,26 @@ void ParallaxFeatHLSL::processPix( Vector &componentList, // Get the rest of our inputs. Var *parallaxInfo = _getUniformVar( "parallaxInfo", "float", cspPotentialPrimitive ); Var *normalMap = getNormalMapTex(); + Var *bumpMapTexture = (Var*)LangElement::find("bumpMapTex"); // Call the library function to do the rest. - if(fd.features.hasFeature( MFT_IsDXTnm, getProcessIndex() )) + if (fd.features.hasFeature(MFT_IsDXTnm, getProcessIndex())) { - meta->addStatement( new GenOp( " @.xy += parallaxOffsetDxtnm( @, @.xy, @, @ );\r\n", - texCoord, normalMap, texCoord, negViewTS, parallaxInfo ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(" @.xy += parallaxOffsetDxtnm( @, @, @.xy, @, @ );\r\n", + texCoord, bumpMapTexture, normalMap, texCoord, negViewTS, parallaxInfo)); + else + meta->addStatement(new GenOp(" @.xy += parallaxOffsetDxtnm( @, @.xy, @, @ );\r\n", + texCoord, normalMap, texCoord, negViewTS, parallaxInfo)); } else { - meta->addStatement( new GenOp( " @.xy += parallaxOffset( @, @.xy, @, @ );\r\n", - texCoord, normalMap, texCoord, negViewTS, parallaxInfo ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(" @.xy += parallaxOffset( @, @, @.xy, @, @ );\r\n", + texCoord, bumpMapTexture, normalMap, texCoord, negViewTS, parallaxInfo)); + else + meta->addStatement(new GenOp(" @.xy += parallaxOffset( @, @.xy, @, @ );\r\n", + texCoord, normalMap, texCoord, negViewTS, parallaxInfo)); } // TODO: Fix second UV maybe? diff --git a/Engine/source/shaderGen/HLSL/paraboloidHLSL.cpp b/Engine/source/shaderGen/HLSL/paraboloidHLSL.cpp index a5afa00e0..105e3c100 100644 --- a/Engine/source/shaderGen/HLSL/paraboloidHLSL.cpp +++ b/Engine/source/shaderGen/HLSL/paraboloidHLSL.cpp @@ -46,9 +46,13 @@ void ParaboloidVertTransformHLSL::processVert( Vector &compon ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); // Grab connector out position. - Var *outPosition = connectComp->getElement( RT_POSITION ); - outPosition->setName( "hpos" ); - outPosition->setStructName( "OUT" ); + RegisterType type = RT_POSITION; + if (mIsDirect3D11) + type = RT_SVPOSITION; + + Var *outPosition = connectComp->getElement(type); + outPosition->setName("hpos"); + outPosition->setStructName("OUT"); // Get the atlas scale. Var *atlasScale = new Var; diff --git a/Engine/source/shaderGen/HLSL/pixSpecularHLSL.cpp b/Engine/source/shaderGen/HLSL/pixSpecularHLSL.cpp index 8b65a9491..b5a5a98b1 100644 --- a/Engine/source/shaderGen/HLSL/pixSpecularHLSL.cpp +++ b/Engine/source/shaderGen/HLSL/pixSpecularHLSL.cpp @@ -77,8 +77,12 @@ void PixelSpecularHLSL::processPix( Vector &componentList, { LangElement * lightMap = LangElement::find( "lightMap" ); LangElement * lmCoord = LangElement::find( "texCoord2" ); + LangElement * lightMapTex = LangElement::find("lightMapTex"); //used only DX11 shaders - lmColor = new GenOp( "tex2D(@, @)", lightMap, lmCoord ); + if (lightMapTex) + lmColor = new GenOp("@.Sample(@, @)", lightMapTex, lightMap, lmCoord); + else + lmColor = new GenOp("tex2D(@, @)", lightMap, lmCoord); } final = new GenOp( "@ * float4(@.rgb,0)", specMul, lmColor ); @@ -138,11 +142,33 @@ void SpecularMapHLSL::processPix( Vector &componentList, const specularMap->uniform = true; specularMap->sampler = true; specularMap->constNum = Var::getTexUnitNum(); - LangElement *texOp = new GenOp( "tex2D(@, @)", specularMap, texCoord ); + Var *specularMapTex = NULL; - Var *specularColor = new Var( "specularColor", "float4" ); + if (mIsDirect3D11) + { + specularMap->setType("SamplerState"); + specularMapTex = new Var; + specularMapTex->setName("specularMapTex"); + specularMapTex->setType("Texture2D"); + specularMapTex->uniform = true; + specularMapTex->texture = true; + specularMapTex->constNum = specularMap->constNum; + } + else + { + specularMap->setType("sampler2D"); + } - output = new GenOp( " @ = @;\r\n", new DecOp( specularColor ), texOp ); + LangElement *texOp = NULL; + + if (specularMapTex) + texOp = new GenOp("@.Sample(@, @)", specularMapTex, specularMap, texCoord); + else + texOp = new GenOp("tex2D(@, @)", specularMap, texCoord); + + Var *specularColor = new Var("specularColor", "float4"); + + output = new GenOp(" @ = @;\r\n", new DecOp(specularColor), texOp); } ShaderFeature::Resources SpecularMapHLSL::getResources( const MaterialFeatureData &fd ) diff --git a/Engine/source/shaderGen/HLSL/shaderCompHLSL.cpp b/Engine/source/shaderGen/HLSL/shaderCompHLSL.cpp index 2d7b80bc9..6aece4ef0 100644 --- a/Engine/source/shaderGen/HLSL/shaderCompHLSL.cpp +++ b/Engine/source/shaderGen/HLSL/shaderCompHLSL.cpp @@ -55,6 +55,25 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32 Var *newVar = new Var; mElementList.push_back( newVar ); newVar->setConnectName( "POSITION" ); + newVar->rank = 0; + return newVar; + } + + case RT_VPOS: + { + Var *newVar = new Var; + mElementList.push_back(newVar); + newVar->setConnectName("VPOS"); + newVar->rank = 0; + return newVar; + } + + case RT_SVPOSITION: + { + Var *newVar = new Var; + mElementList.push_back(newVar); + newVar->setConnectName("SV_Position"); + newVar->rank = 0; return newVar; } @@ -63,6 +82,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32 Var *newVar = new Var; mElementList.push_back( newVar ); newVar->setConnectName( "NORMAL" ); + newVar->rank = 1; return newVar; } @@ -71,6 +91,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32 Var *newVar = new Var; mElementList.push_back( newVar ); newVar->setConnectName( "BINORMAL" ); + newVar->rank = 2; return newVar; } @@ -79,6 +100,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32 Var *newVar = new Var; mElementList.push_back( newVar ); newVar->setConnectName( "TANGENT" ); + newVar->rank = 3; return newVar; } @@ -87,14 +109,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32 Var *newVar = new Var; mElementList.push_back( newVar ); newVar->setConnectName( "COLOR" ); - return newVar; - } - - case RT_VPOS: - { - Var *newVar = new Var; - mElementList.push_back( newVar ); - newVar->setConnectName( "VPOS" ); + newVar->rank = 4; return newVar; } @@ -113,6 +128,7 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32 newVar->setConnectName( out ); newVar->constNum = index; newVar->arraySize = numElements; + newVar->rank = 5 + index; return newVar; } @@ -124,67 +140,27 @@ Var * ShaderConnectorHLSL::getIndexedElement( U32 index, RegisterType type, U32 return NULL; } + + +S32 QSORT_CALLBACK ShaderConnectorHLSL::_hlsl4VarSort(const void* e1, const void* e2) +{ + Var* a = *((Var **)e1); + Var* b = *((Var **)e2); + + return a->rank - b->rank; +} + void ShaderConnectorHLSL::sortVars() { - if ( GFX->getPixelShaderVersion() >= 2.0 ) + + // If shader model 4+ than we gotta sort the vars to make sure the order is consistent + if (GFX->getPixelShaderVersion() >= 4.f) + { + dQsort((void *)&mElementList[0], mElementList.size(), sizeof(Var *), _hlsl4VarSort); return; - - // Sort connector variables - They must be sorted on hardware that is running - // ps 1.4 and below. The reason is that texture coordinate registers MUST - // map exactly to their respective texture stage. Ie. if you have fog - // coordinates being passed into a pixel shader in texture coordinate register - // number 4, the fog texture MUST reside in texture stage 4 for it to work. - // The problem is solved by pushing non-texture coordinate data to the end - // of the structure so that the texture coodinates are all at the "top" of the - // structure in the order that the features are processed. - - // create list of just the texCoords, sorting by 'mapsToSampler' - Vector< Var * > texCoordList; - - // - first pass is just coords mapped to a sampler - for( U32 i=0; imapsToSampler ) - { - texCoordList.push_back( var ); - } - } - - // - next pass is for the others - for( U32 i=0; iconnectName, "TEX" ) && - !var->mapsToSampler ) - { - texCoordList.push_back( var ); - } - } - - // rename the connectNames - for( U32 i=0; isetConnectName( out ); } - // write new, sorted list over old one - if( texCoordList.size() ) - { - U32 index = 0; - - for( U32 i=0; iconnectName, "TEX" ) ) - { - mElementList[i] = texCoordList[index]; - index++; - } - } - } + return; } void ShaderConnectorHLSL::setName( char *newName ) @@ -246,7 +222,7 @@ void ParamsDefHLSL::assignConstantNumbers() Var *var = dynamic_cast(LangElement::elementList[i]); if( var ) { - bool shaderConst = var->uniform && !var->sampler; + bool shaderConst = var->uniform && !var->sampler && !var->texture; AssertFatal((!shaderConst) || var->constSortPos != cspUninit, "Const sort position has not been set, variable will not receive a constant number!!"); if( shaderConst && var->constSortPos == bin) { @@ -328,6 +304,10 @@ void PixelParamsDefHLSL::print( Stream &stream, bool isVerterShader ) { dSprintf( (char*)varNum, sizeof(varNum), ": register(S%d)", var->constNum ); } + else if (var->texture) + { + dSprintf((char*)varNum, sizeof(varNum), ": register(T%d)", var->constNum); + } else { dSprintf( (char*)varNum, sizeof(varNum), ": register(C%d)", var->constNum ); diff --git a/Engine/source/shaderGen/HLSL/shaderCompHLSL.h b/Engine/source/shaderGen/HLSL/shaderCompHLSL.h index 0a3ead4ed..cb4ae5ad1 100644 --- a/Engine/source/shaderGen/HLSL/shaderCompHLSL.h +++ b/Engine/source/shaderGen/HLSL/shaderCompHLSL.h @@ -30,6 +30,8 @@ class ShaderConnectorHLSL : public ShaderConnector { +private: + static S32 QSORT_CALLBACK _hlsl4VarSort(const void* e1, const void* e2); public: // ShaderConnector diff --git a/Engine/source/shaderGen/HLSL/shaderFeatureHLSL.cpp b/Engine/source/shaderGen/HLSL/shaderFeatureHLSL.cpp index 2ab6a75f0..8878f2600 100644 --- a/Engine/source/shaderGen/HLSL/shaderFeatureHLSL.cpp +++ b/Engine/source/shaderGen/HLSL/shaderFeatureHLSL.cpp @@ -173,6 +173,7 @@ LangElement *ShaderFeatureHLSL::expandNormalMap( LangElement *sampleNormalOp, ShaderFeatureHLSL::ShaderFeatureHLSL() { output = NULL; + mIsDirect3D11 = GFX->getAdapterType() == Direct3D11; } Var * ShaderFeatureHLSL::getVertTexCoord( const String &name ) @@ -354,7 +355,7 @@ Var* ShaderFeatureHLSL::getOutTexCoord( const char *name, if ( useTexAnim ) { - inTex->setType( "float4" ); + inTex->setType( "float2" ); // create texture mat var Var *texMat = new Var; @@ -365,7 +366,7 @@ Var* ShaderFeatureHLSL::getOutTexCoord( const char *name, // Statement allows for casting of different types which // eliminates vector truncation problems. - String statement = String::ToString( " @ = (%s)mul(@, @).xy;\r\n", type ); + String statement = String::ToString(" @ = (%s)mul(@, float4(@,1,1));\r\n", type); meta->addStatement( new GenOp( statement, texCoord, texMat, inTex ) ); } else @@ -464,7 +465,17 @@ Var* ShaderFeatureHLSL::getInVpos( MultiLine *meta, ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - if ( GFX->getPixelShaderVersion() >= 3.0f ) + F32 pixelShaderVer = GFX->getPixelShaderVersion(); + + if ( pixelShaderVer >= 4.0f ) + { + inVpos = connectComp->getElement( RT_SVPOSITION ); + inVpos->setName( "vpos" ); + inVpos->setStructName( "IN" ); + inVpos->setType( "float4" ); + return inVpos; + } + else if ( pixelShaderVer >= 3.0f ) { inVpos = connectComp->getElement( RT_VPOS ); inVpos->setName( "vpos" ); @@ -516,15 +527,30 @@ Var* ShaderFeatureHLSL::getInViewToTangent( Vector &componentL Var* ShaderFeatureHLSL::getNormalMapTex() { - Var *normalMap = (Var*)LangElement::find( "bumpMap" ); - if ( !normalMap ) + Var *normalMap = (Var*)LangElement::find("bumpMap"); + if (!normalMap) { normalMap = new Var; - normalMap->setType( "sampler2D" ); - normalMap->setName( "bumpMap" ); + normalMap->setType("sampler2D"); + normalMap->setName("bumpMap"); normalMap->uniform = true; normalMap->sampler = true; normalMap->constNum = Var::getTexUnitNum(); + + // D3D11 + Var* normalMapTex = NULL; + if (GFX->getAdapterType() == Direct3D11) + { + normalMap->setType("SamplerState"); + normalMapTex = new Var; + normalMapTex->setName("bumpMapTex"); + normalMapTex->setType("Texture2D"); + normalMapTex->uniform = true; + normalMapTex->texture = true; + normalMapTex->constNum = normalMap->constNum; + } + + } return normalMap; @@ -780,6 +806,7 @@ Var* ShaderFeatureHLSL::addOutDetailTexCoord( Vector &compon // Grab incoming texture coords. Var *inTex = getVertTexCoord( "texCoord" ); + inTex->setType("float2"); // create detail variable Var *detScale = new Var; @@ -798,8 +825,6 @@ Var* ShaderFeatureHLSL::addOutDetailTexCoord( Vector &compon if ( useTexAnim ) { - inTex->setType( "float4" ); - // Find or create the texture matrix. Var *texMat = (Var*)LangElement::find( "texMat" ); if ( !texMat ) @@ -811,7 +836,7 @@ Var* ShaderFeatureHLSL::addOutDetailTexCoord( Vector &compon texMat->constSortPos = cspPass; } - meta->addStatement( new GenOp( " @ = mul(@, @).xy * @;\r\n", outTex, texMat, inTex, detScale ) ); + meta->addStatement(new GenOp(" @ = mul(@, float4(@,1,1)).xy * @;\r\n", outTex, texMat, inTex, detScale)); } else { @@ -869,6 +894,19 @@ void DiffuseMapFeatHLSL::processPix( Vector &componentList, diffuseMap->sampler = true; diffuseMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + Var* diffuseMapTex = NULL; + if (mIsDirect3D11) + { + diffuseMap->setType("SamplerState"); + + diffuseMapTex = new Var; + diffuseMapTex->setName("diffuseMapTex"); + diffuseMapTex->setType("Texture2D"); + diffuseMapTex->uniform = true; + diffuseMapTex->texture = true; + diffuseMapTex->constNum = diffuseMap->constNum; + } + // create sample color Var *diffColor = new Var; diffColor->setType("float4"); @@ -880,13 +918,14 @@ void DiffuseMapFeatHLSL::processPix( Vector &componentList, if ( fd.features[MFT_CubeMap] ) { - meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", - colorDecl, - diffuseMap, - inTex ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(" @ = @.Sample(@, @);\r\n", colorDecl, diffuseMapTex, diffuseMap, inTex)); + else + meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", colorDecl, diffuseMap, inTex)); + if (!fd.features[MFT_Imposter]) meta->addStatement(new GenOp(" @ = toLinear(@);\r\n", diffColor, diffColor)); - + meta->addStatement(new GenOp(" @;\r\n", assignColor(diffColor, Material::Mul, NULL, targ))); } else if(fd.features[MFT_DiffuseMapAtlas]) @@ -958,15 +997,19 @@ void DiffuseMapFeatHLSL::processPix( Vector &componentList, return; } #endif - - if(is_sm3) + if (mIsDirect3D11) + { + meta->addStatement(new GenOp(" @ = @.SampleLevel(@,@,mipLod);\r\n", + new DecOp(diffColor), diffuseMapTex, diffuseMap, inTex)); + } + else if(is_sm3) { meta->addStatement(new GenOp( " @ = tex2Dlod(@, float4(@, 0.0, mipLod));\r\n", new DecOp(diffColor), diffuseMap, inTex)); } else { - meta->addStatement(new GenOp( " @ = tex2D(@, @);\r\n", + meta->addStatement(new GenOp( " @ = tex2D(@, @);\r\n", new DecOp(diffColor), diffuseMap, inTex)); } if (!fd.features[MFT_Imposter]) @@ -976,7 +1019,11 @@ void DiffuseMapFeatHLSL::processPix( Vector &componentList, } else { - meta->addStatement(new GenOp("@ = tex2D(@, @);\r\n", colorDecl, diffuseMap, inTex)); + if (mIsDirect3D11) + meta->addStatement(new GenOp("@ = @.Sample(@, @);\r\n", colorDecl, diffuseMapTex, diffuseMap, inTex)); + else + meta->addStatement(new GenOp("@ = tex2D(@, @);\r\n", colorDecl, diffuseMap, inTex)); + if (!fd.features[MFT_Imposter]) meta->addStatement(new GenOp(" @ = toLinear(@);\r\n", diffColor, diffColor)); meta->addStatement(new GenOp(" @;\r\n", assignColor(diffColor, Material::Mul, NULL, targ))); @@ -1067,7 +1114,24 @@ void OverlayTexFeatHLSL::processPix( Vector &componentList, diffuseMap->sampler = true; diffuseMap->constNum = Var::getTexUnitNum(); // used as texture unit num here - LangElement *statement = new GenOp( "tex2D(@, @)", diffuseMap, inTex ); + Var* diffuseMapTex = NULL; + if (mIsDirect3D11) + { + diffuseMap->setType("SamplerState"); + diffuseMapTex = new Var; + diffuseMapTex->setName("overlayMapTex"); + diffuseMapTex->setType("Texture2D"); + diffuseMapTex->uniform = true; + diffuseMapTex->texture = true; + diffuseMapTex->constNum = diffuseMap->constNum; + } + + LangElement *statement = NULL; + if (mIsDirect3D11) + statement = new GenOp("@.Sample(@, @)", diffuseMapTex, diffuseMap, inTex); + else + statement = new GenOp("tex2D(@, @)", diffuseMap, inTex); + output = new GenOp( " @;\r\n", assignColor( statement, Material::LerpAlpha ) ); } @@ -1240,6 +1304,17 @@ void LightmapFeatHLSL::processPix( Vector &componentList, lightMap->sampler = true; lightMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + Var *lightMapTex = NULL; + if (mIsDirect3D11) + { + lightMap->setType("SamplerState"); + lightMapTex->setName("lightMapTex"); + lightMapTex->setType("Texture2D"); + lightMapTex->uniform = true; + lightMapTex->texture = true; + lightMapTex->constNum = lightMap->constNum; + } + // argh, pixel specular should prob use this too if( fd.features[MFT_NormalMap] ) @@ -1249,7 +1324,10 @@ void LightmapFeatHLSL::processPix( Vector &componentList, lmColor->setType( "float4" ); LangElement *lmColorDecl = new DecOp( lmColor ); - output = new GenOp( " @ = tex2D(@, @);\r\n", lmColorDecl, lightMap, inTex ); + if (mIsDirect3D11) + output = new GenOp(" @ = @.Sample(@, @);\r\n", lmColorDecl, lightMapTex, lightMap, inTex); + else + output = new GenOp(" @ = tex2D(@, @);\r\n", lmColorDecl, lightMap, inTex); return; } @@ -1269,16 +1347,26 @@ void LightmapFeatHLSL::processPix( Vector &componentList, // Lightmap has already been included in the advanced light bin, so // no need to do any sampling or anything - if(bPreProcessedLighting) - statement = new GenOp( "float4(@, 1.0)", inColor ); + if (bPreProcessedLighting) + statement = new GenOp("float4(@, 1.0)", inColor); else - statement = new GenOp( "tex2D(@, @) + float4(@.rgb, 0.0)", lightMap, inTex, inColor ); + { + if (mIsDirect3D11) + statement = new GenOp("@.Sample(@, @) + float4(@.rgb, 0.0)", lightMapTex, lightMap, inTex, inColor); + else + statement = new GenOp("tex2D(@, @) + float4(@.rgb, 0.0)", lightMap, inTex, inColor); + } } } // If we still don't have it... then just sample the lightmap. - if ( !statement ) - statement = new GenOp( "tex2D(@, @)", lightMap, inTex ); + if (!statement) + { + if (mIsDirect3D11) + statement = new GenOp("@.Sample(@, @)", lightMapTex, lightMap, inTex); + else + statement = new GenOp("tex2D(@, @)", lightMap, inTex); + } // Assign to proper render target MultiLine *meta = new MultiLine; @@ -1365,6 +1453,18 @@ void TonemapFeatHLSL::processPix( Vector &componentList, toneMap->sampler = true; toneMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + Var *toneMapTex = NULL; + if (mIsDirect3D11) + { + toneMap->setType("SamplerState"); + toneMapTex = new Var; + toneMapTex->setName("toneMapTex"); + toneMapTex->setType("Texture2D"); + toneMapTex->uniform = true; + toneMapTex->texture = true; + toneMapTex->constNum = toneMap->constNum; + } + MultiLine * meta = new MultiLine; // First get the toneMap color @@ -1373,7 +1473,10 @@ void TonemapFeatHLSL::processPix( Vector &componentList, toneMapColor->setName( "toneMapColor" ); LangElement *toneMapColorDecl = new DecOp( toneMapColor ); - meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", toneMapColorDecl, toneMap, inTex2 ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(" @ = @.Sample(@, @);\r\n", toneMapColorDecl, toneMapTex, toneMap, inTex2)); + else + meta->addStatement(new GenOp(" @ = tex2D(@, @);\r\n", toneMapColorDecl, toneMap, inTex2)); // We do a different calculation if there is a diffuse map or not Material::BlendOp blendOp = Material::Mul; @@ -1602,6 +1705,18 @@ void DetailFeatHLSL::processPix( Vector &componentList, detailMap->sampler = true; detailMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + Var* detailMapTex = NULL; + if (mIsDirect3D11) + { + detailMap->setType("SamplerState"); + detailMapTex = new Var; + detailMapTex->setName("detailMapTex"); + detailMapTex->setType("Texture2D"); + detailMapTex->uniform = true; + detailMapTex->texture = true; + detailMapTex->constNum = detailMap->constNum; + } + // We're doing the standard greyscale detail map // technique which can darken and lighten the // diffuse texture. @@ -1609,7 +1724,12 @@ void DetailFeatHLSL::processPix( Vector &componentList, // TODO: We could add a feature to toggle between this // and a simple multiplication with the detail map. - LangElement *statement = new GenOp( "( tex2D(@, @) * 2.0 ) - 1.0", detailMap, inTex ); + LangElement *statement = NULL; + if (mIsDirect3D11) + statement = new GenOp("( @.Sample(@, @) * 2.0 ) - 1.0", detailMapTex, detailMap, inTex); + else + statement = new GenOp("( tex2D(@, @) * 2.0 ) - 1.0", detailMap, inTex); + if ( fd.features[MFT_isDeferred]) output = new GenOp( " @;\r\n", assignColor( statement, Material::Add, NULL, ShaderFeature::RenderTarget1 ) ); else @@ -1665,7 +1785,12 @@ void VertPositionHLSL::processVert( Vector &componentList, // grab connector position ShaderConnector *connectComp = dynamic_cast( componentList[C_CONNECTOR] ); - Var *outPosition = connectComp->getElement( RT_POSITION ); + Var *outPosition = NULL; + if (mIsDirect3D11) + outPosition = connectComp->getElement(RT_SVPOSITION); + else + outPosition = connectComp->getElement(RT_POSITION); + outPosition->setName( "hpos" ); outPosition->setStructName( "OUT" ); @@ -1679,6 +1804,19 @@ void VertPositionHLSL::processVert( Vector &componentList, output = meta; } +void VertPositionHLSL::processPix( Vector &componentList, + const MaterialFeatureData &fd) +{ + if (mIsDirect3D11) + { + // grab connector position + ShaderConnector *connectComp = dynamic_cast(componentList[C_CONNECTOR]); + Var *outPosition = connectComp->getElement(RT_SVPOSITION); + outPosition->setName("vpos"); + outPosition->setStructName("IN"); + } +} + //**************************************************************************** // Reflect Cubemap @@ -1738,8 +1876,11 @@ void ReflectCubeFeatHLSL::processVert( Vector &componentList, cubeNormal->setType( "float3" ); LangElement *cubeNormDecl = new DecOp( cubeNormal ); - meta->addStatement( new GenOp( " @ = normalize( mul(@, float4(normalize(@),0.0)).xyz );\r\n", - cubeNormDecl, cubeTrans, inNormal ) ); + meta->addStatement(new GenOp(" @ = ( mul( (@), float4(@, 0) ) ).xyz;\r\n", + cubeNormDecl, cubeTrans, inNormal)); + + meta->addStatement(new GenOp(" @ = bool(length(@)) ? normalize(@) : @;\r\n", + cubeNormal, cubeNormal, cubeNormal, cubeNormal)); // grab the eye position Var *eyePos = (Var*)LangElement::find( "eyePosWorld" ); @@ -1782,10 +1923,10 @@ void ReflectCubeFeatHLSL::processPix( Vector &componentList, // current pass - we need to add one to the current pass to use // its alpha channel as a gloss map. if( !fd.features[MFT_DiffuseMap] && - !fd.features[MFT_NormalMap] ) + !fd.features[MFT_NormalMap]) { if( fd.materialFeatures[MFT_DiffuseMap] || - fd.materialFeatures[MFT_NormalMap] ) + fd.materialFeatures[MFT_NormalMap]) { // grab connector texcoord register Var *inTex = getInTexCoord( "texCoord", "float2", true, componentList ); @@ -1797,6 +1938,19 @@ void ReflectCubeFeatHLSL::processPix( Vector &componentList, newMap->uniform = true; newMap->sampler = true; newMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + + Var* glowMapTex = NULL; + if (mIsDirect3D11) + { + newMap->setType("SamplerState"); + + glowMapTex = new Var; + glowMapTex->setName("glowMapTex"); + glowMapTex->setType("Texture2D"); + glowMapTex->uniform = true; + glowMapTex->texture = true; + glowMapTex->constNum = newMap->constNum; + } // create sample color Var *color = new Var; @@ -1806,7 +1960,10 @@ void ReflectCubeFeatHLSL::processPix( Vector &componentList, glossColor = color; - meta->addStatement( new GenOp( " @ = tex2D( @, @ );\r\n", colorDecl, newMap, inTex ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(" @ = @.Sample( @, @ );\r\n", colorDecl, glowMapTex, newMap, inTex)); + else + meta->addStatement(new GenOp(" @ = tex2D( @, @ );\r\n", colorDecl, newMap, inTex)); } } else @@ -1837,6 +1994,18 @@ void ReflectCubeFeatHLSL::processPix( Vector &componentList, cubeMap->sampler = true; cubeMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + Var* cubeMapTex = NULL; + if (mIsDirect3D11) + { + cubeMap->setType("SamplerState"); + cubeMapTex = new Var; + cubeMapTex->setName("cubeMapTex"); + cubeMapTex->setType("TextureCube"); // cubeMapTex->setType("TextureCube"); + cubeMapTex->uniform = true; + cubeMapTex->texture = true; + cubeMapTex->constNum = cubeMap->constNum; + } + // TODO: Restore the lighting attenuation here! Var *attn = NULL; //if ( fd.materialFeatures[MFT_DynamicLight] ) @@ -1855,15 +2024,37 @@ void ReflectCubeFeatHLSL::processPix( Vector &componentList, //LangElement *texCube = new GenOp( "texCUBElod( @, float4(@, min((1.0 - (@ / 128.0)) * 11.0 + 1.0, 8.0)) )", cubeMap, reflectVec, specPower ); if (fd.features[MFT_DeferredSpecMap]) - texCube = new GenOp("texCUBElod( @, float4(@, (@.a*5)) )", cubeMap, reflectVec, matinfo); + { + if (mIsDirect3D11) + texCube = new GenOp("@.SampleLevel( @, @, @.a*5)", cubeMapTex, cubeMap, reflectVec, matinfo); + else + texCube = new GenOp("texCUBElod( @, float4(@, (@.a*5)) )", cubeMap, reflectVec, matinfo); + } else - texCube = new GenOp("texCUBElod( @, float4(@, ((1.0-@.a)*6)) )", cubeMap, reflectVec, matinfo); + { + if (mIsDirect3D11) + texCube = new GenOp("@.SampleLevel( @, @, (1.0-@.a)*6 )", cubeMapTex, cubeMap, reflectVec, matinfo); + else + texCube = new GenOp("texCUBElod( @, float4(@, ((1.0-@.a)*6)) )", cubeMap, reflectVec, matinfo); + } } else + { if (glossColor) //failing that, rtry and find color data - texCube = new GenOp("texCUBElod( @, float4(@, @.a*5))", cubeMap, reflectVec, glossColor); + { + if (mIsDirect3D11) + texCube = new GenOp("@.SampleLevel( @, @, @.a*5)", cubeMapTex, cubeMap, reflectVec, glossColor); + else + texCube = new GenOp("texCUBElod( @, float4(@, @.a*5))", cubeMap, reflectVec, glossColor); + } else //failing *that*, just draw the cubemap - texCube = new GenOp("texCUBE( @, @)", cubeMap, reflectVec); + { + if (mIsDirect3D11) + texCube = new GenOp("@.Sample( @, @ )", cubeMapTex, cubeMap, reflectVec); + else + texCube = new GenOp("texCUBE( @, @ )", cubeMap, reflectVec); + } + } LangElement *lerpVal = NULL; Material::BlendOp blendOp = Material::LerpAlpha; @@ -1898,7 +2089,7 @@ void ReflectCubeFeatHLSL::processPix( Vector &componentList, if (fd.features[MFT_DeferredSpecMap]) meta->addStatement(new GenOp(" @.rgb = lerp( @.rgb, (@).rgb, (@.b));\r\n", targ, targ, texCube, lerpVal)); else - meta->addStatement(new GenOp(" @.rgb = lerp( @.rgb, (@).rgb, (@.b));\r\n", targ, targ, texCube, lerpVal)); + meta->addStatement(new GenOp(" @.rgb = lerp( @.rgb, (@).rgb, (@.b*128/5));\r\n", targ, targ, texCube, lerpVal)); } else meta->addStatement( new GenOp( " @;\r\n", assignColor( texCube, blendOp, lerpVal ) ) ); @@ -1951,7 +2142,7 @@ void ReflectCubeFeatHLSL::setTexData( Material::StageData &stageDat, } } } - + if( stageDat.getCubemap() ) { passData.mCubeMap = stageDat.getCubemap(); @@ -2397,7 +2588,8 @@ void VisibilityFeatHLSL::processPix( Vector &componentList, // Everything else does a fizzle. Var *vPos = getInVpos( meta, componentList ); - meta->addStatement( new GenOp( " fizzle( @, @ );\r\n", vPos, visibility ) ); + // vpos is a float4 in d3d11 + meta->addStatement( new GenOp( " fizzle( @.xy, @ );\r\n", vPos, visibility ) ); } ShaderFeature::Resources VisibilityFeatHLSL::getResources( const MaterialFeatureData &fd ) diff --git a/Engine/source/shaderGen/HLSL/shaderFeatureHLSL.h b/Engine/source/shaderGen/HLSL/shaderFeatureHLSL.h index b09d4d561..673970945 100644 --- a/Engine/source/shaderGen/HLSL/shaderFeatureHLSL.h +++ b/Engine/source/shaderGen/HLSL/shaderFeatureHLSL.h @@ -33,6 +33,8 @@ struct RenderPassData; class ShaderFeatureHLSL : public ShaderFeature { +protected: + bool mIsDirect3D11; public: ShaderFeatureHLSL(); @@ -188,6 +190,9 @@ class VertPositionHLSL : public ShaderFeatureHLSL public: virtual void processVert( Vector &componentList, const MaterialFeatureData &fd ); + + virtual void processPix( Vector &componentList, + const MaterialFeatureData &fd); virtual String getName() { diff --git a/Engine/source/shaderGen/HLSL/shaderGenHLSL.cpp b/Engine/source/shaderGen/HLSL/shaderGenHLSL.cpp index 23ca8137d..49487624f 100644 --- a/Engine/source/shaderGen/HLSL/shaderGenHLSL.cpp +++ b/Engine/source/shaderGen/HLSL/shaderGenHLSL.cpp @@ -63,21 +63,33 @@ void ShaderGenPrinterHLSL::printPixelShaderOutputStruct(Stream& stream, const Ma for( U32 i = 0; i < FEATUREMGR->getFeatureCount(); i++ ) { const FeatureInfo &info = FEATUREMGR->getAt( i ); - if( featureData.features.hasFeature( *info.type ) ) + if ( featureData.features.hasFeature( *info.type ) ) numMRTs |= info.feature->getOutputTargets( featureData ); } - WRITESTR( "struct Fragout\r\n" ); - WRITESTR( "{\r\n" ); - WRITESTR( " float4 col : COLOR0;\r\n" ); - for( U32 i = 1; i < 4; i++ ) + WRITESTR("struct Fragout\r\n"); + WRITESTR("{\r\n"); + if (GFX->getAdapterType() == Direct3D11) { - if( numMRTs & 1 << i ) - WRITESTR( avar( " float4 col%d : COLOR%d;\r\n", i, i ) ); + WRITESTR(" float4 col : SV_Target0;\r\n"); + for (U32 i = 1; i < 4; i++) + { + if (numMRTs & 1 << i) + WRITESTR(avar(" float4 col%d : SV_Target%d;\r\n", i, i)); + } } - WRITESTR( "};\r\n" ); - WRITESTR( "\r\n" ); - WRITESTR( "\r\n" ); + else + { + WRITESTR(" float4 col : COLOR0;\r\n"); + for (U32 i = 1; i < 4; i++) + { + if (numMRTs & 1 << i) + WRITESTR(avar(" float4 col%d : COLOR%d;\r\n", i, i)); + } + } + WRITESTR("};\r\n"); + WRITESTR("\r\n"); + WRITESTR("\r\n"); } void ShaderGenPrinterHLSL::printPixelShaderCloser(Stream& stream) @@ -141,8 +153,8 @@ ShaderComponent* ShaderGenComponentFactoryHLSL::createVertexInputConnector( cons } else if ( element.isSemantic( GFXSemantic::TANGENTW ) ) { - var = vertComp->getIndexedElement( element.getSemanticIndex(), RT_TEXCOORD ); - var->setName( "tangentW" ); + var = vertComp->getIndexedElement(element.getSemanticIndex(), RT_TEXCOORD); + var->setName("tangentW"); } else if ( element.isSemantic( GFXSemantic::BINORMAL ) ) { diff --git a/Engine/source/shaderGen/HLSL/shaderGenHLSLInit.cpp b/Engine/source/shaderGen/HLSL/shaderGenHLSLInit.cpp index fd30656bd..9e3805cdc 100644 --- a/Engine/source/shaderGen/HLSL/shaderGenHLSLInit.cpp +++ b/Engine/source/shaderGen/HLSL/shaderGenHLSLInit.cpp @@ -119,6 +119,7 @@ MODULE_BEGIN( ShaderGenHLSL ) sInitDelegate.bind(_initShaderGenHLSL); SHADERGEN->registerInitDelegate(Direct3D9, sInitDelegate); SHADERGEN->registerInitDelegate(Direct3D9_360, sInitDelegate); + SHADERGEN->registerInitDelegate(Direct3D11, sInitDelegate); } MODULE_END; diff --git a/Engine/source/shaderGen/langElement.cpp b/Engine/source/shaderGen/langElement.cpp index 9989eb2d2..9a38cdd31 100644 --- a/Engine/source/shaderGen/langElement.cpp +++ b/Engine/source/shaderGen/langElement.cpp @@ -99,6 +99,8 @@ Var::Var() sampler = false; mapsToSampler = false; arraySize = 1; + texture = false; + rank = 0; } Var::Var( const char *inName, const char *inType ) @@ -113,6 +115,8 @@ Var::Var( const char *inName, const char *inType ) texCoordNum = 0; constSortPos = cspUninit; arraySize = 1; + texture = false; + rank = 0; setName( inName ); setType( inType ); diff --git a/Engine/source/shaderGen/langElement.h b/Engine/source/shaderGen/langElement.h index c338aacb8..a1e8c96ad 100644 --- a/Engine/source/shaderGen/langElement.h +++ b/Engine/source/shaderGen/langElement.h @@ -120,8 +120,10 @@ struct Var : public LangElement bool vertData; // argument coming from vertex data bool connector; // variable that will be passed to pixel shader bool sampler; // texture + bool texture; //for D3D11 texture variables bool mapsToSampler; // for ps 1.x shaders - texcoords must be mapped to same sampler stage U32 arraySize; // 1 = no array, > 1 array of "type" + U32 rank; // optional rank system to assist in sorting vars if needed static U32 texUnitCount; static U32 getTexUnitNum(U32 numElements = 1); diff --git a/Engine/source/shaderGen/shaderFeature.cpp b/Engine/source/shaderGen/shaderFeature.cpp index 7e22f72ad..113b05a42 100644 --- a/Engine/source/shaderGen/shaderFeature.cpp +++ b/Engine/source/shaderGen/shaderFeature.cpp @@ -84,4 +84,9 @@ Var* ShaderFeature::findOrCreateLocal( const char *name, } return outVar; +} + +void ShaderFeature::setInstancingFormat(GFXVertexFormat *format) +{ + mInstancingFormat = format; } \ No newline at end of file diff --git a/Engine/source/shaderGen/shaderFeature.h b/Engine/source/shaderGen/shaderFeature.h index c6ac4955d..03426b733 100644 --- a/Engine/source/shaderGen/shaderFeature.h +++ b/Engine/source/shaderGen/shaderFeature.h @@ -99,11 +99,10 @@ protected: /// S32 mProcessIndex; -public: - - // TODO: Make this protected and give it a proper API. GFXVertexFormat *mInstancingFormat; +public: + //************************************************************************** /*! The Resources structure is used by ShaderFeature to indicate how many @@ -293,6 +292,8 @@ public: static Var* findOrCreateLocal( const char *name, const char *type, MultiLine *multi ); + // Set the instancing format + void setInstancingFormat(GFXVertexFormat *format); }; #endif // _SHADERFEATURE_H_ diff --git a/Engine/source/shaderGen/shaderGen.cpp b/Engine/source/shaderGen/shaderGen.cpp index 81e7f644f..eb7685b39 100644 --- a/Engine/source/shaderGen/shaderGen.cpp +++ b/Engine/source/shaderGen/shaderGen.cpp @@ -264,7 +264,7 @@ void ShaderGen::_processVertFeatures( Vector ¯os, bool macro if ( macrosOnly ) continue; - feature->mInstancingFormat = &mInstancingFormat; + feature->setInstancingFormat( &mInstancingFormat ); feature->processVert( mComponents, mFeatureData ); String line; @@ -304,7 +304,7 @@ void ShaderGen::_processPixFeatures( Vector ¯os, bool macros if ( macrosOnly ) continue; - feature->mInstancingFormat = &mInstancingFormat; + feature->setInstancingFormat( &mInstancingFormat ); feature->processPix( mComponents, mFeatureData ); String line; @@ -488,8 +488,7 @@ GFXShader* ShaderGen::getShader( const MaterialFeatureData &featureData, const G generateShader( featureData, vertFile, pixFile, &pixVersion, vertexFormat, cacheKey, shaderMacros ); GFXShader *shader = GFX->createShader(); - shader->mInstancingFormat.copy( mInstancingFormat ); // TODO: Move to init() below! - if ( !shader->init( vertFile, pixFile, pixVersion, shaderMacros, samplers ) ) + if (!shader->init(vertFile, pixFile, pixVersion, shaderMacros, samplers, &mInstancingFormat)) { delete shader; return NULL; diff --git a/Engine/source/terrain/glsl/terrFeatureGLSL.cpp b/Engine/source/terrain/glsl/terrFeatureGLSL.cpp index 7761a8545..4945d4c88 100644 --- a/Engine/source/terrain/glsl/terrFeatureGLSL.cpp +++ b/Engine/source/terrain/glsl/terrFeatureGLSL.cpp @@ -396,9 +396,6 @@ void TerrainDetailMapFeatGLSL::processPix( Vector &component const S32 detailIndex = getProcessIndex(); Var *inTex = getVertTexCoord( "texCoord" ); - // new terrain - bool hasNormal = fd.features.hasFeature(MFT_TerrainNormalMap, detailIndex); - MultiLine *meta = new MultiLine; // We need the negative tangent space view vector @@ -490,7 +487,6 @@ void TerrainDetailMapFeatGLSL::processPix( Vector &component blendDepth->constSortPos = cspPrimitive; } - Var *baseColor = (Var*)LangElement::find("baseColor"); ShaderFeature::OutputTarget target = ShaderFeature::DefaultTarget; if(fd.features.hasFeature( MFT_DeferredTerrainDetailMap )) diff --git a/Engine/source/terrain/hlsl/terrFeatureHLSL.cpp b/Engine/source/terrain/hlsl/terrFeatureHLSL.cpp index b0e16bb64..772c822b1 100644 --- a/Engine/source/terrain/hlsl/terrFeatureHLSL.cpp +++ b/Engine/source/terrain/hlsl/terrFeatureHLSL.cpp @@ -38,7 +38,7 @@ namespace { void register_hlsl_shader_features_for_terrain(GFXAdapterType type) { - if(type != Direct3D9 && type != Direct3D9_360) + if (type != Direct3D9 && type != Direct3D9_360 && type != Direct3D11) return; FEATUREMGR->registerFeature( MFT_TerrainBaseMap, new TerrainBaseMapFeatHLSL ); @@ -70,9 +70,9 @@ MODULE_END; TerrainFeatHLSL::TerrainFeatHLSL() : mTorqueDep( "shaders/common/torque.hlsl" ) - { +{ addDependency( &mTorqueDep ); - } +} Var* TerrainFeatHLSL::_getUniformVar( const char *name, const char *type, ConstantSortPosition csp ) { @@ -129,14 +129,18 @@ Var* TerrainFeatHLSL::_getInMacroCoord( Vector &componentList Var* TerrainFeatHLSL::_getNormalMapTex() { - String name( String::ToString( "normalMap%d", getProcessIndex() ) ); - Var *normalMap = (Var*)LangElement::find( name ); + String name(String::ToString("normalMap%d", getProcessIndex())); + Var *normalMap = (Var*)LangElement::find(name); - if ( !normalMap ) + if (!normalMap) { normalMap = new Var; - normalMap->setType( "sampler2D" ); - normalMap->setName( name ); + if (mIsDirect3D11) + normalMap->setType("SamplerState"); + else + normalMap->setType("sampler2D"); + + normalMap->setName(name); normalMap->uniform = true; normalMap->sampler = true; normalMap->constNum = Var::getTexUnitNum(); @@ -267,12 +271,27 @@ void TerrainBaseMapFeatHLSL::processPix( Vector &componentLis Var *baseColor = new Var; baseColor->setType( "float4" ); baseColor->setName( "baseColor" ); - meta->addStatement( new GenOp( " @ = tex2D( @, @.xy );\r\n", new DecOp( baseColor ), diffuseMap, texCoord ) ); + if (mIsDirect3D11) + { + diffuseMap->setType("SamplerState"); + Var *diffuseTex = new Var; + diffuseTex->setType("Texture2D"); + diffuseTex->setName("baseTexture"); + diffuseTex->uniform = true; + diffuseTex->texture = true; + diffuseTex->constNum = diffuseMap->constNum; + meta->addStatement(new GenOp(" @ = @.Sample( @, @.xy );\r\n", new DecOp(baseColor), diffuseTex, diffuseMap, texCoord)); + } + else + { + meta->addStatement(new GenOp(" @ = tex2D( @, @.xy );\r\n", new DecOp(baseColor), diffuseMap, texCoord)); + } + meta->addStatement(new GenOp(" @ = toLinear(@);\r\n", baseColor, baseColor)); - ShaderFeature::OutputTarget target = ShaderFeature::DefaultTarget; + ShaderFeature::OutputTarget target = ShaderFeature::DefaultTarget; - if (fd.features.hasFeature(MFT_isDeferred)) + if (fd.features.hasFeature(MFT_isDeferred)) { target= ShaderFeature::RenderTarget1; } @@ -433,9 +452,25 @@ void TerrainDetailMapFeatHLSL::processPix( Vector &component layerTex->sampler = true; layerTex->constNum = Var::getTexUnitNum(); - // Read the layer texture to get the samples. - meta->addStatement( new GenOp( " @ = round( tex2D( @, @.xy ) * 255.0f );\r\n", - new DecOp( layerSample ), layerTex, inTex ) ); + if (mIsDirect3D11) + { + layerTex->setType("SamplerState"); + Var* layerTexObj = new Var; + layerTexObj->setName("layerTexObj"); + layerTexObj->setType("Texture2D"); + layerTexObj->uniform = true; + layerTexObj->texture = true; + layerTexObj->constNum = layerTex->constNum; + // Read the layer texture to get the samples. + meta->addStatement(new GenOp(" @ = round( @.Sample( @, @.xy ) * 255.0f );\r\n", + new DecOp(layerSample), layerTexObj, layerTex, inTex)); + } + else + { + // Read the layer texture to get the samples. + meta->addStatement(new GenOp(" @ = round( tex2D( @, @.xy ) * 255.0f );\r\n", + new DecOp(layerSample), layerTex, inTex)); + } } Var *layerSize = (Var*)LangElement::find( "layerSize" ); @@ -478,21 +513,52 @@ void TerrainDetailMapFeatHLSL::processPix( Vector &component // If we had a parallax feature... then factor in the parallax // amount so that it fades out with the layer blending. - if ( fd.features.hasFeature( MFT_TerrainParallaxMap, detailIndex ) ) + if (fd.features.hasFeature(MFT_TerrainParallaxMap, detailIndex)) { // Get the rest of our inputs. Var *normalMap = _getNormalMapTex(); - // Call the library function to do the rest. - if(fd.features.hasFeature( MFT_IsDXTnm, detailIndex ) ) + if (mIsDirect3D11) { - meta->addStatement( new GenOp( " @.xy += parallaxOffsetDxtnm( @, @.xy, @, @.z * @ );\r\n", - inDet, normalMap, inDet, negViewTS, detailInfo, detailBlend ) ); + String name(String::ToString("normalMapTex%d", getProcessIndex())); + Var *normalMapTex = (Var*)LangElement::find(name); + + if (!normalMapTex) + { + normalMapTex = new Var; + normalMapTex->setName(String::ToString("normalMapTex%d", getProcessIndex())); + normalMapTex->setType("Texture2D"); + normalMapTex->uniform = true; + normalMapTex->texture = true; + normalMapTex->constNum = normalMap->constNum; + } + + // Call the library function to do the rest. + if (fd.features.hasFeature(MFT_IsDXTnm, detailIndex)) + { + meta->addStatement(new GenOp(" @.xy += parallaxOffsetDxtnm( @, @, @.xy, @, @.z * @ );\r\n", + inDet, normalMapTex, normalMap, inDet, negViewTS, detailInfo, detailBlend)); + } + else + { + meta->addStatement(new GenOp(" @.xy += parallaxOffset( @, @, @.xy, @, @.z * @ );\r\n", + inDet, normalMapTex, normalMap, inDet, negViewTS, detailInfo, detailBlend)); + } + } else { - meta->addStatement( new GenOp( " @.xy += parallaxOffset( @, @.xy, @, @.z * @ );\r\n", - inDet, normalMap, inDet, negViewTS, detailInfo, detailBlend ) ); + // Call the library function to do the rest. + if (fd.features.hasFeature(MFT_IsDXTnm, detailIndex)) + { + meta->addStatement(new GenOp(" @.xy += parallaxOffsetDxtnm( @, @.xy, @, @.z * @ );\r\n", + inDet, normalMap, inDet, negViewTS, detailInfo, detailBlend)); + } + else + { + meta->addStatement(new GenOp(" @.xy += parallaxOffset( @, @.xy, @, @.z * @ );\r\n", + inDet, normalMap, inDet, negViewTS, detailInfo, detailBlend)); + } } } @@ -531,27 +597,46 @@ void TerrainDetailMapFeatHLSL::processPix( Vector &component // //Sampled detail texture that is not expanded - Var *detailTex = new Var; - detailTex->setType("float4"); - detailTex->setName("detailTex"); - meta->addStatement( new GenOp( " @;\r\n", new DecOp( detailTex ) ) ); - - if ( fd.features.hasFeature( MFT_TerrainSideProject, detailIndex ) ) + if (mIsDirect3D11) { - meta->addStatement( new GenOp(" @ = lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z);\r\n",detailTex,detailMap,inDet,detailMap,inDet,inTex)); - meta->addStatement( new GenOp( " @ = ( @ * 2.0 ) - 1.0;\r\n", detailColor, detailTex) ); + detailMap->setType("SamplerState"); + Var* detailTex = new Var; + detailTex->setName(String::ToString("detailTex%d", detailIndex)); + detailTex->setType("Texture2D"); + detailTex->uniform = true; + detailTex->texture = true; + detailTex->constNum = detailMap->constNum; + + if (fd.features.hasFeature(MFT_TerrainSideProject, detailIndex)) + { + + meta->addStatement(new GenOp(" @ = ( lerp( @.Sample( @, @.yz ), @.Sample( @, @.xz ), @.z ) * 2.0 ) - 1.0;\r\n", + detailColor, detailTex, detailMap, inDet, detailTex, detailMap, inDet, inTex)); + } + else + { + meta->addStatement(new GenOp(" @ = ( @.Sample( @, @.xy ) * 2.0 ) - 1.0;\r\n", + detailColor, detailTex, detailMap, inDet)); + } } else { - meta->addStatement( new GenOp(" @ = tex2D(@,@.xy);\r\n",detailTex,detailMap,inDet)); - meta->addStatement( new GenOp( " @ = ( @ * 2.0 ) - 1.0;\r\n", - detailColor, detailTex) ); + if (fd.features.hasFeature(MFT_TerrainSideProject, detailIndex)) + { + + meta->addStatement(new GenOp(" @ = ( lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z ) * 2.0 ) - 1.0;\r\n", + detailColor, detailMap, inDet, detailMap, inDet, inTex)); + } + else + { + meta->addStatement(new GenOp(" @ = ( tex2D( @, @.xy ) * 2.0 ) - 1.0;\r\n", + detailColor, detailMap, inDet)); + } } meta->addStatement( new GenOp( " @ *= @.y * @.w;\r\n", detailColor, detailInfo, inDet ) ); - Var *baseColor = (Var*)LangElement::find( "baseColor" ); ShaderFeature::OutputTarget target = ShaderFeature::DefaultTarget; if(fd.features.hasFeature( MFT_DeferredTerrainDetailMap )) @@ -718,8 +803,21 @@ void TerrainMacroMapFeatHLSL::processPix( Vector &componentL layerTex->constNum = Var::getTexUnitNum(); // Read the layer texture to get the samples. - meta->addStatement( new GenOp( " @ = round( tex2D( @, @.xy ) * 255.0f );\r\n", - new DecOp( layerSample ), layerTex, inTex ) ); + if (mIsDirect3D11) + { + layerTex->setType("SamplerState"); + Var *layerTexObj = new Var; + layerTexObj->setType("Texture2D"); + layerTexObj->setName("macroLayerTexObj"); + layerTexObj->uniform = true; + layerTexObj->texture = true; + layerTexObj->constNum = layerTex->constNum; + meta->addStatement(new GenOp(" @ = round( @.Sample( @, @.xy ) * 255.0f );\r\n", + new DecOp(layerSample), layerTexObj, layerTex, inTex)); + } + else + meta->addStatement(new GenOp(" @ = round( tex2D( @, @.xy ) * 255.0f );\r\n", + new DecOp(layerSample), layerTex, inTex)); } Var *layerSize = (Var*)LangElement::find( "layerSize" ); @@ -752,7 +850,6 @@ void TerrainMacroMapFeatHLSL::processPix( Vector &componentL if ( !blendTotal ) { blendTotal = new Var; - //blendTotal->setName( "blendTotal" ); blendTotal->setName( "blendTotal" ); blendTotal->setType( "float" ); meta->addStatement( new GenOp( " @ = 0;\r\n", new DecOp( blendTotal ) ) ); @@ -778,6 +875,20 @@ void TerrainMacroMapFeatHLSL::processPix( Vector &componentL detailMap->sampler = true; detailMap->constNum = Var::getTexUnitNum(); // used as texture unit num here + //Create texture object for directx 11 + Var *detailTex = NULL; + if (mIsDirect3D11) + { + detailMap->setType("SamplerState"); + detailTex = new Var; + detailTex->setName(String::ToString("macroMapTex%d", detailIndex)); + detailTex->setType("Texture2D"); + detailTex->uniform = true; + detailTex->texture = true; + detailTex->constNum = detailMap->constNum; + + } + // If we're using SM 3.0 then take advantage of // dynamic branching to skip layers per-pixel. if ( GFX->getPixelShaderVersion() >= 3.0f ) @@ -792,22 +903,30 @@ void TerrainMacroMapFeatHLSL::processPix( Vector &componentL // We take two color samples and lerp between them for // side projection layers... else a single sample. // - if ( fd.features.hasFeature( MFT_TerrainSideProject, detailIndex ) ) + if (fd.features.hasFeature(MFT_TerrainSideProject, detailIndex)) { - meta->addStatement( new GenOp( " @ = ( lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z ) * 2.0 ) - 1.0;\r\n", - detailColor, detailMap, inDet, detailMap, inDet, inTex ) ); + if (mIsDirect3D11) + { + meta->addStatement(new GenOp(" @ = ( lerp( @.Sample( @, @.yz ), @.Sample( @, @.xz ), @.z ) * 2.0 ) - 1.0;\r\n", + detailColor, detailTex, detailMap, inDet, detailTex, detailMap, inDet, inTex)); + } + else + meta->addStatement(new GenOp(" @ = ( lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z ) * 2.0 ) - 1.0;\r\n", + detailColor, detailMap, inDet, detailMap, inDet, inTex)); } else { - meta->addStatement( new GenOp( " @ = ( tex2D( @, @.xy ) * 2.0 ) - 1.0;\r\n", - detailColor, detailMap, inDet ) ); + if (mIsDirect3D11) + meta->addStatement(new GenOp(" @ = ( @.Sample( @, @.xy ) * 2.0 ) - 1.0;\r\n", + detailColor, detailTex, detailMap, inDet)); + else + meta->addStatement(new GenOp(" @ = ( tex2D( @, @.xy ) * 2.0 ) - 1.0;\r\n", + detailColor, detailMap, inDet)); } meta->addStatement( new GenOp( " @ *= @.y * @.w;\r\n", detailColor, detailInfo, inDet ) ); - Var *baseColor = (Var*)LangElement::find( "baseColor" ); - ShaderFeature::OutputTarget target = ShaderFeature::DefaultTarget; if(fd.features.hasFeature(MFT_DeferredTerrainMacroMap)) @@ -907,13 +1026,39 @@ void TerrainNormalMapFeatHLSL::processPix( Vector &component // We take two normal samples and lerp between them for // side projection layers... else a single sample. LangElement *texOp; - if ( fd.features.hasFeature( MFT_TerrainSideProject, normalIndex ) ) + if (mIsDirect3D11) { - texOp = new GenOp( "lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z )", - normalMap, inDet, normalMap, inDet, inTex ); + String name(String::ToString("normalMapTex%d", getProcessIndex())); + Var *normalMapTex = (Var*)LangElement::find(name); + if (!normalMapTex) + { + normalMapTex = new Var; + normalMapTex->setName(String::ToString("normalMapTex%d", getProcessIndex())); + normalMapTex->setType("Texture2D"); + normalMapTex->uniform = true; + normalMapTex->texture = true; + normalMapTex->constNum = normalMap->constNum; + } + if (fd.features.hasFeature(MFT_TerrainSideProject, normalIndex)) + { + texOp = new GenOp("lerp( @.Sample( @, @.yz ), @.Sample( @, @.xz ), @.z )", + normalMapTex, normalMap, inDet, normalMapTex, normalMap, inDet, inTex); + } + else + texOp = new GenOp("@.Sample(@, @.xy)", normalMapTex, normalMap, inDet); + } + else - texOp = new GenOp( "tex2D(@, @.xy)", normalMap, inDet ); + { + if (fd.features.hasFeature(MFT_TerrainSideProject, normalIndex)) + { + texOp = new GenOp("lerp( tex2D( @, @.yz ), tex2D( @, @.xz ), @.z )", + normalMap, inDet, normalMap, inDet, inTex); + } + else + texOp = new GenOp("tex2D(@, @.xy)", normalMap, inDet); + } // create bump normal Var *bumpNorm = new Var; @@ -991,7 +1136,20 @@ void TerrainLightMapFeatHLSL::processPix( Vector &componentLis meta->addStatement( new GenOp( " @ = 1;\r\n", new DecOp( lightMask ) ) ); } - meta->addStatement( new GenOp( " @[0] = tex2D( @, @.xy ).r;\r\n", lightMask, lightMap, inTex ) ); + if (mIsDirect3D11) + { + lightMap->setType("SamplerState"); + Var* lightMapTex = new Var; + lightMapTex->setName("lightMapTexObj"); + lightMapTex->setType("Texture2D"); + lightMapTex->uniform = true; + lightMapTex->texture = true; + lightMapTex->constNum = lightMap->constNum; + meta->addStatement(new GenOp(" @[0] = @.Sample( @, @.xy ).r;\r\n", lightMask, lightMapTex, lightMap, inTex)); + } + else + meta->addStatement(new GenOp(" @[0] = tex2D( @, @.xy ).r;\r\n", lightMask, lightMap, inTex)); + output = meta; } diff --git a/Engine/source/terrain/terrRender.cpp b/Engine/source/terrain/terrRender.cpp index 14280e067..4883d9600 100644 --- a/Engine/source/terrain/terrRender.cpp +++ b/Engine/source/terrain/terrRender.cpp @@ -208,14 +208,14 @@ void TerrainBlock::_updateBaseTexture(bool writeToCache) F32 copyOffsetY = 2.0f * GFX->getFillConventionOffset() / (F32)destSize.y; GFXVertexPT points[4]; - points[0].point = Point3F( -1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 ); - points[0].texCoord = Point2F( 0.0, 1.0f ); - points[1].point = Point3F( -1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 ); - points[1].texCoord = Point2F( 0.0, 0.0f ); - points[2].point = Point3F( 1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0 ); - points[2].texCoord = Point2F( 1.0, 0.0f ); - points[3].point = Point3F( 1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0 ); - points[3].texCoord = Point2F( 1.0, 1.0f ); + points[0].point = Point3F(1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0); + points[0].texCoord = Point2F(1.0, 1.0f); + points[1].point = Point3F(1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0); + points[1].texCoord = Point2F(1.0, 0.0f); + points[2].point = Point3F(-1.0 - copyOffsetX, -1.0 + copyOffsetY, 0.0); + points[2].texCoord = Point2F(0.0, 1.0f); + points[3].point = Point3F(-1.0 - copyOffsetX, 1.0 + copyOffsetY, 0.0); + points[3].texCoord = Point2F(0.0, 0.0f); vb.set( GFX, 4, GFXBufferTypeVolatile ); GFXVertexPT *ptr = vb.lock(); @@ -274,7 +274,7 @@ void TerrainBlock::_updateBaseTexture(bool writeToCache) mBaseShaderConsts->setSafe( mBaseTexScaleConst, Point2F( scale, -scale ) ); mBaseShaderConsts->setSafe( mBaseTexIdConst, (F32)i ); - GFX->drawPrimitive( GFXTriangleFan, 0, 2 ); + GFX->drawPrimitive( GFXTriangleStrip, 0, 2 ); } mBaseTarget->resolve(); diff --git a/Engine/source/ts/tsMesh.cpp b/Engine/source/ts/tsMesh.cpp index 72ee74461..47a60124d 100644 --- a/Engine/source/ts/tsMesh.cpp +++ b/Engine/source/ts/tsMesh.cpp @@ -57,7 +57,7 @@ # include "platformXbox/platformXbox.h" #endif -GFXPrimitiveType drawTypes[] = { GFXTriangleList, GFXTriangleStrip, GFXTriangleFan }; +GFXPrimitiveType drawTypes[] = { GFXTriangleList, GFXTriangleStrip }; #define getDrawType(a) (drawTypes[a]) @@ -2442,7 +2442,6 @@ void TSMesh::_createVBIB( TSVertexBufferHandle &vb, GFXPrimitiveBufferHandle &pb break; case GFXTriangleStrip: - case GFXTriangleFan: pInfo.type = drawType; pInfo.numPrimitives = draw.numElements - 2; pInfo.startIndex = draw.start; @@ -3006,17 +3005,6 @@ void TSMesh::createTangents(const Vector &_verts, const Vector } break; } - case GFXTriangleFan: - { - p1Index = baseIdx[0]; - p2Index = baseIdx[1]; - for( U32 j = 2; j < numElements; j++ ) - { - findTangent( p1Index, p2Index, baseIdx[j], tan0.address(), tan1, _verts ); - p2Index = baseIdx[j]; - } - break; - } default: AssertFatal( false, "TSMesh::createTangents: unknown primitive type!" ); diff --git a/Engine/source/windowManager/win32/win32Window.cpp b/Engine/source/windowManager/win32/win32Window.cpp index c714586b9..7d287cebd 100644 --- a/Engine/source/windowManager/win32/win32Window.cpp +++ b/Engine/source/windowManager/win32/win32Window.cpp @@ -805,6 +805,8 @@ LRESULT PASCAL Win32Window::WindowProc( HWND hWnd, UINT message, WPARAM wParam, Con::warnf("Win32Window::WindowProc - resetting device due to window size change."); window->getGFXTarget()->resetMode(); } + + window->getScreenResChangeSignal().trigger(window, true); } return 0; From bd60f3be1a6038a396cc4f109a5f8d780e0d4d5e Mon Sep 17 00:00:00 2001 From: rextimmy Date: Sun, 20 Mar 2016 21:55:40 +1000 Subject: [PATCH 4/5] Direct3D11 CMake and Project Generator files. --- Tools/CMake/torque3d.cmake | 9 +++++-- Tools/projectGenerator/modules/d3d11.inc | 33 ++++++++++++++++++++++++ projects.xml | 1 + 3 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 Tools/projectGenerator/modules/d3d11.inc diff --git a/Tools/CMake/torque3d.cmake b/Tools/CMake/torque3d.cmake index 83cf63623..7581a6dbb 100644 --- a/Tools/CMake/torque3d.cmake +++ b/Tools/CMake/torque3d.cmake @@ -83,6 +83,10 @@ else() option(TORQUE_DEDICATED "Torque dedicated" OFF) endif() +if(WIN32) + option(TORQUE_D3D11 "Allow Direct3D 11 render" OFF) +endif() + ############################################################################### # options ############################################################################### @@ -391,8 +395,9 @@ if(WIN32) addPath("${srcDir}/platformWin32/videoInfo") addPath("${srcDir}/platformWin32/minidump") addPath("${srcDir}/windowManager/win32") - #addPath("${srcDir}/gfx/D3D8") - addPath("${srcDir}/gfx/D3D") + if(TORQUE_D3D11) + addPath("${srcDir}/gfx/D3D11") + endif() addPath("${srcDir}/gfx/D3D9") addPath("${srcDir}/gfx/D3D9/pc") addPath("${srcDir}/shaderGen/HLSL") diff --git a/Tools/projectGenerator/modules/d3d11.inc b/Tools/projectGenerator/modules/d3d11.inc new file mode 100644 index 000000000..1bfae5092 --- /dev/null +++ b/Tools/projectGenerator/modules/d3d11.inc @@ -0,0 +1,33 @@ + diff --git a/projects.xml b/projects.xml index 18ace6299..1fb3d2fd2 100644 --- a/projects.xml +++ b/projects.xml @@ -29,6 +29,7 @@ Here are some examples: OpenGL Rendering + Direct3D 11 Rendering FMod Sound Engine Leap Motion Controller Razer Hydra Controller From 12621f876b42683c6ef46a62a6b3cfc79fd278a4 Mon Sep 17 00:00:00 2001 From: rextimmy Date: Mon, 28 Mar 2016 10:05:16 +1000 Subject: [PATCH 5/5] Added GFXFormatR8G8B8A8_SRGB format. --- Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp | 1 + Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp | 1 + Engine/source/gfx/gfxEnums.h | 3 +++ Engine/source/gfx/gl/gfxGLEnumTranslate.cpp | 2 ++ 4 files changed, 7 insertions(+) diff --git a/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp b/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp index 24f195247..54c43fa38 100644 --- a/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp +++ b/Engine/source/gfx/D3D11/gfxD3D11EnumTranslate.cpp @@ -72,6 +72,7 @@ void GFXD3D11EnumTranslate::init() GFXD3D11TextureFormat[GFXFormatD24S8] = DXGI_FORMAT_D24_UNORM_S8_UINT; GFXD3D11TextureFormat[GFXFormatD24FS8] = DXGI_FORMAT_UNKNOWN; GFXD3D11TextureFormat[GFXFormatD16] = DXGI_FORMAT_D16_UNORM; + GFXD3D11TextureFormat[GFXFormatR8G8B8A8_SRGB] = DXGI_FORMAT_B8G8R8A8_UNORM_SRGB; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ GFXD3D11TextureFilter[GFXTextureFilterNone] = D3D11_FILTER_MIN_MAG_MIP_POINT; diff --git a/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp b/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp index 77ea67041..93bc86ee9 100644 --- a/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp +++ b/Engine/source/gfx/D3D9/pc/gfxD3D9EnumTranslate.pc.cpp @@ -114,6 +114,7 @@ void GFXD3D9EnumTranslate::init() GFXD3D9TextureFormat[GFXFormatD24S8] = D3DFMT_D24S8; GFXD3D9TextureFormat[GFXFormatD24FS8] = D3DFMT_D24FS8; GFXD3D9TextureFormat[GFXFormatD16] = D3DFMT_D16; + GFXD3D9TextureFormat[GFXFormatR8G8B8A8_SRGB] = D3DFMT_UNKNOWN; VALIDATE_LOOKUPTABLE( GFXD3D9TextureFormat, GFXFormat); //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ diff --git a/Engine/source/gfx/gfxEnums.h b/Engine/source/gfx/gfxEnums.h index 0e3878154..238af2f94 100644 --- a/Engine/source/gfx/gfxEnums.h +++ b/Engine/source/gfx/gfxEnums.h @@ -205,6 +205,9 @@ enum GFXFormat GFXFormatDXT4, GFXFormatDXT5, + // sRGB formats + GFXFormatR8G8B8A8_SRGB, + GFXFormat_COUNT, GFXFormat_8BIT = GFXFormatA8, diff --git a/Engine/source/gfx/gl/gfxGLEnumTranslate.cpp b/Engine/source/gfx/gl/gfxGLEnumTranslate.cpp index 7955590e1..c5af360bd 100644 --- a/Engine/source/gfx/gl/gfxGLEnumTranslate.cpp +++ b/Engine/source/gfx/gl/gfxGLEnumTranslate.cpp @@ -190,6 +190,8 @@ void GFXGLEnumTranslate::init() GFXGLTextureType[GFXFormatDXT4] = GL_ZERO; GFXGLTextureType[GFXFormatDXT5] = GL_UNSIGNED_BYTE; + GFXGLTextureType[GFXFormatR8G8B8A8_SRGB] = GL_SRGB8_ALPHA8; + static GLint Swizzle_GFXFormatA8[] = { GL_NONE, GL_NONE, GL_NONE, GL_RED }; static GLint Swizzle_GFXFormatL[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; GFXGLTextureSwizzle[GFXFormatA8] = Swizzle_GFXFormatA8; // old GL_ALPHA8