Compare commits

..

1 Commits

Author SHA1 Message Date
Powei Feng
f2fd8a57c8 Testing stencilling 3 2024-10-09 16:29:01 -07:00
22 changed files with 393 additions and 399 deletions

View File

@@ -541,6 +541,9 @@ void OpenGLContext::initBugs(Bugs* bugs, Extensions const& exts,
bugs->delay_fbo_destruction = true;
// PowerVR seems to have no problem with this (which is good for us)
bugs->allow_read_only_ancillary_feedback_loop = true;
// PowerVR doesn't respect lengths passed to glShaderSource, so concatenate them into a
// single string.
bugs->concatenate_shader_strings = true;
} else if (strstr(renderer, "Apple")) {
// Apple GPU
} else if (strstr(renderer, "Tegra") ||

View File

@@ -316,6 +316,12 @@ public:
// bugs or performance issues.
bool force_feature_level0;
// Some drivers don't respect the length argument of glShaderSource() and (apparently)
// require each shader source string to be null-terminated. This works around the issue by
// concatenating the strings into a single null-terminated string before passing it to
// glShaderSource().
bool concatenate_shader_strings;
} bugs = {};
// state getters -- as needed.
@@ -562,6 +568,9 @@ private:
{ bugs.force_feature_level0,
"force_feature_level0",
""},
{ bugs.concatenate_shader_strings,
"concatenate_shader_strings",
""},
}};
// this is chosen to minimize code size

View File

