Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce4199b5f7 |
@@ -31,7 +31,7 @@ repositories {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation 'com.google.android.filament:filament-android:1.54.1'
|
||||
implementation 'com.google.android.filament:filament-android:1.54.0'
|
||||
}
|
||||
```
|
||||
|
||||
@@ -51,7 +51,7 @@ Here are all the libraries available in the group `com.google.android.filament`:
|
||||
iOS projects can use CocoaPods to install the latest release:
|
||||
|
||||
```shell
|
||||
pod 'Filament', '~> 1.54.1'
|
||||
pod 'Filament', '~> 1.54.0'
|
||||
```
|
||||
|
||||
### Snapshots
|
||||
|
||||
@@ -7,10 +7,6 @@ A new header is inserted each time a *tag* is created.
|
||||
Instead, if you are authoring a PR for the main branch, add your release note to
|
||||
[NEW_RELEASE_NOTES.md](./NEW_RELEASE_NOTES.md).
|
||||
|
||||
## v1.54.2
|
||||
|
||||
- Add a `name` API to Filament objects for debugging handle use-after-free assertions
|
||||
|
||||
## v1.54.1
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
GROUP=com.google.android.filament
|
||||
VERSION_NAME=1.54.1
|
||||
VERSION_NAME=1.54.0
|
||||
|
||||
POM_DESCRIPTION=Real-time physically based rendering engine for Android.
|
||||
|
||||
|
||||
+2
-11
@@ -1308,12 +1308,7 @@ Description
|
||||
declare a variable called `eyeDirection` you can access it in the fragment shader using
|
||||
`variable_eyeDirection`. In the vertex shader, the interpolant name is simply a member of
|
||||
the `MaterialVertexInputs` structure (`material.eyeDirection` in your example). Each
|
||||
interpolant is of type `float4` (`vec4`) in the shaders. By default the precision of the
|
||||
interpolant is `highp` in *both* the vertex and fragment shaders.
|
||||
An alternate syntax can be used to specify both the name and precision of the interpolant.
|
||||
In this case the specified precision is used as-is in both fragment and vertex stages, in
|
||||
particular if `default` is specified the default precision is used is the fragment shader
|
||||
(`mediump`) and in the vertex shader (`highp`).
|
||||
interpolant is of type `float4` (`vec4`) in the shaders.
|
||||
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ JSON
|
||||
material {
|
||||
@@ -1325,11 +1320,7 @@ material {
|
||||
}
|
||||
],
|
||||
variables : [
|
||||
eyeDirection,
|
||||
{
|
||||
name : eyeColor,
|
||||
precision : medium
|
||||
}
|
||||
eyeDirection
|
||||
],
|
||||
vertexDomain : device,
|
||||
depthWrite : false,
|
||||
|
||||
@@ -61,7 +61,6 @@ set(SRCS
|
||||
src/Engine.cpp
|
||||
src/Exposure.cpp
|
||||
src/Fence.cpp
|
||||
src/FilamentBuilder.cpp
|
||||
src/FrameInfo.cpp
|
||||
src/FrameSkipper.cpp
|
||||
src/Froxelizer.cpp
|
||||
|
||||
@@ -1058,7 +1058,7 @@ struct RasterState {
|
||||
bool inverseFrontFaces : 1; // 31
|
||||
|
||||
//! padding, must be 0
|
||||
uint8_t padding : 1; // 32
|
||||
bool depthClamp : 1; // 32
|
||||
};
|
||||
uint32_t u = 0;
|
||||
};
|
||||
|
||||
@@ -162,10 +162,6 @@ DECL_DRIVER_API_0(finish)
|
||||
// reset state tracking, if the driver does any state tracking (e.g. GL)
|
||||
DECL_DRIVER_API_0(resetState)
|
||||
|
||||
DECL_DRIVER_API_N(setDebugTag,
|
||||
backend::HandleBase::HandleId, handleId,
|
||||
utils::CString, tag)
|
||||
|
||||
/*
|
||||
* Creating driver objects
|
||||
* -----------------------
|
||||
@@ -309,6 +305,7 @@ DECL_DRIVER_API_SYNCHRONOUS_0(bool, isParallelShaderCompileSupported)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(bool, isDepthStencilResolveSupported)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_N(bool, isDepthStencilBlitSupported, backend::TextureFormat, format)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(bool, isProtectedTexturesSupported)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(bool, isDepthClampSupported)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(uint8_t, getMaxDrawBuffers)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(size_t, getMaxUniformBufferSize)
|
||||
DECL_DRIVER_API_SYNCHRONOUS_0(math::float2, getClipSpaceParams)
|
||||
|
||||
@@ -20,12 +20,11 @@
|
||||
#include <backend/Handle.h>
|
||||
|
||||
#include <utils/Allocator.h>
|
||||
#include <utils/CString.h>
|
||||
#include <utils/Log.h>
|
||||
#include <utils/Panic.h>
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/debug.h>
|
||||
#include <utils/ostream.h>
|
||||
#include <utils/Panic.h>
|
||||
|
||||
#include <tsl/robin_map.h>
|
||||
|
||||
@@ -174,10 +173,8 @@ public:
|
||||
uint8_t const age = (tag & HANDLE_AGE_MASK) >> HANDLE_AGE_SHIFT;
|
||||
auto const pNode = static_cast<typename Allocator::Node*>(p);
|
||||
uint8_t const expectedAge = pNode[-1].age;
|
||||
// getHandleTag() is only called if the check fails.
|
||||
FILAMENT_CHECK_POSTCONDITION(expectedAge == age)
|
||||
<< "use-after-free of Handle with id=" << handle.getId()
|
||||
<< ", tag=" << getHandleTag(handle.getId()).c_str_safe();
|
||||
FILAMENT_CHECK_POSTCONDITION(expectedAge == age) <<
|
||||
"use-after-free of Handle with id=" << handle.getId();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,34 +201,6 @@ public:
|
||||
return handle_cast<Dp>(const_cast<Handle<B>&>(handle));
|
||||
}
|
||||
|
||||
void associateTagToHandle(HandleBase::HandleId id, utils::CString&& tag) noexcept {
|
||||
// TODO: for now, only pool handles check for use-after-free, so we only keep tags for
|
||||
// those
|
||||
if (isPoolHandle(id)) {
|
||||
// Truncate the tag's age to N bits.
|
||||
constexpr uint8_t N = 2; // support a history of 4 tags
|
||||
constexpr uint8_t mask = (1 << N) - 1;
|
||||
|
||||
uint8_t const age = (id & HANDLE_AGE_MASK) >> HANDLE_AGE_SHIFT;
|
||||
uint8_t const newAge = age & mask;
|
||||
uint32_t const key = (id & ~HANDLE_AGE_MASK) | (newAge << HANDLE_AGE_SHIFT);
|
||||
|
||||
// This line is the costly part. In the future, we could potentially use a custom
|
||||
// allocator.
|
||||
mDebugTags[key] = std::move(tag);
|
||||
}
|
||||
}
|
||||
|
||||
utils::CString getHandleTag(HandleBase::HandleId id) const noexcept {
|
||||
if (!isPoolHandle(id)) {
|
||||
return "(no tag)";
|
||||
}
|
||||
if (auto pos = mDebugTags.find(id); pos != mDebugTags.end()) {
|
||||
return pos->second;
|
||||
}
|
||||
return "(no tag)";
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
template<typename D>
|
||||
@@ -394,7 +363,6 @@ private:
|
||||
// Below is only used when running out of space in the HandleArena
|
||||
mutable utils::Mutex mLock;
|
||||
tsl::robin_map<HandleBase::HandleId, void*> mOverflowMap;
|
||||
tsl::robin_map<HandleBase::HandleId, utils::CString> mDebugTags;
|
||||
HandleBase::HandleId mId = 0;
|
||||
bool mUseAfterFreeCheckDisabled = false;
|
||||
};
|
||||
|
||||
@@ -80,9 +80,6 @@ HandleAllocator<P0, P1, P2>::HandleAllocator(const char* name, size_t size,
|
||||
bool disableUseAfterFreeCheck) noexcept
|
||||
: mHandleArena(name, size, disableUseAfterFreeCheck),
|
||||
mUseAfterFreeCheckDisabled(disableUseAfterFreeCheck) {
|
||||
// Reserve initial space for debug tags. This prevents excessive calls to malloc when the first
|
||||
// few tags are set.
|
||||
mDebugTags.reserve(512);
|
||||
}
|
||||
|
||||
template <size_t P0, size_t P1, size_t P2>
|
||||
|
||||
@@ -160,8 +160,6 @@ public:
|
||||
size_t size, bool forceGpuBuffer = false);
|
||||
~MetalBuffer();
|
||||
|
||||
[[nodiscard]] bool wasAllocationSuccessful() const noexcept { return mBuffer || mCpuBuffer; }
|
||||
|
||||
MetalBuffer(const MetalBuffer& rhs) = delete;
|
||||
MetalBuffer& operator=(const MetalBuffer& rhs) = delete;
|
||||
|
||||
|
||||
@@ -53,8 +53,8 @@ MetalBuffer::MetalBuffer(MetalContext& context, BufferObjectBinding bindingType,
|
||||
mBuffer = { [context.device newBufferWithLength:size options:MTLResourceStorageModePrivate],
|
||||
TrackedMetalBuffer::Type::GENERIC };
|
||||
}
|
||||
// mBuffer might fail to be allocated. Clients can check for this by calling
|
||||
// wasAllocationSuccessful().
|
||||
FILAMENT_CHECK_POSTCONDITION(mBuffer)
|
||||
<< "Could not allocate Metal buffer of size " << size << ".";
|
||||
}
|
||||
|
||||
MetalBuffer::~MetalBuffer() {
|
||||
|
||||
@@ -112,6 +112,7 @@ struct MetalContext {
|
||||
std::array<BufferState, MAX_SSBO_COUNT> ssboState;
|
||||
CullModeStateTracker cullModeState;
|
||||
WindingStateTracker windingState;
|
||||
DepthClampStateTracker depthClampState;
|
||||
Handle<HwRenderPrimitive> currentRenderPrimitive;
|
||||
|
||||
// State caches.
|
||||
|
||||
@@ -57,6 +57,7 @@ class MetalDriver final : public DriverBase {
|
||||
|
||||
public:
|
||||
static Driver* create(MetalPlatform* platform, const Platform::DriverConfig& driverConfig);
|
||||
void runAtNextTick(const std::function<void()>& fn) noexcept;
|
||||
|
||||
private:
|
||||
|
||||
@@ -72,12 +73,10 @@ private:
|
||||
|
||||
/*
|
||||
* Tasks run regularly on the driver thread.
|
||||
* Not thread-safe; tasks are run from the driver thead and must be enqueued from the driver
|
||||
* thread.
|
||||
*/
|
||||
void runAtNextTick(const std::function<void()>& fn) noexcept;
|
||||
void executeTickOps() noexcept;
|
||||
std::vector<std::function<void()>> mTickOps;
|
||||
std::mutex mTickOpsLock;
|
||||
|
||||
/*
|
||||
* Driver interface
|
||||
|
||||
@@ -320,40 +320,17 @@ void MetalDriver::createVertexBufferR(Handle<HwVertexBuffer> vbh,
|
||||
uint32_t vertexCount, Handle<HwVertexBufferInfo> vbih) {
|
||||
MetalVertexBufferInfo const* const vbi = handle_cast<const MetalVertexBufferInfo>(vbih);
|
||||
construct_handle<MetalVertexBuffer>(vbh, *mContext, vertexCount, vbi->bufferCount, vbih);
|
||||
// No actual GPU memory is allocated here, so no need to check for allocation success.
|
||||
}
|
||||
|
||||
void MetalDriver::createIndexBufferR(Handle<HwIndexBuffer> ibh, ElementType elementType,
|
||||
uint32_t indexCount, BufferUsage usage) {
|
||||
auto elementSize = (uint8_t)getElementTypeSize(elementType);
|
||||
auto* indexBuffer =
|
||||
construct_handle<MetalIndexBuffer>(ibh, *mContext, usage, elementSize, indexCount);
|
||||
auto& buffer = indexBuffer->buffer;
|
||||
// If the allocation was not successful, postpone the error message until the next tick, to give
|
||||
// Filament a chance to call setDebugTag on the handle; this way we get a nicer error message.
|
||||
if (UTILS_UNLIKELY(!buffer.wasAllocationSuccessful())) {
|
||||
const size_t byteCount = buffer.getSize();
|
||||
runAtNextTick([byteCount, this, ibh]() {
|
||||
FILAMENT_CHECK_POSTCONDITION(false)
|
||||
<< "Could not allocate Metal index buffer of size " << byteCount
|
||||
<< ", tag=" << mHandleAllocator.getHandleTag(ibh.getId()).c_str_safe();
|
||||
});
|
||||
}
|
||||
auto elementSize = (uint8_t) getElementTypeSize(elementType);
|
||||
construct_handle<MetalIndexBuffer>(ibh, *mContext, usage, elementSize, indexCount);
|
||||
}
|
||||
|
||||
void MetalDriver::createBufferObjectR(Handle<HwBufferObject> boh, uint32_t byteCount,
|
||||
BufferObjectBinding bindingType, BufferUsage usage) {
|
||||
auto* bufferObject =
|
||||
construct_handle<MetalBufferObject>(boh, *mContext, bindingType, usage, byteCount);
|
||||
// If the allocation was not successful, postpone the error message until the next tick, to give
|
||||
// Filament a chance to call setDebugTag on the handle; this way we get a nicer error message.
|
||||
if (UTILS_UNLIKELY(!bufferObject->getBuffer()->wasAllocationSuccessful())) {
|
||||
runAtNextTick([byteCount, this, boh]() {
|
||||
FILAMENT_CHECK_POSTCONDITION(false)
|
||||
<< "Could not allocate Metal buffer of size " << byteCount
|
||||
<< ", tag=" << mHandleAllocator.getHandleTag(boh.getId()).c_str_safe();
|
||||
});
|
||||
}
|
||||
construct_handle<MetalBufferObject>(boh, *mContext, bindingType, usage, byteCount);
|
||||
}
|
||||
|
||||
void MetalDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint8_t levels,
|
||||
@@ -857,6 +834,10 @@ bool MetalDriver::isProtectedTexturesSupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MetalDriver::isDepthClampSupported() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MetalDriver::isWorkaroundNeeded(Workaround workaround) {
|
||||
switch (workaround) {
|
||||
case Workaround::SPLIT_EASU:
|
||||
@@ -1774,6 +1755,13 @@ void MetalDriver::bindPipeline(PipelineState const& ps) {
|
||||
[mContext->currentRenderPassEncoder setFrontFacingWinding:winding];
|
||||
}
|
||||
|
||||
// depth clip mode
|
||||
MTLDepthClipMode depthClipMode = rs.depthClamp ? MTLDepthClipModeClamp : MTLDepthClipModeClip;
|
||||
mContext->depthClampState.updateState(depthClipMode);
|
||||
if (mContext->depthClampState.stateChanged()) {
|
||||
[mContext->currentRenderPassEncoder setDepthClipMode:depthClipMode];
|
||||
}
|
||||
|
||||
// Set the depth-stencil state, if a state change is needed.
|
||||
DepthStencilState depthState;
|
||||
if (depthAttachment) {
|
||||
@@ -2084,17 +2072,16 @@ void MetalDriver::enumerateBoundBuffers(BufferObjectBinding bindingType,
|
||||
void MetalDriver::resetState(int) {
|
||||
}
|
||||
|
||||
void MetalDriver::setDebugTag(HandleBase::HandleId handleId, utils::CString tag) {
|
||||
mHandleAllocator.associateTagToHandle(handleId, std::move(tag));
|
||||
}
|
||||
|
||||
void MetalDriver::runAtNextTick(const std::function<void()>& fn) noexcept {
|
||||
std::lock_guard<std::mutex> const lock(mTickOpsLock);
|
||||
mTickOps.push_back(fn);
|
||||
}
|
||||
|
||||
void MetalDriver::executeTickOps() noexcept {
|
||||
std::vector<std::function<void()>> ops;
|
||||
mTickOpsLock.lock();
|
||||
std::swap(ops, mTickOps);
|
||||
mTickOpsLock.unlock();
|
||||
for (const auto& f : ops) {
|
||||
f();
|
||||
}
|
||||
|
||||
@@ -257,6 +257,10 @@ void MetalSwapChain::present() {
|
||||
}
|
||||
}
|
||||
|
||||
#ifndef FILAMENT_RELEASE_PRESENT_DRAWABLE_MAIN_THREAD
|
||||
#define FILAMENT_RELEASE_PRESENT_DRAWABLE_MAIN_THREAD 1
|
||||
#endif
|
||||
|
||||
class PresentDrawableData {
|
||||
public:
|
||||
PresentDrawableData() = delete;
|
||||
@@ -275,10 +279,14 @@ public:
|
||||
[that->mDrawable present];
|
||||
}
|
||||
|
||||
#if FILAMENT_RELEASE_PRESENT_DRAWABLE_MAIN_THREAD == 1
|
||||
// mDrawable is acquired on the driver thread. Typically, we would release this object on
|
||||
// the same thread, but after receiving consistent crash reports from within
|
||||
// [CAMetalDrawable dealloc], we suspect this object requires releasing on the main thread.
|
||||
dispatch_async(dispatch_get_main_queue(), ^{ cleanupAndDestroy(that); });
|
||||
#else
|
||||
that->mDriver->runAtNextTick([that]() { cleanupAndDestroy(that); });
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@@ -382,6 +382,7 @@ using SamplerStateCache = StateCache<SamplerState, id<MTLSamplerState>, SamplerS
|
||||
|
||||
using CullModeStateTracker = StateTracker<MTLCullMode>;
|
||||
using WindingStateTracker = StateTracker<MTLWinding>;
|
||||
using DepthClampStateTracker = StateTracker<MTLDepthClipMode>;
|
||||
|
||||
// Argument encoder
|
||||
|
||||
|
||||
@@ -202,6 +202,10 @@ bool NoopDriver::isProtectedTexturesSupported() {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NoopDriver::isDepthClampSupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool NoopDriver::isWorkaroundNeeded(Workaround) {
|
||||
return false;
|
||||
}
|
||||
@@ -388,7 +392,4 @@ void NoopDriver::endTimerQuery(Handle<HwTimerQuery> tqh) {
|
||||
void NoopDriver::resetState(int) {
|
||||
}
|
||||
|
||||
void NoopDriver::setDebugTag(HandleBase::HandleId handleId, utils::CString tag) {
|
||||
}
|
||||
|
||||
} // namespace filament
|
||||
|
||||
@@ -676,6 +676,7 @@ void OpenGLContext::initExtensionsGLES(Extensions* ext, GLint major, GLint minor
|
||||
#ifndef __EMSCRIPTEN__
|
||||
ext->EXT_debug_marker = exts.has("GL_EXT_debug_marker"sv);
|
||||
#endif
|
||||
ext->EXT_depth_clamp = exts.has("GL_EXT_depth_clamp"sv);
|
||||
ext->EXT_discard_framebuffer = exts.has("GL_EXT_discard_framebuffer"sv);
|
||||
#ifndef __EMSCRIPTEN__
|
||||
ext->EXT_disjoint_timer_query = exts.has("GL_EXT_disjoint_timer_query"sv);
|
||||
@@ -746,6 +747,7 @@ void OpenGLContext::initExtensionsGL(Extensions* ext, GLint major, GLint minor)
|
||||
ext->EXT_color_buffer_half_float = true; // Assumes core profile.
|
||||
ext->EXT_clip_cull_distance = true;
|
||||
ext->EXT_debug_marker = exts.has("GL_EXT_debug_marker"sv);
|
||||
ext->EXT_depth_clamp = true;
|
||||
ext->EXT_discard_framebuffer = false;
|
||||
ext->EXT_disjoint_timer_query = true;
|
||||
ext->EXT_multisampled_render_to_texture = false;
|
||||
|
||||
@@ -220,8 +220,9 @@ public:
|
||||
bool EXT_color_buffer_float;
|
||||
bool EXT_color_buffer_half_float;
|
||||
bool EXT_debug_marker;
|
||||
bool EXT_disjoint_timer_query;
|
||||
bool EXT_depth_clamp;
|
||||
bool EXT_discard_framebuffer;
|
||||
bool EXT_disjoint_timer_query;
|
||||
bool EXT_multisampled_render_to_texture2;
|
||||
bool EXT_multisampled_render_to_texture;
|
||||
bool EXT_protected_textures;
|
||||
@@ -239,10 +240,10 @@ public:
|
||||
bool KHR_parallel_shader_compile;
|
||||
bool KHR_texture_compression_astc_hdr;
|
||||
bool KHR_texture_compression_astc_ldr;
|
||||
bool OES_depth_texture;
|
||||
bool OES_depth24;
|
||||
bool OES_packed_depth_stencil;
|
||||
bool OES_EGL_image_external_essl3;
|
||||
bool OES_depth24;
|
||||
bool OES_depth_texture;
|
||||
bool OES_packed_depth_stencil;
|
||||
bool OES_rgb8_rgba8;
|
||||
bool OES_standard_derivatives;
|
||||
bool OES_texture_npot;
|
||||
@@ -627,6 +628,7 @@ constexpr size_t OpenGLContext::getIndexForCap(GLenum cap) noexcept { //NOLINT
|
||||
#ifdef BACKEND_OPENGL_VERSION_GL
|
||||
case GL_PROGRAM_POINT_SIZE: index = 10; break;
|
||||
#endif
|
||||
case GL_DEPTH_CLAMP: index = 11; break;
|
||||
default: break;
|
||||
}
|
||||
assert_invariant(index < state.enables.caps.size());
|
||||
|
||||
@@ -451,6 +451,14 @@ void OpenGLDriver::setRasterState(RasterState rs) noexcept {
|
||||
} else {
|
||||
gl.disable(GL_SAMPLE_ALPHA_TO_COVERAGE);
|
||||
}
|
||||
|
||||
if (gl.ext.EXT_depth_clamp) {
|
||||
if (rs.depthClamp) {
|
||||
gl.enable(GL_DEPTH_CLAMP);
|
||||
} else {
|
||||
gl.disable(GL_DEPTH_CLAMP);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void OpenGLDriver::setStencilState(StencilState ss) noexcept {
|
||||
@@ -2119,6 +2127,10 @@ bool OpenGLDriver::isProtectedTexturesSupported() {
|
||||
return getContext().ext.EXT_protected_textures;
|
||||
}
|
||||
|
||||
bool OpenGLDriver::isDepthClampSupported() {
|
||||
return getContext().ext.EXT_depth_clamp;
|
||||
}
|
||||
|
||||
bool OpenGLDriver::isWorkaroundNeeded(Workaround workaround) {
|
||||
switch (workaround) {
|
||||
case Workaround::SPLIT_EASU:
|
||||
@@ -2210,10 +2222,6 @@ void OpenGLDriver::makeCurrent(Handle<HwSwapChain> schDraw, Handle<HwSwapChain>
|
||||
// Updating driver objects
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
void OpenGLDriver::setDebugTag(HandleBase::HandleId handleId, utils::CString tag) {
|
||||
mHandleAllocator.associateTagToHandle(handleId, std::move(tag));
|
||||
}
|
||||
|
||||
void OpenGLDriver::setVertexBufferObject(Handle<HwVertexBuffer> vbh,
|
||||
uint32_t index, Handle<HwBufferObject> boh) {
|
||||
DEBUG_MARKER()
|
||||
|
||||
@@ -201,6 +201,12 @@ using namespace glext;
|
||||
# define GL_CLIP_DISTANCE1 0x3001
|
||||
#endif
|
||||
|
||||
#if defined(GL_EXT_depth_clamp)
|
||||
# define GL_DEPTH_CLAMP GL_DEPTH_CLAMP_EXT
|
||||
#else
|
||||
# define GL_DEPTH_CLAMP 0x864F
|
||||
#endif
|
||||
|
||||
#if defined(GL_KHR_debug)
|
||||
# define GL_DEBUG_OUTPUT GL_DEBUG_OUTPUT_KHR
|
||||
# define GL_DEBUG_OUTPUT_SYNCHRONOUS GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR
|
||||
|
||||
@@ -165,14 +165,14 @@ constexpr static const int FVK_REQUIRED_VERSION_MINOR = 1;
|
||||
// buffers that have been submitted but have not yet finished rendering. Note that Filament can
|
||||
// issue multiple commit calls in a single frame, and that we use a triple buffered swap chain on
|
||||
// some platforms.
|
||||
constexpr static const int FVK_MAX_COMMAND_BUFFERS = 3;
|
||||
constexpr static const int FVK_MAX_COMMAND_BUFFERS = 10;
|
||||
|
||||
// Number of command buffer submissions that should occur before an unused pipeline is removed
|
||||
// from the cache.
|
||||
//
|
||||
// If this number is low, VkPipeline construction will occur frequently, which can
|
||||
// be extremely slow. If this number is high, the memory footprint will be large.
|
||||
constexpr static const int FVK_MAX_PIPELINE_AGE = 3;
|
||||
constexpr static const int FVK_MAX_PIPELINE_AGE = 10;
|
||||
|
||||
// VulkanPipelineCache does not track which command buffers contain references to which pipelines,
|
||||
// instead it simply waits for at least FVK_MAX_COMMAND_BUFFERS submissions to occur before
|
||||
|
||||
@@ -125,6 +125,10 @@ public:
|
||||
return mPhysicalDeviceFeatures.imageCubeArray == VK_TRUE;
|
||||
}
|
||||
|
||||
inline bool isDepthClampSupported() const noexcept {
|
||||
return mPhysicalDeviceFeatures.depthClamp == VK_TRUE;
|
||||
}
|
||||
|
||||
inline bool isDebugMarkersSupported() const noexcept {
|
||||
return mDebugMarkersSupported;
|
||||
}
|
||||
|
||||
@@ -530,8 +530,6 @@ void VulkanDriver::createTextureR(Handle<HwTexture> th, SamplerType target, uint
|
||||
auto vktexture = mResourceAllocator.construct<VulkanTexture>(th, mPlatform->getDevice(),
|
||||
mPlatform->getPhysicalDevice(), mContext, mAllocator, &mCommands, target, levels,
|
||||
format, samples, w, h, depth, usage, mStagePool);
|
||||
// FVK_LOGE <<"created texture: " << vktexture->getVkImage() << " dim=" <<
|
||||
// vktexture->width << "x" << vktexture->height << utils::io::endl;
|
||||
mResourceManager.acquire(vktexture);
|
||||
}
|
||||
|
||||
@@ -946,6 +944,10 @@ bool VulkanDriver::isProtectedTexturesSupported() {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool VulkanDriver::isDepthClampSupported() {
|
||||
return mContext.isDepthClampSupported();
|
||||
}
|
||||
|
||||
bool VulkanDriver::isWorkaroundNeeded(Workaround workaround) {
|
||||
switch (workaround) {
|
||||
case Workaround::SPLIT_EASU: {
|
||||
@@ -1818,6 +1820,8 @@ void VulkanDriver::bindPipeline(PipelineState const& pipelineState) {
|
||||
.dstAlphaBlendFactor = getBlendFactor(rasterState.blendFunctionDstAlpha),
|
||||
.colorWriteMask = (VkColorComponentFlags) (rasterState.colorWrite ? 0xf : 0x0),
|
||||
.rasterizationSamples = rt->getSamples(),
|
||||
.depthClamp = rasterState.depthClamp,
|
||||
.reserved = 0,
|
||||
.colorTargetCount = rt->getColorTargetCount(mCurrentRenderPass),
|
||||
.colorBlendOp = rasterState.blendEquationRGB,
|
||||
.alphaBlendOp = rasterState.blendEquationAlpha,
|
||||
@@ -2034,10 +2038,6 @@ void VulkanDriver::debugCommandBegin(CommandStream* cmds, bool synchronous, cons
|
||||
void VulkanDriver::resetState(int) {
|
||||
}
|
||||
|
||||
void VulkanDriver::setDebugTag(HandleBase::HandleId handleId, utils::CString tag) {
|
||||
mResourceAllocator.associateHandle(handleId, std::move(tag));
|
||||
}
|
||||
|
||||
// explicit instantiation of the Dispatcher
|
||||
template class ConcreteDispatcher<VulkanDriver>;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
#include "VulkanHandles.h"
|
||||
|
||||
#include "VulkanDriver.h"
|
||||
#include "VulkanConstants.h"
|
||||
#include "VulkanDriver.h"
|
||||
#include "VulkanMemory.h"
|
||||
|
||||
@@ -184,6 +184,7 @@ VulkanPipelineCache::PipelineCacheEntry* VulkanPipelineCache::createPipeline() n
|
||||
vkRaster.polygonMode = VK_POLYGON_MODE_FILL;
|
||||
vkRaster.cullMode = raster.cullMode;
|
||||
vkRaster.frontFace = raster.frontFace;
|
||||
vkRaster.depthClampEnable = raster.depthClamp;
|
||||
vkRaster.depthBiasEnable = raster.depthBiasEnable;
|
||||
vkRaster.depthBiasConstantFactor = raster.depthBiasConstantFactor;
|
||||
vkRaster.depthBiasClamp = 0.0f;
|
||||
|
||||
@@ -90,7 +90,9 @@ public:
|
||||
VkBlendFactor srcAlphaBlendFactor : 5;
|
||||
VkBlendFactor dstAlphaBlendFactor : 5;
|
||||
VkColorComponentFlags colorWriteMask : 4;
|
||||
uint8_t rasterizationSamples; // offset = 4 bytes
|
||||
uint8_t rasterizationSamples : 4;// offset = 4 bytes
|
||||
uint8_t depthClamp : 1;
|
||||
uint8_t reserved : 3;
|
||||
uint8_t colorTargetCount; // offset = 5 bytes
|
||||
BlendEquation colorBlendOp : 4; // offset = 6 bytes
|
||||
BlendEquation alphaBlendOp : 4;
|
||||
|
||||
@@ -105,10 +105,6 @@ public:
|
||||
mHandleAllocatorImpl.deallocate(handle, obj);
|
||||
}
|
||||
|
||||
inline void associateHandle(HandleBase::HandleId id, utils::CString&& tag) noexcept {
|
||||
mHandleAllocatorImpl.associateTagToHandle(id, std::move(tag));
|
||||
}
|
||||
|
||||
private:
|
||||
AllocatorImpl mHandleAllocatorImpl;
|
||||
|
||||
|
||||
@@ -97,11 +97,13 @@ VulkanTexture::VulkanTexture(VkDevice device, VkPhysicalDevice physicalDevice,
|
||||
imageInfo.extent.depth = 1;
|
||||
}
|
||||
|
||||
if (any(usage & TextureUsage::BLIT_SRC)) {
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
|
||||
}
|
||||
if (any(usage & TextureUsage::BLIT_DST)) {
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
// Filament expects blit() to work with any texture, so we almost always set these usage flags.
|
||||
// TODO: investigate performance implications of setting these flags.
|
||||
constexpr VkImageUsageFlags blittable = VK_IMAGE_USAGE_TRANSFER_DST_BIT |
|
||||
VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
|
||||
|
||||
if (any(usage & (TextureUsage::BLIT_DST | TextureUsage::BLIT_SRC))) {
|
||||
imageInfo.usage |= blittable;
|
||||
}
|
||||
|
||||
if (any(usage & TextureUsage::SAMPLEABLE)) {
|
||||
@@ -119,7 +121,7 @@ VulkanTexture::VulkanTexture(VkDevice device, VkPhysicalDevice physicalDevice,
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_SAMPLED_BIT;
|
||||
}
|
||||
if (any(usage & TextureUsage::COLOR_ATTACHMENT)) {
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | blittable;
|
||||
if (any(usage & TextureUsage::SUBPASS_INPUT)) {
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
|
||||
}
|
||||
@@ -128,9 +130,10 @@ VulkanTexture::VulkanTexture(VkDevice device, VkPhysicalDevice physicalDevice,
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
|
||||
}
|
||||
if (any(usage & TextureUsage::UPLOADABLE)) {
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_TRANSFER_DST_BIT;
|
||||
imageInfo.usage |= blittable;
|
||||
}
|
||||
if (any(usage & TextureUsage::DEPTH_ATTACHMENT)) {
|
||||
imageInfo.usage |= blittable;
|
||||
imageInfo.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
|
||||
|
||||
// Depth resolves uses a custom shader and therefore needs to be sampleable.
|
||||
|
||||
@@ -325,6 +325,7 @@ VkDevice createLogicalDevice(VkPhysicalDevice physicalDevice,
|
||||
// We could simply enable all supported features, but since that may have performance
|
||||
// consequences let's just enable the features we need.
|
||||
VkPhysicalDeviceFeatures enabledFeatures{
|
||||
.depthClamp = features.depthClamp,
|
||||
.samplerAnisotropy = features.samplerAnisotropy,
|
||||
.textureCompressionETC2 = features.textureCompressionETC2,
|
||||
.textureCompressionBC = features.textureCompressionBC,
|
||||
|
||||
@@ -54,7 +54,7 @@ public:
|
||||
using BufferDescriptor = backend::BufferDescriptor;
|
||||
using BindingType = backend::BufferObjectBinding;
|
||||
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -78,21 +78,6 @@ public:
|
||||
*/
|
||||
Builder& bindingType(BindingType bindingType) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this BufferObject for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this BufferObject
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
// Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept; // inherited
|
||||
|
||||
/**
|
||||
* Creates the BufferObject and returns a pointer to it. After creation, the buffer
|
||||
* object is uninitialized. Use BufferObject::setBuffer() to initialize it.
|
||||
|
||||
@@ -19,7 +19,6 @@
|
||||
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/PrivateImplementation.h>
|
||||
#include <utils/CString.h>
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
@@ -55,22 +54,6 @@ public:
|
||||
template<typename T>
|
||||
using BuilderBase = utils::PrivateImplementation<T>;
|
||||
|
||||
void builderMakeName(utils::CString& outName, const char* name, size_t len) noexcept;
|
||||
|
||||
template <typename Builder>
|
||||
class UTILS_PUBLIC BuilderNameMixin {
|
||||
public:
|
||||
Builder& name(const char* name, size_t len) noexcept {
|
||||
builderMakeName(mName, name, len);
|
||||
return static_cast<Builder&>(*this);
|
||||
}
|
||||
|
||||
utils::CString const& getName() const noexcept { return mName; }
|
||||
|
||||
private:
|
||||
utils::CString mName;
|
||||
};
|
||||
|
||||
} // namespace filament
|
||||
|
||||
#endif // TNT_FILAMENT_FILAMENTAPI_H
|
||||
|
||||
@@ -59,7 +59,7 @@ public:
|
||||
UINT = uint8_t(backend::ElementType::UINT), //!< 32-bit indices
|
||||
};
|
||||
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -83,21 +83,6 @@ public:
|
||||
*/
|
||||
Builder& bufferType(IndexType indexType) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this IndexBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this IndexBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
// Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept; // inherited
|
||||
|
||||
/**
|
||||
* Creates the IndexBuffer object and returns a pointer to it. After creation, the index
|
||||
* buffer is uninitialized. Use IndexBuffer::setBuffer() to initialize the IndexBuffer.
|
||||
|
||||
@@ -38,7 +38,7 @@ class UTILS_PUBLIC InstanceBuffer : public FilamentAPI {
|
||||
struct BuilderDetails;
|
||||
|
||||
public:
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
friend struct BuilderDetails;
|
||||
|
||||
public:
|
||||
@@ -70,21 +70,6 @@ public:
|
||||
*/
|
||||
Builder& localTransforms(math::mat4f const* UTILS_NULLABLE localTransforms) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this InstanceBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this InstanceBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
// Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept; // inherited
|
||||
|
||||
/**
|
||||
* Creates the InstanceBuffer object and returns a pointer to it.
|
||||
*/
|
||||
|
||||
@@ -39,7 +39,7 @@ class UTILS_PUBLIC MorphTargetBuffer : public FilamentAPI {
|
||||
struct BuilderDetails;
|
||||
|
||||
public:
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -63,21 +63,6 @@ public:
|
||||
*/
|
||||
Builder& count(size_t count) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this MorphTargetBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this MorphTargetBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
// Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept; // inherited
|
||||
|
||||
/**
|
||||
* Creates the MorphTargetBuffer object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -39,7 +39,7 @@ class UTILS_PUBLIC SkinningBuffer : public FilamentAPI {
|
||||
struct BuilderDetails;
|
||||
|
||||
public:
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -69,21 +69,6 @@ public:
|
||||
*/
|
||||
Builder& initialize(bool initialize = true) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this SkinningBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this SkinningBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
// Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept; // inherited
|
||||
|
||||
/**
|
||||
* Creates the SkinningBuffer object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -94,7 +94,7 @@ public:
|
||||
*
|
||||
* To create a NATIVE stream, call the <pre>stream</pre> method on the builder.
|
||||
*/
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -136,21 +136,6 @@ public:
|
||||
*/
|
||||
Builder& height(uint32_t height) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this Stream for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this Stream
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
// Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept; // inherited
|
||||
|
||||
/**
|
||||
* Creates the Stream object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -112,7 +112,7 @@ public:
|
||||
|
||||
|
||||
//! Use Builder to construct a Texture object instance
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -202,21 +202,6 @@ public:
|
||||
*/
|
||||
Builder& swizzle(Swizzle r, Swizzle g, Swizzle b, Swizzle a) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this Texture for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this Texture
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
// Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept; // inherited
|
||||
|
||||
/**
|
||||
* Creates the Texture object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -61,7 +61,7 @@ public:
|
||||
using AttributeType = backend::ElementType;
|
||||
using BufferDescriptor = backend::BufferDescriptor;
|
||||
|
||||
class Builder : public BuilderBase<BuilderDetails>, public BuilderNameMixin<Builder> {
|
||||
class Builder : public BuilderBase<BuilderDetails> {
|
||||
friend struct BuilderDetails;
|
||||
public:
|
||||
Builder() noexcept;
|
||||
@@ -158,21 +158,6 @@ public:
|
||||
*/
|
||||
Builder& advancedSkinning(bool enabled) noexcept;
|
||||
|
||||
/**
|
||||
* Associate an optional name with this VertexBuffer for debugging purposes.
|
||||
*
|
||||
* name will show in error messages and should be kept as short as possible. The name is
|
||||
* truncated to a maximum of 128 characters.
|
||||
*
|
||||
* The name string is copied during this method so clients may free its memory after
|
||||
* the function returns.
|
||||
*
|
||||
* @param name A string to identify this VertexBuffer
|
||||
* @param len Length of name, should be less than or equal to 128
|
||||
* @return This Builder, for chaining calls.
|
||||
*/
|
||||
// Builder& name(const char* UTILS_NONNULL name, size_t len) noexcept; // inherited
|
||||
|
||||
/**
|
||||
* Creates the VertexBuffer object and returns a pointer to it.
|
||||
*
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
/*
|
||||
* Copyright (C) 2024 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <filament/FilamentAPI.h>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace filament {
|
||||
|
||||
void builderMakeName(utils::CString& outName, const char* name, size_t len) noexcept {
|
||||
if (!name) {
|
||||
return;
|
||||
}
|
||||
size_t const length = std::min(len, size_t { 128u });
|
||||
outName = utils::CString(name, length);
|
||||
}
|
||||
|
||||
} // namespace filament
|
||||
@@ -34,6 +34,8 @@
|
||||
|
||||
#include <math/mat4.h>
|
||||
|
||||
#include <utils/Log.h>
|
||||
|
||||
namespace filament {
|
||||
|
||||
using namespace backend;
|
||||
@@ -120,6 +122,8 @@ 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 {
|
||||
|
||||
@@ -2455,18 +2455,24 @@ 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", float4{
|
||||
(float)vp.left / input.width,
|
||||
(float)vp.bottom / input.height,
|
||||
(float)vp.width / input.width,
|
||||
(float)vp.height / input.height
|
||||
});
|
||||
mi->setParameter("viewport", yy);
|
||||
|
||||
utils::slog.e <<"yy------------yy in=" <<
|
||||
input.width << "x" << input.height << " viewport=" << yy << utils::io::endl;
|
||||
|
||||
|
||||
const uint8_t variant = uint8_t(colorGradingConfig.translucent ?
|
||||
PostProcessVariant::TRANSLUCENT : PostProcessVariant::OPAQUE);
|
||||
@@ -2508,6 +2514,17 @@ 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,
|
||||
@@ -2945,10 +2962,6 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::upscale(FrameGraph& fg, bool
|
||||
1.0f / outputDesc.height});
|
||||
}
|
||||
|
||||
if (blitterNames[index] == "blitLow") {
|
||||
mi->setParameter("levelOfDetail", 0.0f);
|
||||
}
|
||||
|
||||
mi->setParameter("viewport", float4{
|
||||
(float)vp.left / inputDesc.width,
|
||||
(float)vp.bottom / inputDesc.height,
|
||||
@@ -3007,8 +3020,9 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::blit(FrameGraph& fg, bool tr
|
||||
SamplerMagFilter filterMag,
|
||||
SamplerMinFilter filterMin) noexcept {
|
||||
|
||||
uint32_t const layer = fg.getSubResourceDescriptor(input).layer;
|
||||
float const levelOfDetail = fg.getSubResourceDescriptor(input).level;
|
||||
// TODO: add support for sub-resources
|
||||
assert_invariant(fg.getSubResourceDescriptor(input).layer == 0);
|
||||
assert_invariant(fg.getSubResourceDescriptor(input).level == 0);
|
||||
|
||||
struct QuadBlitData {
|
||||
FrameGraphId<FrameGraphTexture> input;
|
||||
@@ -3034,8 +3048,7 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::blit(FrameGraph& fg, bool tr
|
||||
// --------------------------------------------------------------------------------
|
||||
// set uniforms
|
||||
|
||||
PostProcessMaterial const& material =
|
||||
getPostProcessMaterial(layer ? "blitArray" : "blitLow");
|
||||
PostProcessMaterial const& material = getPostProcessMaterial("blitLow");
|
||||
auto* mi = material.getMaterialInstance(mEngine);
|
||||
mi->setParameter("color", color, {
|
||||
.filterMag = filterMag,
|
||||
@@ -3047,10 +3060,6 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::blit(FrameGraph& fg, bool tr
|
||||
float(vp.width) / inputDesc.width,
|
||||
float(vp.height) / inputDesc.height
|
||||
});
|
||||
mi->setParameter("levelOfDetail", levelOfDetail);
|
||||
if (layer) {
|
||||
mi->setParameter("layerIndex", layer);
|
||||
}
|
||||
mi->commit(driver);
|
||||
mi->use(driver);
|
||||
|
||||
@@ -3193,7 +3202,6 @@ FrameGraphId<FrameGraphTexture> PostProcessManager::resolve(FrameGraph& fg,
|
||||
assert_invariant(dst);
|
||||
assert_invariant(srcDesc.format == dstDesc.format);
|
||||
assert_invariant(srcDesc.width == dstDesc.width && srcDesc.height == dstDesc.height);
|
||||
assert_invariant(srcDesc.samples > 1 && dstDesc.samples <= 1);
|
||||
driver.resolve(
|
||||
dst, dstSubDesc.level, dstSubDesc.layer,
|
||||
src, srcSubDesc.level, srcSubDesc.layer);
|
||||
|
||||
@@ -419,7 +419,8 @@ RenderPass::Command* RenderPass::instanceify(FEngine& engine,
|
||||
UTILS_ALWAYS_INLINE // This function exists only to make the code more readable. we want it inlined.
|
||||
inline // and we don't need it in the compilation unit
|
||||
void RenderPass::setupColorCommand(Command& cmdDraw, Variant variant,
|
||||
FMaterialInstance const* const UTILS_RESTRICT mi, bool inverseFrontFaces) noexcept {
|
||||
FMaterialInstance const* const UTILS_RESTRICT mi,
|
||||
bool inverseFrontFaces, bool hasDepthClamp) noexcept {
|
||||
|
||||
FMaterial const * const UTILS_RESTRICT ma = mi->getMaterial();
|
||||
variant = Variant::filterVariant(variant, ma->isVariantLit());
|
||||
@@ -460,6 +461,7 @@ void RenderPass::setupColorCommand(Command& cmdDraw, Variant variant,
|
||||
cmdDraw.info.rasterState.colorWrite = mi->isColorWriteEnabled();
|
||||
cmdDraw.info.rasterState.depthWrite = mi->isDepthWriteEnabled();
|
||||
cmdDraw.info.rasterState.depthFunc = mi->getDepthFunc();
|
||||
cmdDraw.info.rasterState.depthClamp = hasDepthClamp;
|
||||
cmdDraw.info.materialVariant = variant;
|
||||
// we keep "RasterState::colorWrite" to the value set by material (could be disabled)
|
||||
}
|
||||
@@ -558,6 +560,9 @@ RenderPass::Command* RenderPass::generateCommandsImpl(RenderPass::CommandTypeFla
|
||||
bool const hasInstancedStereo =
|
||||
renderFlags & IS_INSTANCED_STEREOSCOPIC;
|
||||
|
||||
bool const hasDepthClamp =
|
||||
renderFlags & HAS_DEPTH_CLAMP;
|
||||
|
||||
float const cameraPositionDotCameraForward = dot(cameraPosition, cameraForward);
|
||||
|
||||
auto const* const UTILS_RESTRICT soaWorldAABBCenter = soa.data<FScene::WORLD_AABB_CENTER>();
|
||||
@@ -577,6 +582,7 @@ RenderPass::Command* RenderPass::generateCommandsImpl(RenderPass::CommandTypeFla
|
||||
cmd.info.rasterState.depthWrite = true;
|
||||
cmd.info.rasterState.depthFunc = RasterState::DepthFunc::GE;
|
||||
cmd.info.rasterState.alphaToCoverage = false;
|
||||
cmd.info.rasterState.depthClamp = hasDepthClamp;
|
||||
}
|
||||
|
||||
for (uint32_t i = range.first; i < range.last; ++i) {
|
||||
@@ -691,7 +697,8 @@ RenderPass::Command* RenderPass::generateCommandsImpl(RenderPass::CommandTypeFla
|
||||
cmd.info.morphingOffset = primitive.getMorphingBufferOffset();
|
||||
|
||||
if constexpr (isColorPass) {
|
||||
RenderPass::setupColorCommand(cmd, renderableVariant, mi, inverseFrontFaces);
|
||||
RenderPass::setupColorCommand(cmd, renderableVariant, mi,
|
||||
inverseFrontFaces, hasDepthClamp);
|
||||
const bool blendPass = Pass(cmd.key & PASS_MASK) == Pass::BLENDED;
|
||||
if (blendPass) {
|
||||
// TODO: at least for transparent objects, AABB should be per primitive
|
||||
|
||||
@@ -284,6 +284,7 @@ public:
|
||||
static constexpr RenderFlags HAS_SHADOWING = 0x01;
|
||||
static constexpr RenderFlags HAS_INVERSE_FRONT_FACES = 0x02;
|
||||
static constexpr RenderFlags IS_INSTANCED_STEREOSCOPIC = 0x04;
|
||||
static constexpr RenderFlags HAS_DEPTH_CLAMP = 0x08;
|
||||
|
||||
// Arena used for commands
|
||||
using Arena = utils::Arena<
|
||||
@@ -444,7 +445,7 @@ private:
|
||||
uint8_t instancedStereoEyeCount) noexcept;
|
||||
|
||||
static void setupColorCommand(Command& cmdDraw, Variant variant,
|
||||
FMaterialInstance const* mi, bool inverseFrontFaces) noexcept;
|
||||
FMaterialInstance const* mi, bool inverseFrontFaces, bool hasDepthClamp) noexcept;
|
||||
|
||||
static void updateSummedPrimitiveCounts(
|
||||
FScene::RenderableSoa& renderableData, utils::Range<uint32_t> vr) noexcept;
|
||||
@@ -528,9 +529,7 @@ public:
|
||||
// like above but allows to set specific flags
|
||||
RenderPassBuilder& renderFlags(
|
||||
RenderPass::RenderFlags mask, RenderPass::RenderFlags value) noexcept {
|
||||
value &= mask;
|
||||
mFlags &= ~mask;
|
||||
mFlags |= value;
|
||||
mFlags = (mFlags & mask) | (value & mask);
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +40,6 @@
|
||||
#include <utils/Panic.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
#include <stddef.h>
|
||||
@@ -51,9 +50,8 @@ namespace filament {
|
||||
using namespace backend;
|
||||
using namespace math;
|
||||
|
||||
RendererUtils::ColorPassOutput RendererUtils::colorPass(
|
||||
FrameGraphId<FrameGraphTexture> RendererUtils::colorPass(
|
||||
FrameGraph& fg, const char* name, FEngine& engine, FView const& view,
|
||||
ColorPassInput const& colorPassInput,
|
||||
FrameGraphTexture::Descriptor const& colorBufferDesc,
|
||||
ColorPassConfig const& config, PostProcessManager::ColorGradingConfig colorGradingConfig,
|
||||
RenderPass::Executor passExecutor) noexcept {
|
||||
@@ -69,6 +67,8 @@ RendererUtils::ColorPassOutput RendererUtils::colorPass(
|
||||
FrameGraphId<FrameGraphTexture> structure;
|
||||
};
|
||||
|
||||
Blackboard& blackboard = fg.getBlackboard();
|
||||
|
||||
auto& colorPass = fg.addPass<ColorPassData>(name,
|
||||
[&](FrameGraph::Builder& builder, ColorPassData& data) {
|
||||
|
||||
@@ -76,21 +76,21 @@ RendererUtils::ColorPassOutput RendererUtils::colorPass(
|
||||
TargetBufferFlags clearDepthFlags = config.clearFlags & TargetBufferFlags::DEPTH;
|
||||
TargetBufferFlags clearStencilFlags = config.clearFlags & TargetBufferFlags::STENCIL;
|
||||
|
||||
data.color = colorPassInput.linearColor;
|
||||
data.depth = colorPassInput.depth;
|
||||
data.shadows = colorPassInput.shadows;
|
||||
data.ssao = colorPassInput.ssao;
|
||||
data.shadows = blackboard.get<FrameGraphTexture>("shadows");
|
||||
data.ssao = blackboard.get<FrameGraphTexture>("ssao");
|
||||
data.color = blackboard.get<FrameGraphTexture>("color");
|
||||
data.depth = blackboard.get<FrameGraphTexture>("depth");
|
||||
|
||||
// Screen-space reflection or refractions
|
||||
if (config.hasScreenSpaceReflectionsOrRefractions) {
|
||||
data.ssr = colorPassInput.ssr;
|
||||
data.ssr = blackboard.get<FrameGraphTexture>("ssr");
|
||||
if (data.ssr) {
|
||||
data.ssr = builder.sample(data.ssr);
|
||||
}
|
||||
}
|
||||
|
||||
if (config.hasContactShadows) {
|
||||
data.structure = colorPassInput.structure;
|
||||
data.structure = blackboard.get<FrameGraphTexture>("structure");
|
||||
assert_invariant(data.structure);
|
||||
data.structure = builder.sample(data.structure);
|
||||
}
|
||||
@@ -153,8 +153,6 @@ RendererUtils::ColorPassOutput RendererUtils::colorPass(
|
||||
}
|
||||
|
||||
if (colorGradingConfig.asSubpass) {
|
||||
assert_invariant(config.msaa <= 1);
|
||||
assert_invariant(colorBufferDesc.samples <= 1);
|
||||
data.output = builder.createTexture("Tonemapped Buffer", {
|
||||
.width = colorBufferDesc.width,
|
||||
.height = colorBufferDesc.height,
|
||||
@@ -196,6 +194,7 @@ RendererUtils::ColorPassOutput RendererUtils::colorPass(
|
||||
.samples = config.msaa,
|
||||
.layerCount = static_cast<uint8_t>(colorBufferDesc.depth),
|
||||
.clearFlags = clearColorFlags | clearDepthFlags | clearStencilFlags});
|
||||
blackboard["depth"] = data.depth;
|
||||
},
|
||||
[=, passExecutor = std::move(passExecutor), &view, &engine](FrameGraphResources const& resources,
|
||||
ColorPassData const& data, DriverApi& driver) {
|
||||
@@ -261,21 +260,24 @@ RendererUtils::ColorPassOutput RendererUtils::colorPass(
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
.linearColor = colorPass->color,
|
||||
.tonemappedColor = colorPass->output, // can be null
|
||||
.depth = colorPass->depth
|
||||
};
|
||||
// when color grading is done as a subpass, the output of the color-pass is the ldr buffer
|
||||
auto output = colorGradingConfig.asSubpass ? colorPass->output : colorPass->color;
|
||||
|
||||
blackboard["color"] = output;
|
||||
return output;
|
||||
}
|
||||
|
||||
std::optional<RendererUtils::ColorPassOutput> RendererUtils::refractionPass(
|
||||
std::pair<FrameGraphId<FrameGraphTexture>, bool> RendererUtils::refractionPass(
|
||||
FrameGraph& fg, FEngine& engine, FView const& view,
|
||||
ColorPassInput colorPassInput,
|
||||
ColorPassConfig config,
|
||||
PostProcessManager::ScreenSpaceRefConfig const& ssrConfig,
|
||||
PostProcessManager::ColorGradingConfig colorGradingConfig,
|
||||
RenderPass const& pass) noexcept {
|
||||
|
||||
auto& blackboard = fg.getBlackboard();
|
||||
auto input = blackboard.get<FrameGraphTexture>("color");
|
||||
FrameGraphId<FrameGraphTexture> output;
|
||||
|
||||
// find the first refractive object in channel 2
|
||||
RenderPass::Command const* const refraction = std::partition_point(pass.begin(), pass.end(),
|
||||
[](auto const& command) {
|
||||
@@ -290,35 +292,34 @@ std::optional<RendererUtils::ColorPassOutput> RendererUtils::refractionPass(
|
||||
|
||||
// if there wasn't any refractive object, just skip everything below.
|
||||
if (UTILS_UNLIKELY(hasScreenSpaceRefraction)) {
|
||||
assert_invariant(!colorPassInput.linearColor);
|
||||
assert_invariant(!colorPassInput.depth);
|
||||
PostProcessManager& ppm = engine.getPostProcessManager();
|
||||
|
||||
// clear the color/depth buffers, which will orphan (and cull) the color pass
|
||||
input.clear();
|
||||
blackboard.remove("color");
|
||||
blackboard.remove("depth");
|
||||
|
||||
config.hasScreenSpaceReflectionsOrRefractions = true;
|
||||
|
||||
PostProcessManager& ppm = engine.getPostProcessManager();
|
||||
auto const opaquePassOutput = RendererUtils::colorPass(fg,
|
||||
"Color Pass (opaque)", engine, view, colorPassInput, {
|
||||
input = RendererUtils::colorPass(fg, "Color Pass (opaque)", engine, view, {
|
||||
// When rendering the opaques, we need to conserve the sample buffer,
|
||||
// so create a config that specifies the sample count.
|
||||
.width = config.physicalViewport.width,
|
||||
.height = config.physicalViewport.height,
|
||||
.samples = config.msaa,
|
||||
.format = config.hdrFormat
|
||||
},
|
||||
config, { .asSubpass = false, .customResolve = false },
|
||||
}, config, { .asSubpass = false },
|
||||
pass.getExecutor(pass.begin(), refraction));
|
||||
|
||||
// generate the mipmap chain
|
||||
PostProcessManager::generateMipmapSSR(ppm, fg,
|
||||
opaquePassOutput.linearColor,
|
||||
ssrConfig.refraction,
|
||||
true, ssrConfig);
|
||||
input, ssrConfig.refraction, true, ssrConfig);
|
||||
|
||||
// Now we're doing the refraction pass proper.
|
||||
// This uses the same framebuffer (color and depth) used by the opaque pass.
|
||||
// For this reason, the `colorBufferDesc` parameter of colorPass() below is only used for
|
||||
// the width and height.
|
||||
colorPassInput.linearColor = opaquePassOutput.linearColor;
|
||||
colorPassInput.depth = opaquePassOutput.depth;
|
||||
// This uses the same framebuffer (color and depth) used by the opaque pass. This happens
|
||||
// automatically because these are set in the Blackboard (they were set by the opaque
|
||||
// pass). For this reason, `desc` below is only used in colorPass() for the width and
|
||||
// height.
|
||||
|
||||
// Since we're reusing the existing target we don't want to clear any of its buffer.
|
||||
// Important: if this target ended up being an imported target, then the clearFlags
|
||||
@@ -326,25 +327,22 @@ std::optional<RendererUtils::ColorPassOutput> RendererUtils::refractionPass(
|
||||
// and we'd end up clearing the opaque pass. This scenario never happens because it is
|
||||
// prevented in Renderer.cpp's final blit.
|
||||
config.clearFlags = TargetBufferFlags::NONE;
|
||||
auto transparentPassOutput = RendererUtils::colorPass(fg, "Color Pass (transparent)",
|
||||
engine, view, colorPassInput, {
|
||||
output = RendererUtils::colorPass(fg, "Color Pass (transparent)", engine, view, {
|
||||
.width = config.physicalViewport.width,
|
||||
.height = config.physicalViewport.height },
|
||||
config, colorGradingConfig,
|
||||
pass.getExecutor(refraction, pass.end()));
|
||||
config, colorGradingConfig, pass.getExecutor(refraction, pass.end()));
|
||||
|
||||
if (config.msaa > 1 && !colorGradingConfig.asSubpass) {
|
||||
// We need to do a resolve here because later passes (such as color grading or DoF) will
|
||||
// need to sample from 'output'. However, because we have MSAA, we know we're not
|
||||
// sampleable. And this is because in the SSR case, we had to use a renderbuffer to
|
||||
// conserve the multi-sample buffer.
|
||||
transparentPassOutput.linearColor = ppm.resolve(fg, "Resolved Color Buffer",
|
||||
transparentPassOutput.linearColor, { .levels = 1 });
|
||||
output = ppm.resolve(fg, "Resolved Color Buffer", output, { .levels = 1 });
|
||||
}
|
||||
return transparentPassOutput;
|
||||
} else {
|
||||
output = input;
|
||||
}
|
||||
|
||||
return std::nullopt;
|
||||
return { output, hasScreenSpaceRefraction };
|
||||
}
|
||||
|
||||
UTILS_NOINLINE
|
||||
|
||||
@@ -21,19 +21,14 @@
|
||||
#include "RenderPass.h"
|
||||
|
||||
#include "fg/FrameGraphId.h"
|
||||
#include "fg/FrameGraphTexture.h"
|
||||
|
||||
#include <filament/Viewport.h>
|
||||
|
||||
#include <backend/DriverEnums.h>
|
||||
#include <backend/PixelBufferDescriptor.h>
|
||||
|
||||
#include <math/vec2.h>
|
||||
#include <math/vec4.h>
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
namespace filament {
|
||||
@@ -76,32 +71,15 @@ public:
|
||||
bool screenSpaceReflectionHistoryNotReady;
|
||||
};
|
||||
|
||||
struct ColorPassInput {
|
||||
FrameGraphId<FrameGraphTexture> linearColor;
|
||||
FrameGraphId<FrameGraphTexture> tonemappedColor;
|
||||
FrameGraphId<FrameGraphTexture> depth;
|
||||
FrameGraphId<FrameGraphTexture> shadows;
|
||||
FrameGraphId<FrameGraphTexture> ssao;
|
||||
FrameGraphId<FrameGraphTexture> ssr;
|
||||
FrameGraphId<FrameGraphTexture> structure;
|
||||
};
|
||||
struct ColorPassOutput {
|
||||
FrameGraphId<FrameGraphTexture> linearColor;
|
||||
FrameGraphId<FrameGraphTexture> tonemappedColor;
|
||||
FrameGraphId<FrameGraphTexture> depth;
|
||||
};
|
||||
|
||||
static ColorPassOutput colorPass(
|
||||
static FrameGraphId<FrameGraphTexture> colorPass(
|
||||
FrameGraph& fg, const char* name, FEngine& engine, FView const& view,
|
||||
ColorPassInput const& colorPassInput,
|
||||
FrameGraphTexture::Descriptor const& colorBufferDesc,
|
||||
ColorPassConfig const& config,
|
||||
PostProcessManager::ColorGradingConfig colorGradingConfig,
|
||||
RenderPass::Executor passExecutor) noexcept;
|
||||
|
||||
static std::optional<RendererUtils::ColorPassOutput> refractionPass(
|
||||
static std::pair<FrameGraphId<FrameGraphTexture>, bool> refractionPass(
|
||||
FrameGraph& fg, FEngine& engine, FView const& view,
|
||||
ColorPassInput colorPassInput,
|
||||
ColorPassConfig config,
|
||||
PostProcessManager::ScreenSpaceRefConfig const& ssrConfig,
|
||||
PostProcessManager::ColorGradingConfig colorGradingConfig,
|
||||
|
||||
@@ -829,13 +829,13 @@ ShadowMap::Corners ShadowMap::computeFrustumCorners(
|
||||
Corners const csViewFrustumCorners = {
|
||||
.vertices = {
|
||||
{ -1, -1, far },
|
||||
{ 1, -1, far },
|
||||
{ -1, 1, far },
|
||||
{ 1, 1, far },
|
||||
{ 1, -1, far },
|
||||
{ -1, 1, far },
|
||||
{ 1, 1, far },
|
||||
{ -1, -1, near },
|
||||
{ 1, -1, near },
|
||||
{ -1, 1, near },
|
||||
{ 1, 1, near },
|
||||
{ 1, -1, near },
|
||||
{ -1, 1, near },
|
||||
{ 1, 1, near },
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -66,15 +66,15 @@ namespace filament {
|
||||
using namespace backend;
|
||||
using namespace math;
|
||||
|
||||
// do this only if depth-clamp is available
|
||||
static constexpr bool USE_DEPTH_CLAMP = false;
|
||||
|
||||
ShadowMapManager::ShadowMapManager(FEngine& engine) {
|
||||
ShadowMapManager::ShadowMapManager(FEngine& engine)
|
||||
: mIsDepthClampSupported(engine.getDriverApi().isDepthClampSupported()) {
|
||||
FDebugRegistry& debugRegistry = engine.getDebugRegistry();
|
||||
debugRegistry.registerProperty("d.shadowmap.visualize_cascades",
|
||||
&engine.debug.shadowmap.visualize_cascades);
|
||||
debugRegistry.registerProperty("d.shadowmap.disable_light_frustum_align",
|
||||
&engine.debug.shadowmap.disable_light_frustum_align);
|
||||
debugRegistry.registerProperty("d.shadowmap.depth_clamp",
|
||||
&engine.debug.shadowmap.depth_clamp);
|
||||
}
|
||||
|
||||
ShadowMapManager::~ShadowMapManager() {
|
||||
@@ -367,7 +367,22 @@ FrameGraphId<FrameGraphTexture> ShadowMapManager::render(FEngine& engine, FrameG
|
||||
|
||||
// generate and sort the commands for rendering the shadow map
|
||||
|
||||
RenderPass::RenderFlags renderPassFlags{};
|
||||
if (view.isFrontFaceWindingInverted()) {
|
||||
renderPassFlags |= RenderPass::HAS_INVERSE_FRONT_FACES;
|
||||
}
|
||||
|
||||
bool const canUseDepthClamp =
|
||||
!view.hasVSM() &&
|
||||
mIsDepthClampSupported &&
|
||||
engine.debug.shadowmap.depth_clamp;
|
||||
|
||||
if (canUseDepthClamp) {
|
||||
renderPassFlags |= RenderPass::HAS_DEPTH_CLAMP;
|
||||
}
|
||||
|
||||
RenderPass const pass = passBuilder
|
||||
.renderFlags(renderPassFlags)
|
||||
.camera(cameraInfo)
|
||||
.visibilityMask(entry.visibilityMask)
|
||||
.geometry(scene->getRenderableData(),
|
||||
@@ -641,8 +656,14 @@ 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, USE_DEPTH_CLAMP);
|
||||
lightData, 0, cameraInfo, shadowMapInfo, sceneInfo,
|
||||
canUseDepthClamp);
|
||||
|
||||
if (shadowMap.hasVisibleShadows()) {
|
||||
const size_t shadowIndex = shadowMap.getShadowIndex();
|
||||
|
||||
@@ -232,6 +232,7 @@ private:
|
||||
ShadowMapCacheContainer mShadowMapCache;
|
||||
uint32_t mDirectionalShadowMapCount = 0;
|
||||
uint32_t mSpotShadowMapCount = 0;
|
||||
bool const mIsDepthClampSupported;
|
||||
bool mInitialized = false;
|
||||
|
||||
ShadowMap& getShadowMap(size_t index) noexcept {
|
||||
|
||||
@@ -588,9 +588,6 @@ void FRenderableManager::create(
|
||||
// full size of the UBO.
|
||||
instances.handle = driver.createBufferObject(sizeof(PerRenderableUib),
|
||||
BufferObjectBinding::UNIFORM, backend::BufferUsage::DYNAMIC);
|
||||
if (auto name = instances.buffer->getName(); !name.empty()) {
|
||||
driver.setDebugTag(instances.handle.getId(), std::move(name));
|
||||
}
|
||||
}
|
||||
|
||||
const uint32_t boneCount = builder->mSkinningBoneCount;
|
||||
|
||||
@@ -20,8 +20,6 @@
|
||||
|
||||
#include "FilamentAPI-impl.h"
|
||||
|
||||
#include <utils/CString.h>
|
||||
|
||||
namespace filament {
|
||||
|
||||
struct BufferObject::BuilderDetails {
|
||||
@@ -58,9 +56,6 @@ FBufferObject::FBufferObject(FEngine& engine, const BufferObject::Builder& build
|
||||
FEngine::DriverApi& driver = engine.getDriverApi();
|
||||
mHandle = driver.createBufferObject(builder->mByteCount, builder->mBindingType,
|
||||
backend::BufferUsage::STATIC);
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
driver.setDebugTag(mHandle.getId(), std::move(name));
|
||||
}
|
||||
}
|
||||
|
||||
void FBufferObject::terminate(FEngine& engine) {
|
||||
|
||||
@@ -600,6 +600,7 @@ public:
|
||||
bool focus_shadowcasters = true;
|
||||
bool visualize_cascades = false;
|
||||
bool disable_light_frustum_align = false;
|
||||
bool depth_clamp = true;
|
||||
float dzn = -1.0f;
|
||||
float dzf = 1.0f;
|
||||
float display_shadow_texture_scale = 0.25f;
|
||||
|
||||
@@ -20,8 +20,6 @@
|
||||
|
||||
#include "FilamentAPI-impl.h"
|
||||
|
||||
#include <utils/CString.h>
|
||||
|
||||
namespace filament {
|
||||
|
||||
struct IndexBuffer::BuilderDetails {
|
||||
@@ -60,9 +58,6 @@ FIndexBuffer::FIndexBuffer(FEngine& engine, const IndexBuffer::Builder& builder)
|
||||
(backend::ElementType)builder->mIndexType,
|
||||
uint32_t(builder->mIndexCount),
|
||||
backend::BufferUsage::STATIC);
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
driver.setDebugTag(mHandle.getId(), std::move(name));
|
||||
}
|
||||
}
|
||||
|
||||
void FIndexBuffer::terminate(FEngine& engine) {
|
||||
|
||||
@@ -61,8 +61,7 @@ InstanceBuffer* InstanceBuffer::Builder::build(Engine& engine) {
|
||||
|
||||
// ------------------------------------------------------------------------------------------------
|
||||
|
||||
FInstanceBuffer::FInstanceBuffer(FEngine& engine, const Builder& builder)
|
||||
: mName(builder.getName()) {
|
||||
FInstanceBuffer::FInstanceBuffer(FEngine& engine, const Builder& builder) {
|
||||
mInstanceCount = builder->mInstanceCount;
|
||||
|
||||
mLocalTransforms.reserve(mInstanceCount);
|
||||
|
||||
@@ -25,7 +25,6 @@
|
||||
|
||||
#include <math/mat4.h>
|
||||
|
||||
#include <utils/CString.h>
|
||||
#include <utils/FixedCapacityVector.h>
|
||||
|
||||
namespace filament {
|
||||
@@ -47,13 +46,10 @@ public:
|
||||
void prepare(FEngine& engine, math::mat4f rootTransform, const PerRenderableData& ubo,
|
||||
backend::Handle<backend::HwBufferObject> handle);
|
||||
|
||||
utils::CString const& getName() const noexcept { return mName; }
|
||||
|
||||
private:
|
||||
friend class RenderableManager;
|
||||
|
||||
utils::FixedCapacityVector<math::mat4f> mLocalTransforms;
|
||||
utils::CString mName;
|
||||
size_t mInstanceCount;
|
||||
};
|
||||
|
||||
|
||||
@@ -192,27 +192,19 @@ Material* Material::Builder::build(Engine& engine) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Print a warning if the material's stereo type doesn't align with the engine's setting.
|
||||
MaterialDomain materialDomain;
|
||||
UserVariantFilterMask variantFilterMask;
|
||||
materialParser->getMaterialDomain(&materialDomain);
|
||||
materialParser->getMaterialVariantFilterMask(&variantFilterMask);
|
||||
bool const hasStereoVariants = !(variantFilterMask & UserVariantFilterMask(UserVariantFilterBit::STE));
|
||||
if (materialDomain == MaterialDomain::SURFACE && hasStereoVariants) {
|
||||
if (materialDomain == MaterialDomain::SURFACE) {
|
||||
StereoscopicType const engineStereoscopicType = engine.getConfig().stereoscopicType;
|
||||
// Default materials are always compiled with either 'instanced' or 'multiview'.
|
||||
// So, we only verify compatibility if the engine is set up for stereo.
|
||||
if (engineStereoscopicType != StereoscopicType::NONE) {
|
||||
StereoscopicType materialStereoscopicType = StereoscopicType::NONE;
|
||||
materialParser->getStereoscopicType(&materialStereoscopicType);
|
||||
if (materialStereoscopicType != engineStereoscopicType) {
|
||||
CString name;
|
||||
materialParser->getName(&name);
|
||||
slog.w << "The stereoscopic type in the compiled material '" << name.c_str_safe()
|
||||
<< "' is " << (int)materialStereoscopicType
|
||||
<< ", which is not compatiable with the engine's setting "
|
||||
<< (int)engineStereoscopicType << "." << io::endl;
|
||||
}
|
||||
StereoscopicType materialStereoscopicType = StereoscopicType::NONE;
|
||||
materialParser->getStereoscopicType(&materialStereoscopicType);
|
||||
if (materialStereoscopicType != engineStereoscopicType) {
|
||||
CString name;
|
||||
materialParser->getName(&name);
|
||||
slog.w << "The stereoscopic type in the compiled material '" << name.c_str_safe()
|
||||
<< "' is " << (int)materialStereoscopicType
|
||||
<< ", which is not compatiable with the engine's setting "
|
||||
<< (int)engineStereoscopicType << "." << io::endl;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -618,7 +610,6 @@ Program FMaterial::getProgramWithVariants(
|
||||
|
||||
void FMaterial::createAndCacheProgram(Program&& p, Variant variant) const noexcept {
|
||||
auto program = mEngine.getDriverApi().createProgram(std::move(p));
|
||||
mEngine.getDriverApi().setDebugTag(program.getId(), mName);
|
||||
assert_invariant(program);
|
||||
mCachedPrograms[variant.key] = program;
|
||||
}
|
||||
|
||||
@@ -51,7 +51,6 @@ FMaterialInstance::FMaterialInstance(FEngine& engine, FMaterial const* material)
|
||||
mUniforms = UniformBuffer(material->getUniformInterfaceBlock().getSize());
|
||||
mUbHandle = driver.createBufferObject(mUniforms.getSize(),
|
||||
BufferObjectBinding::UNIFORM, backend::BufferUsage::STATIC);
|
||||
driver.setDebugTag(mUbHandle.getId(), material->getName());
|
||||
}
|
||||
|
||||
if (!material->getSamplerInterfaceBlock().isEmpty()) {
|
||||
@@ -117,7 +116,6 @@ FMaterialInstance::FMaterialInstance(FEngine& engine,
|
||||
mUniforms.setUniforms(other->getUniformBuffer());
|
||||
mUbHandle = driver.createBufferObject(mUniforms.getSize(),
|
||||
BufferObjectBinding::UNIFORM, backend::BufferUsage::DYNAMIC);
|
||||
driver.setDebugTag(mUbHandle.getId(), material->getName());
|
||||
}
|
||||
|
||||
if (!material->getSamplerInterfaceBlock().isEmpty()) {
|
||||
|
||||
@@ -25,8 +25,6 @@
|
||||
#include <math/mat4.h>
|
||||
#include <math/norm.h>
|
||||
|
||||
#include <utils/CString.h>
|
||||
|
||||
namespace filament {
|
||||
|
||||
using namespace backend;
|
||||
@@ -126,11 +124,6 @@ FMorphTargetBuffer::FMorphTargetBuffer(FEngine& engine, const Builder& builder)
|
||||
mCount,
|
||||
TextureUsage::DEFAULT);
|
||||
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
driver.setDebugTag(mPbHandle.getId(), name);
|
||||
driver.setDebugTag(mTbHandle.getId(), std::move(name));
|
||||
}
|
||||
|
||||
// create and update sampler group
|
||||
mSbHandle = driver.createSamplerGroup(PerRenderPrimitiveMorphingSib::SAMPLER_COUNT,
|
||||
utils::FixedSizeString<32>("Morph target samplers"));
|
||||
|
||||
@@ -34,7 +34,7 @@ struct RenderTarget::BuilderDetails {
|
||||
uint32_t mWidth{};
|
||||
uint32_t mHeight{};
|
||||
uint8_t mSamples = 1; // currently not settable in the public facing API
|
||||
uint8_t mLayerCount = 1;// currently not settable in the public facing API
|
||||
uint8_t mLayerCount = 0;// currently not settable in the public facing API
|
||||
};
|
||||
|
||||
using BuilderType = RenderTarget;
|
||||
|
||||
@@ -597,6 +597,7 @@ 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();
|
||||
@@ -610,6 +611,7 @@ 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) {
|
||||
@@ -655,16 +657,16 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
// on qualcomm hardware -- we might need a backend dependent toggle at some point
|
||||
const PostProcessManager::ColorGradingConfig colorGradingConfig{
|
||||
.asSubpass =
|
||||
msaaSampleCount <= 1 &&
|
||||
driver.isFrameBufferFetchSupported() &&
|
||||
hasColorGrading &&
|
||||
msaaSampleCount <= 1 &&
|
||||
!bloomOptions.enabled && !dofOptions.enabled && !taaOptions.enabled &&
|
||||
driver.isFrameBufferFetchSupported() &&
|
||||
!engine.debug.renderer.disable_subpasses,
|
||||
.customResolve =
|
||||
msaaSampleCount > 1 &&
|
||||
driver.isFrameBufferFetchMultiSampleSupported() &&
|
||||
msaaOptions.customResolve &&
|
||||
msaaSampleCount > 1 &&
|
||||
hasColorGrading &&
|
||||
driver.isFrameBufferFetchMultiSampleSupported() &&
|
||||
!engine.debug.renderer.disable_subpasses,
|
||||
.translucent = needsAlphaChannel,
|
||||
.fxaa = hasFXAA,
|
||||
@@ -673,9 +675,6 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
TextureFormat::RGBA8 : getLdrFormat(needsAlphaChannel)
|
||||
};
|
||||
|
||||
// by construction (msaaSampleCount) both asSubpass and customResolve can't be true
|
||||
assert_invariant(colorGradingConfig.asSubpass + colorGradingConfig.customResolve < 2);
|
||||
|
||||
// whether we're scaled at all
|
||||
bool scaled = any(notEqual(scale, float2(1.0f)));
|
||||
|
||||
@@ -698,13 +697,15 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
|
||||
CameraInfo cameraInfo = view.computeCameraInfo(engine);
|
||||
|
||||
// If fxaa and scaling are not enabled, we're essentially in a very fast rendering path -- in
|
||||
// this case, we would need an extra blit to "resolve" the buffer padding (because there are no
|
||||
// other pass that can do it as a side effect). In this case, it is better to skip the padding,
|
||||
// which won't be helping much.
|
||||
const bool noBufferPadding
|
||||
= (!hasFXAA && !scaled) || engine.debug.renderer.disable_buffer_padding;
|
||||
// when colorgrading-as-subpass is active, we know that many other effects are disabled
|
||||
// such as dof, bloom. Moreover, if fxaa and scaling are not enabled, we're essentially in
|
||||
// a very fast rendering path -- in this case, we would need an extra blit to "resolve" the
|
||||
// buffer padding (because there are no other pass that can do it as a side effect).
|
||||
// In this case, it is better to skip the padding, which won't be helping much.
|
||||
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;
|
||||
|
||||
@@ -721,7 +722,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 = 16u;
|
||||
constexpr uint32_t rounding = 256u;
|
||||
return (x + (rounding - 1u)) & ~(rounding - 1u);
|
||||
};
|
||||
|
||||
@@ -729,6 +730,9 @@ 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,
|
||||
@@ -746,9 +750,14 @@ 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);
|
||||
|
||||
@@ -761,6 +770,7 @@ 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);
|
||||
@@ -872,6 +882,9 @@ 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)
|
||||
@@ -954,6 +967,7 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
.scale = aoOptions.resolution,
|
||||
.picking = view.hasPicking()
|
||||
});
|
||||
blackboard["structure"] = structure;
|
||||
const auto picking = picking_;
|
||||
|
||||
|
||||
@@ -1001,6 +1015,7 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
ssReflectionsOptions.enabled ? TextureFormat::RGBA16F : TextureFormat::R11F_G11F_B10F,
|
||||
view.getCameraUser().getFieldOfView(Camera::Fov::VERTICAL), config.scale);
|
||||
config.ssrLodOffset = ssrConfig.lodOffset;
|
||||
blackboard["ssr"] = ssrConfig.ssr;
|
||||
|
||||
// --------------------------------------------------------------------------------------------
|
||||
// screen-space reflections pass
|
||||
@@ -1074,6 +1089,9 @@ 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;
|
||||
@@ -1104,39 +1122,24 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
);
|
||||
|
||||
// the color pass itself + color-grading as subpass if needed
|
||||
auto colorPassOutput = RendererUtils::colorPass(fg, "Color Pass", mEngine, view, {
|
||||
.shadows = blackboard.get<FrameGraphTexture>("shadows"),
|
||||
.ssao = blackboard.get<FrameGraphTexture>("ssao"),
|
||||
.ssr = ssrConfig.ssr,
|
||||
.structure = structure
|
||||
},
|
||||
auto colorPassOutput = RendererUtils::colorPass(fg, "Color Pass", mEngine, view,
|
||||
colorBufferDesc, config, colorGradingConfigForColor, pass.getExecutor());
|
||||
|
||||
if (view.isScreenSpaceRefractionEnabled() && !pass.empty()) {
|
||||
// This cancels the colorPass() call above if refraction is active.
|
||||
// The color pass + refraction + color-grading as subpass if needed
|
||||
auto const output = RendererUtils::refractionPass(fg, mEngine, view, {
|
||||
.shadows = blackboard.get<FrameGraphTexture>("shadows"),
|
||||
.ssao = blackboard.get<FrameGraphTexture>("ssao"),
|
||||
.ssr = ssrConfig.ssr,
|
||||
.structure = structure
|
||||
},
|
||||
// this cancels the colorPass() call above if refraction is active.
|
||||
// the color pass + refraction + color-grading as subpass if needed
|
||||
const auto [output, enabled] = RendererUtils::refractionPass(fg, mEngine, view,
|
||||
config, ssrConfig, colorGradingConfigForColor, pass);
|
||||
|
||||
hasScreenSpaceRefraction = output.has_value();
|
||||
if (hasScreenSpaceRefraction) {
|
||||
colorPassOutput = output.value();
|
||||
}
|
||||
colorPassOutput = output;
|
||||
hasScreenSpaceRefraction = enabled;
|
||||
}
|
||||
|
||||
if (colorGradingConfig.customResolve) {
|
||||
assert_invariant(fg.getDescriptor(colorPassOutput.linearColor).samples <= 1);
|
||||
// TODO: we have to "uncompress" (i.e. detonemap) the color buffer here because it's used
|
||||
// by many other passes (Bloom, TAA, DoF, etc...). We could make this more
|
||||
// efficient by using ARM_shader_framebuffer_fetch. We use a load/store (i.e.
|
||||
// subpass) here because it's more convenient.
|
||||
colorPassOutput.linearColor =
|
||||
ppm.customResolveUncompressPass(fg, colorPassOutput.linearColor);
|
||||
colorPassOutput = ppm.customResolveUncompressPass(fg, colorPassOutput);
|
||||
}
|
||||
|
||||
// export the color buffer if screen-space reflections are enabled
|
||||
@@ -1152,9 +1155,7 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
// The "output" of this pass is going to be used during the next frame as
|
||||
// an "import".
|
||||
builder.sideEffect();
|
||||
|
||||
// we can't use colorPassOutput here because it could be tonemapped
|
||||
data.history = builder.sample(colorPassOutput.linearColor); // FIXME: an access must be declared for detach(), why?
|
||||
data.history = builder.sample(colorPassOutput); // FIXME: an access must be declared for detach(), why?
|
||||
}, [&view, projection](FrameGraphResources const& resources, auto const& data,
|
||||
backend::DriverApi&) {
|
||||
auto& history = view.getFrameHistory();
|
||||
@@ -1164,14 +1165,7 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
});
|
||||
}
|
||||
|
||||
// this is the output of the color pass / input to post processing,
|
||||
// this is only used later for comparing it with the output after post-processing
|
||||
FrameGraphId<FrameGraphTexture> const postProcessInput = colorGradingConfig.asSubpass ?
|
||||
colorPassOutput.tonemappedColor :
|
||||
colorPassOutput.linearColor;
|
||||
|
||||
// input can change below
|
||||
FrameGraphId<FrameGraphTexture> input = postProcessInput;
|
||||
FrameGraphId<FrameGraphTexture> input = colorPassOutput;
|
||||
fg.addTrivialSideEffectPass("Finish Color Passes", [&view](DriverApi& driver) {
|
||||
// Unbind SSAO sampler, b/c the FrameGraph will delete the texture at the end of the pass.
|
||||
view.cleanupRenderPasses();
|
||||
@@ -1182,7 +1176,8 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
// if the depth is not used below or if the depth is not MS (e.g. it could have been
|
||||
// auto-resolved).
|
||||
// In practice, this is used on Vulkan and older Metal devices.
|
||||
auto depth = ppm.resolve(fg, "Resolved Depth Buffer", colorPassOutput.depth, { .levels = 1 });
|
||||
auto depth = blackboard.get<FrameGraphTexture>("depth");
|
||||
depth = ppm.resolve(fg, "Resolved Depth Buffer", depth, { .levels = 1 });
|
||||
|
||||
// Debug: CSM visualisation
|
||||
if (UTILS_UNLIKELY(engine.debug.shadowmap.visualize_cascades &&
|
||||
@@ -1250,11 +1245,13 @@ 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
|
||||
@@ -1268,6 +1265,7 @@ 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,8 +1296,11 @@ void FRenderer::renderJob(RootArenaScope& rootArenaScope, FView& view) {
|
||||
// The intermediate buffer is accomplished with a "fake" opaqueBlit (i.e. blit) operation.
|
||||
|
||||
const bool outputIsSwapChain =
|
||||
(input == postProcessInput) && (viewRenderTarget == mRenderTargetHandle);
|
||||
(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 &&
|
||||
@@ -1308,6 +1309,7 @@ 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 },
|
||||
@@ -1337,6 +1339,10 @@ 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();
|
||||
|
||||
@@ -27,8 +27,6 @@
|
||||
#include <math/half.h>
|
||||
#include <math/mat4.h>
|
||||
|
||||
#include <utils/CString.h>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
namespace filament {
|
||||
@@ -82,11 +80,6 @@ FSkinningBuffer::FSkinningBuffer(FEngine& engine, const Builder& builder)
|
||||
BufferObjectBinding::UNIFORM,
|
||||
BufferUsage::DYNAMIC);
|
||||
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
// TODO: We should also tag the texture created inside createIndicesAndWeightsHandle.
|
||||
driver.setDebugTag(mHandle.getId(), std::move(name));
|
||||
}
|
||||
|
||||
if (builder->mInitialize) {
|
||||
// initialize the bones to identity (before rounding up)
|
||||
auto* out = driver.allocatePod<PerRenderableBoneUib::BoneData>(mBoneCount);
|
||||
|
||||
@@ -23,10 +23,10 @@
|
||||
|
||||
#include <backend/PixelBufferDescriptor.h>
|
||||
|
||||
#include <utils/CString.h>
|
||||
#include <utils/Panic.h>
|
||||
#include <filament/Stream.h>
|
||||
|
||||
|
||||
namespace filament {
|
||||
|
||||
using namespace backend;
|
||||
@@ -80,10 +80,6 @@ FStream::FStream(FEngine& engine, const Builder& builder) noexcept
|
||||
} else {
|
||||
mStreamHandle = engine.getDriverApi().createStreamAcquired();
|
||||
}
|
||||
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
engine.getDriverApi().setDebugTag(mStreamHandle.getId(), std::move(name));
|
||||
}
|
||||
}
|
||||
|
||||
void FStream::terminate(FEngine& engine) noexcept {
|
||||
|
||||
@@ -243,9 +243,6 @@ FTexture::FTexture(FEngine& engine, const Builder& builder) {
|
||||
mHandle = driver.importTexture(builder->mImportedId,
|
||||
mTarget, mLevelCount, mFormat, mSampleCount, mWidth, mHeight, mDepth, mUsage);
|
||||
}
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
driver.setDebugTag(mHandle.getId(), std::move(name));
|
||||
}
|
||||
}
|
||||
|
||||
// frees driver resources, object becomes invalid
|
||||
|
||||
@@ -29,7 +29,6 @@
|
||||
|
||||
#include <utils/bitset.h>
|
||||
#include <utils/compiler.h>
|
||||
#include <utils/CString.h>
|
||||
#include <utils/debug.h>
|
||||
#include <utils/Log.h>
|
||||
#include <utils/ostream.h>
|
||||
@@ -260,9 +259,7 @@ FVertexBuffer::FVertexBuffer(FEngine& engine, const VertexBuffer::Builder& build
|
||||
mBufferCount, mDeclaredAttributes.count(), mAttributes);
|
||||
|
||||
mHandle = driver.createVertexBuffer(mVertexCount, mVertexBufferInfoHandle);
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
driver.setDebugTag(mHandle.getId(), name);
|
||||
}
|
||||
|
||||
|
||||
// calculate buffer sizes
|
||||
size_t bufferSizes[MAX_VERTEX_BUFFER_COUNT] = {};
|
||||
@@ -290,9 +287,6 @@ FVertexBuffer::FVertexBuffer(FEngine& engine, const VertexBuffer::Builder& build
|
||||
if (!mBufferObjects[i]) {
|
||||
BufferObjectHandle bo = driver.createBufferObject(bufferSizes[i],
|
||||
backend::BufferObjectBinding::VERTEX, backend::BufferUsage::STATIC);
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
driver.setDebugTag(bo.getId(), name);
|
||||
}
|
||||
driver.setVertexBufferObject(mHandle, i, bo);
|
||||
mBufferObjects[i] = bo;
|
||||
}
|
||||
@@ -309,9 +303,6 @@ FVertexBuffer::FVertexBuffer(FEngine& engine, const VertexBuffer::Builder& build
|
||||
if (!mBufferObjects[i]) {
|
||||
BufferObjectHandle const bo = driver.createBufferObject(bufferSizes[i],
|
||||
backend::BufferObjectBinding::VERTEX, backend::BufferUsage::STATIC);
|
||||
if (auto name = builder.getName(); !name.empty()) {
|
||||
driver.setDebugTag(bo.getId(), name);
|
||||
}
|
||||
driver.setVertexBufferObject(mHandle, i, bo);
|
||||
mBufferObjects[i] = bo;
|
||||
}
|
||||
|
||||
@@ -10,10 +10,6 @@ material {
|
||||
type : int,
|
||||
name : layerIndex
|
||||
},
|
||||
{
|
||||
type : float,
|
||||
name : levelOfDetail,
|
||||
},
|
||||
{
|
||||
type : float4,
|
||||
name : viewport,
|
||||
@@ -37,6 +33,6 @@ vertex {
|
||||
|
||||
fragment {
|
||||
void postProcess(inout PostProcessInputs postProcess) {
|
||||
postProcess.color = textureLod(materialParams_color, vec3(variable_vertex.xy, materialParams.layerIndex), materialParams.levelOfDetail);
|
||||
postProcess.color = textureLod(materialParams_color, vec3(variable_vertex.xy, materialParams.layerIndex), 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,10 +10,6 @@ material {
|
||||
type : float4,
|
||||
name : viewport,
|
||||
precision: high
|
||||
},
|
||||
{
|
||||
type : float,
|
||||
name : levelOfDetail,
|
||||
}
|
||||
],
|
||||
variables : [
|
||||
@@ -37,7 +33,7 @@ fragment {
|
||||
#if FILAMENT_EFFECTIVE_VERSION == 100
|
||||
postProcess.color = texture2D(materialParams_color, variable_vertex.xy);
|
||||
#else
|
||||
postProcess.color = textureLod(materialParams_color, variable_vertex.xy, materialParams.levelOfDetail);
|
||||
postProcess.color = textureLod(materialParams_color, variable_vertex.xy, 0.0);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
Pod::Spec.new do |spec|
|
||||
spec.name = "Filament"
|
||||
spec.version = "1.54.1"
|
||||
spec.version = "1.54.0"
|
||||
spec.license = { :type => "Apache 2.0", :file => "LICENSE" }
|
||||
spec.homepage = "https://google.github.io/filament"
|
||||
spec.authors = "Google LLC."
|
||||
spec.summary = "Filament is a real-time physically based rendering engine for Android, iOS, Windows, Linux, macOS, and WASM/WebGL."
|
||||
spec.platform = :ios, "11.0"
|
||||
spec.source = { :http => "https://github.com/google/filament/releases/download/v1.54.1/filament-v1.54.1-ios.tgz" }
|
||||
spec.source = { :http => "https://github.com/google/filament/releases/download/v1.54.0/filament-v1.54.0-ios.tgz" }
|
||||
|
||||
# Fix linking error with Xcode 12; we do not yet support the simulator on Apple silicon.
|
||||
spec.pod_target_xcconfig = {
|
||||
|
||||
@@ -323,9 +323,6 @@ public:
|
||||
//! Custom variables (all float4).
|
||||
MaterialBuilder& variable(Variable v, const char* name) noexcept;
|
||||
|
||||
MaterialBuilder& variable(Variable v, const char* name,
|
||||
ParameterPrecision precision) noexcept;
|
||||
|
||||
/**
|
||||
* Require a specified attribute.
|
||||
*
|
||||
@@ -711,17 +708,11 @@ public:
|
||||
ShaderStage stage;
|
||||
};
|
||||
|
||||
struct CustomVariable {
|
||||
utils::CString name;
|
||||
Precision precision = Precision::DEFAULT;
|
||||
bool hasPrecision = false;
|
||||
};
|
||||
|
||||
static constexpr size_t MATERIAL_PROPERTIES_COUNT = filament::MATERIAL_PROPERTIES_COUNT;
|
||||
using Property = filament::Property;
|
||||
|
||||
using PropertyList = bool[MATERIAL_PROPERTIES_COUNT];
|
||||
using VariableList = CustomVariable[MATERIAL_VARIABLES_COUNT];
|
||||
using VariableList = utils::CString[MATERIAL_VARIABLES_COUNT];
|
||||
using OutputList = std::vector<Output>;
|
||||
|
||||
static constexpr size_t MAX_COLOR_OUTPUT = filament::backend::MRT::MAX_SUPPORTED_RENDER_TARGET_COUNT;
|
||||
|
||||
@@ -671,15 +671,13 @@ void GLSLPostProcessor::fixupClipDistance(
|
||||
// - triggers a crash on some Adreno drivers (b/291140208, b/289401984, b/289393290)
|
||||
// However Metal requires this pass in order to correctly generate half-precision MSL
|
||||
//
|
||||
// Note: CreateSimplificationPass() used to creates a lot of problems:
|
||||
// CreateSimplificationPass() creates a lot of problems:
|
||||
// - Adreno GPU show artifacts after running simplification passes (Vulkan)
|
||||
// - spirv-cross fails generating working glsl
|
||||
// (https://github.com/KhronosGroup/SPIRV-Cross/issues/2162)
|
||||
//
|
||||
// However this problem was addressed in spirv-cross here:
|
||||
// https://github.com/KhronosGroup/SPIRV-Cross/pull/2163
|
||||
//
|
||||
// The simplification passes below are necessary when targeting Metal, otherwise the
|
||||
// - generally it makes the code more complicated, e.g.: replacing for loops with
|
||||
// while-if-break, unclear if it helps for anything.
|
||||
// However, the simplification passes below are necessary when targeting Metal, otherwise the
|
||||
// result is mismatched half / float assignments in MSL.
|
||||
|
||||
|
||||
@@ -712,11 +710,11 @@ void GLSLPostProcessor::registerPerformancePasses(Optimizer& optimizer, Config c
|
||||
RegisterPass(CreateAggressiveDCEPass());
|
||||
RegisterPass(CreateRedundancyEliminationPass());
|
||||
RegisterPass(CreateCombineAccessChainsPass());
|
||||
RegisterPass(CreateSimplificationPass());
|
||||
RegisterPass(CreateSimplificationPass(), MaterialBuilder::TargetApi::METAL);
|
||||
RegisterPass(CreateVectorDCEPass());
|
||||
RegisterPass(CreateDeadInsertElimPass());
|
||||
RegisterPass(CreateDeadBranchElimPass());
|
||||
RegisterPass(CreateSimplificationPass());
|
||||
RegisterPass(CreateSimplificationPass(), MaterialBuilder::TargetApi::METAL);
|
||||
RegisterPass(CreateIfConversionPass());
|
||||
RegisterPass(CreateCopyPropagateArraysPass());
|
||||
RegisterPass(CreateReduceLoadSizePass());
|
||||
@@ -725,7 +723,7 @@ void GLSLPostProcessor::registerPerformancePasses(Optimizer& optimizer, Config c
|
||||
RegisterPass(CreateRedundancyEliminationPass());
|
||||
RegisterPass(CreateDeadBranchElimPass());
|
||||
RegisterPass(CreateBlockMergePass());
|
||||
RegisterPass(CreateSimplificationPass());
|
||||
RegisterPass(CreateSimplificationPass(), MaterialBuilder::TargetApi::METAL);
|
||||
}
|
||||
|
||||
void GLSLPostProcessor::registerSizePasses(Optimizer& optimizer, Config const& config) {
|
||||
|
||||
@@ -234,21 +234,7 @@ MaterialBuilder& MaterialBuilder::variable(Variable v, const char* name) noexcep
|
||||
case Variable::CUSTOM2:
|
||||
case Variable::CUSTOM3:
|
||||
assert(size_t(v) < MATERIAL_VARIABLES_COUNT);
|
||||
mVariables[size_t(v)] = { CString(name), Precision::DEFAULT, false };
|
||||
break;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
MaterialBuilder& MaterialBuilder::variable(Variable v,
|
||||
const char* name, ParameterPrecision precision) noexcept {
|
||||
switch (v) {
|
||||
case Variable::CUSTOM0:
|
||||
case Variable::CUSTOM1:
|
||||
case Variable::CUSTOM2:
|
||||
case Variable::CUSTOM3:
|
||||
assert(size_t(v) < MATERIAL_VARIABLES_COUNT);
|
||||
mVariables[size_t(v)] = { CString(name), precision, true };
|
||||
mVariables[size_t(v)] = CString(name);
|
||||
break;
|
||||
}
|
||||
return *this;
|
||||
@@ -1397,7 +1383,7 @@ bool MaterialBuilder::checkMaterialLevelFeatures(MaterialInfo const& info) const
|
||||
|
||||
bool MaterialBuilder::hasCustomVaryings() const noexcept {
|
||||
for (const auto& variable : mVariables) {
|
||||
if (!variable.name.empty()) {
|
||||
if (!variable.empty()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -451,20 +451,15 @@ io::sstream& CodeGenerator::generatePostProcessMain(io::sstream& out, ShaderStag
|
||||
}
|
||||
|
||||
io::sstream& CodeGenerator::generateVariable(io::sstream& out, ShaderStage stage,
|
||||
const MaterialBuilder::CustomVariable& variable, size_t index) {
|
||||
auto const& name = variable.name;
|
||||
const char* precisionString = getPrecisionQualifier(variable.precision);
|
||||
const CString& name, size_t index) {
|
||||
|
||||
if (!name.empty()) {
|
||||
if (stage == ShaderStage::VERTEX) {
|
||||
out << "\n#define VARIABLE_CUSTOM" << index << " " << name.c_str() << "\n";
|
||||
out << "\n#define VARIABLE_CUSTOM_AT" << index << " variable_" << name.c_str() << "\n";
|
||||
out << "LAYOUT_LOCATION(" << index << ") VARYING " << precisionString << " vec4 variable_" << name.c_str() << ";\n";
|
||||
out << "LAYOUT_LOCATION(" << index << ") VARYING vec4 variable_" << name.c_str() << ";\n";
|
||||
} else if (stage == ShaderStage::FRAGMENT) {
|
||||
if (!variable.hasPrecision && variable.precision == Precision::DEFAULT) {
|
||||
// for backward compatibility
|
||||
precisionString = "highp";
|
||||
}
|
||||
out << "\nLAYOUT_LOCATION(" << index << ") VARYING " << precisionString << " vec4 variable_" << name.c_str() << ";\n";
|
||||
out << "\nLAYOUT_LOCATION(" << index << ") VARYING highp vec4 variable_" << name.c_str() << ";\n";
|
||||
}
|
||||
}
|
||||
return out;
|
||||
|
||||
@@ -103,7 +103,7 @@ public:
|
||||
|
||||
// generate declarations for custom interpolants
|
||||
static utils::io::sstream& generateVariable(utils::io::sstream& out, ShaderStage stage,
|
||||
const MaterialBuilder::CustomVariable& variable, size_t index);
|
||||
const utils::CString& name, size_t index);
|
||||
|
||||
// generate declarations for non-custom "in" variables
|
||||
utils::io::sstream& generateShaderInputs(utils::io::sstream& out, ShaderStage type,
|
||||
|
||||
@@ -56,13 +56,7 @@ bool operator==(const MaterialKey& k1, const MaterialKey& k2) {
|
||||
(k1.volumeThicknessUV == k2.volumeThicknessUV) &&
|
||||
(k1.hasSheen == k2.hasSheen) &&
|
||||
(k1.hasIOR == k2.hasIOR) &&
|
||||
(k1.hasVolume == k2.hasVolume) &&
|
||||
(k1.hasSpecular == k2.hasSpecular) &&
|
||||
(k1.hasSpecularTexture == k2.hasSpecularTexture) &&
|
||||
(k1.hasSpecularColorTexture == k2.hasSpecularColorTexture) &&
|
||||
(k1.specularTextureUV == k2.specularTextureUV) &&
|
||||
(k1.specularColorTextureUV == k2.specularColorTextureUV)
|
||||
;
|
||||
(k1.hasVolume == k2.hasVolume);
|
||||
}
|
||||
|
||||
// Filament supports up to 2 UV sets. glTF has arbitrary texcoord set indices, but it allows
|
||||
|
||||
@@ -259,24 +259,6 @@ MaterialInstance* UbershaderProvider::createMaterialInstance(MaterialKey* config
|
||||
mi->setParameter("occlusionUvMatrix", identity);
|
||||
mi->setParameter("emissiveUvMatrix", identity);
|
||||
|
||||
// set to -1 all possibly optional parameters
|
||||
for (auto const* param : {
|
||||
"clearCoatIndex",
|
||||
"clearCoatRoughnessIndex",
|
||||
"clearCoatNormalIndex",
|
||||
"sheenColorIndex",
|
||||
"sheenRoughnessIndex",
|
||||
"volumeThicknessUvMatrix",
|
||||
"volumeThicknessIndex",
|
||||
"transmissionIndex",
|
||||
"specularIndex",
|
||||
"specularColorIndex",
|
||||
}) {
|
||||
if (material->hasParameter(param)) {
|
||||
mi->setParameter(param, -1);
|
||||
}
|
||||
}
|
||||
|
||||
if (config->hasClearCoat) {
|
||||
mi->setParameter("clearCoatIndex",
|
||||
getUvIndex(config->clearCoatUV, config->hasClearCoatTexture));
|
||||
@@ -358,10 +340,10 @@ MaterialInstance* UbershaderProvider::createMaterialInstance(MaterialKey* config
|
||||
mi->setParameter("sheenRoughnessMap", mDummyTexture, sampler);
|
||||
}
|
||||
|
||||
if (material->hasParameter("ior")) {
|
||||
if (mi->getMaterial()->hasParameter("ior")) {
|
||||
mi->setParameter("ior", 1.5f);
|
||||
}
|
||||
if (material->hasParameter("reflectance")) {
|
||||
if (mi->getMaterial()->hasParameter("reflectance")) {
|
||||
mi->setParameter("reflectance", 0.5f);
|
||||
}
|
||||
|
||||
@@ -373,14 +355,6 @@ MaterialInstance* UbershaderProvider::createMaterialInstance(MaterialKey* config
|
||||
mi->setParameter("specularColorMap", mDummyTexture, sampler);
|
||||
}
|
||||
|
||||
if (material->hasParameter("specularColorFactor")) {
|
||||
mi->setParameter("specularColorFactor", float3(1.0f));
|
||||
}
|
||||
|
||||
if (material->hasParameter("specularStrength")) {
|
||||
mi->setParameter("specularStrength", 1.0f);
|
||||
}
|
||||
|
||||
return mi;
|
||||
}
|
||||
|
||||
|
||||
@@ -527,13 +527,11 @@ bool AssetLoaderExtended::createPrimitive(Input* input, Output* out,
|
||||
|
||||
if (!mCgltfBuffersLoaded) {
|
||||
mCgltfBuffersLoaded = utility::loadCgltfBuffers(gltf, mGltfPath.c_str(), mUriDataCache);
|
||||
if (!mCgltfBuffersLoaded) {
|
||||
return false;
|
||||
}
|
||||
utility::decodeMeshoptCompression(gltf);
|
||||
if (!mCgltfBuffersLoaded) return false;
|
||||
}
|
||||
|
||||
utility::decodeDracoMeshes(gltf, prim, input->dracoCache);
|
||||
utility::decodeMeshoptCompression(gltf);
|
||||
|
||||
auto slots = computeGeometries(prim, jobType, attributesMap, morphTargets, out->uvmap, mEngine);
|
||||
|
||||
|
||||
@@ -562,6 +562,8 @@ 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);
|
||||
|
||||
@@ -39,7 +39,6 @@ set(MATERIAL_SRCS
|
||||
materials/sandboxSubsurface.mat
|
||||
materials/sandboxUnlit.mat
|
||||
materials/texturedLit.mat
|
||||
materials/iconTest.mat
|
||||
)
|
||||
|
||||
if (CMAKE_CROSSCOMPILING)
|
||||
@@ -271,14 +270,13 @@ if (NOT ANDROID)
|
||||
add_demo(viewtest)
|
||||
|
||||
# Sample app specific
|
||||
target_link_libraries(hellotriangle PRIVATE gltf-demo-resources uberarchive gltfio)
|
||||
target_link_libraries(frame_generator PRIVATE imageio)
|
||||
target_link_libraries(gltf_viewer PRIVATE gltf-demo-resources uberarchive gltfio viewer)
|
||||
target_link_libraries(gltf_instances PRIVATE gltf-demo-resources uberarchive gltfio viewer)
|
||||
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 filameshio suzanne-resources)
|
||||
target_link_libraries(rendertarget PRIVATE gltf-demo-resources filameshio suzanne-resources gltfio viewer)
|
||||
target_link_libraries(sample_cloth PRIVATE filameshio)
|
||||
target_link_libraries(sample_normal_map PRIVATE filameshio)
|
||||
target_link_libraries(suzanne PRIVATE filameshio suzanne-resources)
|
||||
|
||||
@@ -905,6 +905,8 @@ int main(int argc, char** argv) {
|
||||
debug.getPropertyAddress<bool>("d.shadowmap.focus_shadowcasters"));
|
||||
ImGui::Checkbox("Disable light frustum alignment",
|
||||
debug.getPropertyAddress<bool>("d.shadowmap.disable_light_frustum_align"));
|
||||
ImGui::Checkbox("Depth clamp",
|
||||
debug.getPropertyAddress<bool>("d.shadowmap.depth_clamp"));
|
||||
|
||||
bool debugDirectionalShadowmap;
|
||||
if (debug.getProperty("d.shadowmap.debug_directional_shadowmap",
|
||||
|
||||
+159
-457
@@ -1,490 +1,192 @@
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
/*
|
||||
* Copyright (C) 2018 The Android Open Source Project
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <filament/Camera.h>
|
||||
#include <filament/Engine.h>
|
||||
#include <filament/IndexBuffer.h>
|
||||
#include <filament/LightManager.h>
|
||||
#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/View.h>
|
||||
#include <filament/Viewport.h>
|
||||
#include <filament/SwapChain.h>
|
||||
#include <filament/Texture.h>
|
||||
#include <filament/TransformManager.h>
|
||||
#include <filament/RenderTarget.h>
|
||||
|
||||
#include <filamat/MaterialBuilder.h>
|
||||
#include <filament/VertexBuffer.h>
|
||||
#include <filament/View.h>
|
||||
|
||||
#include <utils/EntityManager.h>
|
||||
#include <utils/Log.h>
|
||||
|
||||
#include <math/norm.h>
|
||||
#include <filamentapp/Config.h>
|
||||
#include <filamentapp/FilamentApp.h>
|
||||
|
||||
#include <gltfio/AssetLoader.h>
|
||||
#include <gltfio/ResourceLoader.h>
|
||||
#include <getopt/getopt.h>
|
||||
|
||||
#include <SDL.h>
|
||||
#include <SDL_syswm.h>
|
||||
#include <SDL_video.h>
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
|
||||
#include <filamentapp/NativeWindowHelper.h>
|
||||
|
||||
#include "generated/resources/resources.h"
|
||||
#include "materials/uberarchive.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
using namespace filament;
|
||||
using namespace math;
|
||||
using namespace utils;
|
||||
using utils::Entity;
|
||||
using utils::EntityManager;
|
||||
|
||||
namespace {
|
||||
|
||||
const static uint32_t gIndices[] = {0, 1, 2, 2, 3, 0};
|
||||
|
||||
float const QUAD_WIDTH = .5;
|
||||
|
||||
const static math::float3 gVertices[] = {
|
||||
float3 {0, 0, 0} * QUAD_WIDTH,
|
||||
float3 {0, 1, 0} * QUAD_WIDTH,
|
||||
float3 {1, 1, 0} * QUAD_WIDTH,
|
||||
float3 {1, 0, 0} * QUAD_WIDTH,
|
||||
};
|
||||
|
||||
const static math::float2 gUVs[] = {
|
||||
{0, 0},
|
||||
{0, 1},
|
||||
{1, 1},
|
||||
{1, 0},
|
||||
};
|
||||
|
||||
const static short4 tbn = math::packSnorm16(mat3f::packTangentFrame(
|
||||
math::mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f},
|
||||
float3{0.0f, 1.0f, 0.0f}}).xyzw);
|
||||
|
||||
const static math::short4 gNormals[]{tbn, tbn, tbn, tbn};
|
||||
|
||||
struct TestPrimitive {
|
||||
TestPrimitive(Engine* engine) {
|
||||
vertexBuffer =
|
||||
VertexBuffer::Builder()
|
||||
.vertexCount(4)
|
||||
.bufferCount(3)
|
||||
.attribute(VertexAttribute::POSITION, 0,
|
||||
VertexBuffer::AttributeType::FLOAT3)
|
||||
.attribute(VertexAttribute::UV0, 1, VertexBuffer::AttributeType::FLOAT2)
|
||||
.attribute(VertexAttribute::TANGENTS, 2, VertexBuffer::AttributeType::FLOAT4)
|
||||
.build(*engine);
|
||||
vertexBuffer->setBufferAt(*engine, 0,
|
||||
VertexBuffer::BufferDescriptor(gVertices,
|
||||
vertexBuffer->getVertexCount() * sizeof(gVertices[0])));
|
||||
vertexBuffer->setBufferAt(*engine, 1,
|
||||
VertexBuffer::BufferDescriptor(gUVs,
|
||||
vertexBuffer->getVertexCount() * sizeof(gUVs[0])));
|
||||
vertexBuffer->setBufferAt(*engine, 2,
|
||||
VertexBuffer::BufferDescriptor(gNormals,
|
||||
vertexBuffer->getVertexCount() * sizeof(gNormals[0])));
|
||||
|
||||
indexBuffer = IndexBuffer::Builder().indexCount(6).build(*engine);
|
||||
|
||||
indexBuffer->setBuffer(*engine, IndexBuffer::BufferDescriptor(gIndices,
|
||||
indexBuffer->getIndexCount() * sizeof(uint32_t)));
|
||||
}
|
||||
|
||||
VertexBuffer* verts() const { return vertexBuffer; }
|
||||
IndexBuffer* inds() const { return indexBuffer; }
|
||||
|
||||
private:
|
||||
VertexBuffer* vertexBuffer;
|
||||
IndexBuffer* indexBuffer;
|
||||
};
|
||||
|
||||
struct TestMaterial {
|
||||
TestMaterial(Engine* engine) {
|
||||
material = Material::Builder()
|
||||
.package(RESOURCES_ICONTEST_DATA, RESOURCES_ICONTEST_SIZE)
|
||||
.build(*engine);
|
||||
}
|
||||
|
||||
MaterialInstance* instance() {
|
||||
auto inst = material->createInstance();
|
||||
instances.push_back(inst);
|
||||
return inst;
|
||||
}
|
||||
|
||||
private:
|
||||
Material* material;
|
||||
std::vector<MaterialInstance*> instances;
|
||||
};
|
||||
|
||||
struct TestTexture {
|
||||
TestTexture(Engine* engine, size_t width, size_t height, bool attachment=false) {
|
||||
auto usage = Texture::Usage::DEFAULT;
|
||||
if (attachment) {
|
||||
usage = usage | Texture::Usage::COLOR_ATTACHMENT;
|
||||
}
|
||||
texture = Texture::Builder()
|
||||
.width(width).height(height).levels(1)
|
||||
.usage(usage)
|
||||
.format(Texture::InternalFormat::RGBA8).build(*engine);
|
||||
uint8_t* data = (uint8_t*) malloc(width * height * 4);
|
||||
std::memset(data, 0xFF, width * height * 4);
|
||||
Texture::PixelBufferDescriptor buffer(data, size_t(width * height * 4),
|
||||
Texture::Format::RGBA, Texture::Type::UBYTE,
|
||||
[](void* buf, size_t size, void* user) {
|
||||
free(buf);
|
||||
});
|
||||
texture->setImage(*engine, 0, 0, 0, 0, width, height, 1, std::move(buffer));
|
||||
}
|
||||
Texture* get() const { return texture; }
|
||||
private:
|
||||
Texture* texture;
|
||||
};
|
||||
|
||||
std::pair<SDL_Window*, void*> createSDLwindow() {
|
||||
const uint32_t windowFlags = SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI;
|
||||
SDL_Window* win = SDL_CreateWindow("Hello World!", 0, 100, 800, 800, windowFlags);
|
||||
if (win == nullptr) {
|
||||
std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl;
|
||||
SDL_Quit();
|
||||
return {NULL, NULL};
|
||||
}
|
||||
|
||||
void* nativeWindow = getNativeWindow(win);
|
||||
#if defined(__APPLE__)
|
||||
prepareNativeWindow(win);
|
||||
setUpMetalLayer(nativeWindow);
|
||||
#endif
|
||||
|
||||
return {win, nativeWindow};
|
||||
}
|
||||
|
||||
struct IconScene {
|
||||
|
||||
struct Option {
|
||||
float border=1.4;
|
||||
bool postProcessing=true;
|
||||
bool useSkybox=false;
|
||||
};
|
||||
|
||||
IconScene(Engine* engine, Renderer* renderer, uint32_t w, uint32_t h, Option option)
|
||||
: engine(engine),
|
||||
renderer(renderer),
|
||||
material(engine),
|
||||
primitives(engine) {
|
||||
cameraEntity = EntityManager::get().create();
|
||||
camera = engine->createCamera(cameraEntity);
|
||||
camera->lookAt(float3(0, 0, -10.f), float3(0, 0, 0), float3(0, 1.0f, 0));
|
||||
float halfWidth = (QUAD_WIDTH / 2) * option.border;
|
||||
camera->setProjection(Camera::Projection::ORTHO,
|
||||
-halfWidth , halfWidth, -halfWidth, halfWidth, -50, 50);
|
||||
|
||||
scene = engine->createScene();
|
||||
|
||||
view = engine->createView();
|
||||
view->setViewport({0, 0, w, h});
|
||||
view->setScene(scene);
|
||||
view->setCamera(camera);
|
||||
view->setPostProcessingEnabled(false);
|
||||
|
||||
Entity renderable = EntityManager::get().create();
|
||||
matInstance = material.instance();
|
||||
RenderableManager::Builder(1)
|
||||
.boundingBox({{-10, -10, -10}, {10, 10, 10}})
|
||||
.material(0, matInstance)
|
||||
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES,
|
||||
primitives.verts(), primitives.inds(), 0, 6)
|
||||
.culling(false)
|
||||
.build(*engine, renderable);
|
||||
|
||||
scene->addEntity(renderable);
|
||||
|
||||
auto& tcm = engine->getTransformManager();
|
||||
tcm.create(renderable);
|
||||
auto inst = tcm.getInstance(renderable);
|
||||
mat4f xlate = mat4f::translation(float3(QUAD_WIDTH / -2.0, QUAD_WIDTH / -2.0, 0));
|
||||
tcm.setTransform(inst, xlate);
|
||||
}
|
||||
|
||||
void render(Texture* texture, Texture* renderTargetTexture, float3 const& multiplier) {
|
||||
TextureSampler sampler{TextureSampler::MinFilter::NEAREST,
|
||||
TextureSampler::MagFilter::NEAREST};
|
||||
|
||||
matInstance->setParameter("tex", texture, sampler);
|
||||
matInstance->setParameter("multiplier", multiplier);
|
||||
|
||||
RenderTarget* target;
|
||||
if (auto itr = targets.find(renderTargetTexture); itr != targets.end()) {
|
||||
target = itr->second;
|
||||
} else {
|
||||
target = RenderTarget::Builder()
|
||||
.texture(RenderTarget::AttachmentPoint::COLOR, renderTargetTexture)
|
||||
.build(*engine);
|
||||
targets[renderTargetTexture] = target;
|
||||
}
|
||||
|
||||
view->setRenderTarget(target);
|
||||
renderer->renderStandaloneView(view);
|
||||
}
|
||||
|
||||
void renderToSwapChain(SwapChain* swapChain, Texture* texture) {
|
||||
TextureSampler sampler{TextureSampler::MinFilter::NEAREST,
|
||||
TextureSampler::MagFilter::NEAREST};
|
||||
matInstance->setParameter("tex", texture, sampler);
|
||||
matInstance->setParameter("multiplier", float3 {1});
|
||||
|
||||
if (renderer->beginFrame(swapChain)) {
|
||||
// for each View
|
||||
renderer->render(view);
|
||||
renderer->endFrame();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private:
|
||||
Engine* engine;
|
||||
Renderer* renderer;
|
||||
View* view;
|
||||
Scene* scene;
|
||||
Camera* camera;
|
||||
TestMaterial material;
|
||||
TestPrimitive primitives;
|
||||
Entity cameraEntity;
|
||||
struct App {
|
||||
Config config;
|
||||
VertexBuffer* vb;
|
||||
IndexBuffer* ib;
|
||||
Material* mat;
|
||||
Camera* cam;
|
||||
Entity camera;
|
||||
Skybox* skybox;
|
||||
MaterialInstance* matInstance;
|
||||
std::unordered_map<Texture*, RenderTarget*> targets;
|
||||
};
|
||||
|
||||
struct MainScene {
|
||||
using TextureMatrix = std::vector<std::vector<Texture*>>;
|
||||
|
||||
MainScene(Engine* engine, Renderer* renderer, uint32_t w, uint32_t h, uint32_t nrows,
|
||||
uint32_t ncols)
|
||||
: renderer(renderer),
|
||||
primitives{engine},
|
||||
material(engine),
|
||||
engine(engine) {
|
||||
cameraEntity = EntityManager::get().create();
|
||||
|
||||
camera = engine->createCamera(cameraEntity);
|
||||
camera->lookAt(float3(0, 0, -10.f), float3(0, 0, 0), float3(0, 1.0f, 0));
|
||||
camera->setProjection(45.0, double(w) / h, 0.1, 50, Camera::Fov::VERTICAL);
|
||||
|
||||
scene = engine->createScene();
|
||||
|
||||
// skybox = Skybox::Builder().color({0.2, 0.2, 0.2, 1.0}).build(*engine);
|
||||
// scene->setSkybox(skybox);
|
||||
|
||||
view = engine->createView();
|
||||
view->setViewport({0, 0, w, h});
|
||||
view->setScene(scene);
|
||||
view->setCamera(camera);
|
||||
view->setPostProcessingEnabled(false);
|
||||
|
||||
root = EntityManager::get().create();
|
||||
auto& tcm = engine->getTransformManager();
|
||||
tcm.create(root);
|
||||
auto rootInst = tcm.getInstance(root);
|
||||
mat4f xlate = mat4f::translation(float3(-QUAD_WIDTH / 2 * nrows , -QUAD_WIDTH / 2 * ncols, 0));
|
||||
tcm.setTransform(rootInst, xlate);
|
||||
|
||||
matInst = material.instance();
|
||||
|
||||
renderable = EntityManager::get().create();
|
||||
scene->addEntity(renderable);
|
||||
RenderableManager::Builder(1)
|
||||
.boundingBox({{-10, -10, -10}, {10, 10, 10}})
|
||||
.material(0, matInst)
|
||||
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES,
|
||||
primitives.verts(), primitives.inds(), 0, 6)
|
||||
.culling(false)
|
||||
.build(*engine, renderable);
|
||||
|
||||
auto transformInst = tcm.getInstance(renderable);
|
||||
tcm.setParent(transformInst, rootInst);
|
||||
}
|
||||
|
||||
void render(Texture* texture, RenderTarget* target, uint32_t r, uint32_t c) {
|
||||
auto& tcm = engine->getTransformManager();
|
||||
TextureSampler sampler{TextureSampler::MinFilter::NEAREST,
|
||||
TextureSampler::MagFilter::NEAREST};
|
||||
matInst->setParameter("tex", texture, sampler);
|
||||
matInst->setParameter("multiplier", float3 {1});
|
||||
|
||||
auto transformInst = tcm.getInstance(renderable);
|
||||
mat4f xlate = mat4f::translation(float3(QUAD_WIDTH * r, QUAD_WIDTH * c, 0));
|
||||
tcm.setTransform(transformInst, xlate);
|
||||
|
||||
view->setRenderTarget(target);
|
||||
renderer->renderStandaloneView(view);
|
||||
}
|
||||
|
||||
void renderToSwapChain(SwapChain* swapChain, Texture* texture, uint32_t r, uint32_t c){
|
||||
auto& tcm = engine->getTransformManager();
|
||||
TextureSampler sampler{TextureSampler::MinFilter::NEAREST,
|
||||
TextureSampler::MagFilter::NEAREST};
|
||||
matInst->setParameter("tex", texture, sampler);
|
||||
matInst->setParameter("multiplier", float3 {1});
|
||||
|
||||
auto transformInst = tcm.getInstance(renderable);
|
||||
mat4f xlate = mat4f::translation(float3(QUAD_WIDTH * r, QUAD_WIDTH * c, 0));
|
||||
tcm.setTransform(transformInst, xlate);
|
||||
|
||||
if (renderer->beginFrame(swapChain)) {
|
||||
// for each View
|
||||
renderer->render(view);
|
||||
renderer->endFrame();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Scene* get() const { return scene; }
|
||||
Camera* getCamera() const { return camera; }
|
||||
View* getView() const { return view; }
|
||||
|
||||
private:
|
||||
Renderer* renderer;
|
||||
TestMaterial material;
|
||||
MaterialInstance* matInst;
|
||||
TestPrimitive primitives;
|
||||
TextureMatrix textures;
|
||||
Scene* scene;
|
||||
Entity light;
|
||||
Entity root;
|
||||
Entity renderable;
|
||||
Camera* camera;
|
||||
Entity cameraEntity;
|
||||
Skybox* skybox;
|
||||
View* view;
|
||||
std::vector<Entity> renderables;
|
||||
Engine* engine;
|
||||
};
|
||||
|
||||
struct Vertex {
|
||||
filament::math::float2 position;
|
||||
uint32_t color;
|
||||
};
|
||||
|
||||
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},
|
||||
};
|
||||
|
||||
static constexpr uint16_t TRIANGLE_INDICES[3] = { 0, 1, 2 };
|
||||
|
||||
static void printUsage(char* name) {
|
||||
std::string exec_name(utils::Path(name).getName());
|
||||
std::string usage(
|
||||
"HELLOTRIANGLE renders a spinning colored triangle\n"
|
||||
"Usage:\n"
|
||||
" HELLOTRIANGLE [options]\n"
|
||||
"Options:\n"
|
||||
" --help, -h\n"
|
||||
" Prints this message\n\n"
|
||||
" --api, -a\n"
|
||||
" Specify the backend API: opengl, vulkan, or metal\n"
|
||||
);
|
||||
const std::string from("HELLOTRIANGLE");
|
||||
for (size_t pos = usage.find(from); pos != std::string::npos; pos = usage.find(from, pos)) {
|
||||
usage.replace(pos, from.length(), exec_name);
|
||||
}
|
||||
std::cout << usage;
|
||||
}
|
||||
|
||||
int main() {
|
||||
SDL_Init(SDL_INIT_EVERYTHING);
|
||||
auto const [window, nativeWindow] = createSDLwindow();
|
||||
|
||||
Engine* engine = Engine::create(filament::backend::Backend::VULKAN);
|
||||
SwapChain* swapChain =
|
||||
engine->createSwapChain(nativeWindow, filament::SwapChain::CONFIG_HAS_STENCIL_BUFFER);
|
||||
Renderer* renderer = engine->createRenderer();
|
||||
|
||||
// Determine the current size of the window in physical pixels.
|
||||
uint32_t w, h;
|
||||
SDL_GL_GetDrawableSize(window, (int*) &w, (int*) &h);
|
||||
|
||||
filamat::MaterialBuilder::init();
|
||||
|
||||
TestTexture matTexture {engine, 27, 27};
|
||||
|
||||
size_t const nrow = 10, ncol = 10;
|
||||
|
||||
uint32_t const iconWidth = 50;
|
||||
uint32_t const iconHeight = 50;
|
||||
|
||||
IconScene iconScene {engine, renderer, iconWidth, iconHeight, {.useSkybox=false} };
|
||||
|
||||
auto buildTargets = [nrow, ncol, engine]() {
|
||||
std::vector<std::vector<Texture*>> targets;
|
||||
for (size_t r = 0; r < nrow; r++) {
|
||||
std::vector<Texture*> row;
|
||||
for (size_t c = 0; c < ncol; c++) {
|
||||
TestTexture ttex {engine, iconWidth, iconHeight, true };
|
||||
row.push_back(ttex.get());
|
||||
}
|
||||
targets.push_back(row);
|
||||
static int handleCommandLineArguments(int argc, char* argv[], App* app) {
|
||||
static constexpr const char* OPTSTR = "ha:";
|
||||
static const struct option OPTIONS[] = {
|
||||
{ "help", no_argument, nullptr, 'h' },
|
||||
{ "api", required_argument, nullptr, 'a' },
|
||||
{ nullptr, 0, nullptr, 0 }
|
||||
};
|
||||
int opt;
|
||||
int option_index = 0;
|
||||
while ((opt = getopt_long(argc, argv, OPTSTR, OPTIONS, &option_index)) >= 0) {
|
||||
std::string arg(optarg ? optarg : "");
|
||||
switch (opt) {
|
||||
default:
|
||||
case 'h':
|
||||
printUsage(argv[0]);
|
||||
exit(0);
|
||||
case 'a':
|
||||
if (arg == "opengl") {
|
||||
app->config.backend = Engine::Backend::OPENGL;
|
||||
} else if (arg == "vulkan") {
|
||||
app->config.backend = Engine::Backend::VULKAN;
|
||||
} else if (arg == "metal") {
|
||||
app->config.backend = Engine::Backend::METAL;
|
||||
} else {
|
||||
std::cerr << "Unrecognized backend. Must be 'opengl'|'vulkan'|'metal'.\n";
|
||||
exit(1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
return optind;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
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()
|
||||
.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);
|
||||
app.vb->setBufferAt(*engine, 0,
|
||||
VertexBuffer::BufferDescriptor(TRIANGLE_VERTICES, 36, nullptr));
|
||||
app.ib = IndexBuffer::Builder()
|
||||
.indexCount(3)
|
||||
.bufferType(IndexBuffer::IndexType::USHORT)
|
||||
.build(*engine);
|
||||
app.ib->setBuffer(*engine,
|
||||
IndexBuffer::BufferDescriptor(TRIANGLE_INDICES, 6, nullptr));
|
||||
app.mat = Material::Builder()
|
||||
.package(RESOURCES_BAKEDCOLOR_DATA, RESOURCES_BAKEDCOLOR_SIZE)
|
||||
.build(*engine);
|
||||
app.renderable = EntityManager::get().create();
|
||||
RenderableManager::Builder(1)
|
||||
.boundingBox({{ -1, -1, -1 }, { 1, 1, 1 }})
|
||||
.material(0, app.mat->getDefaultInstance())
|
||||
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES, app.vb, app.ib, 0, 3)
|
||||
.culling(false)
|
||||
.receiveShadows(false)
|
||||
.castShadows(false)
|
||||
.build(*engine, app.renderable);
|
||||
scene->addEntity(app.renderable);
|
||||
app.camera = utils::EntityManager::get().create();
|
||||
app.cam = engine->createCamera(app.camera);
|
||||
view->setCamera(app.cam);
|
||||
};
|
||||
|
||||
std::vector<std::vector<Texture*>> targets0 = buildTargets();
|
||||
std::vector<std::vector<Texture*>> targets1 = buildTargets();
|
||||
std::vector<std::vector<Texture*>> targets2 = buildTargets();
|
||||
auto cleanup = [&app](Engine* engine, View*, Scene*) {
|
||||
engine->destroy(app.skybox);
|
||||
engine->destroy(app.renderable);
|
||||
engine->destroy(app.mat);
|
||||
engine->destroy(app.vb);
|
||||
engine->destroy(app.ib);
|
||||
engine->destroyCameraComponent(app.camera);
|
||||
utils::EntityManager::get().destroy(app.camera);
|
||||
};
|
||||
|
||||
MainScene scene(engine, renderer, w, h, nrow, ncol);
|
||||
FilamentApp::get().animate([&app](Engine* engine, View* view, double now) {
|
||||
constexpr float ZOOM = 1.5f;
|
||||
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);
|
||||
auto& tcm = engine->getTransformManager();
|
||||
tcm.setTransform(tcm.getInstance(app.renderable),
|
||||
filament::math::mat4f::rotation(now, filament::math::float3{ 0, 0, 1 }));
|
||||
});
|
||||
|
||||
renderer->setClearOptions({.clear = false});
|
||||
float3 const a {.7, .3, .3};
|
||||
float3 const b {.3, .7, .3};
|
||||
std::vector<std::pair<size_t, size_t>> coords;
|
||||
for (size_t r = 0; r < nrow; r++) {
|
||||
for (size_t c = 0; c < ncol; c++) {
|
||||
coords.push_back({r, c});
|
||||
}
|
||||
}
|
||||
FilamentApp::get().run(app.config, setup, cleanup);
|
||||
|
||||
IconScene swapChainScene{engine, renderer, w, h, {
|
||||
.border = 1.0f, .postProcessing = false}};
|
||||
|
||||
TestTexture mainTex{engine, w, h, true};
|
||||
auto mainRT = RenderTarget::Builder()
|
||||
.texture(RenderTarget::AttachmentPoint::COLOR, mainTex.get())
|
||||
.build(*engine);
|
||||
|
||||
bool closeWindow = false;
|
||||
size_t count = 0;
|
||||
while (!closeWindow && ++count) {
|
||||
constexpr int kMaxEvents = 16;
|
||||
SDL_Event events[kMaxEvents];
|
||||
int nevents = 0;
|
||||
while (nevents < kMaxEvents && SDL_PollEvent(&events[nevents]) != 0) {
|
||||
nevents++;
|
||||
}
|
||||
|
||||
// Now, loop over the events a second time for app-side processing.
|
||||
for (int i = 0; i < nevents; i++) {
|
||||
const SDL_Event& event = events[i];
|
||||
switch (event.type) {
|
||||
case SDL_QUIT:
|
||||
closeWindow = true;
|
||||
break;
|
||||
case SDL_WINDOWEVENT:
|
||||
switch (event.window.event) {
|
||||
case SDL_WINDOWEVENT_RESIZED:
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
auto [r, c] = coords[count % coords.size()];
|
||||
float3 color0 = (r + c) % 2 == 0 ? a : b;
|
||||
float3 color1 = (r + c) % 2 == 0 ? b : a;
|
||||
auto rt0 = targets0[r][c];
|
||||
auto rt1 = targets1[r][c];
|
||||
auto rt2 = targets2[r][c];
|
||||
iconScene.render(matTexture.get(), rt0, color0);
|
||||
iconScene.render(rt0, rt1, color1);
|
||||
iconScene.render(rt1, rt2, float3 {.8});
|
||||
// engine->flushAndWait();
|
||||
scene.render(rt2, mainRT, r, c);
|
||||
// engine->flushAndWait();
|
||||
// engine->flush();
|
||||
// scene.renderToSwapChain(swapChain, rt1, r, c);
|
||||
|
||||
|
||||
if (count % 27 == 0) {
|
||||
swapChainScene.renderToSwapChain(swapChain, mainTex.get());
|
||||
}
|
||||
SDL_Delay(16);
|
||||
|
||||
// if (renderer->beginFrame(swapChain)) {
|
||||
// // for each View
|
||||
// renderer->render(scene.getView());
|
||||
// renderer->endFrame();
|
||||
// }
|
||||
|
||||
|
||||
// SDL_Delay(16);
|
||||
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
material {
|
||||
name : Icon,
|
||||
shadingModel : unlit,
|
||||
requires : [
|
||||
uv0
|
||||
],
|
||||
parameters : [
|
||||
{
|
||||
type : sampler2d,
|
||||
name : tex
|
||||
},
|
||||
{
|
||||
type : float3,
|
||||
name : multiplier
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
fragment {
|
||||
void material(inout MaterialInputs material) {
|
||||
prepareMaterial(material);
|
||||
vec3 m = materialParams.multiplier;
|
||||
vec3 rgb = texture(materialParams_tex, getUV0()).rgb * m;
|
||||
material.baseColor = vec4(rgb, 1.0);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,8 @@ material {
|
||||
uv0
|
||||
],
|
||||
shadingModel : unlit,
|
||||
vertexDomain: device,
|
||||
// vertexDomainDeviceJittered: true,
|
||||
}
|
||||
|
||||
fragment {
|
||||
@@ -20,17 +22,11 @@ fragment {
|
||||
if (gl_FrontFacing) {
|
||||
|
||||
// Make a lookup into the mirror texture.
|
||||
vec2 uv = getResolution().zw * gl_FragCoord.xy;
|
||||
// vec2 uv = getResolution().zw * gl_FragCoord.xy;
|
||||
vec2 uv = getNormalizedViewportCoord().xy;
|
||||
material.baseColor.rgb = texture(materialParams_albedo, uv).rgb;
|
||||
|
||||
// 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);
|
||||
|
||||
} else {
|
||||
material.baseColor = vec4(1, 0, 0, 1);
|
||||
}
|
||||
material.baseColor.a = 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
+198
-195
@@ -28,10 +28,17 @@
|
||||
#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>
|
||||
|
||||
@@ -40,11 +47,16 @@
|
||||
#include <iostream>
|
||||
|
||||
#include "generated/resources/resources.h"
|
||||
#include "generated/resources/monkey.h"
|
||||
//#include "generated/resources/monkey.h"
|
||||
#include "generated/resources/gltf_demo.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;
|
||||
@@ -55,8 +67,6 @@ struct App {
|
||||
utils::Entity lightEntity;
|
||||
Material* meshMaterial;
|
||||
MaterialInstance* meshMatInstance;
|
||||
MeshReader::Mesh monkeyMesh;
|
||||
utils::Entity reflectedMonkey;
|
||||
mat4f transform;
|
||||
|
||||
Texture* offscreenColorTexture = nullptr;
|
||||
@@ -66,12 +76,6 @@ struct App {
|
||||
Scene* offscreenScene = nullptr;
|
||||
Camera* offscreenCamera = nullptr;
|
||||
|
||||
enum class ReflectionMode {
|
||||
RENDERABLES,
|
||||
CAMERA,
|
||||
};
|
||||
|
||||
ReflectionMode mode = ReflectionMode::CAMERA;
|
||||
Config config;
|
||||
|
||||
utils::Entity quadEntity;
|
||||
@@ -80,46 +84,22 @@ struct App {
|
||||
Material* quadMaterial = nullptr;
|
||||
MaterialInstance* quadMatInstance = nullptr;
|
||||
|
||||
float3 quadCenter;
|
||||
float3 quadNormal;
|
||||
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;
|
||||
};
|
||||
|
||||
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 const char* DEFAULT_IBL = "assets/ibl/lightroom_14b";
|
||||
|
||||
static void printUsage(char* name) {
|
||||
std::string exec_name(utils::Path(name).getName());
|
||||
@@ -172,14 +152,6 @@ 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;
|
||||
}
|
||||
}
|
||||
@@ -189,126 +161,182 @@ 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 setup = [&app](Engine* engine, View* view, Scene* scene) {
|
||||
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& tcm = engine->getTransformManager();
|
||||
auto& rcm = engine->getRenderableManager();
|
||||
auto& em = utils::EntityManager::get();
|
||||
auto vp = view->getViewport();
|
||||
|
||||
// Offscreen view
|
||||
{
|
||||
// Instantiate offscreen render target.
|
||||
app.offscreenView = engine->createView();
|
||||
app.offscreenScene = engine->createScene();
|
||||
app.offscreenView->setScene(app.offscreenScene);
|
||||
|
||||
// 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.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();
|
||||
|
||||
// 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;
|
||||
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);
|
||||
}
|
||||
|
||||
// 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));
|
||||
// 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 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));
|
||||
app.asset = app.assetLoader->createAsset(GLTF_DEMO_DAMAGEDHELMET_DATA,
|
||||
GLTF_DEMO_DAMAGEDHELMET_SIZE);
|
||||
|
||||
// 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);
|
||||
loadResources();
|
||||
|
||||
// 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.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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
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)));
|
||||
}
|
||||
|
||||
// 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);
|
||||
// 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));
|
||||
|
||||
// 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);
|
||||
// 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);
|
||||
}
|
||||
};
|
||||
|
||||
auto cleanup = [&app](Engine* engine, View*, Scene*) {
|
||||
@@ -318,14 +346,10 @@ 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);
|
||||
@@ -337,43 +361,22 @@ int main(int argc, char** argv) {
|
||||
engine->destroy(app.quadMaterial);
|
||||
};
|
||||
|
||||
auto preRender = [&app](Engine*, View*, Scene*, Renderer* renderer) {
|
||||
auto preRender = [&app](Engine* engine, View* view, Scene*, Renderer* renderer) {
|
||||
renderer->setClearOptions({.clearColor = {0.1,0.2,0.4,1.0}, .clear = true});
|
||||
};
|
||||
|
||||
FilamentApp::get().animate([&app](Engine* engine, View* view, double now) {
|
||||
auto& tcm = engine->getTransformManager();
|
||||
utils::slog.e <<"offscreen view=" << app.offscreenView << " primary view=" <<
|
||||
view << utils::io::endl;
|
||||
|
||||
// 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());
|
||||
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;
|
||||
}
|
||||
});
|
||||
const auto model = camera.getModelMatrix();
|
||||
app.offscreenCamera->setModelMatrix(model);
|
||||
};
|
||||
|
||||
FilamentApp::get().run(app.config, setup, cleanup, FilamentApp::ImGuiCallback(), preRender);
|
||||
FilamentApp::get().run(app.config, setup, cleanup, gui, preRender);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -615,51 +615,14 @@ static bool processVariables(MaterialBuilder& builder, const JsonishValue& value
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < elements.size(); i++) {
|
||||
ParameterPrecision precision = ParameterPrecision::DEFAULT;
|
||||
MaterialBuilder::Variable v = intToVariable(i);
|
||||
std::string nameString;
|
||||
|
||||
auto elementValue = elements[i];
|
||||
if (elementValue->getType() == JsonishValue::Type::OBJECT) {
|
||||
|
||||
JsonishObject const& jsonObject = *elementValue->toJsonObject();
|
||||
|
||||
const JsonishValue* nameValue = jsonObject.getValue("name");
|
||||
if (!nameValue) {
|
||||
std::cerr << "variables: entry without 'name' key." << std::endl;
|
||||
return false;
|
||||
}
|
||||
if (nameValue->getType() != JsonishValue::STRING) {
|
||||
std::cerr << "variables: name value must be STRING." << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
const JsonishValue* precisionValue = jsonObject.getValue("precision");
|
||||
if (precisionValue) {
|
||||
if (precisionValue->getType() != JsonishValue::STRING) {
|
||||
std::cerr << "variables: precision must be a STRING." << std::endl;
|
||||
return false;
|
||||
}
|
||||
auto precisionString = precisionValue->toJsonString();
|
||||
if (!Enums::isValid<ParameterPrecision>(precisionString->getString())){
|
||||
return logEnumIssue("variables", *precisionString, Enums::map<ParameterPrecision>());
|
||||
}
|
||||
}
|
||||
|
||||
nameString = nameValue->toJsonString()->getString();
|
||||
if (precisionValue) {
|
||||
precision = Enums::toEnum<ParameterPrecision>(
|
||||
precisionValue->toJsonString()->getString());
|
||||
}
|
||||
builder.variable(v, nameString.c_str(), precision);
|
||||
} else if (elementValue->getType() == JsonishValue::Type::STRING) {
|
||||
nameString = elementValue->toJsonString()->getString();
|
||||
builder.variable(v, nameString.c_str());
|
||||
} else {
|
||||
MaterialBuilder::Variable v = intToVariable(i);
|
||||
if (elementValue->getType() != JsonishValue::Type::STRING) {
|
||||
std::cerr << "variables: array index " << i << " is not a STRING. found:" <<
|
||||
JsonishValue::typeToString(elementValue->getType()) << std::endl;
|
||||
return false;
|
||||
}
|
||||
builder.variable(v, elementValue->toJsonString()->getString().c_str());
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "filament",
|
||||
"version": "1.54.1",
|
||||
"version": "1.54.0",
|
||||
"description": "Real-time physically based rendering engine",
|
||||
"main": "filament.js",
|
||||
"module": "filament.js",
|
||||
|
||||
Reference in New Issue
Block a user