diff --git a/Engine/source/T3D/lighting/IBLUtilities.cpp b/Engine/source/T3D/lighting/IBLUtilities.cpp index 73d3c1580..b66838778 100644 --- a/Engine/source/T3D/lighting/IBLUtilities.cpp +++ b/Engine/source/T3D/lighting/IBLUtilities.cpp @@ -1,3 +1,26 @@ +//----------------------------------------------------------------------------- +// 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 "T3D/lighting/IBLUtilities.h" #include "console/engineAPI.h" #include "materials/shaderData.h" #include "gfx/gfxTextureManager.h" @@ -167,62 +190,7 @@ namespace IBLUtilities { Con::errorf("IBLUtilities::GenerateAndSavePrefilterMap - Failed to properly save out the baked irradiance!"); } - } - - void GenerateBRDFTexture(GFXTexHandle &textureOut) - { - GFXTransformSaver saver; - - ShaderData *brdfShaderData; - GFXShaderRef brdfShader = Sim::findObject("BRDFLookupShader", brdfShaderData) ? brdfShaderData->getShader() : NULL; - if (!brdfShader) - { - Con::errorf("IBLUtilities::GenerateBRDFTexture() - could not find BRDFLookupShader"); - return; - } - - U32 textureSize = textureOut->getWidth(); - - GFXTextureTargetRef renderTarget = GFX->allocRenderToTextureTarget(); - GFX->pushActiveRenderTarget(); - - GFX->setShader(brdfShader); - renderTarget->attachTexture(GFXTextureTarget::Color0, textureOut); - GFX->setActiveRenderTarget(renderTarget);//potential bug here with the viewport not updating with the new size - GFX->setViewport(RectI(0, 0, textureSize, textureSize));//see above comment - GFX->clear(GFXClearTarget, LinearColorF::BLUE, 1.0f, 0); - GFX->drawPrimitive(GFXTriangleList, 0, 3); - renderTarget->resolve(); - - GFX->popActiveRenderTarget(); - } - - GFXTexHandle GenerateAndSaveBRDFTexture(String outputPath, S32 resolution) - { - GFXTexHandle brdfTexture = TEXMGR->createTexture(resolution, resolution, GFXFormatR8G8B8A8, &GFXRenderTargetProfile, 1, 0); - GenerateBRDFTexture(brdfTexture); - - FileStream fs; - if (fs.open(outputPath, Torque::FS::File::Write)) - { - // Read back the render target, dxt compress it, and write it to disk. - GBitmap brdfBmp(brdfTexture.getHeight(), brdfTexture.getWidth(), false, GFXFormatR8G8B8A8); - brdfTexture.copyToBmp(&brdfBmp); - - brdfBmp.extrudeMipLevels(); - - DDSFile *brdfDDS = DDSFile::createDDSFileFromGBitmap(&brdfBmp); - ImageUtil::ddsCompress(brdfDDS, GFXFormatBC1); - - // Write result to file stream - brdfDDS->write(fs); - - delete brdfDDS; - } - fs.close(); - - return brdfTexture; - } + } void bakeReflection(String outputPath, S32 resolution) { @@ -662,9 +630,3 @@ namespace IBLUtilities return angle; } }; - -DefineEngineFunction(GenerateBRDFTexture, bool, (String outputPath, S32 resolution), ("", 256), - "@brief returns true if control object is inside the fog\n\n.") -{ - return IBLUtilities::GenerateAndSaveBRDFTexture(outputPath, resolution); -} \ No newline at end of file diff --git a/Engine/source/T3D/lighting/IBLUtilities.h b/Engine/source/T3D/lighting/IBLUtilities.h index 1bb6fd531..f8e171dd8 100644 --- a/Engine/source/T3D/lighting/IBLUtilities.h +++ b/Engine/source/T3D/lighting/IBLUtilities.h @@ -1,4 +1,40 @@ -#pragma once +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- + +#ifndef IBL_UTILS_H_ +#define IBL_UTILS_H_ + +#ifndef _GFXTARGET_H_ +#include "gfx/gfxTarget.h" +#endif + +#ifndef _GFXCUBEMAP_H_ +#include "gfx/gfxCubemap.h" +#endif + +#ifndef _COLOR_H_ +#include "core/color.h" +#endif + namespace IBLUtilities { @@ -10,9 +46,6 @@ namespace IBLUtilities void SaveCubeMap(String outputPath, GFXCubemapHandle &cubemap); - GFXTexHandle GenerateAndSaveBRDFTexture(String outputPath, S32 resolution); - void GenerateBRDFTexture(GFXTexHandle &textureOut); - void bakeReflection(String outputPath, S32 resolution); LinearColorF decodeSH(Point3F normal, const LinearColorF SHTerms[9], const F32 SHConstants[5]); @@ -32,4 +65,6 @@ namespace IBLUtilities F32 texelSolidAngle(F32 aU, F32 aV, U32 width, U32 height); F32 areaElement(F32 x, F32 y); -}; \ No newline at end of file +}; + +#endif \ No newline at end of file diff --git a/Engine/source/T3D/lighting/reflectionProbe.cpp b/Engine/source/T3D/lighting/reflectionProbe.cpp index b5941c427..30379eaf2 100644 --- a/Engine/source/T3D/lighting/reflectionProbe.cpp +++ b/Engine/source/T3D/lighting/reflectionProbe.cpp @@ -36,7 +36,6 @@ #include "core/fileObject.h" #include "core/resourceManager.h" #include "console/simPersistId.h" -#include #include "T3D/gameFunctions.h" #include "postFx/postEffect.h" #include "renderInstance/renderProbeMgr.h" @@ -620,16 +619,13 @@ bool ReflectionProbe::createClientResources() Con::errorf("ReflectionProbe::createClientResources() - Unable to load baked prefilter map at %s", getPrefilterMapPath().c_str()); } - //brdf lookup resources - //make the brdf lookup texture the same size as the prefilter texture - + //brdf lookup texture String brdfPath = Con::getVariable("$Core::BRDFTexture", "core/art/pbr/brdfTexture.dds"); - mBrdfTexture = TEXMGR->createTexture(brdfPath, &GFXTexturePersistentProfile); if (!mBrdfTexture) { - mBrdfTexture = IBLUtilities::GenerateAndSaveBRDFTexture(brdfPath, 512); + return false; } mResourcesCreated = true; @@ -652,8 +648,8 @@ void ReflectionProbe::prepRenderImage(SceneRenderState *state) //Culling distance. Can be adjusted for performance options considerations via the scalar if (dist > mMaxDrawDistance * Con::getFloatVariable("$pref::GI::ProbeDrawDistScale", 1.0)) { - mProbeInfo->mScore = mMaxDrawDistance; - return; + mProbeInfo->mScore = mMaxDrawDistance; + return; } if (mReflectionModeType == DynamicCubemap && mRefreshRateMS < (Platform::getRealMilliseconds() - mDynamicLastBakeMS)) @@ -685,7 +681,7 @@ void ReflectionProbe::prepRenderImage(SceneRenderState *state) Point3F cameraOffset; getRenderTransform().getColumn(3, &cameraOffset); cameraOffset -= state->getDiffuseCameraPosition(); - F32 dist = cameraOffset.len(); + dist = cameraOffset.len(); if (dist < 0.01f) dist = 0.01f; @@ -832,7 +828,7 @@ String ReflectionProbe::getPrefilterMapPath() } char fileName[256]; - dSprintf(fileName, 256, "%s%s_Prefilter.DDS", mReflectionPath.c_str(), mProbeUniqueID.c_str()); + dSprintf(fileName, 256, "%s%s_Prefilter.dds", mReflectionPath.c_str(), mProbeUniqueID.c_str()); return fileName; } @@ -846,7 +842,7 @@ String ReflectionProbe::getIrradianceMapPath() } char fileName[256]; - dSprintf(fileName, 256, "%s%s_Irradiance.DDS", mReflectionPath.c_str(), mProbeUniqueID.c_str()); + dSprintf(fileName, 256, "%s%s_Irradiance.dds", mReflectionPath.c_str(), mProbeUniqueID.c_str()); return fileName; } diff --git a/Engine/source/T3D/lighting/skylight.cpp b/Engine/source/T3D/lighting/skylight.cpp index 87823b904..d4705edcb 100644 --- a/Engine/source/T3D/lighting/skylight.cpp +++ b/Engine/source/T3D/lighting/skylight.cpp @@ -36,7 +36,6 @@ #include "core/fileObject.h" #include "core/resourceManager.h" #include "console/simPersistId.h" -#include #include "T3D/gameFunctions.h" #include "postFx/postEffect.h" #include "renderInstance/renderProbeMgr.h" @@ -183,9 +182,6 @@ void Skylight::prepRenderImage(SceneRenderState *state) if (!mEnabled || !Skylight::smRenderSkylights) return; - Point3F distVec = getPosition() - state->getCameraPosition(); - F32 dist = distVec.len(); - //special hook-in for skylights Point3F camPos = state->getCameraPosition(); mProbeInfo->mBounds.setCenter(camPos); diff --git a/Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp b/Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp index e1f667926..38a812228 100644 --- a/Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp +++ b/Engine/source/gfx/D3D11/gfxD3D11Cubemap.cpp @@ -177,7 +177,7 @@ void GFXD3D11Cubemap::initStatic(DDSFile *dds) continue; // convert to Z up - const U32 faceIndex = _zUpFaceIndex(currentFace); + const U32 faceIndex = zUpFaceIndex(currentFace); for(U32 currentMip = 0; currentMip < mMipMapLevels; currentMip++) { diff --git a/Engine/source/gfx/D3D11/gfxD3D11Device.cpp b/Engine/source/gfx/D3D11/gfxD3D11Device.cpp index 5f583450e..5144eba4b 100644 --- a/Engine/source/gfx/D3D11/gfxD3D11Device.cpp +++ b/Engine/source/gfx/D3D11/gfxD3D11Device.cpp @@ -909,6 +909,25 @@ void GFXD3D11Device::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer) //----------------------------------------------------------------------------- +void GFXD3D11Device::copyResource(GFXTextureObject *pDst, GFXCubemap *pSrc, const U32 face) +{ + AssertFatal(pDst, "GFXD3D11Device::copyResource: Destination texture is null"); + AssertFatal(pSrc, "GFXD3D11Device::copyResource: Source cubemap is null"); + + GFXD3D11TextureObject *pD3DDst = static_cast(pDst); + GFXD3D11Cubemap *pD3DSrc = static_cast(pSrc); + + const U32 mipLevels = pD3DSrc->getMipMapLevels(); + for (U32 mip = 0; mip < mipLevels; mip++) + { + const U32 srcSubResource = D3D11CalcSubresource(mip, face, mipLevels); + const U32 dstSubResource = D3D11CalcSubresource(mip, 0, mipLevels); + mD3DDeviceContext->CopySubresourceRegion(pD3DDst->get2DTex(), dstSubResource, 0, 0, 0, pD3DSrc->get2DTex(), srcSubResource, NULL); + } +} + +//----------------------------------------------------------------------------- + void GFXD3D11Device::clear(U32 flags, const LinearColorF& color, F32 z, U32 stencil) { // Make sure we have flushed our render target state. diff --git a/Engine/source/gfx/D3D11/gfxD3D11Device.h b/Engine/source/gfx/D3D11/gfxD3D11Device.h index 3f34d2259..65d69e0cf 100644 --- a/Engine/source/gfx/D3D11/gfxD3D11Device.h +++ b/Engine/source/gfx/D3D11/gfxD3D11Device.h @@ -239,6 +239,11 @@ public: virtual U32 getNumRenderTargets() const { return 8; } // } + // Copy methods + // { + virtual void copyResource(GFXTextureObject *pDst, GFXCubemap *pSrc, const U32 face); + // } + // Misc rendering control // { virtual void clear( U32 flags, const LinearColorF& color, F32 z, U32 stencil ); diff --git a/Engine/source/gfx/D3D11/gfxD3D11TextureObject.cpp b/Engine/source/gfx/D3D11/gfxD3D11TextureObject.cpp index d827b7a17..f44c57081 100644 --- a/Engine/source/gfx/D3D11/gfxD3D11TextureObject.cpp +++ b/Engine/source/gfx/D3D11/gfxD3D11TextureObject.cpp @@ -185,8 +185,7 @@ bool GFXD3D11TextureObject::copyToBmp(GBitmap* bmp) AssertFatal(bmp->getWidth() == getWidth(), "GFXD3D11TextureObject::copyToBmp - source/dest width does not match"); AssertFatal(bmp->getHeight() == getHeight(), "GFXD3D11TextureObject::copyToBmp - source/dest height does not match"); - const U32 width = getWidth(); - const U32 height = getHeight(); + const U32 mipLevels = getMipLevels(); bmp->setHasTransparency(mHasTransparency); @@ -221,52 +220,58 @@ bool GFXD3D11TextureObject::copyToBmp(GBitmap* bmp) //copy the classes texture to the staging texture D3D11DEVICECONTEXT->CopyResource(pStagingTexture, mD3DTexture); - //map the staging resource - D3D11_MAPPED_SUBRESOURCE mappedRes; - hr = D3D11DEVICECONTEXT->Map(pStagingTexture, 0, D3D11_MAP_READ, 0, &mappedRes); - if (FAILED(hr)) + for (U32 mip = 0; mip < mipLevels; mip++) { - //cleanup - SAFE_RELEASE(pStagingTexture); - Con::errorf("GFXD3D11TextureObject::copyToBmp - Failed to map staging texture"); - return false; - } - - // set pointers - const U8* srcPtr = (U8*)mappedRes.pData; - U8* destPtr = bmp->getWritableBits(); - - // we will want to skip over any D3D cache data in the source texture - const S32 sourceCacheSize = mappedRes.RowPitch - width * sourceBytesPerPixel; - AssertFatal(sourceCacheSize >= 0, "GFXD3D11TextureObject::copyToBmp - cache size is less than zero?"); - - // copy data into bitmap - for (U32 row = 0; row < height; ++row) - { - for (U32 col = 0; col < width; ++col) + const U32 width = bmp->getWidth(mip); + const U32 height = bmp->getHeight(mip); + //map the staging resource + D3D11_MAPPED_SUBRESOURCE mappedRes; + const U32 subResource = D3D11CalcSubresource(mip, 0, mipLevels); + hr = D3D11DEVICECONTEXT->Map(pStagingTexture, subResource, D3D11_MAP_READ, 0, &mappedRes); + if (FAILED(hr)) { - 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; + //cleanup + SAFE_RELEASE(pStagingTexture); + Con::errorf("GFXD3D11TextureObject::copyToBmp - Failed to map staging texture"); + return false; } - // skip past the cache data for this row (if any) - srcPtr += sourceCacheSize; + + // set pointers + const U8* srcPtr = (U8*)mappedRes.pData; + U8* destPtr = bmp->getWritableBits(mip); + + // we will want to skip over any D3D cache data in the source texture + const S32 sourceCacheSize = mappedRes.RowPitch - width * sourceBytesPerPixel; + AssertFatal(sourceCacheSize >= 0, "GFXD3D11TextureObject::copyToBmp - cache size is less than zero?"); + + // 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; + } + + // assert if we stomped or underran memory + AssertFatal(U32(destPtr - bmp->getWritableBits(mip)) == width * height * destBytesPerPixel, "GFXD3D11TextureObject::copyToBmp - memory error"); + AssertFatal(U32(srcPtr - (U8*)mappedRes.pData) == height * mappedRes.RowPitch, "GFXD3D11TextureObject::copyToBmp - memory error"); + + D3D11DEVICECONTEXT->Unmap(pStagingTexture, subResource); } - // assert if we stomped or underran memory - AssertFatal(U32(destPtr - bmp->getWritableBits()) == width * height * destBytesPerPixel, "GFXD3D11TextureObject::copyToBmp - memory error"); - AssertFatal(U32(srcPtr - (U8*)mappedRes.pData) == height * mappedRes.RowPitch, "GFXD3D11TextureObject::copyToBmp - memory error"); - - D3D11DEVICECONTEXT->Unmap(pStagingTexture, 0); - SAFE_RELEASE(pStagingTexture); PROFILE_END(); diff --git a/Engine/source/gfx/Null/gfxNullDevice.h b/Engine/source/gfx/Null/gfxNullDevice.h index 672e86bbd..a2ebe6c23 100644 --- a/Engine/source/gfx/Null/gfxNullDevice.h +++ b/Engine/source/gfx/Null/gfxNullDevice.h @@ -150,7 +150,7 @@ public: virtual GFXShader* createShader() { return NULL; }; - + virtual void copyResource(GFXTextureObject *pDst, GFXCubemap *pSrc, const U32 face) { }; virtual void clear( U32 flags, const LinearColorF& color, F32 z, U32 stencil ) { }; virtual void clearColorAttachment(const U32 attachment, const LinearColorF& color) { }; virtual bool beginSceneInternal() { return true; }; diff --git a/Engine/source/gfx/bitmap/cubemapSaver.cpp b/Engine/source/gfx/bitmap/cubemapSaver.cpp index 541e9c8bf..ae9d09b56 100644 --- a/Engine/source/gfx/bitmap/cubemapSaver.cpp +++ b/Engine/source/gfx/bitmap/cubemapSaver.cpp @@ -32,29 +32,10 @@ #include "math/mathUtils.h" #include "math/mTransform.h" - namespace CubemapSaver { const U32 CubeFaces = 6; - void _setConstBuffer(GFXShaderConstHandle* handle, GFXShaderConstBuffer *cbuf, const VectorF &vLookatPt, const VectorF &vUpVec) - { - VectorF cross = mCross(vUpVec, vLookatPt); - cross.normalizeSafe(); - - MatrixF matView(true); - matView.setColumn(0, cross); - matView.setColumn(1, vLookatPt); - matView.setColumn(2, vUpVec); - matView.setPosition(VectorF(0.0f, 0.0f, 1.0f)); - matView.inverse(); - - if (handle->isValid()) - cbuf->set(handle, matView); - else - Con::errorf("CubemapSaver: Failed to set a shader constant handle."); - } - bool save(GFXCubemapHandle cubemap, const Torque::Path &path, GFXFormat compressionFormat) { if (!cubemap.isValid()) @@ -63,93 +44,40 @@ namespace CubemapSaver return false; } - // This can sometimes occur outside a begin/end scene. - const bool sceneBegun = GFX->canCurrentlyRender(); - if (!sceneBegun) - GFX->beginScene(); GFXCubemap *pCubemap = cubemap.getPointer(); - U32 faceSize = pCubemap->getSize(); + const U32 faceSize = pCubemap->getSize(); + const U32 mipLevels = pCubemap->getMipMapLevels(); - ShaderData *shaderData = nullptr; - GFXShaderRef shader = Sim::findObject("CubemapSaveShader", shaderData) ? shaderData->getShader() : nullptr; - if (!shader) - { - Con::errorf("CubemapSaver::save - could not find CubemapSaveShader"); - return false; - } - - GFXShaderConstHandle *matHandles[CubeFaces]; - - matHandles[0] = shader->getShaderConstHandle("$matrix0"); - matHandles[1] = shader->getShaderConstHandle("$matrix1"); - matHandles[2] = shader->getShaderConstHandle("$matrix2"); - matHandles[3] = shader->getShaderConstHandle("$matrix3"); - matHandles[4] = shader->getShaderConstHandle("$matrix4"); - matHandles[5] = shader->getShaderConstHandle("$matrix5"); - - GFXShaderConstBufferRef cbuffer = shader->allocConstBuffer(); - - GFXTextureTarget *pTarget = GFX->allocRenderToTextureTarget(); - GFX->pushActiveRenderTarget(); - - GFXFormat renderTargetFmt = GFXFormatR8G8B8A8; + GFXFormat targetFmt = pCubemap->getFormat(); //setup render targets GFXTexHandle pTextures[CubeFaces]; - for (U32 i = 0; i < CubeFaces; i++) + for (U32 face = 0; face < CubeFaces; face++) { - pTextures[i].set(faceSize, faceSize, renderTargetFmt, - &GFXRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__), - 1, GFXTextureManager::AA_MATCH_BACKBUFFER); + pTextures[face].set(faceSize, faceSize, targetFmt, + &GFXStaticTextureProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__), + mipLevels, GFXTextureManager::AA_MATCH_BACKBUFFER); - pTarget->attachTexture(GFXTextureTarget::RenderSlot(GFXTextureTarget::Color0 + i), pTextures[i]); + // yep t3d has funky z up, need to change the face order + GFX->copyResource(pTextures[face], pCubemap, GFXCubemap::zUpFaceIndex(face) ); } - //create stateblock - GFXStateBlockDesc desc; - desc.setZReadWrite(false, false); - desc.samplersDefined = true; - desc.samplers[0].addressModeU = GFXAddressClamp; - desc.samplers[0].addressModeV = GFXAddressClamp; - desc.samplers[0].addressModeW = GFXAddressClamp; - desc.samplers[0].magFilter = GFXTextureFilterLinear; - desc.samplers[0].minFilter = GFXTextureFilterLinear; - desc.samplers[0].mipFilter = GFXTextureFilterLinear; - - //yep funky order and rotations with t3d z up - _setConstBuffer(matHandles[0], cbuffer, VectorF(0.0f, 1.0f, 0.0f), VectorF(-1.0f, 0.0f, 0.0f)); - _setConstBuffer(matHandles[1], cbuffer, VectorF(0.0f, 1.0f, 0.0f), VectorF(1.0f, 0.0f, 0.0f)); - _setConstBuffer(matHandles[2], cbuffer, VectorF(0.0f, 1.0f, 0.0f), VectorF(0.0f, 0.0f, -1.0f)); - _setConstBuffer(matHandles[3], cbuffer, VectorF(0.0f, 1.0f, 0.0f), VectorF(0.0f, 0.0f, 1.0f)); - _setConstBuffer(matHandles[4], cbuffer, VectorF(0.0f, 0.0f, -1.0f), VectorF(0.0f, -1.0f, 0.0f)); - _setConstBuffer(matHandles[5], cbuffer, VectorF(0.0f, 0.0f, 1.0f), VectorF(0.0f, 1.0f, 0.0f)); - - GFXTransformSaver saver; - GFX->setActiveRenderTarget(pTarget); - GFX->clear(GFXClearTarget, ColorI(0, 0, 0, 0), 1.0f, 0); - GFX->setStateBlockByDesc(desc); - GFX->setWorldMatrix(MatrixF::Identity); - GFX->setProjectionMatrix(MatrixF::Identity); - GFX->setCubeTexture(0, pCubemap); - GFX->setShaderConstBuffer(cbuffer); - GFX->setShader(shader); - GFX->drawPrimitive(GFXTriangleList, 0, 3); - pTarget->resolve(); - GBitmap *pBitmaps[CubeFaces]; bool error = false; const bool compressedFormat = ImageUtil::isCompressedFormat(compressionFormat); + const bool hasMips = mipLevels > 1 ? true : false; for (U32 i = 0; i < CubeFaces; i++) { - pBitmaps[i] = new GBitmap(faceSize, faceSize, false, renderTargetFmt); + pBitmaps[i] = new GBitmap(faceSize, faceSize, hasMips, targetFmt); bool result = pTextures[i].copyToBmp(pBitmaps[i]); if (!result) { Con::errorf("CubemapSaver: cubemap number %u failed to copy", i); error = true; } - //gen mip maps - pBitmaps[i]->extrudeMipLevels(); + //gen mip maps if there are none + if(!hasMips) + pBitmaps[i]->extrudeMipLevels(); } if (!error) @@ -176,20 +104,10 @@ namespace CubemapSaver } } + //cleanup for (U32 i = 0; i < CubeFaces; i++) SAFE_DELETE(pBitmaps[i]); - //cleaup - GFX->popActiveRenderTarget(); - GFX->setTexture(0, NULL); - GFX->setShader(NULL); - GFX->setShaderConstBuffer(NULL); - GFX->setVertexBuffer(NULL); - - // End it if we begun it. - if (!sceneBegun) - GFX->endScene(); - return true; } @@ -202,135 +120,6 @@ namespace CubemapSaver return false; } - // This can sometimes occur outside a begin/end scene. - const bool sceneBegun = GFX->canCurrentlyRender(); - if (!sceneBegun) - GFX->beginScene(); - - GFXCubemap *pCubemap = cubemap.getPointer(); - U32 faceSize = pCubemap->getSize(); - - ShaderData *shaderData = nullptr; - GFXShaderRef shader = Sim::findObject("CubemapSaveShader", shaderData) ? shaderData->getShader() : nullptr; - if (!shader) - { - Con::errorf("CubemapSaver::save - could not find CubemapSaveShader"); - return false; - } - - GFXShaderConstHandle *matHandles[CubeFaces]; - - matHandles[0] = shader->getShaderConstHandle("$matrix0"); - matHandles[1] = shader->getShaderConstHandle("$matrix1"); - matHandles[2] = shader->getShaderConstHandle("$matrix2"); - matHandles[3] = shader->getShaderConstHandle("$matrix3"); - matHandles[4] = shader->getShaderConstHandle("$matrix4"); - matHandles[5] = shader->getShaderConstHandle("$matrix5"); - - GFXShaderConstBufferRef cbuffer = shader->allocConstBuffer(); - - GFXTextureTarget *pTarget = GFX->allocRenderToTextureTarget(); - GFX->pushActiveRenderTarget(); - - GFXFormat renderTargetFmt = GFXFormatR8G8B8A8; - //setup render targets - GFXTexHandle pTextures[CubeFaces]; - for (U32 i = 0; i < CubeFaces; i++) - { - pTextures[i].set(faceSize, faceSize, renderTargetFmt, - &GFXRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__), - 1, GFXTextureManager::AA_MATCH_BACKBUFFER); - - pTarget->attachTexture(GFXTextureTarget::RenderSlot(GFXTextureTarget::Color0 + i), pTextures[i]); - } - - //create stateblock - GFXStateBlockDesc desc; - desc.setZReadWrite(false, false); - desc.samplersDefined = true; - desc.samplers[0].addressModeU = GFXAddressClamp; - desc.samplers[0].addressModeV = GFXAddressClamp; - desc.samplers[0].addressModeW = GFXAddressClamp; - desc.samplers[0].magFilter = GFXTextureFilterLinear; - desc.samplers[0].minFilter = GFXTextureFilterLinear; - desc.samplers[0].mipFilter = GFXTextureFilterLinear; - - //yep funky order and rotations with t3d z up - _setConstBuffer(matHandles[0], cbuffer, VectorF(0.0f, 1.0f, 0.0f), VectorF(-1.0f, 0.0f, 0.0f)); - _setConstBuffer(matHandles[1], cbuffer, VectorF(0.0f, 1.0f, 0.0f), VectorF(1.0f, 0.0f, 0.0f)); - _setConstBuffer(matHandles[2], cbuffer, VectorF(0.0f, 1.0f, 0.0f), VectorF(0.0f, 0.0f, -1.0f)); - _setConstBuffer(matHandles[3], cbuffer, VectorF(0.0f, 1.0f, 0.0f), VectorF(0.0f, 0.0f, 1.0f)); - _setConstBuffer(matHandles[4], cbuffer, VectorF(0.0f, 0.0f, -1.0f), VectorF(0.0f, -1.0f, 0.0f)); - _setConstBuffer(matHandles[5], cbuffer, VectorF(0.0f, 0.0f, 1.0f), VectorF(0.0f, 1.0f, 0.0f)); - - GFXTransformSaver saver; - GFX->setActiveRenderTarget(pTarget); - GFX->clear(GFXClearTarget, ColorI(0, 0, 0, 0), 1.0f, 0); - GFX->setStateBlockByDesc(desc); - GFX->setWorldMatrix(MatrixF::Identity); - GFX->setProjectionMatrix(MatrixF::Identity); - GFX->setCubeTexture(0, pCubemap); - GFX->setShaderConstBuffer(cbuffer); - GFX->setShader(shader); - GFX->drawPrimitive(GFXTriangleList, 0, 3); - pTarget->resolve(); - - bool error = false; - const bool compressedFormat = ImageUtil::isCompressedFormat(compressionFormat); - for (U32 i = 0; i < CubeFaces; i++) - { - //faceBitmaps[i] = new GBitmap(faceSize, faceSize, false, renderTargetFmt); - bool result = pTextures[i].copyToBmp(faceBitmaps[i]); - if (!result) - { - Con::errorf("CubemapSaver: cubemap number %u failed to copy", i); - error = true; - } - //gen mip maps - faceBitmaps[i]->extrudeMipLevels(); - } - - /*if (!error) - { - DDSFile *pDds = DDSFile::createDDSCubemapFileFromGBitmaps(pBitmaps); - if (pDds) - { - // non compressed format needs swizzling - if (!compressedFormat) - ImageUtil::swizzleDDS(pDds, Swizzles::bgra); - - if (compressedFormat) - ImageUtil::ddsCompress(pDds, compressionFormat); - - FileStream stream; - stream.open(path, Torque::FS::File::Write); - - if (stream.getStatus() == Stream::Ok) - pDds->write(stream); - else - Con::errorf("CubemapSaver: failed to open file stream for file %s", path.getFullPath().c_str()); - - SAFE_DELETE(pDds); - } - } - - for (U32 i = 0; i < CubeFaces; i++) - SAFE_DELETE(pBitmaps[i]);*/ - - //cleaup - GFX->popActiveRenderTarget(); - GFX->setTexture(0, NULL); - GFX->setShader(NULL); - GFX->setShaderConstBuffer(NULL); - GFX->setVertexBuffer(NULL); - - // End it if we begun it. - if (!sceneBegun) - GFX->endScene(); - - if (error) - return false; - - return true; + return false; } } diff --git a/Engine/source/gfx/gfxCubemap.cpp b/Engine/source/gfx/gfxCubemap.cpp index 9a556663f..8ca38899d 100644 --- a/Engine/source/gfx/gfxCubemap.cpp +++ b/Engine/source/gfx/gfxCubemap.cpp @@ -35,7 +35,7 @@ GFXCubemap::~GFXCubemap() TEXMGR->releaseCubemap( this ); } -U32 GFXCubemap::_zUpFaceIndex(const U32 index) +U32 GFXCubemap::zUpFaceIndex(const U32 index) { switch (index) { diff --git a/Engine/source/gfx/gfxCubemap.h b/Engine/source/gfx/gfxCubemap.h index ed175e73e..95ead55b5 100644 --- a/Engine/source/gfx/gfxCubemap.h +++ b/Engine/source/gfx/gfxCubemap.h @@ -47,8 +47,6 @@ protected: /// Sets the cubemap file path. void _setPath( const String &path ) { mPath = path; } - /// Get Z up face index of the cubemap. DDS files will be stored Y up - U32 _zUpFaceIndex(const U32 index); U32 mMipMapLevels; public: @@ -81,6 +79,9 @@ public: /// Get the number of mip maps const U32 getMipMapLevels() const { return mMipMapLevels; } + + /// Get Z up face index of the cubemap. DDS files will be stored Y up + static U32 zUpFaceIndex(const U32 index); }; diff --git a/Engine/source/gfx/gfxDevice.h b/Engine/source/gfx/gfxDevice.h index c893287d0..1cb7a41fc 100644 --- a/Engine/source/gfx/gfxDevice.h +++ b/Engine/source/gfx/gfxDevice.h @@ -826,6 +826,13 @@ public: //----------------------------------------------------------------------------- + /// @name Copying methods + /// @{ + + virtual void copyResource(GFXTextureObject *pDst, GFXCubemap *pSrc, const U32 face) = 0; + + /// @} + /// @name Rendering methods /// @{ diff --git a/Engine/source/gfx/gl/gfxGLCubemap.cpp b/Engine/source/gfx/gl/gfxGLCubemap.cpp index c74d44025..c7b7dd89a 100644 --- a/Engine/source/gfx/gl/gfxGLCubemap.cpp +++ b/Engine/source/gfx/gl/gfxGLCubemap.cpp @@ -165,7 +165,7 @@ void GFXGLCubemap::initStatic( DDSFile *dds ) } // convert to Z up - const U32 faceIndex = _zUpFaceIndex(i); + const U32 faceIndex = zUpFaceIndex(i); // Now loop thru the mip levels! for (U32 mip = 0; mip < mMipMapLevels; ++mip) diff --git a/Engine/source/gfx/gl/gfxGLDevice.h b/Engine/source/gfx/gl/gfxGLDevice.h index 5fdb63c41..29740c1c5 100644 --- a/Engine/source/gfx/gl/gfxGLDevice.h +++ b/Engine/source/gfx/gl/gfxGLDevice.h @@ -116,7 +116,8 @@ public: virtual U32 getNumRenderTargets() const; virtual GFXShader* createShader(); - + //TODO: implement me! + virtual void copyResource(GFXTextureObject *pDst, GFXCubemap *pSrc, const U32 face) {}; virtual void clear( U32 flags, const LinearColorF& color, F32 z, U32 stencil ); virtual void clearColorAttachment(const U32 attachment, const LinearColorF& color); virtual bool beginSceneInternal(); diff --git a/Engine/source/lighting/advanced/advancedLightBinManager.cpp b/Engine/source/lighting/advanced/advancedLightBinManager.cpp index 89443d28c..df96f436f 100644 --- a/Engine/source/lighting/advanced/advancedLightBinManager.cpp +++ b/Engine/source/lighting/advanced/advancedLightBinManager.cpp @@ -286,8 +286,6 @@ void AdvancedLightBinManager::render( SceneRenderState *state ) MatrixSet &matrixSet = getRenderPass()->getMatrixSet(); matrixSet.restoreSceneViewProjection(); - const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera(); - // Set up the SG Data SceneData sgData; sgData.init( state ); @@ -528,17 +526,6 @@ void AdvancedLightBinManager::_setupPerFrameParameters( const SceneRenderState * farPlane, vsFarPlane); } - - MatrixSet &matrixSet = getRenderPass()->getMatrixSet(); - //matrixSet.restoreSceneViewProjection(); - - const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera(); - - MatrixF inverseViewMatrix = worldToCameraXfm; - //inverseViewMatrix.fullInverse(); - //inverseViewMatrix.transpose(); - - //MatrixF inverseViewMatrix = MatrixF::Identity; } void AdvancedLightBinManager::setupSGData( SceneData &data, const SceneRenderState* state, LightInfo *light ) @@ -623,10 +610,9 @@ AdvancedLightBinManager::LightMaterialInfo::LightMaterialInfo( const String &mat lightPosition(NULL), lightDirection(NULL), lightColor(NULL), - lightAttenuation(NULL), - lightRange(NULL), - lightAmbient(NULL), - lightTrilight(NULL), + lightRange(NULL), + lightInvSqrRange(NULL), + lightAmbient(NULL), lightSpotParams(NULL) { Material *mat = MATMGR->getMaterialDefinitionByName( matName ); @@ -642,10 +628,9 @@ AdvancedLightBinManager::LightMaterialInfo::LightMaterialInfo( const String &mat lightDirection = matInstance->getMaterialParameterHandle("$lightDirection"); lightAmbient = matInstance->getMaterialParameterHandle("$lightAmbient"); - lightTrilight = matInstance->getMaterialParameterHandle("$lightTrilight"); lightSpotParams = matInstance->getMaterialParameterHandle("$lightSpotParams"); - lightAttenuation = matInstance->getMaterialParameterHandle("$lightAttenuation"); lightRange = matInstance->getMaterialParameterHandle("$lightRange"); + lightInvSqrRange = matInstance->getMaterialParameterHandle("$lightInvSqrRange"); lightPosition = matInstance->getMaterialParameterHandle("$lightPosition"); farPlane = matInstance->getMaterialParameterHandle("$farPlane"); vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane"); @@ -686,87 +671,47 @@ void AdvancedLightBinManager::LightMaterialInfo::setLightParameters( const Light { MaterialParameters *matParams = matInstance->getMaterialParameters(); - // Set color in the right format, set alpha to the luminance value for the color. - LinearColorF col = lightInfo->getColor(); - - // TODO: The specularity control of the light - // is being scaled by the overall lumiance. - // - // Not sure if this may be the source of our - // bad specularity results maybe? - // - - const Point3F colorToLumiance( 0.3576f, 0.7152f, 0.1192f ); - F32 lumiance = mDot(*((const Point3F *)&lightInfo->getColor()), colorToLumiance ); - col.alpha *= lumiance; - - matParams->setSafe( lightColor, col ); + matParams->setSafe( lightColor, lightInfo->getColor() ); matParams->setSafe( lightBrightness, lightInfo->getBrightness() ); switch( lightInfo->getType() ) { case LightInfo::Vector: { - const VectorF lightDir = lightInfo->getDirection(); - matParams->setSafe( lightDirection, lightDir ); - - // Set small number for alpha since it represents existing specular in - // the vector light. This prevents a divide by zero. - LinearColorF ambientColor = renderState->getAmbientLightColor(); - ambientColor.alpha = 0.00001f; - matParams->setSafe( lightAmbient, ambientColor ); - - // If no alt color is specified, set it to the average of - // the ambient and main color to avoid artifacts. - // - // TODO: Trilight disabled until we properly implement it - // in the light info! - // - //LinearColorF lightAlt = lightInfo->getAltColor(); - LinearColorF lightAlt( LinearColorF::BLACK ); // = lightInfo->getAltColor(); - if ( lightAlt.red == 0.0f && lightAlt.green == 0.0f && lightAlt.blue == 0.0f ) - lightAlt = (lightInfo->getColor() + renderState->getAmbientLightColor()) / 2.0f; - - LinearColorF trilightColor = lightAlt; - matParams->setSafe(lightTrilight, trilightColor); + matParams->setSafe( lightDirection, lightInfo->getDirection()); + matParams->setSafe( lightAmbient, renderState->getAmbientLightColor()); } break; case LightInfo::Spot: { const F32 outerCone = lightInfo->getOuterConeAngle(); - const F32 innerCone = getMin( lightInfo->getInnerConeAngle(), outerCone ); - const F32 outerCos = mCos( mDegToRad( outerCone / 2.0f ) ); - const F32 innerCos = mCos( mDegToRad( innerCone / 2.0f ) ); - Point4F spotParams( outerCos, - innerCos - outerCos, - mCos( mDegToRad( outerCone ) ), - 0.0f ); + const F32 innerCone = getMin(lightInfo->getInnerConeAngle(), outerCone); + const F32 outerCos = mCos(mDegToRad(outerCone / 2.0f)); + const F32 innerCos = mCos(mDegToRad(innerCone / 2.0f)); + Point2F spotParams(outerCos,innerCos - outerCos); matParams->setSafe( lightSpotParams, spotParams ); matParams->setSafe( lightDirection, lightInfo->getDirection()); matParams->setSafe( lightPosition, lightInfo->getPosition()); + + const F32 radius = lightInfo->getRange().x; + const F32 invSqrRadius = 1.0f / mSquared(radius); + matParams->setSafe(lightRange, radius); + matParams->setSafe(lightInvSqrRange, invSqrRadius); } - // Fall through + break; case LightInfo::Point: - { - const F32 radius = lightInfo->getRange().x; - matParams->setSafe( lightRange, radius ); - matParams->setSafe( lightPosition, lightInfo->getPosition()); + { + matParams->setSafe(lightPosition, lightInfo->getPosition()); - // Get the attenuation falloff ratio and normalize it. - Point3F attenRatio = lightInfo->getExtended()->attenuationRatio; - F32 total = attenRatio.x + attenRatio.y + attenRatio.z; - if ( total > 0.0f ) - attenRatio /= total; - - Point2F attenParams( ( 1.0f / radius ) * attenRatio.y, - ( 1.0f / ( radius * radius ) ) * attenRatio.z ); - - matParams->setSafe( lightAttenuation, attenParams ); + const F32 radius = lightInfo->getRange().x; + const F32 invSqrRadius = 1.0f / (radius * radius); + matParams->setSafe( lightRange, radius); + matParams->setSafe( lightInvSqrRange, invSqrRadius); + } break; - } default: AssertFatal( false, "Bad light type!" ); diff --git a/Engine/source/lighting/advanced/advancedLightBinManager.h b/Engine/source/lighting/advanced/advancedLightBinManager.h index 8751c0815..5267391e0 100644 --- a/Engine/source/lighting/advanced/advancedLightBinManager.h +++ b/Engine/source/lighting/advanced/advancedLightBinManager.h @@ -165,10 +165,9 @@ protected: MaterialParameterHandle *lightDirection; MaterialParameterHandle *lightColor; MaterialParameterHandle *lightBrightness; - MaterialParameterHandle *lightAttenuation; MaterialParameterHandle *lightRange; + MaterialParameterHandle *lightInvSqrRange; MaterialParameterHandle *lightAmbient; - MaterialParameterHandle *lightTrilight; MaterialParameterHandle *lightSpotParams; LightMaterialInfo( const String &matName, diff --git a/Templates/Full/game/core/scripts/client/lighting/advanced/shaders.cs b/Templates/Full/game/core/scripts/client/lighting/advanced/shaders.cs index ca8171bf5..72a1bdccd 100644 --- a/Templates/Full/game/core/scripts/client/lighting/advanced/shaders.cs +++ b/Templates/Full/game/core/scripts/client/lighting/advanced/shaders.cs @@ -92,7 +92,7 @@ new CustomMaterial( AL_VectorLightMaterial ) sampler["colorBuffer"] = "#color"; sampler["matInfoBuffer"] = "#matinfo"; - target = "diffuseLighting"; + target = "AL_FormatToken"; pixVersion = 3.0; }; @@ -170,7 +170,7 @@ new CustomMaterial( AL_PointLightMaterial ) sampler["colorBuffer"] = "#color"; sampler["matInfoBuffer"] = "#matinfo"; - target = "diffuseLighting"; + target = "AL_FormatToken"; pixVersion = 3.0; }; @@ -209,7 +209,7 @@ new CustomMaterial( AL_SpotLightMaterial ) sampler["colorBuffer"] = "#color"; sampler["matInfoBuffer"] = "#matinfo"; - target = "diffuseLighting"; + target = "AL_FormatToken"; pixVersion = 3.0; }; @@ -375,17 +375,6 @@ new ShaderData( PrefiterCubemapShader ) pixVersion = 3.0; }; -new ShaderData( BRDFLookupShader ) -{ - DXVertexShaderFile = "shaders/common/lighting/advanced/cubemapV.hlsl"; - DXPixelShaderFile = "shaders/common/lighting/advanced/brdfLookupP.hlsl"; - - OGLVertexShaderFile = "shaders/common/lighting/advanced/gl/cubemapV.glsl"; - OGLPixelShaderFile = "shaders/common/lighting/advanced/gl/brdfLookupP.glsl"; - - pixVersion = 3.0; -}; - new ShaderData( SkyLightShader ) { DXVertexShaderFile = "shaders/common/lighting/advanced/convexGeometryV.hlsl"; diff --git a/Templates/Full/game/core/scripts/client/shaders.cs b/Templates/Full/game/core/scripts/client/shaders.cs index 4eb389dae..fe364a01d 100644 --- a/Templates/Full/game/core/scripts/client/shaders.cs +++ b/Templates/Full/game/core/scripts/client/shaders.cs @@ -138,16 +138,3 @@ singleton ShaderData( VolumetricFogReflectionShader ) pixVersion = 3.0; }; - -singleton ShaderData( CubemapSaveShader ) -{ - DXVertexShaderFile = "shaders/common/cubemapSaveV.hlsl"; - DXPixelShaderFile = "shaders/common/cubemapSaveP.hlsl"; - - OGLVertexShaderFile = "shaders/common/gl/cubemapSaveV.glsl"; - OGLPixelShaderFile = "shaders/common/gl/cubemapSaveP.glsl"; - - samplerNames[0] = "$cubemapTex"; - - pixVersion = 3.0; -}; \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/cubemapSaveP.hlsl b/Templates/Full/game/shaders/common/cubemapSaveP.hlsl deleted file mode 100644 index 540bb4764..000000000 --- a/Templates/Full/game/shaders/common/cubemapSaveP.hlsl +++ /dev/null @@ -1,63 +0,0 @@ -//----------------------------------------------------------------------------- -// 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 "shaderModel.hlsl" - -struct Conn -{ - float4 hpos : TORQUE_POSITION; - float3 face_pos_x : TEXCOORD0; - float3 face_neg_x : TEXCOORD1; - float3 face_pos_y : TEXCOORD2; - float3 face_neg_y : TEXCOORD3; - float3 face_pos_z : TEXCOORD4; - float3 face_neg_z : TEXCOORD5; -}; - -struct Fragout -{ - float4 target0 : TORQUE_TARGET0; - float4 target1 : TORQUE_TARGET1; - float4 target2 : TORQUE_TARGET2; - float4 target3 : TORQUE_TARGET3; - float4 target4 : TORQUE_TARGET4; - float4 target5 : TORQUE_TARGET5; -}; - -TORQUE_UNIFORM_SAMPLERCUBE(cubemapTex, 0); - -//----------------------------------------------------------------------------- -// Main -//----------------------------------------------------------------------------- -Fragout main(Conn In) -{ - Fragout Out; - - Out.target0 = TORQUE_TEXCUBE(cubemapTex, In.face_pos_x); - Out.target1 = TORQUE_TEXCUBE(cubemapTex, In.face_neg_x); - Out.target2 = TORQUE_TEXCUBE(cubemapTex, In.face_pos_y); - Out.target3 = TORQUE_TEXCUBE(cubemapTex, In.face_neg_y); - Out.target4 = TORQUE_TEXCUBE(cubemapTex, In.face_pos_z); - Out.target5 = TORQUE_TEXCUBE(cubemapTex, In.face_neg_z); - - return Out; -} diff --git a/Templates/Full/game/shaders/common/cubemapSaveV.hlsl b/Templates/Full/game/shaders/common/cubemapSaveV.hlsl deleted file mode 100644 index 17b9d05e3..000000000 --- a/Templates/Full/game/shaders/common/cubemapSaveV.hlsl +++ /dev/null @@ -1,56 +0,0 @@ -//----------------------------------------------------------------------------- -// 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 "shaderModel.hlsl" - -struct Conn -{ - float4 hpos : TORQUE_POSITION; - float3 face_pos_x : TEXCOORD0; - float3 face_neg_x : TEXCOORD1; - float3 face_pos_y : TEXCOORD2; - float3 face_neg_y : TEXCOORD3; - float3 face_pos_z : TEXCOORD4; - float3 face_neg_z : TEXCOORD5; -}; - -uniform float4x4 matrix0; -uniform float4x4 matrix1; -uniform float4x4 matrix2; -uniform float4x4 matrix3; -uniform float4x4 matrix4; -uniform float4x4 matrix5; - -Conn main(uint id: SV_VertexID) -{ - Conn Out; - float4 vertex = float4(float2((id << 1) & 2, id & 2) * float2(2, -2) + float2(-1, 1), 0, 1); - Out.hpos = vertex; - Out.face_pos_x = mul(matrix0, vertex).xyz; - Out.face_neg_x = mul(matrix1, vertex).xyz; - Out.face_pos_y = mul(matrix2, vertex).xyz; - Out.face_neg_y = mul(matrix3, vertex).xyz; - Out.face_pos_z = mul(matrix4, vertex).xyz; - Out.face_neg_z = mul(matrix5, vertex).xyz; - - return Out; -} diff --git a/Templates/Full/game/shaders/common/lighting.hlsl b/Templates/Full/game/shaders/common/lighting.hlsl index 1a1b2b37e..b4105decf 100644 --- a/Templates/Full/game/shaders/common/lighting.hlsl +++ b/Templates/Full/game/shaders/common/lighting.hlsl @@ -122,7 +122,7 @@ struct Surface } }; -inline Surface CreateSurface(float4 gbuffer0, TORQUE_SAMPLER2D(gbufferTex1), TORQUE_SAMPLER2D(gbufferTex2), in float2 uv, in float3 wsEyePos, in float3 wsEyeRay, in float4x4 invView) +inline Surface createSurface(float4 gbuffer0, TORQUE_SAMPLER2D(gbufferTex1), TORQUE_SAMPLER2D(gbufferTex2), in float2 uv, in float3 wsEyePos, in float3 wsEyeRay, in float4x4 invView) { Surface surface = (Surface)0; @@ -148,15 +148,17 @@ inline Surface CreateSurface(float4 gbuffer0, TORQUE_SAMPLER2D(gbufferTex1), TOR struct SurfaceToLight { float3 L; // surface to light vector + float3 Lu; // un-normalized surface to light vector float3 H; // half-vector between view vector and light vector float NdotL; // cos(angle between N and L) float HdotV; // cos(angle between H and V) = HdotL = cos(angle between H and L) float NdotH; // cos(angle between N and H) }; -inline SurfaceToLight CreateSurfaceToLight(in Surface surface, in float3 L) +inline SurfaceToLight createSurfaceToLight(in Surface surface, in float3 L) { SurfaceToLight surfaceToLight = (SurfaceToLight)0; + surfaceToLight.Lu = L; surfaceToLight.L = normalize(L); surfaceToLight.H = normalize(surface.V + surfaceToLight.L); surfaceToLight.NdotL = saturate(dot(surfaceToLight.L, surface.N)); @@ -187,15 +189,32 @@ float3 BRDF_GetDiffuse(in Surface surface, in SurfaceToLight surfaceToLight) return diffuse; } -// inverse square falloff from Epic Games' paper -float Attenuate(float distToLight, float radius) +//attenuations functions from "moving frostbite to pbr paper" +//https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf +float smoothDistanceAtt ( float squaredDistance , float invSqrAttRadius ) { - float distanceByRadius = 1.0f - pow((distToLight / radius), 4); - float clamped = pow(clamp(distanceByRadius, 0.0f, 1.0f), 2.0f); - return clamped / (sqr(distToLight) + 1.0f); + float factor = squaredDistance * invSqrAttRadius ; + float smoothFactor = saturate (1.0f - factor * factor ); + return sqr(smoothFactor); } -inline float3 GetDirectionalLight(in Surface surface, in SurfaceToLight surfaceToLight, float3 lightColor, float lightIntensity, float shadow) +float getDistanceAtt( float3 unormalizedLightVector , float invSqrAttRadius ) +{ + float sqrDist = dot ( unormalizedLightVector , unormalizedLightVector ); + float attenuation = 1.0 / (max ( sqrDist , 0.01*0.01) ); + attenuation *= smoothDistanceAtt ( sqrDist , invSqrAttRadius ); + return attenuation; +} + + float getSpotAngleAtt( float3 normalizedLightVector , float3 lightDir , float2 lightSpotParams ) + { + float cd = dot ( lightDir , normalizedLightVector ); + float attenuation = saturate ( ( cd - lightSpotParams.x ) / lightSpotParams.y ); + // smooth the transition + return sqr(attenuation); +} + +inline float3 getDirectionalLight(in Surface surface, in SurfaceToLight surfaceToLight, float3 lightColor, float lightIntensity, float shadow) { float3 factor = lightColor * max(surfaceToLight.NdotL, 0) * shadow * lightIntensity; float3 diffuse = BRDF_GetDiffuse(surface,surfaceToLight) * factor; @@ -205,10 +224,9 @@ inline float3 GetDirectionalLight(in Surface surface, in SurfaceToLight surfaceT return final; } -inline float3 GetPointLight(in Surface surface, in SurfaceToLight surfaceToLight, float3 lightColor, float lightIntensity,float distToLight, float radius, float shadow) +inline float3 getPunctualLight(in Surface surface, in SurfaceToLight surfaceToLight, float3 lightColor, float lightIntensity, float radius, float shadow) { - float attenuation = Attenuate(distToLight,radius); - + float attenuation = getDistanceAtt(surfaceToLight.Lu, radius); float3 factor = lightColor * max(surfaceToLight.NdotL, 0) * shadow * lightIntensity * attenuation; float3 diffuse = BRDF_GetDiffuse(surface,surfaceToLight) * factor; @@ -217,15 +235,3 @@ inline float3 GetPointLight(in Surface surface, in SurfaceToLight surfaceToLight float3 final = max(0.0f, diffuse + spec * surface.ao * surface.F); return final; } - -inline float3 GetSpotLight(in Surface surface, in SurfaceToLight surfaceToLight, float3 lightColor, float lightIntensity,float distToLight, float radius, float shadow) -{ - float attenuation = Attenuate(distToLight,radius); - //attenuation *= ( cosAlpha - lightSpotParams.x ) / lightSpotParams.y; - float3 factor = lightColor * max(surfaceToLight.NdotL, 0) * shadow * lightIntensity * attenuation; - float3 diffuse = BRDF_GetDiffuse(surface,surfaceToLight) * factor; - float3 spec = BRDF_GetSpecular(surface,surfaceToLight) * factor; - - float3 final = max(0.0f, diffuse + spec * surface.ao * surface.F); - return final; -} diff --git a/Templates/Full/game/shaders/common/lighting/advanced/brdfLookupP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/brdfLookupP.hlsl deleted file mode 100644 index 8dd093870..000000000 --- a/Templates/Full/game/shaders/common/lighting/advanced/brdfLookupP.hlsl +++ /dev/null @@ -1,138 +0,0 @@ -//----------------------------------------------------------------------------- -// 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 "../../torque.hlsl" - -struct ConnectData -{ - float4 hpos : TORQUE_POSITION; - float2 uv : TEXCOORD; -}; - -// ---------------------------------------------------------------------------- -// http://holger.dammertz.org/stuff/notes_HammersleyOnHemisphere.html -// efficient VanDerCorpus calculation. -float RadicalInverse_VdC(uint bits) -{ - bits = (bits << 16u) | (bits >> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - return float(bits) * 2.3283064365386963e-10; // / 0x100000000 -} -// ---------------------------------------------------------------------------- -float2 Hammersley(uint i, uint N) -{ - return float2(float(i)/float(N), RadicalInverse_VdC(i)); -} -// ---------------------------------------------------------------------------- -float3 ImportanceSampleGGX(float2 Xi, float3 N, float roughness) -{ - float a = roughness*roughness; - - float phi = 2.0 * M_PI_F * Xi.x; - float cosTheta = sqrt((1.0 - Xi.y) / (1.0 + (a*a - 1.0) * Xi.y)); - float sinTheta = sqrt(1.0 - cosTheta*cosTheta); - - // from spherical coordinates to cartesian coordinates - halfway vector - float3 H; - H.x = cos(phi) * sinTheta; - H.y = sin(phi) * sinTheta; - H.z = cosTheta; - - // from tangent-space H vector to world-space sample vector - float3 up = abs(N.z) < 0.999 ? float3(0.0, 0.0, 1.0) : float3(1.0, 0.0, 0.0); - float3 tangent = normalize(cross(up, N)); - float3 bitangent = cross(N, tangent); - - float3 sampleVec = tangent * H.x + bitangent * H.y + N * H.z; - return normalize(sampleVec); -} -// ---------------------------------------------------------------------------- -float GeometrySchlickGGX(float NdotV, float roughness) -{ - // note that we use a different k for IBL - float a = roughness; - float k = (a * a) / 2.0; - - float nom = NdotV; - float denom = NdotV * (1.0 - k) + k; - - return nom / denom; -} -// ---------------------------------------------------------------------------- -float GeometrySmith(float3 N, float3 V, float3 L, float roughness) -{ - float NdotV = max(dot(N, V), 0.0); - float NdotL = max(dot(N, L), 0.0); - float ggx2 = GeometrySchlickGGX(NdotV, roughness); - float ggx1 = GeometrySchlickGGX(NdotL, roughness); - - return ggx1 * ggx2; -} -// ---------------------------------------------------------------------------- -float2 IntegrateBRDF(float NdotV, float roughness) -{ - float3 V; - V.x = sqrt(1.0 - NdotV*NdotV); - V.y = 0.0; - V.z = NdotV; - - float A = 0.0; - float B = 0.0; - - float3 N = float3(0.0, 0.0, 1.0); - - const uint SAMPLE_COUNT = 1024u; - for(uint i = 0u; i < SAMPLE_COUNT; ++i) - { - // generates a sample vector that's biased towards the - // preferred alignment direction (importance sampling). - float2 Xi = Hammersley(i, SAMPLE_COUNT); - float3 H = ImportanceSampleGGX(Xi, N, roughness); - float3 L = normalize(2.0 * dot(V, H) * H - V); - - float NdotL = max(L.z, 0.0); - float NdotH = max(H.z, 0.0); - float VdotH = max(dot(V, H), 0.0); - - if(NdotL > 0.0) - { - float G = GeometrySmith(N, V, L, roughness); - float G_Vis = (G * VdotH) / (NdotH * NdotV); - float Fc = pow(1.0 - VdotH, 5.0); - - A += (1.0 - Fc) * G_Vis; - B += Fc * G_Vis; - } - } - A /= float(SAMPLE_COUNT); - B /= float(SAMPLE_COUNT); - return float2(A, B); -} - -float4 main(ConnectData IN) : TORQUE_TARGET0 -{ - return float4(IntegrateBRDF(IN.uv.x, IN.uv.y).rg,0,1); - //return float2(1,1); -} \ No newline at end of file diff --git a/Templates/Full/game/shaders/common/lighting/advanced/pointLightP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/pointLightP.hlsl index b02229b00..2173309cc 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/pointLightP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/pointLightP.hlsl @@ -36,7 +36,6 @@ struct ConvexConnectP float4 vsEyeDir : TEXCOORD2; }; - #ifdef USE_COOKIE_TEX /// The texture for cookie rendering. @@ -130,12 +129,11 @@ uniform float4 lightMapParams; uniform float4 vsFarPlane; uniform float4 lightParams; -uniform float lightRange; +uniform float lightRange; +uniform float lightInvSqrRange; uniform float shadowSoftness; uniform float4x4 worldToCamera; -uniform float3x3 viewToLightProj; uniform float3x3 worldToLightProj; -uniform float3x3 dynamicViewToLightProj; uniform float3 eyePosWorld; uniform float4x4 cameraToWorld; @@ -154,7 +152,7 @@ float4 main( ConvexConnectP IN ) : SV_TARGET float3 wsEyeRay = mul(cameraToWorld, float4(vsEyeRay, 0)).xyz; //create surface - Surface surface = CreateSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), + Surface surface = createSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), uvScene, eyePosWorld, wsEyeRay, cameraToWorld); //early out if emissive @@ -165,12 +163,12 @@ float4 main( ConvexConnectP IN ) : SV_TARGET float3 L = lightPosition - surface.P; float dist = length(L); - float3 result = 0.0.xxx; + float3 lighting = 0.0.xxx; [branch] - if (dist < lightRange) + if(dist < lightRange) { float distToLight = dist / lightRange; - SurfaceToLight surfaceToLight = CreateSurfaceToLight(surface, L); + SurfaceToLight surfaceToLight = createSurfaceToLight(surface, L); #ifdef NO_SHADOW float shadowed = 1.0; @@ -183,50 +181,29 @@ float4 main( ConvexConnectP IN ) : SV_TARGET float shadowed = saturate( exp( lightParams.y * ( occ - distToLight ) ) ); #else - // Static float2 shadowCoord = decodeShadowCoord( mul( worldToLightProj, -surfaceToLight.L ) ).xy; - float static_shadowed = softShadow_filter(TORQUE_SAMPLER2D_MAKEARG(shadowMap), - ssPos.xy, - shadowCoord, - shadowSoftness, - distToLight, - surfaceToLight.NdotL, - lightParams.y); - - // Dynamic - float dynamic_shadowed = softShadow_filter(TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), - ssPos.xy, - shadowCoord, - shadowSoftness, - distToLight, - surfaceToLight.NdotL, - lightParams.y); - + float static_shadowed = softShadow_filter(TORQUE_SAMPLER2D_MAKEARG(shadowMap), ssPos.xy, shadowCoord, shadowSoftness, distToLight, surfaceToLight.NdotL, lightParams.y); + float dynamic_shadowed = softShadow_filter(TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), ssPos.xy, shadowCoord, shadowSoftness, distToLight, surfaceToLight.NdotL, lightParams.y); float shadowed = min(static_shadowed, dynamic_shadowed); - #endif #endif // !NO_SHADOW - float3 lightcol = lightColor.rgb; + float3 lightCol = lightColor.rgb; #ifdef USE_COOKIE_TEX - // Lookup the cookie sample. float4 cookie = TORQUE_TEXCUBE(cookieMap, mul(worldToLightProj, -surfaceToLight.L)); - // Multiply the light with the cookie tex. - lightcol *= cookie.rgb; - + lightCol *= cookie.rgb; // Use a maximum channel luminance to attenuate // the lighting else we get specular in the dark // regions of the cookie texture. - atten *= max(cookie.r, max(cookie.g, cookie.b)); - + lightCol *= max(cookie.r, max(cookie.g, cookie.b)); #endif - //get point light contribution - result = GetPointLight(surface, surfaceToLight, lightcol, lightBrightness, dist, lightRange, shadowed); + //get punctual light contribution + lighting = getPunctualLight(surface, surfaceToLight, lightCol, lightBrightness, lightInvSqrRange, shadowed); } - return float4(result, 0); + return float4(lighting, 0); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/probeShadingP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/probeShadingP.hlsl deleted file mode 100644 index 248896b9c..000000000 --- a/Templates/Full/game/shaders/common/lighting/advanced/probeShadingP.hlsl +++ /dev/null @@ -1,69 +0,0 @@ -//----------------------------------------------------------------------------- -// 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(diffuseLightingBuffer,1); -TORQUE_UNIFORM_SAMPLER2D(matInfoTex,2); -TORQUE_UNIFORM_SAMPLER2D(specularLightingBuffer,3); -TORQUE_UNIFORM_SAMPLER2D(deferredTex,4); - -uniform float radius; -uniform float2 targetSize; -uniform int captureRez; -float4 main( PFXVertToPix IN ) : TORQUE_TARGET0 -{ - float depth = TORQUE_DEFERRED_UNCONDITION( deferredTex, IN.uv0 ).w; - - if (depth>0.9999) - return float4(0,0,0,0); - - float3 albedo = TORQUE_TEX2D( colorBufferTex, IN.uv0 ).rgb; //albedo - float4 matInfo = TORQUE_TEX2D(matInfoTex, IN.uv0); //flags|smoothness|ao|metallic - - bool emissive = getFlag(matInfo.r, 0); - if (emissive) - { - return float4(albedo, 1.0); - } - - float4 diffuse = TORQUE_TEX2D( diffuseLightingBuffer, IN.uv0 ); //shadowmap*specular - float4 specular = TORQUE_TEX2D( specularLightingBuffer, IN.uv0 ); //environment mapping*lightmaps - - float metalness = matInfo.a; - - float3 diffuseColor = albedo - (albedo * metalness); - float3 specularColor = lerp(float3(0.04,0.04,0.04), albedo, metalness); - - float3 light = (diffuseColor * diffuse.rgb) + (specularColor * specular.rgb); - float2 relUV = IN.uv0*targetSize/captureRez; - - //we use a 1k depth range in the capture frustum. - //reduce that a bit to get something resembling depth fidelity out of 8 bits - depth*=2000/radius; - - float rLen = length(float3(relUV,depth)-float3(0.5,0.5,0)); - return hdrEncode( float4(light,rLen)); -} diff --git a/Templates/Full/game/shaders/common/lighting/advanced/reflectionProbeP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/reflectionProbeP.hlsl index 69ed63c1e..a6296ff5c 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/reflectionProbeP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/reflectionProbeP.hlsl @@ -79,31 +79,6 @@ float3 iblBoxSpecular(float3 normal, float3 wsPos, float roughness, float3 surfT return radiance; } -/* -float defineSphereSpaceInfluence(float3 centroidPosVS, float rad, float2 atten, float3 surfPosVS, float3 norm) -{ - // Build light vec, get length, clip pixel if needed - float3 lightVec = centroidPosVS - surfPosVS; - float lenLightV = length( lightVec ); - if (( rad - lenLightV )<0) - return -1; - - // Get the attenuated falloff. - float attn = attenuate( float4(1,1,1,1), atten, lenLightV ); - if ((attn - 1e-6)<0) - return -1; - - // Normalize lightVec - lightVec = lightVec /= lenLightV; - - // If we can do dynamic branching then avoid wasting - // fillrate on pixels that are backfacing to the light. - float nDotL = abs(dot( lightVec, norm )); - - return saturate( nDotL * attn ); -} -*/ - float defineBoxSpaceInfluence(float3 surfPosWS, float3 probePos, float radius, float atten) { float3 surfPosLS = mul( worldToObj, float4(surfPosWS,1.0)).xyz; @@ -120,18 +95,6 @@ float defineBoxSpaceInfluence(float3 surfPosWS, float3 probePos, float radius, f return max(localDir.x, max(localDir.y, localDir.z)) * -1; } -float defineDepthInfluence(float3 probePosWS, float3 surfPosWS, TORQUE_SAMPLERCUBE(radianceCube)) -{ - //TODO properly: filter out pixels projected uppon by probes behind walls by looking up the depth stored in the probes cubemap alpha - //and comparing legths - float3 probeToSurf = probePosWS-surfPosWS; - - float depthRef = TORQUE_TEXCUBELOD(cubeMap, float4(-probeToSurf,0)).a*radius; - float dist = length( probeToSurf ); - - return depthRef-dist; -} - float4 main( ConvexConnectP IN ) : SV_TARGET { // Compute scene UV @@ -146,16 +109,14 @@ float4 main( ConvexConnectP IN ) : SV_TARGET float4 normDepth = TORQUE_DEFERRED_UNCONDITION(deferredBuffer, uvScene); //create surface - Surface surface = CreateSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), + Surface surface = createSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), uvScene, eyePosWorld, wsEyeRay, cameraToWorld); float tempAttenVal = 3.5; float blendVal = defineBoxSpaceInfluence(surface.P, probeWSPos, radius, tempAttenVal); clip(blendVal); - //flip me on to have probes filter by depth - //clip(defineDepthInfluence(probeWSPos, worldPos, TORQUE_SAMPLERCUBE_MAKEARG(cubeMap))); - + //render into the bound space defined above float3 surfToEye = normalize(surface.P - eyePosWorld); float3 irradiance = TORQUE_TEXCUBELOD(irradianceCubemap, float4(surface.N,0)).xyz; diff --git a/Templates/Full/game/shaders/common/lighting/advanced/skylightP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/skylightP.hlsl index 6b63515f7..3bf8c111f 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/skylightP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/skylightP.hlsl @@ -46,7 +46,7 @@ float4 main( ConvexConnectP IN ) : SV_TARGET float4 normDepth = TORQUE_DEFERRED_UNCONDITION(deferredBuffer, uvScene); //create surface - Surface surface = CreateSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), + Surface surface = createSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), uvScene, eyePosWorld, wsEyeRay, cameraToWorld); float3 F = FresnelSchlickRoughness(surface.NdotV, surface.f0, surface.roughness); @@ -58,7 +58,5 @@ float4 main( ConvexConnectP IN ) : SV_TARGET //final diffuse color float3 diffuse = kD * irradiance * surface.baseColor.rgb; - float blendVal = 0.0001; - return float4(diffuse + specular * surface.ao, 0); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/spotLightP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/spotLightP.hlsl index 3a669ab8e..b4f4b1b43 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/spotLightP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/spotLightP.hlsl @@ -57,10 +57,11 @@ uniform float3 lightPosition; uniform float4 lightColor; -uniform float lightRange; +uniform float lightRange; +uniform float lightInvSqrRange; uniform float3 lightDirection; -uniform float4 lightSpotParams; +uniform float2 lightSpotParams; uniform float4 lightMapParams; uniform float4 vsFarPlane; uniform float4x4 worldToLightProj; @@ -70,6 +71,7 @@ uniform float shadowSoftness; uniform float3 eyePosWorld; uniform float4x4 cameraToWorld; +uniform float4x4 worldToCamera; float4 main( ConvexConnectP IN ) : SV_TARGET { @@ -85,7 +87,7 @@ float4 main( ConvexConnectP IN ) : SV_TARGET float3 wsEyeRay = mul(cameraToWorld, float4(vsEyeRay, 0)).xyz; //create surface - Surface surface = CreateSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), + Surface surface = createSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), uvScene, eyePosWorld, wsEyeRay, cameraToWorld); //early out if emissive @@ -93,27 +95,45 @@ float4 main( ConvexConnectP IN ) : SV_TARGET { return 0.0.xxxx; } - + float3 L = lightPosition - surface.P; float dist = length(L); - float3 result = 0.0.xxx; + float3 lighting = 0.0.xxx; [branch] - if (dist < lightRange) + if(dist < lightRange) { - float distToLight = dist / lightRange; - float spotFactor = dot(L, lightDirection); - float spotCutOff = lightSpotParams.x; - [branch] - //if (spotFactor > spotCutOff) - { - SurfaceToLight surfaceToLight = CreateSurfaceToLight(surface, L); - float shadowed = 1.0; - float3 lightcol = lightColor.rgb; - //get spot light contribution - result = GetSpotLight(surface, surfaceToLight, lightcol, lightBrightness, dist, lightRange, shadowed); - //result = float3(1.0,0,0); - } + SurfaceToLight surfaceToLight = createSurfaceToLight(surface, L); + #ifdef NO_SHADOW + float shadowed = 1.0; + #else + // Get the shadow texture coordinate + float4 pxlPosLightProj = mul( worldToLightProj, float4( surface.P, 1 ) ); + float2 shadowCoord = ( ( pxlPosLightProj.xy / pxlPosLightProj.w ) * 0.5 ) + float2( 0.5, 0.5 ); + shadowCoord.y = 1.0f - shadowCoord.y; + //distance to light in shadow map space + float distToLight = pxlPosLightProj.z / lightRange; + float static_shadowed = softShadow_filter(TORQUE_SAMPLER2D_MAKEARG(shadowMap), ssPos.xy, shadowCoord, shadowSoftness, distToLight, surfaceToLight.NdotL, lightParams.y); + float dynamic_shadowed = softShadow_filter(TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), ssPos.xy, shadowCoord, shadowSoftness, distToLight, surfaceToLight.NdotL, lightParams.y); + float shadowed = min(static_shadowed, dynamic_shadowed); + #endif + + float3 lightCol = lightColor.rgb; + #ifdef USE_COOKIE_TEX + // Lookup the cookie sample. + float4 cookie = TORQUE_TEXCUBE(cookieMap, mul(worldToLightProj, -surfaceToLight.L)); + // Multiply the light with the cookie tex. + lightCol *= cookie.rgb; + // Use a maximum channel luminance to attenuate + // the lighting else we get specular in the dark + // regions of the cookie texture. + lightCol *= max(cookie.r, max(cookie.g, cookie.b)); + #endif + + //get Punctual light contribution + lighting = getPunctualLight(surface, surfaceToLight, lightCol, lightBrightness, lightInvSqrRange, shadowed); + //get spot angle attenuation + lighting *= getSpotAngleAtt(-surfaceToLight.L, lightDirection, lightSpotParams ); } - return float4(result, 0); + return float4(lighting, 0); } diff --git a/Templates/Full/game/shaders/common/lighting/advanced/vectorLightP.hlsl b/Templates/Full/game/shaders/common/lighting/advanced/vectorLightP.hlsl index bb7417e46..8c15470f5 100644 --- a/Templates/Full/game/shaders/common/lighting/advanced/vectorLightP.hlsl +++ b/Templates/Full/game/shaders/common/lighting/advanced/vectorLightP.hlsl @@ -79,7 +79,6 @@ uniform float4 dynamicFarPlaneScalePSSM; float4 AL_VectorLightShadowCast( TORQUE_SAMPLER2D(sourceShadowMap), float2 texCoord, - float4x4 worldToLightProj, float3 worldPos, float4 scaleX, float4 scaleY, @@ -187,7 +186,7 @@ float4 main(FarFrustumQuadConnectP IN) : SV_TARGET float4 normDepth = TORQUE_DEFERRED_UNCONDITION(deferredBuffer, IN.uv0); //create surface - Surface surface = CreateSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), + Surface surface = createSurface( normDepth, TORQUE_SAMPLER2D_MAKEARG(colorBuffer),TORQUE_SAMPLER2D_MAKEARG(matInfoBuffer), IN.uv0, eyePosWorld, IN.wsEyeRay, cameraToWorld); //early out if emissive @@ -197,7 +196,7 @@ float4 main(FarFrustumQuadConnectP IN) : SV_TARGET } //create surface to light - SurfaceToLight surfaceToLight = CreateSurfaceToLight(surface, -lightDirection); + SurfaceToLight surfaceToLight = createSurfaceToLight(surface, -lightDirection); //light color might be changed by PSSM_DEBUG_RENDER float3 lightingColor = lightColor.rgb; @@ -210,11 +209,10 @@ float4 main(FarFrustumQuadConnectP IN) : SV_TARGET float4 zDist = (zNearFarInvNearFar.x + zNearFarInvNearFar.y * surface.depth); float fadeOutAmt = ( zDist.x - fadeStartLength.x ) * fadeStartLength.y; - //there must be a more effecient way of doing this, two shadowcast lookups = very yucky! - float4 static_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(shadowMap), IN.uv0.xy, worldToLightProj, surface.P, scaleX, scaleY, offsetX, offsetY, + float4 static_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(shadowMap), IN.uv0.xy, surface.P, scaleX, scaleY, offsetX, offsetY, farPlaneScalePSSM, surfaceToLight.NdotL); - float4 dynamic_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), IN.uv0.xy, dynamicWorldToLightProj, surface.P, dynamicScaleX, + float4 dynamic_shadowed_colors = AL_VectorLightShadowCast( TORQUE_SAMPLER2D_MAKEARG(dynamicShadowMap), IN.uv0.xy, surface.P, dynamicScaleX, dynamicScaleY, dynamicOffsetX, dynamicOffsetY, dynamicFarPlaneScalePSSM, surfaceToLight.NdotL); float static_shadowed = static_shadowed_colors.a; @@ -237,7 +235,7 @@ float4 main(FarFrustumQuadConnectP IN) : SV_TARGET #endif //NO_SHADOW //get directional light contribution - float3 result = GetDirectionalLight(surface, surfaceToLight, lightingColor.rgb, lightBrightness, shadow); + float3 lighting = getDirectionalLight(surface, surfaceToLight, lightingColor.rgb, lightBrightness, shadow); - return float4(result, 0); + return float4(lighting, 0); }