@@ -597,30 +597,40 @@ void ShaderCompilerService::compileShaders(OpenGLContext& context,
version = "#version 310 es\n";
}
std::array<std::string_view, 5> sources = {
version,
prolog,
specializationConstantString,
packingFunctions,
{ body.data(), body.size() - 1 } // null-terminated
const std::array<const char*, 5> sources = {
version.data(),
prolog.data(),
specializationConstantString.c_str(),
packingFunctions.data(),
body.data()
};
// Some of the sources may be zero-length. Remove them as to avoid passing lengths of
// zero to glShaderSource(). glShaderSource should work with lengths of zero, but some
// drivers instead interpret zero as a sentinel for a null-terminated string.
auto partitionPoint = std::stable_partition(
sources.begin(), sources.end(), [](std::string_view s) { return !s.empty(); });
size_t count = std::distance(sources.begin(), partitionPoint);
std::array<const char*, 5> shaderStrings;
std::array<GLint, 5> lengths;
for (size_t i = 0; i < count; i++) {
shaderStrings[i] = sources[i].data();
lengths[i] = sources[i].size();
}
const std::array<GLint, 5> lengths = {
(GLint)version.length(),
(GLint)prolog.length(),
(GLint)specializationConstantString.length(),
(GLint)packingFunctions.length(),
(GLint)body.length() - 1 // null terminated
};
GLuint const shaderId = glCreateShader(glShaderType);
glShaderSource(shaderId, count, shaderStrings.data(), lengths.data());
if (UTILS_UNLIKELY(context.bugs.concatenate_shader_strings)) {
size_t totalSize = 0;
for (size_t i = 0; i < sources.size(); i++) {
totalSize += lengths[i];
}
std::string concatenatedShaderSource;
concatenatedShaderSource.reserve(totalSize);
for (size_t i = 0; i < sources.size(); i++) {
concatenatedShaderSource.append(sources[i], lengths[i]);
}
const GLchar* ptr = concatenatedShaderSource.c_str();
GLint length = concatenatedShaderSource.length();
glShaderSource(shaderId, 1, &ptr, &length);
} else {
glShaderSource(shaderId, sources.size(), sources.data(), lengths.data());
}
glCompileShader(shaderId);

View File

@@ -606,7 +606,7 @@ void VulkanDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
}
}
VulkanAttachment depthStencil[2] = {};
VulkanAttachment depthStencil;
if (depth.handle) {
depthStencil[0] = {
.texture = mResourceAllocator.handle_cast<VulkanTexture*>(depth.handle),
@@ -621,19 +621,8 @@ void VulkanDriver::createRenderTargetR(Handle<HwRenderTarget> rth,
attachmentCount++;
}
if (stencil.handle) {
depthStencil[1] = {
.texture = mResourceAllocator.handle_cast<VulkanTexture*>(stencil.handle),
.level = stencil.level,
.baseViewIndex = stencil.baseViewIndex,
.layerCount = layerCount,
.layer = stencil.layer,
};
UTILS_UNUSED_IN_RELEASE VkExtent2D extent = depthStencil[1].getExtent2D();
tmin = { std::min(tmin.x, extent.width), std::min(tmin.y, extent.height) };
tmax = { std::max(tmax.x, extent.width), std::max(tmax.y, extent.height) };
attachmentCount++;
}
// The stencil buffer is always assumed to be part of the depth-stencil buffer.
assert_invariant(!stencil.handle || stencil.handle == depth.handle);
// All attachments must have the same dimensions, which must be greater than or equal to the
// render target dimensions.

View File

@@ -314,7 +314,7 @@ void VulkanRenderTarget::bindToSwapChain(VulkanSwapChain& swapChain) {
assert_invariant(!mOffscreen);
VkExtent2D const extent = swapChain.getExtent();
mColor[0] = { .texture = swapChain.getCurrentColor() };
mDepth = { .texture = swapChain.getDepth() };
mDepthStencil = { .texture = swapChain.getDepth() };
width = extent.width;
height = extent.height;
}
@@ -323,7 +323,7 @@ VulkanRenderTarget::VulkanRenderTarget(VkDevice device, VkPhysicalDevice physica
VulkanContext const& context, VmaAllocator allocator, VulkanCommands* commands,
uint32_t width, uint32_t height, uint8_t samples,
VulkanAttachment color[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT],
VulkanAttachment depthStencil[2], VulkanStagePool& stagePool, uint8_t layerCount)
VulkanAttachment depthStencil, VulkanStagePool& stagePool, uint8_t layerCount)
: HwRenderTarget(width, height),
VulkanResource(VulkanResourceType::RENDER_TARGET),
mOffscreen(true),
@@ -332,8 +332,8 @@ VulkanRenderTarget::VulkanRenderTarget(VkDevice device, VkPhysicalDevice physica
for (int index = 0; index < MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT; index++) {
mColor[index] = color[index];
}
mDepth = depthStencil[0];
VulkanTexture* depthTexture = (VulkanTexture*) mDepth.texture;
mDepthStencil = depthStencil[0];
VulkanTexture* depthTexture = (VulkanTexture*) mDepthStencil.texture;
if (samples == 1) {
return;
@@ -372,7 +372,7 @@ VulkanRenderTarget::VulkanRenderTarget(VkDevice device, VkPhysicalDevice physica
// There is no need for sidecar depth if the depth texture is already MSAA.
if (depthTexture->samples > 1) {
mMsaaDepthAttachment = mDepth;
mMsaaDepthAttachment = mDepthStencil;
return;
}
@@ -392,7 +392,7 @@ VulkanRenderTarget::VulkanRenderTarget(VkDevice device, VkPhysicalDevice physica
mMsaaDepthAttachment = {
.texture = msTexture,
.level = msLevel,
.layer = mDepth.layer,
.layer = mDepthStencil.layer,
};
}
@@ -418,8 +418,8 @@ VulkanAttachment& VulkanRenderTarget::getMsaaColor(int target) {
return mMsaaAttachments[target];
}
VulkanAttachment& VulkanRenderTarget::getDepth() {
return mDepth;
VulkanAttachment& VulkanRenderTarget::getDepthStencil() {
return mDepthStencil;
}
VulkanAttachment& VulkanRenderTarget::getMsaaDepth() {

View File

@@ -304,7 +304,7 @@ struct VulkanRenderTarget : private HwRenderTarget, VulkanResource {
VulkanContext const& context, VmaAllocator allocator,
VulkanCommands* commands, uint32_t width, uint32_t height,
uint8_t samples, VulkanAttachment color[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT],
VulkanAttachment depthStencil[2], VulkanStagePool& stagePool, uint8_t layerCount);
VulkanAttachment depthStencil, VulkanStagePool& stagePool, uint8_t layerCount);
// Creates a special "default" render target (i.e. associated with the swap chain)
explicit VulkanRenderTarget();
@@ -326,7 +326,7 @@ struct VulkanRenderTarget : private HwRenderTarget, VulkanResource {
private:
VulkanAttachment mColor[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT] = {};
VulkanAttachment mDepth = {};
VulkanAttachment mDepthStencil = {};
VulkanAttachment mMsaaAttachments[MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT] = {};
VulkanAttachment mMsaaDepthAttachment = {};
const bool mOffscreen : 1;

View File

@@ -16,22 +16,16 @@
#include "FrameSkipper.h"
#include <backend/DriverEnums.h>
#include <utils/compiler.h>
#include <utils/Log.h>
#include <utils/debug.h>
#include <algorithm>
#include <stddef.h>
namespace filament {
using namespace utils;
using namespace backend;
FrameSkipper::FrameSkipper(size_t latency) noexcept
: mLast(std::max(latency, MAX_FRAME_LATENCY) - 1) {
: mLast(latency - 1) {
assert_invariant(latency <= MAX_FRAME_LATENCY);
}
@@ -47,32 +41,31 @@ void FrameSkipper::terminate(DriverApi& driver) noexcept {
bool FrameSkipper::beginFrame(DriverApi& driver) noexcept {
auto& fences = mDelayedFences;
if (fences.front()) {
// Do we have a latency old fence?
auto status = driver.getFenceStatus(fences.front());
if (UTILS_UNLIKELY(status == FenceStatus::TIMEOUT_EXPIRED)) {
// The fence hasn't signaled yet, skip this frame
auto fence = fences.front();
if (fence) {
auto status = driver.getFenceStatus(fence);
if (status == FenceStatus::TIMEOUT_EXPIRED) {
// Sync not ready, skip frame
return false;
}
assert_invariant(status == FenceStatus::CONDITION_SATISFIED);
driver.destroyFence(fence);
}
// shift all fences down by 1
std::move(fences.begin() + 1, fences.end(), fences.begin());
fences.back() = {};
return true;
}
void FrameSkipper::endFrame(DriverApi& driver) noexcept {
auto& fences = mDelayedFences;
size_t const last = mLast;
// pop the oldest fence and advance the other ones
if (fences.front()) {
driver.destroyFence(fences.front());
// If the user produced a new frame despite the fact that the previous one wasn't finished
// (i.e. FrameSkipper::beginFrame() returned false), we need to make sure to replace
// a fence that might be here already)
auto& fence = mDelayedFences[mLast];
if (fence) {
driver.destroyFence(fence);
}
std::move(fences.begin() + 1, fences.end(), fences.begin());
// add a new fence to the end
assert_invariant(!fences[last]);
fences[last] = driver.createFence();
fence = driver.createFence();
}
} // namespace filament

View File

@@ -22,9 +22,6 @@
#include <array>
#include <stddef.h>
#include <stdint.h>
namespace filament {
/*
@@ -63,7 +60,7 @@ public:
private:
using Container = std::array<backend::Handle<backend::HwFence>, MAX_FRAME_LATENCY>;
mutable Container mDelayedFences{};
uint8_t const mLast;
size_t mLast;
};
} // namespace filament

View File

@@ -34,8 +34,6 @@
#include <math/mat4.h>
#include <utils/Log.h>
namespace filament {
using namespace backend;
@@ -122,8 +120,6 @@ void PerViewUniforms::prepareViewport(
s.resolution = { physical.zw, 1.0f / physical.zw };
s.logicalViewportScale = physical.zw / logical.zw;
s.logicalViewportOffset = -logical.xy / logical.zw;
utils::slog.e << "resolution=" << s.resolution << " logical=" <<
s.logicalViewportScale << " " << s.logicalViewportOffset << utils::io::endl;
}
void PerViewUniforms::prepareTime(FEngine& engine, math::float4 const& userTime) noexcept {

View File

@@ -2455,24 +2455,18 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::colorGrading(FrameGraph& fg,
const float temporalNoise = mUniformDistribution(mEngine.getRandomEngine());
auto yy = float4{
(float)vp.left / input.width,
(float)vp.bottom / input.height,
(float)vp.width / input.width,
(float)vp.height / input.height
};
mi->setParameter("dithering", colorGradingConfig.dithering);
mi->setParameter("bloom", bloomParameters);
mi->setParameter("vignette", vignetteParameters);
mi->setParameter("vignetteColor", vignetteOptions.color);
mi->setParameter("fxaa", colorGradingConfig.fxaa);
mi->setParameter("temporalNoise", temporalNoise);
mi->setParameter("viewport", yy);
utils::slog.e <<"yy------------yy in=" <<
input.width << "x" << input.height << " viewport=" << yy << utils::io::endl;
mi->setParameter("viewport", float4{
(float)vp.left / input.width,
(float)vp.bottom / input.height,
(float)vp.width / input.width,
(float)vp.height / input.height
});
const uint8_t variant = uint8_t(colorGradingConfig.translucent ?
PostProcessVariant::TRANSLUCENT : PostProcessVariant::OPAQUE);
@@ -2514,17 +2508,6 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::fxaa(FrameGraph& fg,
.filterMag = SamplerMagFilter::LINEAR,
.filterMin = SamplerMinFilter::LINEAR
});
auto xx = float4{
(float)vp.left / inDesc.width,
(float)vp.bottom / inDesc.height,
(float)vp.width / inDesc.width,
(float)vp.height / inDesc.height
};
utils::slog.e <<"xx-----------xx" <<
"in=" << inDesc.width <<"x" << inDesc.height << " vp=" << vp << " viewport=" << xx << utils::io::endl;
mi->setParameter("viewport", float4{
(float)vp.left / inDesc.width,
(float)vp.bottom / inDesc.height,

View File

@@ -75,6 +75,7 @@ FrameGraphId<FrameGraphTexture> RendererUtils::colorPass(
TargetBufferFlags const clearColorFlags = config.clearFlags & TargetBufferFlags::COLOR;
TargetBufferFlags clearDepthFlags = config.clearFlags & TargetBufferFlags::DEPTH;
TargetBufferFlags clearStencilFlags = config.clearFlags & TargetBufferFlags::STENCIL;
uint8_t layerCount = 1;
data.shadows = blackboard.get<FrameGraphTexture>("shadows");
data.ssao = blackboard.get<FrameGraphTexture>("ssao");
@@ -171,6 +172,9 @@ FrameGraphId<FrameGraphTexture> RendererUtils::colorPass(
data.color = builder.write(data.color, FrameGraphTexture::Usage::COLOR_ATTACHMENT);
data.depth = builder.write(data.depth, FrameGraphTexture::Usage::DEPTH_ATTACHMENT);
if (view.hasStereo() && engine.getConfig().stereoscopicType == StereoscopicType::MULTIVIEW) {
layerCount = engine.getConfig().stereoscopicEyeCount;
}
/*
* There is a bit of magic happening here regarding the viewport used.
@@ -192,7 +196,7 @@ FrameGraphId<FrameGraphTexture> RendererUtils::colorPass(
.stencil = data.stencil },
.clearColor = config.clearColor,
.samples = config.msaa,
.layerCount = static_cast<uint8_t>(colorBufferDesc.depth),
.layerCount = layerCount,
.clearFlags = clearColorFlags | clearDepthFlags | clearStencilFlags});
blackboard["depth"] = data.depth;
},

View File

@@ -371,13 +371,7 @@ FrameGraphId<FrameGraphTexture> ShadowMapManager::render(FEngine& engine, FrameG
if (view.isFrontFaceWindingInverted()) {
renderPassFlags |= RenderPass::HAS_INVERSE_FRONT_FACES;
}
bool const canUseDepthClamp =
!view.hasVSM() &&
mIsDepthClampSupported &&
engine.debug.shadowmap.depth_clamp;
if (canUseDepthClamp) {
if (mIsDepthClampSupported && engine.debug.shadowmap.depth_clamp) {
renderPassFlags |= RenderPass::HAS_DEPTH_CLAMP;
}
@@ -656,14 +650,9 @@ ShadowMapManager::ShadowTechnique ShadowMapManager::updateCascadeShadowMaps(FEng
cameraInfo.zf = -nearFarPlanes[i + 1];
updateNearFarPlanes(&cameraInfo.cullingProjection, cameraInfo.zn, cameraInfo.zf);
bool const canUseDepthClamp =
!view.hasVSM() &&
mIsDepthClampSupported &&
engine.debug.shadowmap.depth_clamp;
auto shaderParameters = shadowMap.updateDirectional(engine,
lightData, 0, cameraInfo, shadowMapInfo, sceneInfo,
canUseDepthClamp);
mIsDepthClampSupported && engine.debug.shadowmap.depth_clamp);
if (shadowMap.hasVisibleShadows()) {
const size_t shadowIndex = shadowMap.getShadowIndex();

View File

@@ -597,7 +597,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
bool hasColorGrading = hasPostProcess;
bool hasDithering = view.getDithering() == Dithering::TEMPORAL;
bool hasFXAA = view.getAntiAliasing() == AntiAliasing::FXAA;
// bool hasFXAA = false;//view.getAntiAliasing() == AntiAliasing::FXAA;
float2 scale = view.updateScale(engine, mFrameInfoManager.getLastFrameInfo(), mFrameRateOptions, mDisplayInfo);
auto msaaOptions = view.getMultiSampleAntiAliasingOptions();
auto dsrOptions = view.getDynamicResolutionOptions();
@@ -611,7 +610,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
auto guardBandOptions = view.getGuardBandOptions();
const bool isRenderingMultiview = view.hasStereo() &&
engine.getConfig().stereoscopicType == backend::StereoscopicType::MULTIVIEW;
utils::slog.e <<"hasFXAA=" <<hasFXAA << " view=" << &view << utils::io::endl;
// FIXME: This is to override some settings that are not supported for multiview at the moment.
// Remove this when all features are supported.
if (isRenderingMultiview) {
@@ -705,7 +703,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
const bool noBufferPadding = (colorGradingConfig.asSubpass && !hasFXAA && !scaled)
|| engine.debug.renderer.disable_buffer_padding;
// guardBandOptions.enabled = !noBufferPadding;
// guardBand must be a multiple of 16 to guarantee the same exact rendering up to 4 mip levels.
float const guardBand = guardBandOptions.enabled ? 16.0f : 0.0f;
@@ -722,7 +719,7 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
// the SwapChain, and we might want to keep it this way.
auto round = [](uint32_t x) {
constexpr uint32_t rounding = 256u;
constexpr uint32_t rounding = 16u;
return (x + (rounding - 1u)) & ~(rounding - 1u);
};
@@ -730,9 +727,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
const float width = float(round(svp.width )) + 2.0f * guardBand;
const float height = float(round(svp.height)) + 2.0f * guardBand;
utils::slog.e << "new dim=" << width <<"x" << height <<
" old dim=" << svp.width << "x" << svp.height << utils::io::endl;
// scale the field-of-view up, so it covers exactly the extra pixels
const float3 clipSpaceScaling{
float(svp.width) / width,
@@ -750,14 +744,9 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
1.0f - clipSpaceScaling.y - 2.0f * guardBand / height
};
utils::slog.e <<"clipspace scaling=" << clipSpaceScaling << utils::io::endl;
utils::slog.e <<"clipspace translation=" << clipSpaceTranslation << utils::io::endl;
mat4f ts = mat4f::scaling(clipSpaceScaling);
ts[3].xy = -clipSpaceTranslation;
utils::slog.e <<"mat=" << ts << utils::io::endl;
// update the camera projection
cameraInfo.projection = highPrecisionMultiply(ts, cameraInfo.projection);
@@ -770,7 +759,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
svp.height = uint32_t(height);
xvp.left = int32_t(guardBand);
xvp.bottom = int32_t(guardBand);
utils::slog.e <<"xvp.left=" << int32_t(guardBand) << utils::io::endl;
}
view.prepare(engine, driver, rootArenaScope, svp, cameraInfo, getShaderUserTime(), needsAlphaChannel);
@@ -882,9 +870,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
const TextureFormat hdrFormat = getHdrFormat(view, needsAlphaChannel);
utils::slog.e <<"padding=" << !noBufferPadding << " svp=" << svp << utils::io::endl;
utils::slog.e <<"padding=" << !noBufferPadding << " xvp=" << xvp << utils::io::endl;
// the clearFlags and clearColor specified below will only apply when rendering into the
// temporary color buffer. In particular, they won't apply when rendering into the main
// swapchain (imported render target above)
@@ -1089,9 +1074,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
.format = config.hdrFormat
};
utils::slog.e <<"color buffer output=" << colorBufferDesc.width <<"x" << colorBufferDesc.height
<< utils::io::endl;
// Set the depth to the number of layers if we're rendering multiview.
if (isRenderingMultiview) {
colorBufferDesc.depth = engine.getConfig().stereoscopicEyeCount;
@@ -1245,13 +1227,11 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
bloomOptions, vignetteOptions);
// the padded buffer is resolved now
xvp.left = xvp.bottom = 0;
utils::slog.e <<"color grading is resolved" << utils::io::endl;
svp = xvp;
}
}
if (hasFXAA) {
utils::slog.e <<"fxaa=" << xvp << utils::io::endl;
input = ppm.fxaa(fg, input, xvp, colorGradingConfig.ldrFormat,
!hasColorGrading || needsAlphaChannel);
// the padded buffer is resolved now
@@ -1265,7 +1245,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
.width = viewport.width, .height = viewport.height,
.format = colorGradingConfig.ldrFormat }, SamplerMagFilter::LINEAR);
xvp.left = xvp.bottom = 0;
utils::slog.e <<"scaled" << utils::io::endl;
svp = xvp;
}
}
@@ -1298,9 +1277,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
const bool outputIsSwapChain =
(input == colorPassOutput) && (viewRenderTarget == mRenderTargetHandle);
if (mightNeedFinalBlit) {
utils::slog.e <<"inside might need final blit xvp!=svp=" << (xvp != svp) <<
" xvp=" << xvp << " svp=" << svp <<
utils::io::endl;
if (blendModeTranslucent ||
xvp != svp ||
(outputIsSwapChain &&
@@ -1309,7 +1285,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
hasScreenSpaceRefraction ||
ssReflectionsOptions.enabled))) {
assert_invariant(!scaled);
utils::slog.e <<"doing final blit " << svp << " " << xvp << utils::io::endl;
input = ppm.blit(fg, blendModeTranslucent, input, xvp, {
.width = vp.width, .height = vp.height,
.format = colorGradingConfig.ldrFormat },
@@ -1339,10 +1314,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
fg.forwardResource(fgViewRenderTarget, input);
utils::slog.e <<"present view=" << &view << " scaled=" << scaled << " mightNeedFinalBlit=" <<
mightNeedFinalBlit <<
utils::io::endl;
fg.present(fgViewRenderTarget);
fg.compile();

View File

@@ -190,10 +190,10 @@ void RenderPassNode::resolve() noexcept {
minHeight = std::min(minHeight, h);
maxHeight = std::max(maxHeight, h);
}
// additionally, clear implies discardStart
rt.backend.params.flags.discardStart |= (
rt.descriptor.clearFlags & rt.targetBufferFlags);
}
// additionally, clear implies discardStart
rt.backend.params.flags.discardStart |= (
rt.descriptor.clearFlags & rt.targetBufferFlags);
assert_invariant(minWidth == maxWidth);
assert_invariant(minHeight == maxHeight);

View File

@@ -224,9 +224,6 @@ public:
*/
static void exportSettings(const Settings& settings, const char* filename);
static void exportScreenshot(View* view, Renderer* renderer, std::string filename,
bool autoclose, AutomationEngine* automationEngine);
Options getOptions() const { return mOptions; }
bool isRunning() const { return mIsRunning; }
size_t currentTest() const { return mCurrentTest; }

View File

@@ -56,7 +56,7 @@ static void convertRGBAtoRGB(void* buffer, uint32_t width, uint32_t height) {
}
}
void AutomationEngine::exportScreenshot(View* view, Renderer* renderer, std::string filename,
static void exportScreenshot(View* view, Renderer* renderer, std::string filename,
bool autoclose, AutomationEngine* automationEngine) {
const Viewport& vp = view->getViewport();
const size_t byteCount = vp.width * vp.height * 4;
@@ -244,8 +244,7 @@ void AutomationEngine::tick(Engine* engine, const ViewerContent& content, float
}
if (mOptions.exportScreenshots) {
AutomationEngine::exportScreenshot(
content.view, content.renderer, prefix + ".ppm", isLastTest, this);
exportScreenshot(content.view, content.renderer, prefix + ".ppm", isLastTest, this);
}
if (isLastTest) {

View File

@@ -562,8 +562,6 @@ int parse(jsmntok_t const* tokens, int i, const char* jsonChunk, Settings* out)
}
void applySettings(Engine* engine, const ViewSettings& settings, View* dest) {
utils::slog.e << "antialiasing=" << (int) settings.antiAliasing << " view=" << dest
<< utils::io::endl;
dest->setAntiAliasing(settings.antiAliasing);
dest->setTemporalAntiAliasingOptions(settings.taa);
dest->setMultiSampleAntiAliasingOptions(settings.msaa);

View File

@@ -276,7 +276,7 @@ if (NOT ANDROID)
target_link_libraries(hellopbr PRIVATE filameshio suzanne-resources)
target_link_libraries(image_viewer PRIVATE viewer imageio)
target_link_libraries(multiple_windows PRIVATE filameshio suzanne-resources)
target_link_libraries(rendertarget PRIVATE gltf-demo-resources filameshio suzanne-resources gltfio viewer)
target_link_libraries(rendertarget PRIVATE filameshio suzanne-resources)
target_link_libraries(sample_cloth PRIVATE filameshio)
target_link_libraries(sample_normal_map PRIVATE filameshio)
target_link_libraries(suzanne PRIVATE filameshio suzanne-resources)

View File

@@ -61,10 +61,8 @@
#include <algorithm>
#include <array>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include "generated/resources/gltf_demo.h"
@@ -139,8 +137,6 @@ struct App {
AutomationSpec* automationSpec = nullptr;
AutomationEngine* automationEngine = nullptr;
bool screenshot = false;
uint8_t screenshotSeq = 0;
};
static const char* DEFAULT_IBL = "assets/ibl/lightroom_14b";
@@ -881,15 +877,10 @@ int main(int argc, char** argv) {
if (ImGui::CollapsingHeader("Debug")) {
auto& debug = engine->getDebugRegistry();
if (engine->getBackend() == Engine::Backend::METAL) {
if (ImGui::Button("Capture frame")) {
bool* captureFrame =
debug.getPropertyAddress<bool>("d.renderer.doFrameCapture");
*captureFrame = true;
}
}
if (ImGui::Button("Screenshot")) {
app.screenshot = true;
if (ImGui::Button("Capture frame")) {
bool* captureFrame =
debug.getPropertyAddress<bool>("d.renderer.doFrameCapture");
*captureFrame = true;
}
ImGui::Checkbox("Disable buffer padding",
debug.getPropertyAddress<bool>("d.renderer.disable_buffer_padding"));
@@ -1147,14 +1138,6 @@ int main(int argc, char** argv) {
};
auto postRender = [&app](Engine* engine, View* view, Scene*, Renderer* renderer) {
if (app.screenshot) {
std::ostringstream stringStream;
stringStream << "screenshot" << std::setfill('0') << std::setw(2) << +app.screenshotSeq;
AutomationEngine::exportScreenshot(
view, renderer, stringStream.str() + ".ppm", false, app.automationEngine);
++app.screenshotSeq;
app.screenshot = false;
}
if (app.automationEngine->shouldClose()) {
FilamentApp::get().close();
return;

View File

@@ -20,6 +20,7 @@
#include <filament/Material.h>
#include <filament/MaterialInstance.h>
#include <filament/RenderableManager.h>
#include <filament/Renderer.h>
#include <filament/Scene.h>
#include <filament/Skybox.h>
#include <filament/TransformManager.h>
@@ -46,23 +47,33 @@ using utils::EntityManager;
struct App {
Config config;
VertexBuffer* vb;
VertexBuffer* vb2;
IndexBuffer* ib;
Material* mat;
Camera* cam;
Entity camera;
Skybox* skybox;
Entity renderable;
Entity r2;
};
struct Vertex {
filament::math::float2 position;
filament::math::float3 position;
uint32_t color;
};
float const z = 5;
static const Vertex TRIANGLE_VERTICES[3] = {
{{1, 0}, 0xffff0000u},
{{cos(M_PI * 2 / 3), sin(M_PI * 2 / 3)}, 0xff00ff00u},
{{cos(M_PI * 4 / 3), sin(M_PI * 4 / 3)}, 0xff0000ffu},
{{1, 0, z}, 0xffff0000u},
{{cos(M_PI * 2 / 3), sin(M_PI * 2 / 3), z}, 0xff00ff00u},
{{cos(M_PI * 4 / 3), sin(M_PI * 4 / 3), z}, 0xff0000ffu},
};
static Vertex T2[3] = {
TRIANGLE_VERTICES[0],
TRIANGLE_VERTICES[1],
TRIANGLE_VERTICES[2],
};
static constexpr uint16_t TRIANGLE_INDICES[3] = { 0, 1, 2 };
@@ -120,25 +131,36 @@ static int handleCommandLineArguments(int argc, char* argv[], App* app) {
}
int main(int argc, char** argv) {
T2[0].position.z = z - 10;
T2[1].position.z = z - 10;
T2[2].position.z = z - 10;
T2[0].color = 0xFF0000FF;
T2[1].color = 0xFF0000FF;
T2[2].color = 0xFF0000FF;
App app{};
app.config.title = "hellotriangle";
app.config.featureLevel = backend::FeatureLevel::FEATURE_LEVEL_0;
handleCommandLineArguments(argc, argv, &app);
auto setup = [&app](Engine* engine, View* view, Scene* scene) {
app.skybox = Skybox::Builder().color({0.1, 0.125, 0.25, 1.0}).build(*engine);
scene->setSkybox(app.skybox);
view->setPostProcessingEnabled(false);
static_assert(sizeof(Vertex) == 12, "Strange vertex size.");
app.vb = VertexBuffer::Builder()
view->setStencilBufferEnabled(true);
static_assert(sizeof(Vertex) == 16, "Strange vertex size.");
auto builder = VertexBuffer::Builder()
.vertexCount(3)
.bufferCount(1)
.attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT2, 0, 12)
.attribute(VertexAttribute::COLOR, 0, VertexBuffer::AttributeType::UBYTE4, 8, 12)
.normalized(VertexAttribute::COLOR)
.build(*engine);
.attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3, 0, 16)
.attribute(VertexAttribute::COLOR, 0, VertexBuffer::AttributeType::UBYTE4, 12, 16)
.normalized(VertexAttribute::COLOR);
app.vb = builder.build(*engine);
app.vb2 = builder.build(*engine);
app.vb->setBufferAt(*engine, 0,
VertexBuffer::BufferDescriptor(TRIANGLE_VERTICES, 36, nullptr));
VertexBuffer::BufferDescriptor(TRIANGLE_VERTICES, 48, nullptr));
app.vb2->setBufferAt(*engine, 0,
VertexBuffer::BufferDescriptor(T2, 48, nullptr));
app.ib = IndexBuffer::Builder()
.indexCount(3)
.bufferType(IndexBuffer::IndexType::USHORT)
@@ -149,22 +171,67 @@ int main(int argc, char** argv) {
.package(RESOURCES_BAKEDCOLOR_DATA, RESOURCES_BAKEDCOLOR_SIZE)
.build(*engine);
app.renderable = EntityManager::get().create();
app.r2 = EntityManager::get().create();
auto inst1 = app.mat->createInstance();
inst1->setDepthWrite(false);
inst1->setDepthFunc(MaterialInstance::DepthFunc::A);
inst1->setDepthCulling(false);
inst1->setStencilWrite(true);
inst1->setStencilCompareFunction(MaterialInstance::StencilCompareFunc::E);
inst1->setStencilOpDepthStencilPass(MaterialInstance::StencilOperation::REPLACE);
inst1->setStencilReferenceValue(6);
auto inst2 = app.mat->createInstance();
inst2->setDepthWrite(false);
inst2->setDepthFunc(MaterialInstance::DepthFunc::A);
inst2->setDepthCulling(false);
inst2->setStencilWrite(true);
inst2->setStencilCompareFunction(MaterialInstance::StencilCompareFunc::L);
inst2->setStencilOpDepthStencilPass(MaterialInstance::StencilOperation::REPLACE);
inst2->setStencilReferenceValue(6);
auto& renderableMan = engine->getRenderableManager();
RenderableManager::Builder(1)
.boundingBox({{ -1, -1, -1 }, { 1, 1, 1 }})
.material(0, app.mat->getDefaultInstance())
.material(0, inst1)
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.vb, app.ib, 0, 3)
.culling(false)
.receiveShadows(false)
.castShadows(false)
.build(*engine, app.renderable);
RenderableManager::Builder(1)
.boundingBox({{ -1, -1, -1 }, { 1, 1, 1 }})
.material(0, inst2)
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.vb2, app.ib, 0, 3)
.culling(false)
.receiveShadows(false)
.castShadows(false)
.build(*engine, app.r2);
scene->addEntity(app.renderable);
auto r1inst = renderableMan.getInstance(app.renderable);
renderableMan.setPriority(r1inst, 7);
scene->addEntity(app.r2);
auto r2inst = renderableMan.getInstance(app.r2);
renderableMan.setPriority(r2inst, 6);
app.camera = utils::EntityManager::get().create();
app.cam = engine->createCamera(app.camera);
view->setCamera(app.cam);
};
auto cleanup = [&app](Engine* engine, View*, Scene*) {
engine->destroy(app.skybox);
// engine->destroy(app.skybox);
engine->destroy(app.renderable);
engine->destroy(app.mat);
engine->destroy(app.vb);
@@ -174,19 +241,24 @@ int main(int argc, char** argv) {
};
FilamentApp::get().animate([&app](Engine* engine, View* view, double now) {
constexpr float ZOOM = 1.5f;
constexpr float ZOOM = 1.5;
const uint32_t w = view->getViewport().width;
const uint32_t h = view->getViewport().height;
const float aspect = (float) w / h;
app.cam->setProjection(Camera::Projection::ORTHO,
-aspect * ZOOM, aspect * ZOOM,
-ZOOM, ZOOM, 0, 1);
-ZOOM, ZOOM, -100, 100);
auto& tcm = engine->getTransformManager();
tcm.setTransform(tcm.getInstance(app.renderable),
filament::math::mat4f::rotation(now, filament::math::float3{ 0, 0, 1 }));
});
FilamentApp::get().run(app.config, setup, cleanup);
auto preRender = [](Engine*, View* view, Scene*, Renderer* renderer) {
renderer->setClearOptions({ .clearStencil = 0u, .clear = true });
};
FilamentApp::get().run(app.config, setup, cleanup, {}, preRender);
return 0;
}

View File

@@ -12,8 +12,6 @@ material {
uv0
],
shadingModel : unlit,
vertexDomain: device,
// vertexDomainDeviceJittered: true,
}
fragment {
@@ -22,11 +20,17 @@ fragment {
if (gl_FrontFacing) {
// Make a lookup into the mirror texture.
// vec2 uv = getResolution().zw * gl_FragCoord.xy;
vec2 uv = getNormalizedViewportCoord().xy;
vec2 uv = getResolution().zw * gl_FragCoord.xy;
material.baseColor.rgb = texture(materialParams_albedo, uv).rgb;
} else {
material.baseColor = vec4(1, 0, 0, 1);
// Add black borders to the mirror.
vec2 st = getUV0();
float minDist0 = min(st.x, st.y);
float minDist1 = min(1.0 - st.x, 1.0 - st.y);
float minDist = min(minDist0, minDist1);
material.baseColor.rgb *= smoothstep(0.0, 0.1, minDist);
}
material.baseColor.a = 1.0;
}
}

View File

@@ -28,17 +28,10 @@
#include <filament/VertexBuffer.h>
#include <filament/View.h>
#include <gltfio/AssetLoader.h>
#include <gltfio/FilamentAsset.h>
#include <gltfio/ResourceLoader.h>
#include <gltfio/TextureProvider.h>
#include <utils/NameComponentManager.h>
#include <utils/EntityManager.h>
#include <imgui.h>
#include <filagui/ImGuiExtensions.h>
#include <viewer/ViewerGui.h>
#include <filameshio/MeshReader.h>
#include <filamentapp/Config.h>
#include <filamentapp/FilamentApp.h>
@@ -47,16 +40,11 @@
#include <iostream>
#include "generated/resources/resources.h"
//#include "generated/resources/monkey.h"
#include "generated/resources/gltf_demo.h"
#include "generated/resources/monkey.h"
using namespace filament;
using namespace filamesh;
using namespace filament::math;
using namespace filament::viewer;
using namespace filament::gltfio;
#include <utils/Log.h>
struct Vertex {
float3 position;
@@ -67,6 +55,8 @@ struct App {
utils::Entity lightEntity;
Material* meshMaterial;
MaterialInstance* meshMatInstance;
MeshReader::Mesh monkeyMesh;
utils::Entity reflectedMonkey;
mat4f transform;
Texture* offscreenColorTexture = nullptr;
@@ -76,6 +66,12 @@ struct App {
Scene* offscreenScene = nullptr;
Camera* offscreenCamera = nullptr;
enum class ReflectionMode {
RENDERABLES,
CAMERA,
};
ReflectionMode mode = ReflectionMode::CAMERA;
Config config;
utils::Entity quadEntity;
@@ -84,22 +80,46 @@ struct App {
Material* quadMaterial = nullptr;
MaterialInstance* quadMatInstance = nullptr;
MaterialProvider* materials;
AssetLoader* assetLoader;
ResourceLoader* resourceLoader;
FilamentAsset* asset = nullptr;
utils::NameComponentManager* names;
gltfio::TextureProvider* stbDecoder = nullptr;
gltfio::TextureProvider* ktxDecoder = nullptr;
Engine* engine;
ViewerGui* viewer;
utils::Entity rootTransformEntity;
float3 quadCenter;
float3 quadNormal;
};
static const char* DEFAULT_IBL = "assets/ibl/lightroom_14b";
static mat4f reflectionMatrix(float4 plane) {
mat4f m;
m[0][0] = -2 * plane.x * plane.x + 1;
m[0][1] = -2 * plane.x * plane.y;
m[0][2] = -2 * plane.x * plane.z;
m[0][3] = -2 * plane.x * plane.w;
m[1][0] = -2 * plane.x * plane.y;
m[1][1] = -2 * plane.y * plane.y + 1;
m[1][2] = -2 * plane.y * plane.z;
m[1][3] = -2 * plane.y * plane.w;
m[2][0] = -2 * plane.z * plane.x;
m[2][1] = -2 * plane.z * plane.y;
m[2][2] = -2 * plane.z * plane.z + 1;
m[2][3] = -2 * plane.z * plane.w;
m[3][0] = 0;
m[3][1] = 0;
m[3][2] = 0;
m[3][3] = 1;
return transpose(m);
}
static void setReflectionMode(App& app, App::ReflectionMode mode) {
switch (mode) {
case App::ReflectionMode::RENDERABLES:
app.offscreenScene->addEntity(app.reflectedMonkey);
app.offscreenScene->remove(app.monkeyMesh.renderable);
app.offscreenView->setFrontFaceWindingInverted(false);
break;
case App::ReflectionMode::CAMERA:
app.offscreenScene->addEntity(app.monkeyMesh.renderable);
app.offscreenScene->remove(app.reflectedMonkey);
app.offscreenView->setFrontFaceWindingInverted(true);
break;
}
app.mode = mode;
}
static void printUsage(char* name) {
std::string exec_name(utils::Path(name).getName());
@@ -152,6 +172,14 @@ static int handleCommandLineArguments(int argc, char* argv[], App* app) {
}
break;
case 'm':
if (arg == "camera") {
app->mode = App::ReflectionMode::CAMERA;
} else if (arg == "renderables") {
app->mode = App::ReflectionMode::RENDERABLES;
} else {
std::cerr << "Unrecognized mode. Must be 'camera'|'renderables'.\n";
exit(1);
}
break;
}
}
@@ -161,182 +189,126 @@ static int handleCommandLineArguments(int argc, char* argv[], App* app) {
int main(int argc, char** argv) {
App app{};
app.config.title = "rendertarget";
app.config.iblDirectory = FilamentApp::getRootAssetsPath() + DEFAULT_IBL;
handleCommandLineArguments(argc, argv, &app);
auto gui = [&app](Engine*, View*) {
app.viewer->updateUserInterface();
FilamentApp::get().setSidebarWidth(app.viewer->getSidebarWidth());
};
auto loadResources = [&app] () {
// Load external textures and buffers.
std::string const gltfPath;
ResourceConfiguration configuration = {};
configuration.engine = app.engine;
configuration.gltfPath = gltfPath.c_str();
configuration.normalizeSkinningWeights = true;
app.resourceLoader = new gltfio::ResourceLoader(configuration);
app.stbDecoder = createStbProvider(app.engine);
app.ktxDecoder = createKtx2Provider(app.engine);
app.resourceLoader->addTextureProvider("image/png", app.stbDecoder);
app.resourceLoader->addTextureProvider("image/jpeg", app.stbDecoder);
app.resourceLoader->addTextureProvider("image/ktx2", app.ktxDecoder);
if (!app.resourceLoader->loadResources(app.asset)) {
std::cerr << "Unable to start loading resources" << std::endl;
exit(1);
}
app.asset->getInstance()->recomputeBoundingBoxes();
app.asset->releaseSourceData();
// Enable stencil writes on all material instances.
auto instance = app.asset->getInstance();
const size_t matInstanceCount = instance->getMaterialInstanceCount();
MaterialInstance* const* const instances = instance->getMaterialInstances();
for (int mi = 0; mi < matInstanceCount; mi++) {
instances[mi]->setStencilWrite(true);
instances[mi]->setStencilOpDepthStencilPass(MaterialInstance::StencilOperation::INCR);
}
auto ibl = FilamentApp::get().getIBL();
if (ibl) {
app.viewer->setIndirectLight(ibl->getIndirectLight(), ibl->getSphericalHarmonics());
app.viewer->getSettings().view.fogSettings.fogColorTexture = ibl->getFogTexture();
}
};
auto setup = [&app, loadResources](Engine* engine, View* view, Scene* scene) {
app.engine = engine;
auto& em = utils::EntityManager::get();
auto setup = [&app](Engine* engine, View* view, Scene* scene) {
auto& tcm = engine->getTransformManager();
auto& rcm = engine->getRenderableManager();
// Offscreen view
{
// Instantiate offscreen render target.
app.offscreenView = engine->createView();
app.offscreenScene = engine->createScene();
app.offscreenView->setScene(app.offscreenScene);
auto& em = utils::EntityManager::get();
auto vp = view->getViewport();
app.viewer = new ViewerGui(engine, app.offscreenScene, app.offscreenView, 410);
app.viewer->setUiCallback([&app, scene, view, engine]() {
if (ImGui::CollapsingHeader("Debug")) {
auto& debug = engine->getDebugRegistry();
ImGui::Checkbox("Disable buffer padding",
debug.getPropertyAddress<bool>("d.renderer.disable_buffer_padding"));
ImGui::Checkbox("Disable sub-passes",
debug.getPropertyAddress<bool>("d.renderer.disable_subpasses"));
}
});
Viewport vp = view->getViewport();
vp.width = vp.width - app.viewer->getSidebarWidth();
// Instantiate offscreen render target.
app.offscreenView = engine->createView();
app.offscreenScene = engine->createScene();
app.offscreenView->setScene(app.offscreenScene);
app.offscreenView->setPostProcessingEnabled(false);
app.offscreenColorTexture = Texture::Builder()
.width(vp.width).height(vp.height).levels(1)
.usage(Texture::Usage::COLOR_ATTACHMENT | Texture::Usage::SAMPLEABLE)
.format(Texture::InternalFormat::RGBA8).build(*engine);
app.offscreenDepthTexture = Texture::Builder()
.width(vp.width).height(vp.height).levels(1)
.usage(Texture::Usage::DEPTH_ATTACHMENT)
.format(Texture::InternalFormat::DEPTH24).build(*engine);
app.offscreenRenderTarget = RenderTarget::Builder()
.texture(RenderTarget::AttachmentPoint::COLOR, app.offscreenColorTexture)
.texture(RenderTarget::AttachmentPoint::DEPTH, app.offscreenDepthTexture)
.build(*engine);
app.offscreenView->setRenderTarget(app.offscreenRenderTarget);
app.offscreenView->setViewport({0, 0, vp.width, vp.height});
app.offscreenCamera = engine->createCamera(em.create());
app.offscreenView->setCamera(app.offscreenCamera);
FilamentApp::get().addOffscreenView(app.offscreenView);
app.offscreenColorTexture =
Texture::Builder()
.width(vp.width)
.height(vp.height)
.levels(1)
.usage(Texture::Usage::COLOR_ATTACHMENT | Texture::Usage::SAMPLEABLE)
.format(Texture::InternalFormat::RGBA8)
.build(*engine);
app.offscreenDepthTexture = Texture::Builder()
.width(vp.width)
.height(vp.height)
.levels(1)
.usage(Texture::Usage::DEPTH_ATTACHMENT)
.format(Texture::InternalFormat::DEPTH32F)
.build(*engine);
app.offscreenRenderTarget = RenderTarget::Builder()
.texture(RenderTarget::AttachmentPoint::COLOR,
app.offscreenColorTexture)
.texture(RenderTarget::AttachmentPoint::DEPTH,
app.offscreenDepthTexture)
.build(*engine);
app.offscreenView->setRenderTarget(app.offscreenRenderTarget);
app.offscreenView->setViewport({0, 0, vp.width, vp.height});
app.offscreenCamera = engine->createCamera(em.create());
app.offscreenView->setCamera(app.offscreenCamera);
FilamentApp::get().addOffscreenView(app.offscreenView);
}
// Position and orient the mirror in an interesting way.
float3 c = app.quadCenter = {-2, 0, -5};
float3 n = app.quadNormal = normalize(float3 {1, 0, 2});
float3 u = normalize(cross(app.quadNormal, float3(0, 1, 0)));
float3 v = cross(n, u);
u = 1.5 * u;
v = 1.5 * v;
static Vertex kQuadVertices[4] = { {{}, {1, 0}}, {{}, {0, 0}}, {{}, {1, 1}}, {{}, {0, 1}} };
kQuadVertices[0].position = c - u - v;
kQuadVertices[1].position = c + u - v;
kQuadVertices[2].position = c - u + v;
kQuadVertices[3].position = c + u + v;
// damaged helmet gltf
{
app.names = new utils::NameComponentManager(em);
app.materials = createJitShaderProvider(engine, true);
app.assetLoader = AssetLoader::create({engine, app.materials, app.names});
// Create quad vertex buffer.
static_assert(sizeof(Vertex) == 20, "Strange vertex size.");
app.quadVb = VertexBuffer::Builder()
.vertexCount(4)
.bufferCount(1)
.attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3, 0, 20)
.attribute(VertexAttribute::UV0, 0, VertexBuffer::AttributeType::FLOAT2, 12, 20)
.build(*engine);
app.quadVb->setBufferAt(*engine, 0,
VertexBuffer::BufferDescriptor(kQuadVertices, 80, nullptr));
app.asset = app.assetLoader->createAsset(GLTF_DEMO_DAMAGEDHELMET_DATA,
GLTF_DEMO_DAMAGEDHELMET_SIZE);
// Create quad index buffer.
static constexpr uint16_t kQuadIndices[6] = { 0, 1, 2, 3, 2, 1 };
app.quadIb = IndexBuffer::Builder()
.indexCount(6)
.bufferType(IndexBuffer::IndexType::USHORT)
.build(*engine);
app.quadIb->setBuffer(*engine, IndexBuffer::BufferDescriptor(kQuadIndices, 12, nullptr));
loadResources();
// Create quad material and renderable.
app.quadMaterial = Material::Builder()
.package(RESOURCES_MIRROR_DATA, RESOURCES_MIRROR_SIZE)
.build(*engine);
app.quadMatInstance = app.quadMaterial->createInstance();
TextureSampler sampler(TextureSampler::MinFilter::LINEAR, TextureSampler::MagFilter::LINEAR);
app.quadMatInstance->setParameter("albedo", app.offscreenColorTexture, sampler);
app.quadEntity = em.create();
RenderableManager::Builder(1)
.boundingBox({{ -1, -1, -1 }, { 1, 1, 1 }})
.material(0, app.quadMatInstance)
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.quadVb, app.quadIb, 0, 6)
.culling(false)
.receiveShadows(false)
.castShadows(false)
.build(*engine, app.quadEntity);
scene->addEntity(app.quadEntity);
app.offscreenScene->addEntities(app.asset->getLightEntities(),
app.asset->getLightEntityCount());
static constexpr int kNumAvailable = 128;
utils::Entity renderables[kNumAvailable];
gltfio::FilamentAsset::SceneMask mask;
mask.set(0);
while (size_t numWritten = app.asset->popRenderables(renderables, kNumAvailable)) {
app.asset->addEntitiesToScene(*app.offscreenScene, renderables, numWritten, mask);
}
// Instantiate mesh material.
app.meshMaterial = Material::Builder()
.package(RESOURCES_AIDEFAULTMAT_DATA, RESOURCES_AIDEFAULTMAT_SIZE).build(*engine);
auto mi = app.meshMatInstance = app.meshMaterial->createInstance();
mi->setParameter("baseColor", RgbType::LINEAR, {0.8, 1.0, 1.0});
mi->setParameter("metallic", 0.0f);
mi->setParameter("roughness", 0.4f);
mi->setParameter("reflectance", 0.5f);
app.rootTransformEntity = engine->getEntityManager().create();
tcm.create(app.rootTransformEntity);
TransformManager::Instance const& root = tcm.getInstance(app.rootTransformEntity);
tcm.setParent(tcm.getInstance(app.asset->getRoot()), root);
tcm.setTransform(root, mat4::translation(float3(0, 0, -4)));
}
// Add monkey into the scene.
app.monkeyMesh = MeshReader::loadMeshFromBuffer(engine, MONKEY_SUZANNE_DATA, nullptr, nullptr, mi);
auto ti = tcm.getInstance(app.monkeyMesh.renderable);
app.transform = mat4f{ mat3f(1), float3(0, 0, -4) } * tcm.getWorldTransform(ti);
rcm.setCastShadows(rcm.getInstance(app.monkeyMesh.renderable), false);
scene->addEntity(app.monkeyMesh.renderable);
// full-screen quad
{
static Vertex kQuadVertices[4] = {{{1, 1, 0}, {1, 1}}, {{1, -1, 0}, {1, 0}},
{{-1, -1, 0}, {0, 0}}, {{-1, 1, 0}, {0, 1}}};
// Create quad vertex buffer.
static_assert(sizeof(Vertex) == 20, "Strange vertex size.");
app.quadVb = VertexBuffer::Builder()
.vertexCount(4)
.bufferCount(1)
.attribute(VertexAttribute::POSITION, 0,
VertexBuffer::AttributeType::FLOAT3, 0, 20)
.attribute(VertexAttribute::UV0, 0,
VertexBuffer::AttributeType::FLOAT2, 12, 20)
.build(*engine);
app.quadVb->setBufferAt(*engine, 0,
VertexBuffer::BufferDescriptor(kQuadVertices, 80, nullptr));
// Create a reflected monkey, which is used only for App::ReflectionMode::RENDERABLES.
app.reflectedMonkey = em.create();
RenderableManager::Builder(1)
.boundingBox({{ -2, -2, -2 }, { 2, 2, 2 }})
.material(0, mi)
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.monkeyMesh.vertexBuffer, app.monkeyMesh.indexBuffer)
.receiveShadows(true)
.castShadows(false)
.build(*engine, app.reflectedMonkey);
setReflectionMode(app, app.mode);
// Create quad index buffer.
static constexpr uint16_t kQuadIndices[6] = {0, 2, 1, 2, 0, 3};
app.quadIb = IndexBuffer::Builder()
.indexCount(6)
.bufferType(IndexBuffer::IndexType::USHORT)
.build(*engine);
app.quadIb->setBuffer(*engine,
IndexBuffer::BufferDescriptor(kQuadIndices, 12, nullptr));
// Create quad material and renderable.
// NOTE: this material is VertexDomain=device
app.quadMaterial = Material::Builder()
.package(RESOURCES_MIRROR_DATA, RESOURCES_MIRROR_SIZE)
.build(*engine);
app.quadMatInstance = app.quadMaterial->createInstance();
TextureSampler sampler(TextureSampler::MinFilter::LINEAR,
TextureSampler::MagFilter::LINEAR);
app.quadMatInstance->setParameter("albedo", app.offscreenColorTexture, sampler);
app.quadEntity = em.create();
RenderableManager::Builder(1)
.boundingBox({{-1, -1, -1}, {1, 1, 1}})
.material(0, app.quadMatInstance)
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.quadVb,
app.quadIb, 0, 6)
.culling(false)
.receiveShadows(false)
.castShadows(false)
.build(*engine, app.quadEntity);
scene->addEntity(app.quadEntity);
}
// Add light source to both scenes.
// NOTE: this is slightly wrong when the reflection mode is RENDERABLES.
app.lightEntity = em.create();
LightManager::Builder(LightManager::Type::SUN)
.color(Color::toLinear<ACCURATE>(sRGBColor(0.98f, 0.92f, 0.89f)))
.intensity(110000)
.direction({ 0.7, -1, -0.8 })
.sunAngularRadius(1.9f)
.castShadows(false)
.build(*engine, app.lightEntity);
scene->addEntity(app.lightEntity);
app.offscreenScene->addEntity(app.lightEntity);
};
auto cleanup = [&app](Engine* engine, View*, Scene*) {
@@ -346,10 +318,14 @@ int main(int argc, char** argv) {
engine->destroyCameraComponent(camera);
em.destroy(camera);
engine->destroy(app.reflectedMonkey);
engine->destroy(app.lightEntity);
engine->destroy(app.quadEntity);
engine->destroy(app.meshMatInstance);
engine->destroy(app.meshMaterial);
engine->destroy(app.monkeyMesh.renderable);
engine->destroy(app.monkeyMesh.vertexBuffer);
engine->destroy(app.monkeyMesh.indexBuffer);
engine->destroy(app.offscreenColorTexture);
engine->destroy(app.offscreenDepthTexture);
engine->destroy(app.offscreenRenderTarget);
@@ -361,22 +337,43 @@ int main(int argc, char** argv) {
engine->destroy(app.quadMaterial);
};
auto preRender = [&app](Engine* engine, View* view, Scene*, Renderer* renderer) {
auto preRender = [&app](Engine*, View*, Scene*, Renderer* renderer) {
renderer->setClearOptions({.clearColor = {0.1,0.2,0.4,1.0}, .clear = true});
};
utils::slog.e <<"offscreen view=" << app.offscreenView << " primary view=" <<
view << utils::io::endl;
FilamentApp::get().animate([&app](Engine* engine, View* view, double now) {
auto& tcm = engine->getTransformManager();
// Animate the monkey by spinning and sliding back and forth along Z.
auto ti = tcm.getInstance(app.monkeyMesh.renderable);
mat4f xlate = mat4f::translation(float3(0, 0, 0.5 + sin(now)));
mat4f xform = app.transform * xlate * mat4f::rotation(now, float3{ 0, 1, 0 });
tcm.setTransform(ti, xform);
// Generate a reflection matrix from the plane equation Ax + By + Cz + D = 0.
const float3 planeNormal = app.quadNormal;
const float4 planeEquation(planeNormal, -dot(planeNormal, app.quadCenter));
const mat4f reflection = reflectionMatrix(planeEquation);
// Apply the reflection matrix to either the renderable or the camera, depending on mode.
Camera const& camera = view->getCamera();
const auto model = camera.getModelMatrix();
const auto renderingProjection = camera.getProjectionMatrix();
const auto cullingProjection = camera.getCullingProjectionMatrix();
app.offscreenCamera->setCustomProjection(renderingProjection, cullingProjection,
camera.getNear(), camera.getCullingFar());
const auto model = camera.getModelMatrix();
app.offscreenCamera->setModelMatrix(model);
};
switch (app.mode) {
case App::ReflectionMode::RENDERABLES:
tcm.setTransform(tcm.getInstance(app.reflectedMonkey), reflection * xform);
app.offscreenCamera->setModelMatrix(model);
break;
case App::ReflectionMode::CAMERA:
app.offscreenCamera->setModelMatrix(reflection * model);
break;
}
});
FilamentApp::get().run(app.config, setup, cleanup, gui, preRender);
FilamentApp::get().run(app.config, setup, cleanup, FilamentApp::ImGuiCallback(), preRender);
return 0;
}