Compare commits

..

1129 Commits

Author SHA1 Message Date
prideout
073a6c7696 Prepare for a new npm release. 2019-07-03 11:26:49 -07:00
Philip Rideout
b30f6e5332 gltfio: JavaScript friendly error message for glb files. 2019-07-03 10:20:17 -07:00
Philip Rideout
384651e21a gltfio: fix JavaScript utility for glb files. 2019-07-03 10:20:17 -07:00
Philip Rideout
22dcdc770f gltfio: fix issue with bounding box computation.
If the client opts in to "recomputeBoundingBoxes", then we manually
compute a bounding box that ignores the glTF min / max annotations.

This computation was erroneously including the transform of the injected
root node, which is not part of the model.

This could cause a problem when creating the asset, then immediately
positioning it with its injected root node before the ResourceLoader
is done downloading vertex buffers.
2019-07-03 10:20:17 -07:00
Philip Rideout
fd4d6c0d44 Use std::move in MeshAssimp.
Tested this via material_sandbox, seems to be fine.

Fixes #1366.
2019-07-02 14:20:55 -07:00
Philip Rideout
ca5b52b2ce Add JavaScript / TypeScript support for RenderTarget. 2019-07-02 13:26:56 -07:00
Ben Doherty
cc4e9db81b Fix spherical harmonics parsing (#1370) 2019-07-02 12:54:52 -07:00
Ben Doherty
2bfea16459 Update usage of KtxUtility in iOS projects (#1371) 2019-07-02 12:33:55 -07:00
Philip Rideout
927662ea4d Add JNI for KTX, simplify the bloom Android demo. 2019-07-02 11:02:45 -07:00
Ben Doherty
5b2dc1d3de Link against IBL library in iOS projects, update README (#1369) 2019-07-02 10:43:54 -07:00
Ben Doherty
097feb0372 Delete accidentally committed file (#1368) 2019-07-02 09:58:48 -07:00
Romain Guy
9cd2971b65 Fix typo in documentation 2019-07-01 17:58:03 -07:00
Ben Doherty
fb16516480 Post-process materials: add post-process variant enum, split writeChunks function (#1365) 2019-07-01 12:57:41 -10:00
Mathias Agopian
76027cab85 fix a JobSystem bug in waitAndRelease()
We were not checking for jobs to execute during waitAndRelease(), so
this thread would essentially not participate to the work pool.
2019-07-01 14:25:26 -07:00
Mathias Agopian
64c95c615a Fix a theoretical wrapping around issue in WSDQ
The Work-stealing dequeue indices could wrap around after ~2 billion
calls to steal(). This could probably be achieved in a few hours.
By using 64-bits indices, we avoid the problem entirely.
2019-07-01 14:25:26 -07:00
Mathias Agopian
31745f6025 fix benchamrk JobSystem de-initialization
JobSystem's API requires to call emancipate() for each adopt() before
destroying the JobSystem.
2019-07-01 14:25:26 -07:00
Ben Doherty
2a8f04c791 Limit material compilation to supported backends (#1359) 2019-07-01 10:05:00 -10:00
Philip Rideout
3fdecfdefa gltf_viewer should not crash when there is no IBL. 2019-06-28 15:40:43 -07:00
Philip Rideout
26cbef7452 Fix intermittent cmgen crash. 2019-06-28 14:49:40 -07:00
Romain Guy
571a9b1ff3 Update README 2019-06-28 13:52:52 -07:00
Romain Guy
b84117eb92 Update READMEs 2019-06-28 13:51:57 -07:00
Romain Guy
6af0c72d0d Add missing getter in IndirectLight (#1356)
This change also factors a bunch of assert methods in a single place
which should slightly decrease binary size.
2019-06-28 13:38:51 -07:00
Mathias Agopian
12fde30f31 better comments and potential fix for work-stealing dequeue
It's better to use std::memory_order_seq_cst in pop() and
steal() because we rely on ordering of access to
mTop and mBottom members.
2019-06-28 13:08:56 -07:00
Philip Rideout
56c2d6338e Add spherical harmonics parser, reduce code duplication.
This uses strtof rather than stringstream and provides a common location
that can be leveraged by the upcoming JNI bindings.

Note that this new method lives in KtxBundle rather than KtxUtility. The
latter creates Filament textures and therefore does not get built into
libimage.
2019-06-28 11:10:04 -07:00
Romain Guy
10c8ff352d Try with clang 7.0.1 on Windows 2019-06-27 10:52:48 -07:00
Romain Guy
53ea1a00ec Fix warnings 2019-06-27 10:46:52 -07:00
Romain Guy
62a458099a Fix more warnings 2019-06-27 09:56:43 -07:00
Romain Guy
826d52bca2 Fix Windows build and warnings 2019-06-27 09:18:31 -07:00
Romain Guy
299a600377 Add CMake to PATH during install 2019-06-26 19:02:21 -07:00
Romain Guy
a4ebf23baa Update PATH 2019-06-26 18:53:05 -07:00
Romain Guy
d23a703ca5 Echo on again 2019-06-26 18:45:47 -07:00
Romain Guy
2beb9c5588 Don't update PATH 2019-06-26 18:40:43 -07:00
Romain Guy
a7fc4d8fbb Update PATH 2019-06-26 18:28:48 -07:00
Romain Guy
a5dc89b071 Don't use refreshenv 2019-06-26 18:18:16 -07:00
Philip Rideout
2bfec9f4af gltfio: Disable file formats that we do not need.
This only removes 40k but at least it is easy.
2019-06-26 18:15:02 -07:00
Romain Guy
1aa7fac8c2 Remove ci-common 2019-06-26 18:03:58 -07:00
Romain Guy
c01107fd52 Exit from the if statement to see what's going on 2019-06-26 17:55:43 -07:00
Romain Guy
5b27361ef0 Try with LLVM 6 2019-06-26 17:47:41 -07:00
Romain Guy
494ddc10e4 More logging 2019-06-26 17:36:24 -07:00
Mathias Agopian
6151f78d28 Update RELEASE_NOTES.md 2019-06-26 17:29:46 -07:00
Romain Guy
46c67632c7 Add logging to test Windows build 2019-06-26 17:28:33 -07:00
Philip Rideout
3f7cf2f971 Increase epsilon in test_cmgen. 2019-06-26 16:46:57 -07:00
Mathias Agopian
84cc8ff9c8 update release notes 2019-06-26 16:05:30 -07:00
Mathias Agopian
921c2bcd61 mitigate overhead of jobsystem
For jobs with that do very little work, the jobsystem can introduce
a lot of overhead, we mitigate this by:

- don't wake-up worker threads when scheduling several very small jobs,
like when scheduling the per-face jobs. 

- don't wait for per-face jobs to finish -- we only did that to avoid
a copy of the job's data.

- don't use multi-threading at all if the job has too little work. We
evaluate the work using the scanline length and number of samples.
2019-06-26 16:05:30 -07:00
Mathias Agopian
6ea8ed07ed a few libibl optimizations 2019-06-26 16:05:30 -07:00
Mathias Agopian
a5addd2257 convert libibl from double to float
since libibl is now used online, it makes more sense to do all the
math in float instead of double. It doesn't seem to impact quality.
2019-06-26 16:05:30 -07:00
Mathias Agopian
8b1d4ee06a a way to fold mirroring with prefiltering 2019-06-26 16:05:30 -07:00
Mathias Agopian
3e23d9742b fixup: remove code that wasn't supposed to be comited 2019-06-26 16:05:30 -07:00
Romain Guy
847d7dd71a Fix various errors discovered by clang-tidy (#1351)
- Move the static function declared in MaterialVariants.h to the .cpp
- Fix several use-after-move that were horribly wrong
2019-06-26 15:25:58 -07:00
Philip Rideout
10dc3a24e8 Add Kotlin sample for gltfio and custom render targets. 2019-06-26 13:55:23 -07:00
Romain Guy
c6c1cfef3c Small cleanups 2019-06-26 12:43:37 -07:00
Romain Guy
cc8a2f736b Fix progress bars display in cmgen 2019-06-26 12:43:37 -07:00
Philip Rideout
7fcd3e1a4f Java clients can now get material instances from renderables.
Discussed this feature with Mathias, we decided to create
MaterialInstance Java wrappers on the fly, and create Material Java
wrappers lazily. This is simple and avoids caching the wrapper objects,
which might otherwise lead to complexity and bugs.

Note that gltfio creates material instances behind the scenes, so this
feature is particularly useful for gltfio clients.
2019-06-25 19:47:49 -07:00
Philip Rideout
481fe5a087 Fix build break of gltfio-android. 2019-06-25 16:31:30 -07:00
Philip Rideout
2d690ac585 Add View::getRenderTarget to JNI. 2019-06-25 16:31:25 -07:00
Philip Rideout
a118299cfb Fix JNI for parameter arrays in MaterialInstance.
Previously we used the <T=float> template instantiation of setParameter
when the client specified FLOAT4. This resulted in the lower layer
adding needless padding, thus causing a buffer overflow.

Moreover the JNI code for this was somewhat cryptic because it casted an
enum value to an int, then added 1 to compute the size. We now use
a switch statement to improve readability.

This issue was discovered (and the fix was verified) with the upcoming
Android port of the bloom demo.
2019-06-25 15:32:30 -07:00
Mathias Agopian
bc01475920 optimize libibl for smaller workloads
We now never process mirroring or mipmaping with multithreading
it's just not worth it given the overhead of the jobsystem.

We also require 64 lines per job, below that, we only multithread per
face (6 threads). This should probably depends on the sample count,
but we don't have this facility yet.

Special case downsampling for mipmaping.

This alone improves performance by 2x for small cubemaps (e.g. 16x16).
2019-06-25 15:08:15 -07:00
Mathias Agopian
56e9d8eda5 Utility to prefilter an environment at runtime
This adds a utility function on IndirectLight populate the reflection
map from an environment at runtime. This performs some processing
similar to cmgen, albeit at a reduced quality.
2019-06-25 15:08:15 -07:00
Mathias Agopian
902e7021fd libibl doesn't use its own JobSystem instance 2019-06-25 15:08:15 -07:00
Adrian Perez
1773c42398 Comment fixes (#1346) 2019-06-25 13:42:52 -07:00
Philip Rideout
ae88536f0c Fix GL_INVALID_OPERATION in the default IBL.
In commit d955e73 we changed the default IBL from RGBM to RGB, but we
kept its internal format of RGBA8. Since the internal format is not
compatible with the data format, we see GL_INVALID_OPERATION during the
texture upload.

This is a single-pixel black texture, so the format does not really
matter, but this clears up a GL error seen on some platforms.
2019-06-24 13:22:34 -07:00
Philip Rideout
b4d6583901 Fix up WebGL bindings after RGBM removal. 2019-06-24 13:22:34 -07:00
Philip Rideout
b31e420064 Fix GL_INVALID_OPERATION in the default IBL.
In commit d955e73 we changed the default IBL from RGBM to RGB, but we
kept its internal format of RGBA8. Since the internal format is not
compatible with the data format, we see GL_INVALID_OPERATION during the
texture upload.

This is a single-pixel black texture, so the format does not really
matter, but this clears up a GL error seen on some platforms.
2019-06-24 13:21:45 -07:00
Philip Rideout
e4e439e2bf Fix build break. 2019-06-21 18:48:40 -07:00
Philip Rideout
a79a83d6da gltfio: gracefully error when mesh uses draco. 2019-06-21 16:12:59 -07:00
Philip Rideout
50d4dc6499 Update cgltf. 2019-06-21 14:51:41 -07:00
Philip Rideout
cbc662085e cgltf: expose extension lists 2019-06-21 14:51:41 -07:00
Philip Rideout
02a5541fed gltfio: minor improvements to error handling. 2019-06-21 10:09:57 -07:00
Romain Guy
14248621fe Workaround for a Mali driver bug (#1337)
Fixes #1320
2019-06-21 09:57:50 -07:00
Romain Guy
8c299d7b0b Update documentation to fix #1336 2019-06-21 09:29:49 -07:00
Ben Doherty
57d6bdff1b Allow mutliple API flags in matc (#1327) 2019-06-21 09:27:49 -07:00
Romain Guy
957ec9be60 Use R11G11B10F instead of RGBM in Android sample apps (#1333) 2019-06-20 16:31:17 -07:00
Philip Rideout
76147a7231 gltfio: fix bug with colliding TANGENT buffers.
ResourceLoader was mistakenly assuming that all primitives in the
entire model have TANGENTS in the same slot index.

Fixes #1326.
2019-06-20 16:29:22 -07:00
Philip Rideout
eff3d1a09b gltfio: show warning for missing normals. 2019-06-20 16:29:22 -07:00
Mathias Agopian
5f6d7a279c fix some warnings 2019-06-20 16:19:02 -07:00
Mathias Agopian
9bce361b3e Remove RGBM support entirely from filament.
⚠️ this break c++ and java source compatibility
2019-06-20 16:17:27 -07:00
Mathias Agopian
925e414e7b fix cmgen test 2019-06-20 15:19:59 -07:00
Mathias Agopian
aeec6f2df5 skygen handles rgb_11_11_10 2019-06-20 14:36:37 -07:00
Mathias Agopian
9358650bd4 remove generated test ibls
we're not using them in the build and they can easily get out of date.
2019-06-20 14:36:37 -07:00
Mathias Agopian
54d44a76a7 fix linux builds 2019-06-20 14:36:37 -07:00
Mathias Agopian
cc22183f20 update samples/envs 2019-06-20 14:36:37 -07:00
Mathias Agopian
2ded1c955f cmgen and filament now support RGB_10_11_11_REV
- RGB_11_11_10 is exported in a RGBA PNG file where the 4 channels are
  used as a uint32 storing a RGB_10_11_11_REV pixel.
  We use the .rgb32f extension, and those PNG files contain garbage 
  when seen in a PNG viewer.

- This is now the default for the -x option.

- compressed KTX files don't encode RGBM, which means they can't
  support HDR, unless an HDR compression scheme is used.
2019-06-20 14:36:37 -07:00
Mathias Agopian
d955e733bf remove RGBM support for skybox and ibl cubemap 2019-06-20 14:36:37 -07:00
Mathias Agopian
99a501f0c3 fix s3tc compression with HDR input
HDR input where producing garbage pixels, instead we saturate.
2019-06-20 14:36:37 -07:00
Ben Doherty
cdb2b47e0f Add material domains boilerplate (#1305) 2019-06-20 08:53:36 -07:00
joetoth
366e20cbe8 Compile gltfio with -fPIC 2019-06-19 19:34:25 -07:00
Philip Rideout
d5179bd9ed Fix JsonishParser to handle parameter arrays. 2019-06-19 15:32:40 -07:00
Philip Rideout
12506784da Expose texture usage flags to Java / Kotlin. 2019-06-19 15:32:26 -07:00
Romain Guy
4fee4d8da2 Don't use clear coat roughness as base roughness if clear coat is 0 (#1323)
This change finds the max of the clear coat and base layer roughness
then lerps the base layer roughness according to the amount of clear
coat.
2019-06-19 15:22:09 -07:00
Romain Guy
b1242163f7 Make CMake 3.10 the minimum version, add LTO option (#1316)
* Make CMake 3.10 the minimum version, add LTO option

* Install a newer CMake on Linux CI builds

* Update LLVM and Cmake on Windows CI

* Update build/windows/ci-common.bat

Co-Authored-By: Ben Doherty <benjdoherty15@gmail.com>

* Update formatting

* Apply suggestions from code review

* Update build/windows/ci-common.bat

* Update CMake

* Switch Android projects back to CMake 3.6
2019-06-19 12:53:03 -07:00
Mathias Agopian
8cd44fb2e8 rework math::half to be more generic
We introduce a templated fp<> class that can represent any float
format and convert to/from float32.
2019-06-19 12:22:01 -07:00
Romain Guy
33a8c9da7e Don't enable specularAO and multiBounceAO by default on mobile (#1319) 2019-06-19 11:04:40 -07:00
Pixelflinger
37facf7f7b fix build breakage on OpenGL ES targets 2019-06-19 01:25:37 -07:00
Mathias Agopian
1d20973363 IBL cubemaps can now be any size.
⚠️ breaks materials

There used to be a constraint that ibl cubemap needed to be
256x256. This constraint is now relaxed. IBL cubemaps can be any size.

We also add 16 float4 of padding to the frameUniform, which brings
its size to 1 KiB, the idea is to prevent more breakages in the
future.
2019-06-18 18:39:06 -07:00
Ben Doherty
0cb08cd114 Add mipmap level selection to Metal render targets (#1310) 2019-06-18 16:13:04 -07:00
Philip Rideout
c97ba45eed Fix several bugs in the gltfio JNI build. 2019-06-18 13:53:45 -07:00
Philip Rideout
74fcc456dc gltfio-android code review changes. 2019-06-18 13:53:45 -07:00
Philip Rideout
b17d606ed2 Introduce JNI bindings for gltfio.
For now this uses gltfio in the ubershader configuration in order
to avoid the filamat dependency. Note that we have not yet done a size
analysis of the `gltfio_core` library.

New Kotlin-based sample app is forthcoming.
2019-06-18 13:53:45 -07:00
Philip Rideout
3e97ac5268 Add Scene::getEntities to JNI. 2019-06-17 15:17:37 -07:00
Philip Rideout
a7ab0d98fa gltfio: allow clients to pass in EntityManager.
NOTE: Should we expose Engine::getEntityManager() to help with issues
like this? e.g. it would allow gltfio to extract it from the engine
rather than consuming an additional argument.

This fixes an entity id collision that I saw when building gltfio into
its own DSO (e.g. on Android). Since it is a separate executable it has
its own EntityManager singleton. This id collision was causing unwanted
entities to be added to the scene.
2019-06-17 11:11:06 -07:00
Philip Rideout
94b4f92bc5 Android: move JNI C++ utils into a common folder.
No need for a proper library, this is just a common location to simplify
JNI bindings in other projects like filamat and gltfio.

There is no need to move the one Java source file (`NioUtils.java`)
since downstream libraries will have a dependency on Filament, and
FindClass should work fine.
2019-06-17 08:47:27 -07:00
Romain Guy
77d058cf76 Fix MaterialInstance Java color bindings (#1308)
This changes addresses issue #1307. We recently fixed the way we support arrays
of parameters to allow arrays of 1 element. Previously single elements (e.g. float)
were treated as an array of 1 element and the other way around. Unfortunately our
Java bindings relied on this behavior to set colors. This change simply directly
calls the float3 and float4 variants of setParameter() when setting a color.
2019-06-16 19:15:18 -07:00
Mathias Agopian
52f815e240 Properly inverse the projection matrix for the shader
Some projections matrices were incorrectly inverted. 
This also fix #1281, fortunately, the incorrect matrix wasn't used
in that case.

Camera::inverseProjection only handles projection matrices it
created (as opposed to custom ones, which is what the shadowmap
code uses)
2019-06-14 16:59:05 -07:00
Philip Rideout
83b329c123 Fix incomplete FBO when rendering to cubemap.
The bug was reproduced and the fix was verified by making the following
changes to the lucy_bloom demo.

Fixes #1300.

diff --git a/samples/lucy_bloom.cpp b/samples/lucy_bloom.cpp
index c3a887ca..98f19c53 100644
--- a/samples/lucy_bloom.cpp
+++ b/samples/lucy_bloom.cpp
@@ -87,6 +87,7 @@ static void setup(LucyApp& app, Engine* engine, View* finalView, Scene* finalSce

     app.reflection.color = Texture::Builder()
         .width(FBO_WIDTH).height(FBO_HEIGHT).levels(1)
+        .sampler(Texture::Sampler::SAMPLER_CUBEMAP)
         .usage(Texture::Usage::COLOR_ATTACHMENT | Texture::Usage::SAMPLEABLE)
         .format(Texture::InternalFormat::RGBA8).build(*engine);
     app.reflection.depth = Texture::Builder()
@@ -96,6 +97,7 @@ static void setup(LucyApp& app, Engine* engine, View* finalView, Scene* finalSce
     app.reflection.target = RenderTarget::Builder()
         .texture(RenderTarget::COLOR, app.reflection.color)
         .texture(RenderTarget::DEPTH, app.reflection.depth)
+        .face(RenderTarget::COLOR, RenderTarget::CubemapFace::POSITIVE_Y)
         .build(*engine);

     app.primary.color = Texture::Builder()
diff --git a/samples/lucy_utils.cpp b/samples/lucy_utils.cpp
index 647a97f2..59a0135b 100644
--- a/samples/lucy_utils.cpp
+++ b/samples/lucy_utils.cpp
@@ -300,7 +300,8 @@ Entity createDisk(Engine* engine, Texture* reflection) {
                 material.ambientOcclusion = texture(materialParams_ao, getUV0()).r;

                 float2 uv = gl_FragCoord.xy * getResolution().zw; uv.y = 1.0 - uv.y;
-                vec3 reflection = texture(materialParams_reflection, uv).xyz;
+                float3 dir = float3(uv.x * 2.0 - 1.0, 1.0, uv.y * 2.0 - 1.0); // select POSITIVE_Y
+                vec3 reflection = texture(materialParams_reflection, dir).xyz;

                 // HACK: blend the reflection with the baseColor.
                 material.baseColor.rgb = mix(reflection, material.baseColor.rgb, 0.75);
@@ -311,7 +312,7 @@ Entity createDisk(Engine* engine, Texture* reflection) {
         .parameter(filamat::MaterialBuilder::SamplerType::SAMPLER_2D, "color")
         .parameter(filamat::MaterialBuilder::SamplerType::SAMPLER_2D, "roughness")
         .parameter(filamat::MaterialBuilder::SamplerType::SAMPLER_2D, "ao")
-        .parameter(filamat::MaterialBuilder::SamplerType::SAMPLER_2D, "reflection")
+        .parameter(filamat::MaterialBuilder::SamplerType::SAMPLER_CUBEMAP, "reflection")
         .targetApi(filamat::MaterialBuilder::TargetApi::OPENGL)
         .specularAntiAliasing(true)
         .shading(Shading::LIT)
2019-06-14 15:14:34 -07:00
Philip Rideout
909806b8ce API comments should not refer to backend types. 2019-06-14 15:14:13 -07:00
Mathias Agopian
d67d5cc267 Fix #1288, a division-by-zero in the SAO shader 2019-06-14 14:47:39 -07:00
Mathias Agopian
0b95f61549 Fix #477, add a way to set the intensity of the skybox
When there is no indirect light it wasn't possible to control the
skybox's intensity. Now the skybox has its own intensity that
is used in that case.
2019-06-14 14:47:15 -07:00
Mathias Agopian
6620edebb3 Add IndirectLight::radiance()
This allows to specify the irradiance by providing only the radiance
as SH, which might be easier in some case.
2019-06-13 13:23:56 -07:00
Mathias Agopian
4e4f7fd4ac improve IndirectLight::irradiance() documentation 2019-06-13 13:23:56 -07:00
Philip Rideout
f3769d8e86 lucy_bloom: minor fixups.
Tangents are required on the disk, not the quads...
2019-06-13 12:29:52 -07:00
Ben Doherty
5caf9b9575 SPIRV-cross update (#1295) 2019-06-13 12:15:37 -07:00
Philip Rideout
6d927f61aa lucy_bloom: use LINEAR to reduce texture lookups.
Many thanks to Dr. Rajan Srinivasan, who helped me with the math for this.
2019-06-13 12:10:53 -07:00
Philip Rideout
65a20df7c1 lucy_bloom: improve blur quality by not skipping texels 2019-06-13 12:10:53 -07:00
Philip Rideout
8ba0849bcf lucy_bloom: improve code comments 2019-06-13 12:10:53 -07:00
Philip Rideout
55abd67e81 lucy_bloom: do not dither intermediate framebuffers 2019-06-13 12:10:53 -07:00
Mathias Agopian
8cb38344ae remove float3 specialization 2019-06-12 18:31:24 -07:00
Mathias Agopian
d90d30d10b Fix #1270 Inconsistent setParameter behavior for arrays
Arrays in unform buffers are stored in std140, i.e. they have an
alignment of float4. This wasn't taken into account when setting
arrays (other than mat3)
2019-06-12 18:31:24 -07:00
Philip Rideout
709c5884ea geometry: tweak provided tangents to enforce orthonormality.
Fixes #1291.
2019-06-12 16:44:18 -07:00
Ben Doherty
5795bef02a Split runStaticCodeAnalysis into separate methods (#1287) 2019-06-12 13:42:18 -07:00
Philip Rideout
1f72b3ac24 gltfio: improve robustness for missing attributes.
The bistro model has some UV-free primitives associated with textured
materials. This caused Filament to emit warnings like:

[entity=445, primitive @ 0] missing required attributes (0xb), declared=0x3

We now catch these in gltfio, which enables a friendlier warning so that
the artist can go make a fix:

Missing UV0 data in Bistro_Research_Exterior_Paris_Building_01_paris_building_01_bottom_4669
2019-06-12 11:22:18 -07:00
Philip Rideout
0949e0a6f3 gltfio: fix bad color in ubershader mode. 2019-06-12 11:22:18 -07:00
Philip Rideout
1139209551 Add JNI bindings for RenderTarget.
New Kotlin sample app is forthcoming.
2019-06-12 10:18:30 -07:00
Philip Rideout
9c4fecb5c6 RenderTarget API now has per-attachment config, etc. 2019-06-11 15:56:24 -07:00
Philip Rideout
8142ffdfb7 Add bloom demo and release notes for #119. 2019-06-11 15:56:24 -07:00
Philip Rideout
961ad36443 Add View::setRenderTarget() for #119. 2019-06-11 15:56:24 -07:00
Philip Rideout
11309a8cf2 Introduce RenderTarget API for #119. 2019-06-11 15:56:24 -07:00
Romain Guy
7fadc438ec Add Filmic ALU tone mapping operator (#1286)
This change also cleans up tone mapping and transfer functions by
getting rid of unused code paths
2019-06-11 12:15:44 -07:00
Romain Guy
7388aeff55 Add Filmic ALU tone mapping operator (#1285) 2019-06-11 11:20:01 -07:00
Mathias Agopian
c886d5bcfd rename mirrorFrame() to copyFrame()
"mirror" was misleading, like it would apply a symmetry to the frame.
mirrorFrame() is just a blit from a swapchain to another, so it's a
copy.

The Java language API is kept for compatibility.
2019-06-10 23:45:38 -07:00
Mathias Agopian
58187f5c2c better command queue flushing
Instead of flushing the driver and command queue in RenderPass, we now
do that in the framegraph.

We flush the command queue after each pass -- which reduces memory
pressure on the command queue and improves parallel execution
with the backend thread. We flush the driver only after the last
pass -- maybe we could improve this in the future as the framegraph
gain more knowledge about what's going on.
2019-06-10 23:43:45 -07:00
Ben Doherty
6129930fb0 Show missing required attribute warning in release builds (#1278) 2019-06-10 21:48:52 -07:00
Romain Guy
505bb391c6 Remove file that shouldn't have been checked in 2019-06-10 18:13:55 -07:00
Mathias Agopian
3483eed412 address PR comments.
Typo, comments, unneeded code.
2019-06-10 15:45:32 -07:00
Mathias Agopian
aee938b51e Added resolution quality setting for SSAO 2019-06-10 15:45:32 -07:00
Mathias Agopian
ba95e522c4 Added SAO "reference" mode for debugging & comments
Reference mode allows to set an arbitrary
number of samples, which are computed in the 
shader.
2019-06-10 15:45:32 -07:00
Mathias Agopian
4c4303eacf Don't use derivative for computing normals
derivative-based normals are essentially
half-resolution, which creates artifacts around
geometry edges.
2019-06-10 15:45:32 -07:00
Mathias Agopian
6a7b1e8cb0 Tweak blur pass trying to improve perfs 2019-06-10 15:45:32 -07:00
Mathias Agopian
62cab7710c Add blur pass to SSAO 2019-06-10 15:45:32 -07:00
Mathias Agopian
96d34349ec encapsulate material data for postprocessing 2019-06-10 15:45:32 -07:00
Mathias Agopian
e4c6dcf3bc more efficient depth mipmaping
We simply pick one of the 4 depth texel based on its screen
space offset. Literature showed it doesn't impact AO
significantly.
2019-06-10 15:45:32 -07:00
Romain Guy
0f23633809 Fix warning in OpenGLDriver in release builds 2019-06-10 14:37:19 -07:00
Jeff McGlynn
53adfedc83 Fix msan use-of-uninitialized-value in destroyVertexBuffer (#1277)
GLVertexBuffer.gl.buffers is a std::array which is not
default-initialized, and createVertexBuffer only initializes the first
bufferCount fields of the array.

When destructing, destroyVertexBuffer iterated over all buffers to unset
bindings, but it was erroneously iterating over the entire array instead
of the initialized values.  Update the loop to only iterate over known
initialized values.
2019-06-10 13:38:00 -07:00
Romain Guy
2f736bee19 Update README.md 2019-06-09 21:43:59 -07:00
Ben Doherty
ae37ace15b Refactor MaterialBuilder, remove code duplication (#1269) 2019-06-09 18:58:35 -07:00
Romain Guy
1aed2379b9 Use a 32 bit index buffer when necessary (#1273)
Fixes #1272
2019-06-08 17:44:49 -07:00
Philip Rideout
f93046308c gltf_baker: improve error handling throughout. 2019-06-05 15:25:47 -07:00
Philip Rideout
1d514e6bf6 gltf_baker: allow re-baking after tweaking options. 2019-06-05 15:25:47 -07:00
Ben Doherty
62e51649fa Refactor MaterialBuilder chunks, findProperties (#1254) 2019-06-05 15:08:00 -07:00
Mathias Agopian
edb1beac3d give internet permission to ibl sample
this allows us to use snapdragon profiler
2019-06-05 14:34:58 -07:00
Romain Guy
f441e4ec4e Switch desktop to interleaved RGB noise (#1263)
This eliminates the flicker caused by triangle noise based dithering
when FXAA is turned on. This will require further investigation to
see if we can use triangle noise with FXAA without such artifacts.
2019-06-05 10:45:04 -07:00
Philip Rideout
70d569029b gltf_baker: allow adjustment to seed iterations. 2019-06-05 10:11:23 -07:00
Ben Doherty
018d6461f5 Update README with CoreVideo flag (#1266) 2019-06-04 21:15:42 -07:00
Romain Guy
413ce37681 Code formatting cleanup (#1264) 2019-06-04 21:11:00 -07:00
Romain Guy
9d31b7c008 Formatting of shaders 2019-06-04 16:23:20 -07:00
Philip Rideout
fb004a1990 AssetPipeline: fix crash with meshes that already have TEXCOORD_4.
Fixes #1256.
2019-06-04 15:48:54 -07:00
Philip Rideout
0262a38c7e gltf_baker: fix radio button numbering 2019-06-04 15:48:54 -07:00
Philip Rideout
d3f784d4f9 gltf_baker: add vertex normals visualization 2019-06-04 14:36:03 -07:00
Philip Rideout
475cd80faf gltfio: consolidate buffer slots.
Instead of using the actual glTF attribute indices, we now pack them
so that unused indices do not take up any VertexBuffer slots.

Fixes #1256.
2019-06-04 14:35:51 -07:00
Philip Rideout
37ff2d903f Additional validation in VertexBuffer::Builder::build.
If a client asks for more than 8 buffers in a VertexBuffer, they will
either crash (release) or hit an assert in OpenGLDriver (debug). It's
better to catch this earlier.

This was noticed while investigating #1256.
2019-06-04 13:23:07 -07:00
Philip Rideout
a900851abc gltfio: add optional diagnostic shading. 2019-06-03 17:30:56 -07:00
Romain Guy
3ae91957be Reorder shader 2019-06-03 17:24:00 -07:00
Philip Rideout
be11944f99 gltf_baker: AssetPipeline now has an options struct. 2019-06-03 13:03:14 -07:00
Philip Rideout
f3a70d82cd gltf_baker: make denoise optional. 2019-06-03 13:03:14 -07:00
Philip Rideout
61423f6900 gltf_baker: dilate charts for bent normals. 2019-06-03 13:03:14 -07:00
Philip Rideout
29d2f51fca gltf_baker: make chart dilation optional. 2019-06-03 13:03:14 -07:00
Philip Rideout
bfaa2bdd4e gltf_baker: allow 3D visualization of mesh normals. 2019-06-03 13:03:14 -07:00
Philip Rideout
ce4a3edf7b gltf_baker: visualizers now use fp32 textures.
This allows us to skip the CPU-side vector-to-color conversion that
occured at the end, and makes the real-time visualization consistent
with the final visualization.
2019-06-03 13:03:14 -07:00
Philip Rideout
6c153b046f gltf_baker: allow visualization of mesh normals. 2019-06-03 13:03:14 -07:00
Philip Rideout
7a732eb9c4 gltf_baker: show the bounds of the asset
Parameterization can run into problems for very large, very small, or
off-center assets. Showingthe min/max helps users diagnose these issues.
2019-06-03 13:03:14 -07:00
Philip Rideout
fdfb8862eb gltf_baker: allow tmin adjustment. 2019-06-03 13:03:14 -07:00
Philip Rideout
8df3253955 Resurrect the denoiser.
This follows the convention of providing our own CMake files in the tnt
folder(s) and successfully builds with the -i option (install).
2019-06-03 10:39:56 -07:00
Philip Rideout
78ec315b69 Overhaul the gltf_baker UI.
As per the design doc, this makes the app somewhat usable by eliminating
hardcoded filenames, the hidden state machine, etc.
2019-06-03 08:32:48 -07:00
Philip Rideout
13fc64470a Add shader_ball in glTF 2.0 format. 2019-05-31 15:02:35 -07:00
Philip Rideout
97b5d43bd5 AssetPipeline: renormalize after baking transforms. 2019-05-30 16:03:13 -07:00
Philip Rideout
c2fcb39336 resgen: remove unused flag. 2019-05-30 16:02:55 -07:00
Mathias Agopian
4e718f592c fix typo in ashmem fallback code
There was typo that prevented the ashmem fallback code to work.
This became briefly a problem on Android Q before we fixed our
use of private APIs.
2019-05-30 13:39:09 -07:00
Romain Guy
d780e8b2a0 Add link_library(libc++.a) (#1245)
* Add link_library(libc++.a)

* Always link statically against libc++ and libc++abi on Linux
2019-05-30 11:49:03 -07:00
Romain Guy
e1b773958f Add screen and multiply blending modes (#1241)
* Add screen and multiply blending modes

This change also fixes a sorting issue: different sorting modes
were sorted in different buckets which is incorrect. We want
to sort only by distance.

* Update release notes and Java API

* Fix build error
2019-05-30 10:17:16 -07:00
Ben Doherty
326a67acdb Fix iOS README formatting 2019-05-30 10:01:56 -07:00
Ben Doherty
2c36d0aaae Add gLTF iOS sample (#1236) 2019-05-30 10:00:21 -07:00
Jack Diver
1b45f253eb Removed unnecessary nullptr guard from MeshReader::MaterialRegistry destructor. 2019-05-30 09:54:37 -07:00
nitronoid
7a2b5125ed Moved back to [] syntax, works for exisitng string keys now. 2019-05-30 09:54:37 -07:00
nitronoid
da39dbcb57 Fixed move constructors for MeshReader::MaterialRegistry 2019-05-30 09:54:37 -07:00
Philip Rideout
fab70e878a Repair redball tutorial.
Our GitHub Pages site is currently using an older version of the
filament wasm file so we should avoid using the new API here.
2019-05-30 09:34:08 -07:00
Jack Diver
0d2fe62d68 Fixed enum scoping in DriverEnums.h to allow compilation with gcc (#1244) 2019-05-30 09:05:18 -07:00
Philip Rideout
bafa62cdec Repair the install target, disable denoise.
This rolls back denoise functionality to repair install builds.
Will investigate a proper fix by authoring a tnt/CMakeLists.
2019-05-29 15:41:34 -07:00
Ben Doherty
fd318826c5 Update spirv-cross (#1238) 2019-05-29 15:16:02 -07:00
Mathias Agopian
5403a19076 compute the projection scale properly.
It used to be hard-coded, which meant the size SAO radius changed with
the screen resolution.
2019-05-29 13:08:41 -07:00
Ben Doherty
89c4647c3c Expose gltfio library so it can be used by third_parties (#1230) 2019-05-28 14:50:38 -07:00
Mathias Agopian
9befaeb3ae SAO now uses a hierarchical depth to improve performance
- we generate LODs for the depth map using the framegraph
- these LODs are used in the SAO shader to improve data access locality
2019-05-28 13:09:11 -07:00
Philip Rideout
122eb8c82e gltf_baker: add UV visualization option 2019-05-28 11:44:04 -07:00
Philip Rideout
81b3f1b244 Build OpenImageDenoise only if TBB is available. 2019-05-28 11:43:50 -07:00
Philip Rideout
cc89b6ad1e PathTracer now applies OpenImageDenoise. 2019-05-28 11:43:50 -07:00
Philip Rideout
0f7aa70f2d Add OpenImageDenoise. 2019-05-28 11:43:50 -07:00
François Guthmann
b7304084d9 Corrected minor LaTeX typo (#1234)
The Jacobian formula display was broken in the cloth IBL section.
2019-05-25 13:14:35 -07:00
Romain Guy
a99d3b613f Remove unnecessary variants 2019-05-24 18:27:39 -07:00
Romain Guy
e896ed9d87 Add support for Parallax Occlusion Mapping in the PBR demo 2019-05-24 17:45:26 -07:00
Romain Guy
975395ce98 Simplify duplicate code 2019-05-24 17:01:57 -07:00
Philip Rideout
761b407159 AssetPipeline now has replaceOcclusion function.
This preserve original materials and substitutes the occlusion texture
with the generated AO.
2019-05-24 14:59:10 -07:00
Philip Rideout
5bdbf63ff6 gltf_baker now has an export modal. 2019-05-24 14:59:10 -07:00
Mathias Agopian
d3753ca463 fix framegraph test 2019-05-24 11:10:18 -07:00
Mathias Agopian
ca20ae3851 handle levels of textures in the framegraph
- it's now possible to use a level of a texture as an attachment of
  a rendertarget in the framegraph, by simply setting the desired level
  when specifying an attachment.

- for now, removed the (never used) feature where the framegraph could
  resize a resource under-the-hood.

- when requesting the physical renderder target by calling
  getRenderTarget(), we now must specify the same level that was used
  when the rendertarget was created. This is not ideal, and we hope
  to fix that in the future, but it'll require some serious internal
  changes (and maybe API changes)
2019-05-24 10:22:23 -07:00
Mathias Agopian
ea6d8dd212 Simplify useRenderTarget() helper and update accesses
- useRenderTarget() has a helper for simple cases, make it even more
easy to use. It assumes a single color attachment w/ WRITE access,
which is a common case.

- update all useRenderTarget() access flags
2019-05-24 10:22:23 -07:00
Mathias Agopian
92dfeb63dc Fix wrong assert in createRenderTarget()
- we were not taking the attachment's level into account.
2019-05-24 10:22:23 -07:00
Ben Doherty
68d6b5718e Unbind textures / sampler groups in Metal backend when destroyed, add SSAO workaround (#1222) 2019-05-24 09:14:25 -07:00
Philip Rideout
8f1d4ffa4d gltf_baker now parameterizes in a background thread. 2019-05-23 22:06:43 -07:00
Philip Rideout
3b2d75e129 gltf_baker now has adjustable resolution. 2019-05-23 22:06:43 -07:00
Mathias Agopian
2d2be0a214 update min/max LOD when using a texture as attachment
This fixes a problem where the min lod of a texture would be set
incorrectly when first drawing into the base level (common case) and
then creating a mipmap chain from it using blits.
Because drawing into the texture doesn't set the base level, after the
blit, the min level would be set to 1 instead of 0.

In fact, there was no way to set the level of a texture by drawing into
it, the only ways were by blitting or uploading data.


This change updates the min/max LOD when a texture level is attached to 
a rendertarget, regardless of whether we read or write -- assuming that
we will write to it. The problem is that at that stage we don't know
if we will read or write. That said, if the user attaches an uninitialized
level to read from it, who cares what really happens
2019-05-23 21:47:05 -07:00
Mathias Agopian
1716f9e7cd fix our ostream << hex << char
Even when hex modifier is used, 'char' should be printed as characters,
this is particularly relevant with 0.
e.g. out << (char)0, should write a nul terminator, not "0".
2019-05-23 21:46:28 -07:00
Mathias Agopian
da0d94caf2 promote uint8_t (i.e. uchar) to printable ints
An easy way to do this is to prepend a "+" to the variable.
2019-05-23 21:46:03 -07:00
Pixelflinger
1b41ef78cd Use depth culling when computing SSAO
Since we have a depth buffer, we might as well use it for depth-culling,
this automatically discards the skybox's fragments -- which we can
assume won't participate in SSAO.
2019-05-23 16:35:16 -07:00
Mathias Agopian
83c523256d fix debug builds 2019-05-23 13:09:11 -07:00
Pixelflinger
507aeb1e34 ssao is now done in quarter resolution
- this means that we cannot share the depth pass between ssao and color
passes, so all this code is removed, which simplify things a lot.

- the depth pass code is moved into the ssao codepath since they're now
intimately linked.

- and finals ssao shader can't rely on frameUniform which is set up with
the main buffer's size (instead of 1/4 res).
2019-05-23 12:59:22 -07:00
Romain Guy
43115e1f3b Update release notes 2019-05-23 12:56:56 -07:00
Romain Guy
0a5c068cb6 Switch specular AA to Tokuyoshi and Kaplanyan (#1218)
This replaces the previous "curvature to roughness" method. Both are related
and rely on the screen space variance of geometric normals but this new
solution offers more control (the screen space variance and the clamping
threshold can be controlled).
2019-05-23 12:56:26 -07:00
Ben Doherty
af559a1344 Use correct iPhone SDK availability flag, remove iOS OpenGL warnings (#1214) 2019-05-23 10:48:43 -07:00
Pixelflinger
0f69dbb0cf FrameGraph RenderTarget can now control how they're accessed
It's now possible to set if a render target's attachment is accessed
for read and/or write -- instead of always being hardcoded to both.

We just add an "access" field to Attachment, which is still set to
RW by default, but can be set in useRenderTarget(). 

The access mode only affects building the graph -- in the end it's just
a regular render target.
2019-05-22 18:40:52 -07:00
Philip Rideout
d7778e29b0 Light maps are now dilated to remove seams. 2019-05-22 12:33:07 -07:00
Mathias Agopian
9388aab32e fix ssao issue and rework RenderPass commandTypeFlags
There are now only 2 main commandTypeFlags, COLOR and DEPTH,
indicating if we need to generate respectively COLOR and DEPTH commands.
The command generation code, only has 3 implementations: DEPTH, COLOR and
DEPTH + COLOR.

We also add "options" flags that get passed along, used to control what
goes into the the depth pass -- this because sometimes we don't want
translucent or alpha masked objects. e.g. when rendering the shadow pass,
we want the DEPTH + shadow casters regardless of if they're translucent.


With this, we can fix a SSAO problem where alpha-masked objects where
not participating when the depth pre-pass was used. Now, we add those
objects to the DEPTH if SSAO is active and MSAA is not.
2019-05-22 09:54:13 -07:00
Ben Doherty
6d3cbb8d32 Accept MSAA render targets in MetalBlitter (#1194) 2019-05-22 09:05:06 -07:00
Ben Doherty
dd0e0840b8 Fix Metal error when sampler has not been bound (#1210) 2019-05-22 08:56:09 -07:00
Philip Rideout
5a5b6720b0 Add distance field generator to libimage.
This adds some new functions to libimage for computing distance fields
and coordinate fields. This runs on the CPU but uses an efficient
algorithm. This will initially be leveraged by the baking pipeline to
dilate charts, but could be useful in other applications.
2019-05-21 20:21:41 -07:00
Romain Guy
a4a26ef528 Update RELEASE_NOTES 2019-05-21 19:27:58 -07:00
Jeff McGlynn
9fe60a6368 Add proguard annotations for code used by native/reflection (#1207)
Filament references a few classes from native code and by reflections,
so when proguarding binaries we typically had to add an exception for
filament to make it run:

-keep class com.google.android.filament.** {*;}

In a compiled .dex file, the filament namespace takes about 120kb
(before compression), even if the classes aren't used.

To enable proguarding and stripping out unused filament classes,
introduce a UsedByNative and UsedByReflection annotation to explicitly
mark classes that need to be kept in the dex, so that the rest can be
potentially stripped out.

In my testing, this reduces the filament namespace in the .dex from
120kb->40kb, which translates to about 30kb apk size savings after
compression.
2019-05-20 21:02:54 -07:00
Philip Rideout
e2c3dfd341 xatlas: do not remove small faces 2019-05-20 19:37:37 -07:00
Philip Rideout
2687bf99d6 xatlas: fix crash caused by faulty spatial hash.
If A and B are equal keys, then hash(A) and hash(B) should be equal, but
xatlas was violating this constraint.

This bug was not present in Thekla's original code, it was introduced
later by the xatlas project.
2019-05-20 19:37:37 -07:00
Romain Guy
3d39f64c0d Move comment 2019-05-20 14:56:00 -07:00
Romain Guy
60bc860e76 Move IOR code to common_lighting 2019-05-20 14:54:44 -07:00
Romain Guy
2377287890 Fix curvatureToRoughnes 2019-05-20 14:50:44 -07:00
Romain Guy
cabdc255f5 Shader code cleanup
roughness is now called perceptualRoughness and linearRoughness
is now called roughness. It better matches papers, etc.
2019-05-20 14:45:26 -07:00
Philip Rideout
ac11e2b79a cgltf_writer: fix inconsistent buffer size.
`extension_flags` was uninitialized, which caused intermittent junk in
the output.
2019-05-20 13:23:47 -07:00
Philip Rideout
8f0fcc4efd xatlas: fix read-from-freed.
This fix has also been been submitted to the upstream repo.
2019-05-20 13:23:47 -07:00
Ben Doherty
399f7c24ac Fix flaky sstream test (#1205) 2019-05-20 13:09:03 -06:00
Philip Rideout
fdefa16cae jsbindings: add setColor4Parameter and rename setColorParam.
JavaScript does not have overloading so we generally use a numeric
suffix to distinguish overloads.

Fixes #1202
2019-05-20 10:43:38 -07:00
Mathias Agopian
95b4cdf819 Fix SSAO and SAO on Mobile devices
The fragment shader didn't work because of the default mediump
precision for floats on mobile.
We had the highp precision qualifier where needed.
2019-05-19 23:25:28 -07:00
Mathias Agopian
517bfc54c5 Use SAO style ambient occlusion
Both SSAO and SAO are available, but currently only
SSAO can be used.
SAO is more correct and produces less "halos", but
SSAO is sometimes more pleasant.

Note that this doesn't implement all the SAO optimizations
yet.
2019-05-19 23:25:28 -07:00
Pixelflinger
e840e72755 improve depth test usage and tracking
We now disable the depth test entirely when possible. this should save
a few gl calls.
2019-05-19 23:24:45 -07:00
Philip Rideout
992e27c4e0 Update cgltf to fix unlit materials. 2019-05-18 20:43:31 -07:00
Philip Rideout
cfb6a1c917 gltf_baker: add diagnostics. 2019-05-18 20:43:31 -07:00
Romain Guy
0347fb0441 Add new material properties: specular/multiBounceAmbientOcclusion (#1198) 2019-05-18 14:30:08 -07:00
Philip Rideout
24a77023bd Add AssetPipeline::bakeAllOutputs for diagnostic purposes. 2019-05-17 10:01:26 -07:00
Philip Rideout
07be9d1721 PathTracer: add bent normals and diagnostic targets. 2019-05-17 10:01:26 -07:00
Ben Doherty
88f6f4827c Allow creating and using MSAA textures as render targets (#1186) 2019-05-16 16:44:38 -07:00
Philip Rideout
9a72831a33 AssetPipeline can now preview baked texture. 2019-05-16 15:53:20 -07:00
Philip Rideout
59f929c7d3 Fix "already freed" bug in gltf_baker. 2019-05-16 15:53:20 -07:00
Romain Guy
f0aab6e46a Add micro-shadowing feature (#1188)
* Add micro-shadowing based on ambient occlusion

* Prevent crash when IBL is turned off

* Apply micro-shadows to baked AO only

* Remove debug code

* Add opacity control

* Fix opacity term

* Switch to micro-shadowing from Chan 2018
2019-05-16 12:24:16 -07:00
Romain Guy
8d7d10ae81 Use 64x64 DFG LUT on mobile targets (#1191)
The size of the LUT is now configurable at build-time with
-DDFG_LUT_SIZE=XX. It is 128x128 on desktop, 64x64 on Android,
WebGL and iOS.
2019-05-16 11:35:49 -07:00
Philip Rideout
c112b3ce40 Introduce AssetPipeline::SCALE_TO_UNIT to boost bake quality. 2019-05-15 16:44:33 -07:00
Philip Rideout
affc947ce0 gltf_baker: improve error reporting. 2019-05-15 16:44:33 -07:00
Philip Rideout
cbfb364c41 Introduce libs/rays and implement AO baking.
The AO baking procedure consists of the following steps:

1. Flatten the glTF hierarchy.
2. Generate a single 2D parameterization for the entire scene.
3. Embree Pass 1: Create G-Buffer using the above UVs as vert positions.
4. Embree Pass 2: Cast rays from the positions embedded in the G-Buffer.

The `gltf_baker` tool is not ready for general use but already
produces reasonable results for certain well-formed models.
2019-05-15 13:10:56 -07:00
Philip Rideout
c84c60112e Implement the bake button, uses a "UV camera" to cast primary rays. 2019-05-15 13:10:56 -07:00
Romain Guy
a9ef45dc9a Remember the high intensity for directional lights (#1184)
Fixes #1183
2019-05-14 09:02:09 -07:00
Romain Guy
bdd3e343ba Add multi-bounce AO based on GTAO (#1180) 2019-05-14 08:58:49 -07:00
Philip Rideout
cd364b029c gltf_baker: fix needless reload for rendering. 2019-05-13 18:55:56 -07:00
Philip Rideout
3e1ed97187 Add QUIET to find_package with embree, etc. 2019-05-13 18:55:37 -07:00
Ben Doherty
daddc25de8 Remove std::sstream from filamat (#1176) 2019-05-13 13:56:15 -07:00
Philip Rideout
4237ff42c9 PathTracer now generates ambient occlusion.
For now this uses the geometric normals provided by embree rather than
the smooth normals that ship with the model, I will fix this next.
2019-05-13 10:25:12 -07:00
Philip Rideout
3291fb6a1b Introduce gltf_baker tool. 2019-05-13 10:25:12 -07:00
Philip Rideout
f5b47dc95e PathTracer should not exceed MAX_JOB_COUNT. 2019-05-10 14:40:17 -07:00
Mathias Agopian
4f6d15d849 Try to handle “bad” normals
Normals reconstructed from derivatives at an edge are invalid and 
Cause dark spots in the final AO. We try to detect this case and
Assume no AO, which could be wrong too, but looks better more often.

I don’t think it’ll have an impact on performance because the normals
for the whole quad should be wrong together.
2019-05-10 13:58:00 -07:00
Ben Doherty
c35c1b6426 Fix Metal warnings (#1175) 2019-05-10 09:33:47 -07:00
Philip Rideout
80f6f18e54 Introduce gltfio::PathTracer and baking API.
AssetPipeline now has a path tracer and optionally uses embree. For now,
the path tracer only sends out visibility rays and generates a simple
hit-or-miss monochrome bitmap. It splits the render target into tiles
and invokes a JobSystem task for each tile.

Filament developers can optionally install embree using homebrew or a
debian package. This avoids bloating third_party and increasing our
build time. If embree is not installed, a friendly run-time error will
occur when attempting to invoke the rendering functionality in
AssetPipeline.

The AO code is not yet implemented, but this PR sets up the
infrastructure, API, and camera rays.
2019-05-10 08:04:09 -07:00
Romain Guy
ac8f55099d Indent SSAO options 2019-05-09 17:18:37 -07:00
Adrian Perez
3987da830c Fix -Wconversion issue in public header (#1172) 2019-05-09 17:00:34 -07:00
Mathias Agopian
cbae6120e1 Ambient Occlusion APIs are more descriptive
Use “AmbientOcclusion” instead of SSAO in all APIs.
2019-05-09 16:36:18 -07:00
Mathias Agopian
011daa952e Add API for controlling SSAO 2019-05-09 16:36:18 -07:00
Philip Rideout
cb98b75400 Implement AssetPipeline::parameterize() using xatlas. (#1167)
This feature consumes a flattened glTF asset and produces a glTF asset
with new topology and an additional set of UV coordinates suitable for
baking light maps.

I verified with a couple glTF models that the generated assets are
visually equivalent to the source assets, even though the topology and
scene hierarchy is different.

The actual light baking is not yet implemented, but this is a major step
towards that goal.
2019-05-09 14:09:27 -07:00
Ben Doherty
9a87b05570 Add new filamat_lite target to filamat (#1168) 2019-05-08 14:04:00 -07:00
Mathias Agopian
725ea06400 Add a contrast control for SSAO
This approximates ao^n with 1 <= n <=2 and gives a little bit of
control over the ambient occlusion contrast.
2019-05-07 18:35:19 -07:00
Mathias Agopian
facaa3326b SSAO is now configurable through the debug manager 2019-05-07 18:35:19 -07:00
Mathias Agopian
062ec48ee6 Implement basic SSAO 2019-05-07 18:35:19 -07:00
Mathias Agopian
6e0dc1dd2c set-up framegraph for SSAO
wip: This is very early stage.
2019-05-07 18:35:19 -07:00
Mathias Agopian
64afe136f6 Fix linkage errors
FMaterialInstance::setParameter<> template needs to be accessible from
other modules.
2019-05-07 18:35:19 -07:00
Ben Doherty
e7749c59ce Implement Metal fences (#1162) 2019-05-07 10:16:20 -07:00
Romain Guy
841f76f510 Update roughness-prefilter 2019-05-03 12:01:31 -07:00
Philip Rideout
2e391b01fe Introduce AssetPipeline for performing glTF manipulations. (#1163)
* Introduce AssetPipeline for performing glTF manipulations.

AssetPipeline offers a place for doing things like scene flattening,
transform baking, and optimization of glTF assets. These types of scene
manipulations will allow us to tackle lightmap baking in the upcoming
atlasgen tool.

This initial PR includes support for scene flattening, which is fairly
non-trivial. Support for parameterization via xatlas will be added in a
subsequent PR.

In a glTF asset, a single mesh can be referenced by several nodes, and
each reference can have a unique transform. AssetPipeline can flatten
the asset such that each instanced mesh has its own vertex data, and the
node transform gets baked into the vertex data.

Recall that gltfio is composed of two libraries: the core library (no
filamat) and the full library. This adds to the size of the full library
but leaves the core library as is.

* Fix various Windows build issues.
2019-05-03 09:49:04 -07:00
Philip Rideout
57fffab7b6 Improve SurfaceOrientation robustness when using UVs. (#1161)
Fix #1158
2019-05-03 08:18:13 -07:00
Gareth Morgan
45636e5afe Correct JS bindings for (#1137)
* Correct bindings for TransformManager::create and VertexBuffer::Builder::attribute

* Correct types
2019-05-01 17:09:32 -07:00
Ben Doherty
843372ace3 Only use Depth24Stencil8 textures on supported devices (#1160) 2019-05-01 12:35:45 -07:00
Benjamin Doherty
511a11a573 Implement Metal blitting 2019-05-01 12:06:27 -07:00
Mathias Agopian
13ae670568 framegraph improvements
- can now return the name of a pass in setup or execute
- can easily retrieve a rsrc descriptor in setup
2019-04-30 22:28:52 -07:00
Romain Guy
97850c62c7 Cleanup of filamat (#1157)
* Cleanup of filamat

* Add missing include
2019-04-30 16:39:22 -07:00
Pixelflinger
5b4ec6fd7d break dependency of Platforms on their backend
Platform implementations shouldn't depend on the concrete implementation
of the driver. e.g. PlatfromEGL.h shouldn't include OpenglDriver.h,
there is no reason for it.

Instead, we now have a {OpenGL|Vulkan|Metal}DriverFactory.h which is
only responsible to instantiate the correct concrete implementation
of the driver and Platform implementation only depend on that.

This effectively completely isolate the backend's header, which should
be completely private, and now is.

One benefit is that the backend's header needs to include 
DriverAPI.inc which uses complex macros and this used to be expanded
multiple times, for each Platform. So this should help a bit with 
build times.

We also mark *all* methods of all backends as "ALWAYS_INLINE inline",
which save quite a bit of code, without it, the compiler had to
instantiate each method twice. This saves 12KB on the final, stripped
libfilament-jni.so
2019-04-30 14:37:04 -07:00
Mathias Agopian
e4107201a3 Size optimizations
Most time we use ALWAYS_INLINE, we also intent to use "inline", which
allows the compiler to not emit the inlined function at all.
2019-04-30 14:37:04 -07:00
Philip Rideout
b9879cf23b Repair Vulkan: addBlob should return an index. (#1156) 2019-04-30 14:08:39 -07:00
Philip Rideout
2bc0e49bc7 Vulkan support for new RenderTarget DriverAPI. (#1153) 2019-04-30 13:20:24 -07:00
Romain Guy
f6767b59f5 Remove use after moves (#1155)
* Remove use after moves

* Remove unnecessary dependency
2019-04-30 13:18:49 -07:00
Philip Rideout
5228aba5dd Add xatlas and cgltf_write to third_party. (#1154)
This preps for an upcoming AO baking tool.
2019-04-30 12:54:40 -07:00
Benjamin Doherty
9a69a755bc Add Metal support 2019-04-30 00:14:07 -07:00
Pixelflinger
c688874064 Explicit RenderBuffer in RenderTarget
RendeTargets are now created with explicit RenderBuffer (that is 
Texture object in filament vocabulary).
2019-04-30 00:14:07 -07:00
Mathias Agopian
9e6d5f7727 backend textures can now represent a renderbuffer
We have a new TextureUsage::SAMPLEABLE flag, that is the default,
used for "regular" textures that can be sampled.
When this flag is not set, a RenderBuffer (in GL parlance) is
created instead.

This will be needed in an upcoming PR for creating RenderTarget more
explicitly.
2019-04-30 00:14:07 -07:00
Philip Rideout
59f1fb8956 gltfio: fix file path bug. (#1151)
The cgltf "base path" that gets passed to cgltf_load_buffers should
actually be the path to original glTF file, otherwise bin filepaths
are resolved incorrectly.
2019-04-29 22:42:17 -07:00
Mathias Agopian
224faeacb6 update code style / formatting clion config files 2019-04-26 15:38:40 -07:00
Mathias Agopian
f0465e442f release notes file.
this is intended to help creating releases. this
file should be updated each time a commit is significant enough that it should be mentioned in
release notes.

when doing code reviews, reviewers should take this into account for approval.
2019-04-26 14:50:38 -07:00
Benjamin Doherty
849bc91506 Remove necessity for frames to render to the default render target 2019-04-26 12:39:12 -07:00
Benjamin Doherty
f15667838b Fix bug-prone shader text loading 2019-04-26 12:39:12 -07:00
Benjamin Doherty
9ae2fe84f4 Remove automatic depth buffer creation for Metal swap chains 2019-04-26 12:39:12 -07:00
Mathias Agopian
0398aa4c67 fix minor issues
- use the clear flags to skip the clear code earlier

- better detection of the msaa RenderTarger with non msaa attachments
2019-04-25 16:22:39 -07:00
Mathias Agopian
409f95b50a disable "reverse resolve" and add some asserts
"reverse resolve" is needed on desktop to emulate
EXT_multisampled_render_to_texture. However, it is not easily supported
on Metal or GLES. So for now we avoid relying on this.

This means that filament requirements are lower than what
EXT_multisampled_render_to_texture guarantees.

Essentially filament doesn't rely on being able to preserve the 
content of a non-ms texture attached to a ms RenderTarget.

Also don't rely on being able to resolve+resize/move, which is
not supported in GLES.
2019-04-25 15:27:33 -07:00
Mathias Agopian
510451a35e minor clean-up 2019-04-25 15:27:33 -07:00
Mathias Agopian
a781fb6f2b support compilers that don't have attribute(packed)
this fixes #1140
2019-04-24 22:08:14 -07:00
Mathias Agopian
a429f361b8 TargetBufferFlags is now more comfortable to use
Added BitmaskType requirements so that we can easily and
safely do bitmask operations on TargetBufferFlags.
2019-04-24 16:21:11 -07:00
Mathias Agopian
be5d06d3c8 Emulate better EXT_multisampled_render_to_texture
We need to load the content of the resolved texture at
beginRenderPass time.
2019-04-24 16:21:11 -07:00
Mathias Agopian
ce6baeb714 debug: clear discarded buffers in debug builds
We now always clear in red/green discarded start/end attachments.
This is to make sure to expose discard bugs.
2019-04-23 18:27:39 -07:00
Mathias Agopian
85122d3fa9 method to get the GLbitfield from TargetBufferFlags 2019-04-23 18:27:39 -07:00
Mathias Agopian
5255871f1a fix blit from multi-sample rendertarget
there was a case where blitting from a multisample target with
a mix of multisample and non multisample attachments wouldn't work,
only the resolved non-multisample texture could be blitted.

this fix assumes that resolving doesn't damage the multisample buffer,
which is NOT TRUE on android with the EXT_multisampled_render_to_texture
extension. this will be fixed later.
2019-04-23 18:27:39 -07:00
Mathias Agopian
bd145cf18b Fix a FrameGraph discard bug with imported rendertargets
Imported render target's discard flags (i.e. the imported flags)
were ignored, which means we were discarding the imported buffer
each time we were drawing into it, especially the 2nd time when
drawing the ImGUI.
2019-04-23 18:27:24 -07:00
Ben Doherty
04859da116 Add hello-ar iOS sample (#1124) 2019-04-23 18:11:22 -07:00
Ben Doherty
1b41a73eb0 Fix incorrect depth comparisons with floating point depth formats (#1129) 2019-04-23 18:10:47 -07:00
Philip Rideout
9081a0b657 Add another missing file to site. 2019-04-23 15:14:54 -07:00
Philip Rideout
d87714e4ef Add missing files to web site. 2019-04-23 15:13:24 -07:00
Philip Rideout
45fae716de Update WebGL docs. 2019-04-23 15:04:06 -07:00
prideout
8d9ebb7a68 Use older JS syntax to fix Linux + Web. 2019-04-23 13:33:49 -07:00
Philip Rideout
15a8828a6c Bump the npm package to v1.2.0. 2019-04-23 12:54:32 -07:00
Philip Rideout
ad79bb8532 Upgrade Gradle and gradle wrappers. (#1123)
This includes a small change to our custom material task because old
gradle passed only the contents of out-of-date directories, newer gradle
passes both the contents and the directory itself.
2019-04-23 12:19:06 -07:00
Ben Doherty
7923964f50 Fix matinfo bug when printing Metal shaders (#1128) 2019-04-23 11:30:37 -07:00
Philip Rideout
7cf121b5c2 Fix intermittent JavaScript bug in gltfio. (#1132)
* gltfio + web: do not call loadResource twice.

* Fix intermittent JavaScript bug in gltfio.
2019-04-23 11:30:22 -07:00
Mathias Agopian
4da4c07b52 fix FBO leak when using MSAA in some cases
We would leak an FBO when using the same texture with multiple FBOs 
and MSAA, this is because we have to allocate a sidecar FBO in this case
and we were doing so even if it was already existing.

Also store the sidecar fbo with the texture instead of the RenderTarget,
because it has nothing to do with the later. In fact we could have
several textures (e.g. color + depth) who both need a sidecar fbo,
so it can't be stored in the RenderTarget structure.

Also clean-up bindTexture().
2019-04-23 10:13:52 -07:00
Mathias Agopian
524b33aa52 Fix crasher in framegraph
It would happen when using a rendertarget without a color buffer and 
a moveResource operation was set. We would incorrectly dereference the
color texture (which didn't exist).
2019-04-23 10:13:30 -07:00
Philip Rideout
657473ae2e gltfio: remove alpha cutoff from MaterialKey. (#1127)
Harmless cleanup. The cutoff value is a uniform and therefore does not
need to be a part of the material configuration structure.
2019-04-22 16:06:36 -07:00
Philip Rideout
dba5b05db6 Fix spelling errors. 2019-04-22 13:37:08 -07:00
Philip Rideout
b033334cbe Honor clear color, fixes #1125. (#1126) 2019-04-22 13:32:35 -07:00
Mathias Agopian
3f11af49a0 simplify RenderPass
Now that generate and execute commands are separate, we don’t need the
setExecuteSync() functionality — it can just be done explicitly when
needed.
2019-04-21 12:43:27 -07:00
Mathias Agopian
3ad41cd20c Fix dynamic lighting
We were not committing the frozen data UBOs. This broke recently.
Fixes: #1119
2019-04-20 22:42:52 -07:00
Mathias Agopian
1a7d517d4f Switch back triangle/segment intersection to float
Use a better and simpler algorithm that has less error.
2019-04-20 22:42:36 -07:00
Philip Rideout
061bcfc63c Fix warning about macro expansion. 2019-04-20 10:30:24 -07:00
Mathias Agopian
22be5f17b4 conversion between vec<T> and vec<U> are now implicit
This change allows for e.g. to call a method that takes double4 with
float4 parameters -- just like it would work with double and floats.
2019-04-19 17:31:37 -07:00
Mathias Agopian
e63282c9a2 removed unnecessary arithmetic check 2019-04-19 17:31:37 -07:00
Mathias Agopian
7795de4ac2 added vec{2|3|4}<T>
We can now use for e.g. vec4<float> instead of float4, this is
useful for templated code. The existing solution was to reach
out to the math::detail::TVec<> class.
2019-04-19 17:31:37 -07:00
Mathias Agopian
0cdfbc9524 fix a "shadow disappear" bug introduced recently
We were too aggressive removing vertices resulting from
the triangle/segment intersection test, that were not
contained in the frustum (this invariant should hold).
This happens because our triangle/segment intersection
is not watertight. Removing those vertices entirely would lead
to wrongly reduced light frustum.

Now that the lispsm code is more robust to these invalid vertices,
we can keep them. Most of the time they're harmless, because they're
close to the correct solution.
2019-04-19 16:48:43 -07:00
Ben Doherty
65718ceb81 Add external image support to Metal backend (#1104) 2019-04-18 10:57:55 -07:00
Mathias Agopian
1c81fcb535 Improve shadows depth resolution for large scenes
Compute the znear/zfar of the light space based on the bounding box
of each object in the scene instead of the bounding box of the union
of them. This is a bit more expensive, but we needs to run through
all of them anyways.
2019-04-18 10:37:57 -07:00
Mathias Agopian
a9089aef8a Improve stable mode significantly
"stable shadows" now work in all configurations of fitting,
camera origin, and light space origin.
2019-04-18 10:37:57 -07:00
Philip Rideout
2f7898e146 Update cgltf to v1.1. (#1113) 2019-04-18 09:46:17 -07:00
Mathias Agopian
beb2f74bdc Better frustum/box intersection, make code more robust
- switched the frustum/box intersection code to double. With large 
scenes, we were getting very wrong intersection points (up to 1m off).
This doesn't seem to happen with doubles. 

- reject points that end-up outside the frustum

- made LiSPSM code more robust against the problem above. When points
were falsely placed behind the near plane (due to bad intersections),
we could end-up with NaN (sqrt of negative numbers).
2019-04-17 18:12:31 -07:00
Ben Doherty
44754a9368 Revamp iOS samples to use XcodeGen (#1110) 2019-04-17 16:16:46 -07:00
Philip Rideout
4671b7c090 Some matinfo fixes. (#1108)
- Fix the "CString size mismatch" assert seen in debug config.
- Fix the --print-glsl option, which was printing junk.
2019-04-17 12:49:47 -07:00
Philip Rideout
0bdde49b47 Fix Vulkan validation layer ordering. 2019-04-17 09:55:01 -07:00
Philip Rideout
ac8d0c78a1 Vulkan: fix validation reporting for 64-bit, etc. (#1107) 2019-04-17 08:56:38 -07:00
Romain Guy
88098f99b9 Fix typo in equation 138 2019-04-16 13:39:24 -07:00
Philip Rideout
4e175421e0 Repair FILAMENT_VULKAN_VERBOSE. 2019-04-16 11:48:31 -07:00
Ben Doherty
8518c52a65 Add Filamat documentation (#1103) 2019-04-16 10:27:06 -07:00
Pixelflinger
af7c3784d6 add support for polygon offset in shadow map parameters
Also use new default bias parameters that seem to work better with
more scenes.

Renamed SAMPLING_HARD to SAMPLING_PCF_HARD because the GPU still
performs 4-taps PCF.
2019-04-15 18:53:41 -07:00
Pixelflinger
33600aa72c Handle DEPTH24 textures in the metal driver.
Metal only supports DEPTH24_STENCIL8, which is
what we're selecting for DEPTH24 (instead of
FLOAT32), this is closer to what the user asks
and doesn't use more memory.

Note that iOS doesn't support either.
2019-04-15 18:53:41 -07:00
Pixelflinger
c2b54c900a Handle float32 depth texture for the shadowmap
this is mostly for debugging because we really
don't want to use float textures for the shadow map.
2019-04-15 18:53:41 -07:00
Romain Guy
4349de5614 Better clamping for dot(N, V) (#1106)
* Better clamping for dot(N, V)

The previous clamping used abs(NoV) + EPS which could be much higher
than needed when NoV < -EPS.

* Move clampNoV()
2019-04-15 18:21:58 -07:00
Mathias Agopian
87e066ae91 shadowmap: cleanup jacobian code 2019-04-14 14:16:14 -07:00
Mathias Agopian
072c5ffd78 improve code readibility 2019-04-14 14:15:49 -07:00
Mathias Agopian
ad62b1e4ed Bake the constant bias into the shadow-map
The constant bias can be baked in the shadow map,
which saves some cycles in the vertex shader.
2019-04-13 11:01:02 -07:00
Mathias Agopian
16374cb11e Fix the calculation of the shadow constant bias
The previous code worked only for directional lights and didn't handle
LISPSM correctly (the bias was scaled down).
We now apply the bias in world space, which works with all configurations.

Additionally the bias was always wrongly scaled by 2x.

The cost is 3 multiply-add.
2019-04-13 11:01:02 -07:00
Pixelflinger
f6480921c0 don't approximate sin(x) by sin(x)^2
This is optimization is not worth it in the 
vertex shader, and the error is quite large
for some angles, resulting in harder to control
acne.
2019-04-13 11:01:02 -07:00
Mathias Agopian
9b0fa727f4 Added normal bias slider to debug ui 2019-04-13 11:01:02 -07:00
Philip Rideout
7b05d4fdeb Convert web helmet demo to use gltfio. (#1094)
This also adds an overlay element to show progress since this model
can take a while to load.
2019-04-12 09:41:04 -07:00
Philip Rideout
90c5af3b0e Add specular-glossiness to material_sandbox. (#1095) 2019-04-12 09:40:03 -07:00
Philip Rideout
1ddfe4b9a9 Fix fence-related Vulkan validation warnings. (#1093)
This adds a condition variable to ensure that the wait occurs after the
flush.

Longer term we would like to not use fences to measure frame time and
instead use timing queries.

Fixes #1051.
2019-04-12 08:20:21 -07:00
Philip Rideout
c6e2086e67 gltfio: add JavaScript bindings. (#1092) 2019-04-11 20:05:32 -07:00
Philip Rideout
fe2c5f6a9e Fix build issue due to static initialization order. 2019-04-10 14:37:32 -07:00
Philip Rideout
0a0c2497d5 Temporary fix for build break. 2019-04-10 14:28:02 -07:00
Philip Rideout
6663f6584b Simplify matc ParametersProcessor. (#1091)
(1) Merge two same-sized lists into a single map with struct values.

(2) Constify all the string-to-enum maps and move them into the
scope where they are used.

(3) Move a bunch of object methods into static free functions to
simplify the header and reduce code duplication.

(4) The PARAM_KEY_FOO string constants were referenced only once (except
in a few error messages) so replace them with string literals.
2019-04-10 14:07:58 -07:00
Romain Guy
23cdb56dcd Update static docs 2019-04-10 12:42:18 -07:00
Mathias Agopian
1a313ed299 Use ASharedMemory on Android when available 2019-04-10 12:29:51 -07:00
Philip Rideout
77237fd3fa Rename specular-glossiness parameters to their canonical names. (#1086)
* Rename specular-glossiness parameters to their canonical names.

* Remove roughness from MaterialInputs for specular-glossiness.
2019-04-10 07:10:27 -07:00
Romain Guy
724e9abf96 Tweak specularGlossiness 2019-04-09 13:45:07 -07:00
Philip Rideout
3629a8154c gltfio: support specular-glossiness (#1084)
Fixes #1068
2019-04-09 13:36:47 -07:00
Philip Rideout
37cb9247fd Add new shading model to Filament for specularGlossiness. (#1083)
* Add new shading model to Filament for specularGlossiness.

This adds a shading model based on KHR_materials_pbrSpecularGlossiness.
The corollary gltfio change will be in an upcoming PR.

* Improve documentation for specular-glossiness
2019-04-09 13:22:16 -07:00
Ben Doherty
9df268b2e1 Add MetalResourceTracker to Metal backend (#1082) 2019-04-09 10:58:25 -07:00
Mathias Agopian
45fdece973 Fix documentation typos 2019-04-08 16:42:21 -07:00
Philip Rideout
bd20d005ce gltfio: split out a core library for WebGL and Android (#1080) 2019-04-08 12:43:30 -07:00
Philip Rideout
dcc17b9b7e Allow dynamic doubleSided and materialThreshold. (#1072)
* MaterialInstance now has setMaskThreshold for convenience.

* Materials now support dynamic doubleSided property.

This does not change the format of material packages because they
already have both getDoubleSided() and getDoubleSidedSet().

The only way in which this change could impact existing applications is
that materials that explicity set doubleSided to "false" will now
respect the material's culling mode, rather than forcing it to NONE.

Fixes gltf_viewer with littlest_tokyo in ubershader mode.

Fixes #963.

* JNI for dynamic material properties.

* Add underscore prefix to internal material params.

* Remove un-needed mat info field.
2019-04-08 11:43:01 -07:00
Mathias Agopian
1634a8a2db debug option to fill the shadowmap with a checkerboard 2019-04-05 18:45:35 -07:00
Mathias Agopian
ff1053523c move the shadowmap renering code to ShadowMap.cpp 2019-04-05 18:45:35 -07:00
Mathias Agopian
e423611e39 first step of lispsm documentation 2019-04-05 18:45:03 -07:00
Ben Doherty
5ddbcdf418 Update filament/src/details/ShadowMap.h
Co-Authored-By: pixelflinger <pixelflinger@gmail.com>
2019-04-05 11:29:56 -07:00
Mathias Agopian
138c7e091e Fix a bug when computing the warp-space alignment matrix
We where treating a direction as a vector when projecting the camera's
forward vector. We never saw this bug before because we always used
<0,0,0> as the origin of the light space.

Now that we can pick an arbitrary light-space, we use the camera's
origin. Other choices are possible. But the camera origin is a nice
reference point.

Also simplify some code.
2019-04-05 11:29:56 -07:00
Mathias Agopian
bc381ac1b7 Add a "stable" shadow-map option
- "stable" mode disables all resolution optimizations that can affect
stability of the shadow map (e.g. lispsm, focusing)

- expose near/far hint + stable option to java
2019-04-05 11:29:56 -07:00
Mathias Agopian
147dfec5e5 Minor code/comment cleanup 2019-04-05 11:29:56 -07:00
Mathias Agopian
098f8f539d fix LISPSM warping frustum computation
We were using the view frustum as a basis instead of the shadow 
receivers volume which didn't give a good warping for the scene, we
were working around it by setting a virtual near plane dynamically.

Now that the warping frustum is tight, the virtual near plane is 
no longer needed -- it's still needed for the user to adjust the
precision and the default is still 1m.
2019-04-05 11:29:56 -07:00
Philip Rideout
230f0e1b2b Fix setCustomProjection JS binding.
Fixes #1073.
2019-04-05 08:37:45 -07:00
Philip Rideout
10251821c6 filagui: Introduce widget for manipulating vectors.
This is our first ImGui extension, it draws a draggable 3D arrow for
manipulating a unit vector. This is especially useful for tweaking the
light direction.
2019-04-04 10:59:38 -07:00
Ben Doherty
ba0bc9e481 Add correct Metal load and store actions (#1070) 2019-04-04 08:25:12 -07:00
Philip Rideout
ccc9606ffc gltfio: allow folder paths and disable auto-scale 2019-04-03 10:18:05 -07:00
Philip Rideout
ab52a759b8 Update Vulkan documentation. 2019-04-03 12:08:46 -04:00
Philip Rideout
396801b3d0 Fix stale comments in VulkanHandles. 2019-04-02 11:18:03 -07:00
Mathias Agopian
ca7f942b7b uhm, actually set the IBL rotation from the builder
Thankfully, the setRotation() method does work, which provides a
workaround.
2019-04-01 19:03:19 -07:00
Romain Guy
7b87662db0 Don't flip the normals (#1060)
* Don't flip the normals

* Fix the ubershader as well
2019-04-01 12:04:27 -07:00
Mathias Agopian
6374c9ab59 Expose the depth buffer to the postprocess pass 2019-04-01 10:57:32 -07:00
Pixelflinger
6bec21d611 split RenderPass::render()
instead we now have generateSortedCommands() and execute().
2019-04-01 10:57:32 -07:00
Mathias Agopian
c667fd3087 reorganize shadow and color pass
this is mostly simplifying and playing nicer with the framegraph, in
particular, now the framegraph computes the discard and clear flags
for the color pass.

the next step will be to move the shadow pass to the framegraph.
2019-04-01 10:57:32 -07:00
Mathias Agopian
9f99904a1f recordDriverCommands() now takes a range 2019-04-01 10:57:32 -07:00
Mathias Agopian
84c08d3abc rename updateUniformBuffer to loadUniformBuffer
This is to make it more evident that uploading a buffer
partially, doesn't keep its content and the back of the buffer
becomes undefined.
2019-04-01 10:56:46 -07:00
Ben Doherty
b020311c8c Add MetalBufferPool to Metal backend (#1053) 2019-03-29 17:00:24 -07:00
Romain Guy
9a72773c29 Move markdeep-rasterizer 2019-03-29 10:02:40 -07:00
Romain Guy
ab12d1d1bb Add postLightingColor property to materials (#1057)
* Add postLightingColor property to materials

This property can be used to modify the color computed in the lighting
passes of the materials. That color is blended with the computed color
according to the postLightingBlending option (add, transparent or opaque).

* Remove test

* Update docs

* Address code review comment

* Switch postLightingColor default blend mode to transparent
2019-03-29 10:02:07 -07:00
Philip Rideout
1fc8e8dbeb WebGL fix for "createContext is not a function".
One of the recent releases of emsdk moved its GL-related utility methods
into an object called GL, previously it exposed them directly.

This change also makes it so that we create the WebGL 2.0 context
and register it with emscripten, rather than the other way around.

Note that our CI does "emsdk activate latest", not sure when this broke
exactly.
2019-03-28 11:23:05 -07:00
Philip Rideout
feb7d968b6 Fix web build break. 2019-03-28 08:09:24 -07:00
Jack Diver
5366105ed2 Removing STL headers from filameshio (#1050)
* Removed STL headers from filameshio/MeshReader.h modified the samples to work the same, and made an effort to remedy the jsbindings although I'm not experienced with them.

* Fixed assignment operators for MaterialRegistry

* Fixed formating for MeshReader Material Registry

* Forgot one format

* Forgot another format
2019-03-28 07:30:22 -07:00
Philip Rideout
c92700ce28 Simplification due to sampler bindings starting at 0. 2019-03-28 07:29:14 -07:00
Ben Doherty
aa90f7edd6 Update Filament dependencies in iOS samples and README (#1049) 2019-03-27 14:37:51 -07:00
Philip Rideout
7a106be627 MATERIAL BREAK: VulkanBinder now binds 2 descriptor sets at a time.
This allows us to start Vulkan sampler bindings at zero, similar
to uniforms. Further cleanup will be implemented in a subsequent pull
request.
2019-03-27 13:11:24 -07:00
Philip Rideout
01e8154bc8 Rename CodeGenTargetApi to TargetLanguage.
This is just a cleanup and does not change any behavior. The old code
was a little strange because we'd generate code designed for OpenGL but
we'd pass VULKAN to the code generator. This was a little white lie that
really meant: "I will need SPIRV (for optimization purposes only)"
2019-03-27 10:17:02 -07:00
Philip Rideout
0076de25fa Configurability fixups per code review. 2019-03-27 09:24:44 -07:00
Philip Rideout
5090fe6395 Allow configurable attribute and binding counts.
This fixes two issues related to the Vulkan backend, one being a build
issue and the other being a run-time issue:

(1) Compile-Time Issue

To prevent accidental introduction of padding into hashed structures,
the Vulkan backend was static-asserting the size of the hash input. I
think it's fine to simply use a pragma pack instead.

(2) Run-Time Issue

SibGenerator was erroneuously using BindingPoints::COUNT instead of
UNIFORM_BINDING_COUNT for determining the first sampler binding index.
(Hopefully this logic will go away after some upcoming Vulkan cleanup.)
Since SibGenerator does not include Program, this moves the uniform and
sampler counts into EngineEnums, which might be a good place anyway
since they are ideally "config" constants.
2019-03-27 09:24:44 -07:00
Philip Rideout
abdfc44aa8 Fix Vulkan sampler enumeration to be similar to MetalDriver.
There will (probably) be a follow-up change that makes this even
simpler.
2019-03-26 15:36:36 -07:00
Mathias Agopian
2eb2f910b1 make OpenGLPlatform semi-public again
There is a new static method that can be used by derived classes to
instantiate an OpenGLDriver.

This is to support existing clients that use their own implementation
of OpenGLPlatform with filament's OpenGLDriver implementation.
2019-03-26 13:38:38 -07:00
Mathias Agopian
46877abd8c Handle.h is definitely a public API of libbackend 2019-03-26 11:47:47 -07:00
Mathias Agopian
e37701c097 Minor header cleanup
remove unneeded includes and reorder includes.
2019-03-26 11:47:47 -07:00
Mathias Agopian
09cae083b2 update doxygen config file 2019-03-26 11:47:47 -07:00
Mathias Agopian
0b8acb451d attempt to fix filament-js 2019-03-26 11:47:47 -07:00
Mathias Agopian
b26684deed rename namespace filament::driver -> filament::backend 2019-03-26 11:47:47 -07:00
Mathias Agopian
639d05374b update layering: libbackend is now at the bottom
We now have:

backend -> filabridge -> filaflat -> filament
                      -> filamat

Instead of backend depending on filabridge.
2019-03-26 11:47:47 -07:00
Philip Rideout
3f0bd4596e Add HwFence support to the Vulkan backend.
There are two changes involved here:

1) Recreate (do not recycle) the submission fences at every frame.

2) Add shared ownership semantics to existing fences to allow DriverAPI
   clients to "own" fences.

The first change was motivated by FrameSkipper, which might have a
fence list that is longer than the number of swap chain contexts.

The second change was implemented simply by creating a tiny wrapper
struct for VkFence with a proper constructor and destructor, then
leveraging shared_ptr.
2019-03-25 18:27:38 -07:00
Philip Rideout
c0c6b4bea0 (affects OpenGL) Move beginFrame calls to fix fence lifetime.
There are a couple reasons for this change. First of all, creating a
Vulkan fence outside of beginFrame / endFrame is not ideal because
the backend does not know yet which command buffer will be chosen
during swap chain acquisition.

Secondly, the Renderer currently calls endFrame in this order:

    frameInfoManager.endFrame
    mFrameSkipper.endFrame
    driver.endFrame

However the beginFrame calls were ordered like this:

    frameInfoManager.beginFrame
    driver.beginFrame
    mFrameSkipper.beginFrame

This change makes it such that the beginFrame calls have the reverse
ordering of the endFrame calls, which is less surprising.

I did a poor man's sanity check by running textured-object on a Pixel 2,
(which enables dynamic resolution) and hacking PostProcessManager to
make it visually obvious if anything were amiss.
2019-03-25 18:26:42 -07:00
Mathias Agopian
4bec201717 naming convention NUM_FOOS -> FOO_COUNT 2019-03-25 17:55:19 -07:00
Mathias Agopian
8ec3b62715 libbackend header cleanup
This is mostly about moving constant from EngineEnums.h to
the backend, either in Program.h or DriverEnums.h

The goal is that libbackend doesn't depend on EngineEnums.h
2019-03-25 17:55:19 -07:00
Mathias Agopian
3ca691cb40 API BREAK: Make all subclasses of Platform private
OpenGLPlatform, VulkanPlatform and MetalPlatfrom are no longer public
classes, they never should have been.

This will break code using those, the solution is simply to copy the
header locally.
2019-03-25 17:55:19 -07:00
Philip Rideout
570dd8a869 Add an extra clean task to Android samples.
It is easy to run into our new material version error if a stale
filamat file is sitting around, this helps with that.
2019-03-25 17:39:47 -07:00
Romain Guy
9c69b377b7 Fix #1039 (#1040) 2019-03-25 16:24:19 -07:00
Ben Doherty
8b7c2159d3 Fix issue with Windows JAWT swapchains (#1021) 2019-03-25 14:41:46 -07:00
Ben Doherty
25eef9dddb Implement mipmap generation for Metal backends (#1035) 2019-03-25 14:41:22 -07:00
Mathias Agopian
25c5bbd624 move the last public things out of Driver:: 2019-03-25 09:51:41 -07:00
Mathias Agopian
1f183def46 move more public stuff out of Driver:: into DriverEnums.h
These data structures are part of the public API of libbackend.
2019-03-25 09:51:41 -07:00
Mathias Agopian
a1bce26765 Major cleanup/refactoring
- get rid of type aliases in Driver:: we use the driver:: version instead.

- Only use the Handle<> aliases in DriverAPI.inc -- they exist only
  because of the macro hackery we have to do.

- move all public-ish types of libbackend into the 'driver' namespace
  (later to be renamed to 'backend')
2019-03-25 09:51:41 -07:00
Mathias Agopian
395e68a73e DriverBase.h is now private like it should be.
This removes a dependency on DriverBase.h of libfilament.a

This also means that Platform::create() and createDriver() are now
public APIs of libbackend -- not reserved to FEngine anymore.
2019-03-22 16:23:20 -07:00
Pixelflinger
99e1e37964 Move GPUBuffer out of libbackend 2019-03-22 16:23:20 -07:00
Pixelflinger
aad584e521 fix windows/linux build 2019-03-22 09:45:51 -07:00
Mathias Agopian
2b5f6cafa6 Separate src/driver into its own library
In this first step, we just "blindly" move everything under src/driver
to a new library libbackend.a. And all headers are moved under
private/backend.

Note that "driver" is renamed "backend", but namespaces are unchanged for now.

Later we'll have to untangle the actual private headers from public
ones and ideally not have any private headers.
2019-03-22 09:45:51 -07:00
Romain Guy
7d31d1a384 Use LINEAR/LINEAR_MIPMAP_LINEAR as the default sampling methods (#1028)
If the glTF file defines bits of the sampler but not the min/mag filters,
gltfio otherwise uses NEAREST. And it looks bad.
2019-03-21 17:52:40 -07:00
Mathias Agopian
004ffce334 MSAA is now disabled when post-processing is disabled
It's more logical to do it this way in the API. Also, MSAA needs an
intermediate buffer (currently), so enabling MSAA in the "UI" view 
wouldn't do what's expected -- it would prevent the "UI" to be blended
properly (again, currently).
2019-03-21 17:42:02 -07:00
Pixelflinger
43175adcae A way to get the corner vertices of an Aabb + typo 2019-03-21 17:40:44 -07:00
Philip Rideout
ab3626570a Rename VulkanDriverImpl h/cpp to VulkanContext and VulkanUtility. 2019-03-21 09:49:18 -07:00
Pixelflinger
a2fec34c4b turns out the NoopDriver is needed in some tests 2019-03-21 09:45:51 -07:00
Pixelflinger
daba56ee85 generate the ImportExecutable*.cmake files in the build directory
ImportExecutable* was generated in the root, instead of the out
folder when using the build script. This is more hermetic.
2019-03-20 22:06:08 -07:00
prideout
b66a1184e9 VulkanDriver: remove all CPU work queues. 2019-03-20 18:49:45 -07:00
Ben Doherty
0632d7ac3f Fix Metal sampler binding and memory leak (#1017)
* Fix memory leak

* Rework enumerateSamplerBuffers

* Fix segfault
2019-03-21 09:48:32 +09:00
Mathias Agopian
a6aa3934b1 add Aabb::extent() + comments + typo 2019-03-20 17:47:36 -07:00
Mathias Agopian
e458c94e7f filament::math:: -> math:: in libfilament
also, don't fully qualify math:: in .cpp
2019-03-20 17:31:23 -07:00
Philip Rideout
b684bdc83d VulkanDriver: do not defer uploads.
This gets us closer to being able to remove the pendingWork queues.
2019-03-20 12:51:07 -07:00
Philip Rideout
3265e0d68e Clean up VulkanDisposer per code review. 2019-03-20 12:10:10 -07:00
Philip Rideout
48723fb10f VulkanDriver: introduce disposer and command buffer wrapper.
This introduces a reference counting mechanism to allow us to defer
destruction of Vulkan resources to the correct time, rather than doing
an aggressive flush-and-wait before every vkDestroy*().

This also preps for removal of the "pending work" queues of
std::function, in favor of using the new Vulkan command buffer
designated for extra-frame activities such as uploads, blits, and layout
transitions.
2019-03-20 12:10:10 -07:00
Mathias Agopian
0ce6c8d8d0 rework scissor/viewport API a bit in the backend
- the IGNORE_VIEWPORT flag is gone. It wasn't actually needed and what
  it was doing was ambiguous.

- removed the backend viewport() API which wasn't actually needed.

- beginRenderPass() now ALWAYS sets the viewport and scissor but 
  doesn't necessarily clears honoring the scissor (based on the
  IGNORE_SCISSOR flag).

- the GLES backend now just sets the scissor when it needs it, as opposed
  to always trying to keep it set. we now rely on state tracking to
  de-dup the gl calls.
2019-03-20 11:37:21 -07:00
Mathias Agopian
2052116a35 don't call EGL during static initialization
On Android this can cause a dead-lock, because it looks like dlopen()
holds a lock while calling static initializers.

Bug: 126424427
2019-03-19 17:53:23 -07:00
Mathias Agopian
c6aebd61f6 Add filter parameter to the blit() backend function
Because with OpenGL ES backends, it's not allowed
to blit with a linear filter when depth/stencil is used, we need to
expose the filtering option.
In the GLES backend if the linear filter is selected and depth/stencil 
is selected, filtering is downgraded to nearest silently.
2019-03-19 17:21:08 -07:00
Mathias Agopian
02ed4c6c4d update filamesh file 2019-03-19 17:20:52 -07:00
Mathias Agopian
e07a634c06 fix msaa and post-processing documentation 2019-03-19 11:38:47 -07:00
Mathias Agopian
9daf7aab64 Decouple tone-mapping, fxaa, msaa and dynamic resolution
It's now possible to enable/disable tone-mapping, fxaa, msaa and
dynamic resolution independently.

A new set/getToneMapping() method is added to View.

It's still possible to disable *all* these post-processing effects
together using setPostProcessing(). This is currently needed when
rendering a transparent view (such as UI) on top of another view.
This limitation might be addressed in the future.

This fixes #621
2019-03-19 11:38:47 -07:00
Mathias Agopian
b94c032489 Clear newly allocated color buffers in DEBUG
On DEBUG builds, we always clear newly allocated buffers to
yellow.

Also did some minor cleanups.
2019-03-19 11:38:47 -07:00
Mathias Agopian
4a5323fa53 fg: fix an issue with imported rendertargets
when a resource that is also an attachment of a rendertarget is aliased
(with moveResource) with a resource from an imported rendertarget, the later
wouldn't always replace the former as expected.
2019-03-19 11:38:47 -07:00
Romain Guy
2e22a26ca5 Fix filamat build (#1005)
Filamat public headers were including a private header. This PR fixes
this problem. It also forces filamat to always be compiled to avoid
breaking filamat without noticing. The flag `-l` is not available
anymore in build.sh as a result.
2019-03-18 18:40:48 -07:00
prideout
861a0bbb8f VulkanDriver: remove badly named "releaseCommandBuffer" 2019-03-18 14:59:38 -07:00
prideout
fe35a98c91 VulkanDriver: remove depth from SurfaceContext. 2019-03-18 14:59:38 -07:00
prideout
3b528263e5 VulkanDriver: introduce "work" command buffer. 2019-03-18 14:59:38 -07:00
Ben Doherty
54fe2a6f2e Add additional documentation on filamat flag for material builder sample (#1004) 2019-03-19 04:20:32 +09:00
Mathias Agopian
289b889a1a oops fix build, missed file.
remove dependency on JobSystem.h in public header
this should fix #995
2019-03-15 17:07:29 -07:00
Mathias Agopian
67743db2b7 Texture format must be specified in the framegraph
Eventually the framefraph will deduce some of these things automatically,
but for now, the texture format must be specified.

Also added a couple error checks in the gl backend.
2019-03-15 16:58:20 -07:00
Mathias Agopian
ea7e9556c0 don't re-resolve when blitting from multisample render target
when blitting from a multisample render target, we must use the 
resolved buffer (b/c resolve is always done in endRenderPass), currently
we were basically resolving twice.
2019-03-15 16:58:20 -07:00
Mathias Agopian
d25dd6234c remove dependency on JobSystem.h in public header
this should fix #995
2019-03-15 16:58:03 -07:00
Ben Doherty
38e08131bc Update libs/utils/include/utils/compiler.h
Co-Authored-By: pixelflinger <pixelflinger@gmail.com>
2019-03-15 15:42:28 -07:00
Mathias Agopian
5383174df4 Use proper "restrict" syntax on visual studio 2019-03-15 15:42:28 -07:00
Romain Guy
8a6881544f Fix Android samples (#993)
Fixes issue #992
2019-03-15 09:09:00 -07:00
Mathias Agopian
08457e1f16 Workaround a UBO/glFlush interaction on some GPUs
Some GPU seem to loose the content of UBOs for draw calls emitted 
before a glFlush followed by more draw calls.

On those GPUs, we just never call glFlush, which could result in
reduced parallelism between the cpu and gpu.
2019-03-14 22:31:05 -07:00
prideout
b4270909c4 Reduce watermark console spew. 2019-03-14 16:18:28 -07:00
Romain Guy
1c37eb37b6 Don't test an undeclared variable (#987) 2019-03-14 15:33:51 -07:00
Mathias Agopian
2f34f9f857 remove vector comparison operators
they're dangerous as they will make things like
std::min() work, but probably won't do the
right thing.
2019-03-14 13:13:57 -07:00
Mathias Agopian
ee28f0adac Fix #978 -- iOS samples don't build 2019-03-14 13:13:41 -07:00
Philip Rideout
df9791faaf gltf_viewer: add stats and view controls. 2019-03-14 12:18:56 -07:00
Romain Guy
6b39569c14 Defend against Windows' near/far defines (#985) 2019-03-14 11:49:43 -07:00
Romain Guy
82be8e1553 Fix min/max calls in Box::unionSelf (#984) 2019-03-14 11:26:33 -07:00
Philip Rideout
06850cf934 Add Engine::getBackend, fix gltf_viewer + Vulkan. 2019-03-14 10:55:08 -07:00
Philip Rideout
e3e7073f74 gltf_viewer: add support for drag-and-drop.
You can now drop gltf or glb files into the app.

Note that we will soon be migrating from SDL to GLFW, which also
has support for drag-and-drop.
2019-03-14 10:06:44 -07:00
heitaoflower
fbcdcc24af Modify incorrect static format (#979) 2019-03-14 07:38:32 -07:00
Philip Rideout
cc3177ce34 gltf_viewer: fix indirect light controls. 2019-03-13 17:12:58 -07:00
Philip Rideout
c97e812056 Update FlightHelmet path. 2019-03-13 16:21:58 -07:00
Philip Rideout
7bc6b3c818 Replace gltf_viewer and introduce gltfio::SimpleViewer.
The new gltf_viewer app has an optional zero-arguments mode whereby it
loads a resgen-embedded binary model, which is useful for quick
sanity testing. If you don't specify an IBL, it loads a compressed
version of the pillars IBL.
2019-03-13 16:21:58 -07:00
Romain Guy
583bfa54d9 Add NDK version check 2019-03-13 14:29:44 -07:00
Mathias Agopian
a8a37a537a simplify a lot libibl's Image class 2019-03-13 13:45:43 -07:00
Mathias Agopian
13d3ade5bb libibl doesn't need to depend on libimage 2019-03-13 13:45:43 -07:00
Mathias Agopian
54d292bc8a move all libibl APIs in namespace filament::ibl 2019-03-12 22:36:54 -07:00
Mathias Agopian
43ac656a38 Cleanup libibl a bit. Add some basic documentation. 2019-03-12 22:36:54 -07:00
Mathias Agopian
f8fc2dd808 split cmgen into an exe + libibl.a 2019-03-12 22:36:54 -07:00
Mathias Agopian
529c44e548 cleanup cmgen in praparation of lib split
we mostly remove dependencies on includes.
2019-03-12 22:36:54 -07:00
Mathias Agopian
637390ea85 Update MaterialParser.cpp 2019-03-12 15:37:05 -07:00
Mathias Agopian
69db5134a6 simplify MaterialParser
no need to hide the implementation anymore, since the whole thing
is internal and doesn't appear in public headers.

this saves a dynamic allocation when unflattening materials.
2019-03-12 15:37:05 -07:00
Philip Rideout
0102489748 gltfio: add UbershaderLoader, an implemention of MaterialProvider. 2019-03-12 15:29:17 -07:00
Philip Rideout
3b827da834 geometry: add JS bindings for SurfaceOrientation
These bindings are not user friendly because clients need to
manually allocate / deallocate memory. However it gets the job done.

Fixes #959.
2019-03-12 14:31:09 -07:00
Philip Rideout
ce50ea17c0 Avoid NaN when normal is colinear with fake axis.
I reproduced the issue by hacking our redball demo and visually
verified the fix.

cc @AdrianAtGoogle
2019-03-12 14:30:25 -07:00
Mathias Agopian
ca79e9d420 More doxygen documentation 2019-03-12 13:35:58 -07:00
Mathias Agopian
fb4e498bc1 fix documentation typos 2019-03-12 13:35:58 -07:00
Mathias Agopian
b44717ae54 Add doxygen documentation 2019-03-12 13:35:58 -07:00
Mathias Agopian
6e4491c852 Make dithering an enum. 2019-03-12 13:32:28 -07:00
Mathias Agopian
07bb62490b Add an option to turn dithering on/off 2019-03-12 13:32:28 -07:00
Romain Guy
b8f72590bb Fix Android builds on Windows (#968)
* Fix Android builds on Windows

This PR fixes #927

* Add missing endline

* Fix armv7a Android builds
2019-03-12 10:49:26 -07:00
Philip Rideout
39c63146e0 gltfio: add ubershader template.
We will need 6 pre-compiled materials (lit vs nonlit and the 3 blend
modes). This uses CMake's "configure_file" functionality to generate 6
mat files, then invokes matc on each one. They are then combined using
resgen.
2019-03-12 08:16:55 -07:00
Philip Rideout
960d1321e6 Repair web builds. 2019-03-11 18:36:29 -07:00
Mathias Agopian
8ffba072b2 remove the "byteSize" parameter from update[Vertex|Index]Buffer
It was redundant with BufferDescriptor::size.
2019-03-11 18:27:06 -07:00
Philip Rideout
031ff260f7 Repair web builds. 2019-03-11 17:44:12 -07:00
Mathias Agopian
c78db48b81 Better Camera component management
- getCameraComponent(Entity) retrieves a Camera component from an entity
- destroyCameraComponent(Entity) destroys just the camera component
  attached to an entity.

destroyCamera() are now deprecated because the API is confusing, it's
not immediately clear that it's destroying all component + the entity
itself.

Node: We don't add the corresponding Java APIs yet because there is no 
easy way to guarantee they're safe without making sure that 
getCameraComponent() will always return the same instance (which it
wouldn't currently).
2019-03-11 15:51:38 -07:00
Romain Guy
11eaad7992 Fix CI builds 2019-03-11 14:37:29 -07:00
Romain Guy
eda6ea64c8 Require CMake 3.10 2019-03-11 14:32:50 -07:00
Romain Guy
79dec2f8b5 Give our own CMake a higher priority 2019-03-11 14:28:26 -07:00
Romain Guy
41397e1b82 Move 3p models to models/ directory 2019-03-11 14:21:51 -07:00
Romain Guy
31a70d2352 Print CMake version number 2019-03-11 14:14:09 -07:00
Romain Guy
98ce5e2f5a Require CMake 3.12 because of CI 2019-03-11 14:07:13 -07:00
Romain Guy
9d8c000bcc Make CMake 3.13 the minimum version 2019-03-11 14:05:45 -07:00
Romain Guy
d238d7f6f2 Add CMake version check 2019-03-11 14:03:05 -07:00
Romain Guy
73af2620f9 Cleanup build.sh 2019-03-11 14:02:56 -07:00
yoshi (Yoshihisa Kaino)
160297db9c Fix Activate link #957 (#958) 2019-03-11 07:45:46 -07:00
Philip Rideout
8628c43fbf gltfio: material generator cleanup. 2019-03-10 15:11:58 -07:00
Philip Rideout
af9b3a99e0 gltfio: introduce MaterialProvider interface.
This prepares for an alternate "sans filamat" implementation of
MaterialProvider, which will be especially useful for web.
2019-03-10 11:59:47 -07:00
Philip Rideout
7a2924738c gltfio: transparency fixups
- rename gltfio::AlphaMode to use glTF nomenclature
- keep depth writes enabled for transparent renderables
2019-03-09 18:58:04 -08:00
Philip Rideout
06964a787a Repair parquet and helmet web demos. 2019-03-09 06:39:31 -08:00
Romain Guy
2e8c01d8aa Update README.md per #946 2019-03-08 23:11:29 -08:00
Mathias Agopian
b2738a2c8c Don't expose private structure in public header 2019-03-08 19:16:46 -08:00
Philip Rideout
0e4ca0bc7b Fix falling streetcar / quaternion slerp. 2019-03-08 17:50:15 -08:00
Philip Rideout
64f2a580da Update public site with latest JavaScript demos.
It has been a while, we've made a fix to our KTX writer, added a helmet
demo, etc.
2019-03-08 17:49:28 -08:00
Philip Rideout
f1f9fde3a4 Various JavaScript updates.
Add shadows to the FlightHelmet demo, add a link to it on the site,
and add recently-introduced entry points to the JS bindings.
2019-03-08 12:56:48 -08:00
Philip Rideout
c98ac44827 gltfio: fix UV set issue seen in littlest_tokyo 2019-03-08 11:31:22 -08:00
Philip Rideout
3c2a6d5f8c Link to rasterized markdown on website. 2019-03-08 09:59:01 -08:00
Mathias Agopian
d5178f862a minor cleanup: remove unneeded complexity 2019-03-07 17:21:58 -08:00
Mathias Agopian
4de71f7239 Remove dependency of UniformBuffer on UniformInterfaceBlock 2019-03-07 16:42:02 -08:00
Mathias Agopian
302d296949 Remove driver's UniformInterfaceBlock dependency 2019-03-07 16:42:02 -08:00
Mathias Agopian
1836377753 don't have two version of SamplerFormat
Instead, alias one on the other.
Also sort aliases in the header.
2019-03-07 16:42:02 -08:00
Mathias Agopian
462251bde6 Remove unused code and data
This is no longer used. Get rid of it.
2019-03-07 16:42:02 -08:00
Mathias Agopian
a1eedb95a0 'driver' shouldn't include filament/*.h headers
only filament/driver/* are allowed. These were not even needed.
2019-03-07 16:41:43 -08:00
Philip Rideout
b14759a0a4 gltfio: add wireframe functionality.
This makes it easy to draw a transformed box around each renderable for
diagnostic purposes. The API is similar to Animator in that it is
exposed through FilamentAsset but is created lazily and is implementated
outside of FilamentAsset.
2019-03-07 15:03:43 -08:00
Romain Guy
f02fe33070 Reformat comments 2019-03-07 14:53:33 -08:00
Philip Rideout
1ccf2d6a08 gltfio: fix up and enhance AABB functionality.
gltfio computes two types of bounding boxes: one for renderables (used
for frustum culling) and one for the overall asset (used for
positioning the camera or asset).

Both of these are based on the min+max attributes in the glTF file, but
the asset-level box was incorrect because only two corners of the
transformed AABB were considered.

This CL also adds optional computation of bounding boxes that crawls
through the vertex positions. This is useful when diagnosing potential
issues with the asset's min+max info.

These enhancements are motivated by a culling issue seen with the voxel
Cathedral on sketchfab.
2019-03-07 14:11:21 -08:00
Mathias Agopian
d2afc27703 Address review comments 2019-03-07 13:43:27 -08:00
Mathias Agopian
801d24b6e7 Remove some unused code and includes 2019-03-07 13:43:27 -08:00
Mathias Agopian
91738d0513 Remove the 'group' parameter from SamplerBindingMap 2019-03-07 13:43:27 -08:00
Mathias Agopian
2a72e8aee8 break dependency of Program on SamplerInterfaceBlock and SamplerBindingMap
Instead of passing SamplerInterfaceBlocks and a SamplerBindingMap to
Program, we now set a 'sampler group' per binding point:

Program::addSamplerGroup(...)

A sampler group here consists of a list of N 'Sampler' and a 'Sampler'
is just a unique name (unifrom name in the shader) and binding point in
the shader.

That's all the driver layer needs.

With this change we get rid of the code that re-created the uniform
names in the driver -- this should never have been done there. And we
also remove the hash-map lookups in vulkan and metal drivers.
2019-03-07 13:43:27 -08:00
Mathias Agopian
b0d640832a cleaup of Program.h 2019-03-07 13:43:27 -08:00
Mathias Agopian
50d8a8a2d8 fix SamplerBindingMap for non postprocess materials
This fixes #935

SamplerBindingMap was always adding the post-process samplers to the
map -- but matc doesn't generate those. This led the vulkan backend
to believe there was a post-process sampler bound, when there wasn't.

This is also technically a bug in the Vulkan backend because it should
have used the SamplerInterfaceBlock to determine which shaders are
actually used instead of blindly going through the whole list and 
trusting SamplerBindingMap.

The fix is kind of a hack, but the whole SamplerBindingMap is kind of a
hack anyways.
2019-03-06 18:26:08 -08:00
Romain Guy
23fe2cba98 Update MoltenVK to 1.1.101.0 (#937) 2019-03-06 16:52:24 -08:00
sebavan
906097625e Add Charlie importance sampling to cmgen.exe (#936) 2019-03-06 15:43:07 -08:00
Philip Rideout
8d979a7cb8 Resurrect quat slerp NaN protection.
In my previous NaN-related commit, I added a conditional similar to the
one seen in glMatrix, but this was insufficient for the interpolation
seen in a glTF skinning test because a divide-by-zero was occuring later
in the function. This commit simply adds back the previous protection.
2019-03-06 12:36:20 -08:00
Romain Guy
5ef0247569 Fix normal map sample 2019-03-06 12:03:34 -08:00
Pixelflinger
46e3326b81 move getSamplerBindingsStart() to SibGenerator
This is a bit more logical to have it there because SibGenerator
is about about what filament needs, whereas SamplerInterfaceBlock.h
is generic.
2019-03-06 11:47:26 -08:00
Pixelflinger
413f6a97b1 Engine.h doesn't need to store the per-view/post-process Sib
It's only used to get the size of the SamplerGroup.
Actually, Engine also uses the post-process Sib to create the
post-process material, but this should go away when we have
material domains -- so pretend it's not there.
2019-03-06 11:47:26 -08:00
Pixelflinger
1597b6f572 rename SamplerBuffer to SamplerGroup
This is the first part of a larger rework:
- Rename SamplerBuffer to SamplerGroup
- remove dependency on SamplerInterfaceGroup
2019-03-06 11:47:26 -08:00
Mathias Agopian
dc57eb4b7b fix filameshio test
when testing we're often using the NoopDriver, which
is has neither spirv or text shaders, so we default
to text to make this case work.
2019-03-05 18:38:01 -08:00
Mathias Agopian
7d81d9bb51 cleanup filamat namespace 2019-03-05 17:54:37 -08:00
Mathias Agopian
4abe017bc5 cleanup MaterialChunkType.h 2019-03-05 17:54:37 -08:00
Mathias Agopian
0f6f53d501 MaterialChunk doesn't expose the Unflattener in its API
this makes the API more robust, because now it's not possible
to mess up the call to getShader(), by construction.
2019-03-05 17:54:37 -08:00
Mathias Agopian
084fd95489 Factorize all the various getShader() methods
This removes a lot of code and complexity. MaterialParser now has 
a single, generic getShader() method.
2019-03-05 17:54:37 -08:00
Mathias Agopian
ff53515295 Merge [Spirv|Text]DictionaryReadder into DictionaryReader 2019-03-05 17:54:37 -08:00
prideout
bba42ea81f Repair Vulkan sychronization, fixes #929. 2019-03-05 16:57:09 -08:00
Philip Rideout
66f6031e2c Vulkan: support R16G16B16 textures via DataReshaper.
This change happens to "fix" issue #875, although we may wish to rethink
our DFG representation in the future.
2019-03-05 09:20:26 -08:00
Mathias Agopian
f2ba48f4a7 Program::shader() now only takes a void* + size
Program::shader() was taking a string before which didn't make sense
for spirv.  Now it's just a blob, in the case of GL/Metal, the blob
must be a null terminated c-string, and the size must include the
terminating null character.

This fixes an out-of-bound access in ShaderBuilder::getShader() (which
doesn't exist anymore), because it was creating a CString passing
a size that included the null terminating char, which is not was CString
expects. CString can now assert() in that case.


driver::Program now uses a std::vector<> for storage, which we should
fix at some point (b/c it's a public header). CString was not suited to
store binary blobs.
2019-03-04 19:00:26 -08:00
Mathias Agopian
955ab2d2f3 Cleanup in MaterialParser 2019-03-04 19:00:26 -08:00
Mathias Agopian
561726b938 remove unneeded dependency on SamplerBindingMap.h 2019-03-04 15:52:46 -08:00
Mathias Agopian
7b3475f1da API change: rename matrix factory functions
scale() -> scaling()
translate() -> translation()
rotate() -> rotation()

These static functions create a matrix, they don't modify it.
Fixes #826
2019-03-04 14:34:02 -08:00
Romain Guy
923db48614 Add build command for Markdeep files (#919)
* Add build command for Markdeep files

build.sh -w can now be used to "rasterize" Markdeep .md.html files
to regular, static .html files. These files load faster and do not
suffer from an initial flash of uninitialized content.

This new command requires node, npm and nx to run puppeteer to
"rasterize" the Markdeep documents. This should eventually be
integrated in the actual build system to automatically re-generate
the HTML files when the Markdeep documents are edited.

* Remove unnecessary .gitignore file

* Change constant names for JS docs
2019-03-04 14:23:05 -08:00
Romain Guy
9558f0d6ca Use uniform sampling for cloth DFG (#921) 2019-03-02 14:10:38 -08:00
Mathias Agopian
3297c9bc78 More headers clean-up
- EngineEnums.h is not a private headers as it contained mostly private
stuff

- MaterialEnums.h is still public, but now only contains public stuff.
Private parts were moved to MaterialEnums.h or MaterialBuilder.h

- And finally SamplerBinderMap is moved under private/ as well, since
it's certainly not a public API.

With this change, the public headers of filabridge become more reasonable
and limited.
2019-03-02 00:21:09 -08:00
Philip Rideout
6c75c6436e Add support for glb files.
Tested with DamagedHelmet.glb
2019-03-02 00:02:40 -08:00
Mathias Agopian
28ebc64fd9 cleanup. use createResourceNode() everywhere appropriate
now that we have a createResourceNode() method, use it.
2019-03-01 18:26:43 -08:00
Mathias Agopian
3c027b9ea0 When moving a resource we invalidate the 'from' handle
This is because 'from' is now written to, so we should invalidate it
just like for a regular write.

moveResource() now asserts when using an invalid handle. The caller can
use isValid() to check the handle if desired.
2019-03-01 18:26:43 -08:00
Mathias Agopian
8861b55d3d Get rid of RenderTargetPool
This might come back in some form in the future, for now we rely on
the driver not being too slow allocating memory.
2019-03-01 16:46:52 -08:00
Mathias Agopian
bb72e796bf Switch to FrameGraph
Filament's main rendering loop now uses the new FrameGraph API.
2019-03-01 16:46:52 -08:00
Mathias Agopian
c5fc7a01e8 remove an incorrect assert() in shadow mapping
when we compute the depth range of the shadow map, if znear is behind
zfar, it just means we don't have any shadow caster in front of
a receiver, and we can just bail out without shadowing -- as opposed
to asserting.
2019-03-01 16:43:45 -08:00
Mathias Agopian
ee1377fcad Always centers the camera to the world origin
This is effectively moving all shader computations to view space,
improving floating-point precision in the shaders, by staying
around zero where fp precision is highest. This also ensures that
when the camera is very far from the origin, objects are still
rendered and lit properly.
2019-03-01 16:43:27 -08:00
Ben Doherty
1aa4eff190 Fix post processing issue for Metal (#906) 2019-03-01 12:46:53 -08:00
Philip Rideout
16d878186c Finalize Animator implementation.
- Add support for CUBICSPLINE and STEP interpolation methods.
- Use cgltf_accessor_read_float() instead of manually unpacking values.
- Fix potential NaN in decomposeMatrix.
- Reduce malloc churn by stashing the vector of bone matrices.
2019-03-01 12:35:55 -08:00
Mathias Agopian
bf93468c3f Minor MaterialEnum.h cleanup -- first step. 2019-03-01 08:43:01 -08:00
Mathias Agopian
71762cf55e remove dependency on [Sampler|Uniform]InterfaceBlock.h
it just wasn't needed.
2019-03-01 08:43:01 -08:00
Mathias Agopian
a6a4055a0a don't fully qualify filament namespaces 2019-03-01 08:43:01 -08:00
Mathias Agopian
8d484dd762 break dependency of filaflat on filabridge
filaflat only had on header dependency on filabridge (DriverEnums.h)
and only needed two small enum types.
In fact, I don't think it was right for filaflat to assume any 
particular value for these fields -- this is the responsibility of the
callers.
2019-03-01 08:43:01 -08:00
Philip Rideout
6e7c705c92 AssetLoader fixups after code review. 2019-03-01 08:36:27 -08:00
Philip Rideout
38facc9038 AssetLoader cleanup per code review. 2019-03-01 07:27:03 -08:00
Philip Rideout
c7848efd86 Introduce the gltfio library.
This is our new mobile-friendly and web-friendly library for loading
glTF assets. It is still a work in progress, but already capable of
loading many conformance models, including those with animation,
skinning, and a couple of extensions (nonlit and texture transforms).

Next week we will add a sample app demonstrating its usage.
2019-03-01 07:27:03 -08:00
Philip Rideout
13cd77bc9a SurfaceOrientation now supports uint32 indices. 2019-03-01 07:27:03 -08:00
Romain Guy
fa9ba2c592 Update README.md
Mention Metal support
2019-02-28 15:00:00 -08:00
Ben Doherty
4f22eb44e6 Add transparent-rendering iOS demo (#905) 2019-02-28 14:42:14 -08:00
Mathias Agopian
4b587a1f6d silence a few warnings 2019-02-28 12:29:56 -08:00
Mathias Agopian
583645a943 Move MaterialParser from filaflat to filament
With this change, filaflat looses almost all its dependencies on
filabridge (only needs DriverEnums.h) and becomes only a parsing
library that doesn't know anything about materials.
It still knows about "shaders" as blobs of text or data (spirv).

Filaflat itself is used by matinfo and filament.
2019-02-28 12:29:56 -08:00
Mathias Agopian
42875b7809 break dependency of matinfo on MaterialParser 2019-02-28 12:29:56 -08:00
Mathias Agopian
54283291d1 Expose more APIs of filaflat publicly
We now expose things like 

BlobDictionary: dictionary content
MaterialChunk: construct a material from the BlobDictionary
SpirvDictionaryReader: reads a spirv dictionary
TextDictionaryReader: reads an ascii dictionary

All these classes are generic enough and don't have any outside
dependencies.

The only remaining class which has outside dependencies is 
MaterialParser, which will be eliminated soon.
2019-02-28 12:29:56 -08:00
Mathias Agopian
9263eda90e Remove dependency on Variant.h in MaterialChunk.cpp
this dependency was only used to restrict the variant to filament's
usage of it. but really this shouldn't be done here.
2019-02-28 12:29:56 -08:00
Mathias Agopian
16cef02441 break Unflattener dependency on ChunkCountainer.h 2019-02-28 12:29:56 -08:00
Mathias Agopian
d07222fc3c cleanup: break dependency filamat->filaflat dependency 2019-02-28 12:29:56 -08:00
Mathias Agopian
0dd8414844 minor cleanup, try to remove some uneeded dependencies
this is in praparation for much larger changes
2019-02-28 12:29:56 -08:00
Philip Rideout
7a5ca724fc Add cgltf to third_party (MIT License).
This is used by our upcoming gltfio library and is the lightest-weight
glTF reader that we know of. In fact it does not do much other than
parse the JSON and provide C structures for the data.
2019-02-28 12:29:44 -08:00
Ben Doherty
c8a6a4dd62 Implement MSAA for Metal (#897) 2019-02-28 12:27:20 -08:00
Ben Doherty
4d90b9d0f0 Link iOS sample apps with the geometry library (#899) 2019-02-28 12:26:05 -08:00
Ondrej Stava
ebe7b2e182 Fixed uninitialized properties in the Viewport class. (#903)
The default constructor of the Viewport class left the view properties in an uninitialized state that could lead to an undeterministic behavior in the later stages during rendering.
In our case, the issue manifested in the Froxelizer class in the setViewport() method that was flaky because sometimes the old viewport in the Froxelizer class (mViewport) was equal to the newly set viewport which caused the mDirtyFlags to not be updated. This then resulted in a crash because mPlanesX and mPlanesY were not allocated in the update() function even though they were used.
2019-02-28 10:25:55 -08:00
Philip Rideout
08af0f06bc Add new queries to TransformManager and Scene. 2019-02-28 02:17:18 -08:00
Mathias Agopian
cdbfbcc1e4 docs: fix a few warnings when invoking doxygen 2019-02-27 19:01:05 -08:00
Benjamin Doherty
ced19bde17 Fix a few documentation issues 2019-02-27 18:47:12 -08:00
Ben Doherty
523e1b957f Metal context cleanup (#895)
* Rename MetalImpl to MetalContext and move to separate header

* Remove m prefix from MetalContext variables

* Refactor out acquireDrawable method

* mCommandQueue -> commandQueue
2019-02-27 13:42:17 -08:00
Mathias Agopian
2ec6916f63 Fix a default material instance sampler initialization
This fixes #887. this bug existed since forever, when setting the
samplers on a new material instance from the default material
instance, we were losing the dirty bits (i.e. they were copied),
and so the newly initialized buffer would never be comited.


This adds a setSamplers() methods which does exactly that, and for
symmetry (and more efficiently) we also add setUniforms() to 
UniformBuffer.
2019-02-27 11:47:57 -08:00
Mathias Agopian
9d78f1a54e cleanup regarding SamplerBuffer and UniformBuffer
- UniformBuffer::toBufferDescriptor() now cleans the dirty flags
- SamplerBuffer move ctor and operator now clean the dirty flags of the
  moved (source) buffer.
- SamplerBuffer::toCommandStream() can be used to more efficiently copy
  a SamplerBuffer into the command stream -- this saves a copy.
- simplified SamplerBuffer's copy and move ctor/operator
- added a few constexpr here and there
2019-02-27 11:47:57 -08:00
Mathias Agopian
1ec8fc16a4 more support for 2D texture arrays in the driver
Very much untested, but it should work!
2019-02-27 11:47:38 -08:00
Romain Guy
705c1969b2 Add clearCoatIorChange property to materials (#890)
This property can be used to control the darkening of the base layer
due to a change in index of refraction when going through the clear
coat layer.
2019-02-27 10:30:46 -08:00
Philip Rideout
ace38eff24 SurfaceOrientation cleanup per code review. 2019-02-27 08:47:24 -08:00
Philip Rideout
6d1e0ed6f4 Introduce SurfaceOrientation helper class.
This moves our existing VertexBuffer utility into a new "geometry"
library and adds new functionality for computing tangents based on UV's.
The UV-based method comes from Eric Lengyel.

We considered mikktspace (which thankfully has a zlib-style license) but
it would require re-indexing via meshoptimizer and is therefore a bit
heavyweight.

The new library has no dependencies and will add only 7 KB to Filament's
Android aar file.

Fixes #858 and preps for #528.
2019-02-27 08:47:24 -08:00
Philip Rideout
c65e561c59 Fix nans in math::slerp, second attempt.
My earlier fix (3b373e5) was insufficient in some cases, this new
approach is cribbed from glMatrix.
2019-02-26 21:03:49 -08:00
Romain Guy
552b1c551f The cloth material model is not more expensive 2019-02-26 14:50:25 -08:00
Philip Rideout
b1ba798312 Disable macOS deprecation warnings. 2019-02-26 14:14:59 -08:00
Mathias Agopian
e40935dae8 Fix #871 -- double free if RenderableManager::Builder (#886)
The move ctor wasn't implemented properly. We actually fix this by
using a std::vector<> instead of a raw allocation for storing entries.
This std::vector<> is never reallocated.
2019-02-25 15:32:31 -08:00
Adrian Perez
38a6d047c9 Add a public method for creating atlas textures (#844) 2019-02-25 15:32:14 -08:00
Romain Guy
b3284edb36 Android standalone toolchains are not longer necessary (#874)
* Android standalone toolchains are not longer necessary

The latest NDK (19) contains ABI/API level specific command line
tools making standalone toolchains unnecessary. This change adapts
to the new model which greatly simplifies the build script and
ensures the latest version of the tools is being used.

Note that this requires a fairly recent version of CMake which fixes
a bug related to ranlib. This change was tested with CMake 3.13
(CMake 3.7 does not work).

* Modify CI build script to fetch recent CMake

* Remove dependency on standalone toolchains in Windows README

* Use correct CMake path

* Update NDK to latest

* Only download CMake and NDK for Android builds

* Add version constant for ninja

* Make output more quiet
2019-02-25 15:14:31 -08:00
Ben Doherty
2378e64153 Add material-builder Android sample (#884) 2019-02-25 14:46:05 -08:00
Philip Rideout
186920e8d0 Fix up emissive energy compensation for glTF. 2019-02-25 14:32:58 -08:00
Ben Doherty
d8ca867691 Small changes to iOS readme
Add `-i` flag to ensure installs and "apps" is now plural.
2019-02-25 13:57:43 -08:00
Ben Doherty
5e27fdea68 Add glRenderbufferStorageMultisampleEXT declaration to iOS (#866) 2019-02-25 13:22:38 -08:00
Mathias Agopian
c0e63b24c1 rework multisample driver api
It's now possible to create a multisample FBO with a non-multisample
texture attachment. In this case, the drive is responsible for
automatically resolving the multisample buffer into the texture on
endRenderPass().

This allows us to avoid doing a "resolve blit" on the client side, but 
more importantly, it allows the driver to do this efficiently,
especially on tilers.

The semantic of this operation is the same than with
EXT_multisampled_render_to_texture. i.e. the multisample buffer is
lost after resolve. For GL/GLES drivers if 
EXT_multisampled_render_to_texture is not available this behavior
is emulated with a renderbuffer + blit.


This CL also fixes the creation of attachments to a face of a cubemap.
2019-02-25 13:22:38 -08:00
Pixelflinger
8a6de4cff1 Fix fxaa offset (#868)
vertex shader interpolants are interpolated at pixel centers by the GPU,
but we were doing our own "pixel-center" adjustment, so we ended-up with
"vertex_uv" at a pixel corner instead of center.

with this change, the vertex shader always compute vertex_uv in
fractional texels and the conversion to texture coordinates is done
in the fxaa code.

The half-pixel adjustment is removed.

This leads to sharper looking images because in addition to shifting
everything by 0.5 pixels, this was essentially applying a box-filter
to the whole picture -- kind of like taking 1 mip level down.
2019-02-25 13:22:14 -08:00
Philip Rideout
e56ff75e1b Fix WebGL continuous builds. 2019-02-25 12:31:36 -08:00
Philip Rideout
147dafb4c1 Fix webgl on kokoro. 2019-02-25 12:02:47 -08:00
Ben Doherty
5f6f026648 Correct typo in Windows readme for Android
Fixes #882
2019-02-25 11:19:11 -08:00
Romain Guy
fdee8e2e5c Add missing call to surfaceChanged()
Fixes #842
2019-02-23 22:34:43 -08:00
Philip Rideout
e9430dd07f Do not use CMAKE_SOURCE_DIR.
This is one of those CMake gotchas, we should always use
CMAKE_CURRENT_SOURCE_DIR instead of CMAKE_SOURCE_DIR to allow
Filament to exist as a subproject.

In particular, this was causing the following build error when trying to
build Filament as a nested project.

    combine-static-libs.sh: No such file or directory

Fixes #861.
2019-02-22 15:38:52 -08:00
Ben Doherty
538243295c Add TextureReshaper (#862) 2019-02-22 12:34:29 -08:00
Ben Doherty
fa3f34ea4b Update iOS samples README (#857) 2019-02-22 09:14:22 -08:00
Ben Doherty
3faef1f9cb Complete the MaterialBuilder JNI (#845) 2019-02-21 14:53:32 -08:00
Ben Doherty
d0bab0fa8a Add hello-pbr iOS demo (#851) 2019-02-21 12:57:29 -08:00
Romain Guy
4738e93b83 Replace Cloth DFG approximation with DFG LUT
By removing the Fresnel term (often ommitted from fabric/cloth BRDFs)
we can store the DG term for the cloth BRDF in the 3rd channel of the
existing DFG LUT.
2019-02-21 11:44:52 -08:00
Ben Doherty
803c922ac1 Fix, can't set material parameters on default material instance (#854) 2019-02-21 10:30:01 -08:00
Ben Doherty
cc637870b6 Fix Vulkan swapchain size on Windows (#852) 2019-02-20 17:25:29 -08:00
Ben Doherty
5c57a18b35 Initialize MaterialBuilder in samples (#850) 2019-02-20 14:47:29 -08:00
Philip Rideout
d538e71959 Repair gltf_viewer by calling Material::init. 2019-02-20 14:39:30 -08:00
Mathias Agopian
c1c84f6400 minor code and comments cleanups in dfg computations
also added uniform hemisphere sampling function for reference.
2019-02-20 13:52:57 -08:00
Philip Rideout
84eb9547f5 Tangent-related fixups in MeshAssimp.
Assimp's CalcTangentSpace deviates from de facto glTF 2.0 so we were
compensating for this with an unconditional fixup in MeshAssimp. However
the fixup should apply only when CalcTangentSpace is active, i.e. when
the model is missing tangents.

This makes it so that NormalTangentMirrorTest (has tangents) and
NormalTangentTest (needs tangents) both look reasonable.

I also noticed that MeshAssimp was inexplicably applying
aiProcess_CalcTangentSpace twice: once as a flag, and once as a
post-process. I removed the latter.

This will be fixed in the upcoming cgltf-based loader, which will
use our officially-sanctioned utility method in VertexBuffer.

See #528
2019-02-20 13:29:44 -08:00
Mathias Agopian
9b5060bb1d improve bindBufferRange() state tracking
we never rely (or should rely) on the fact that glBinderBufferRange()
also sets the generic binding, so we don't need to check for that when
calling glBindBufferRange().

This helps a little bit reducing the numbers of GL calls, especially
when several consecutive draw calls use the same material instance.
2019-02-20 12:34:45 -08:00
Ben Doherty
d22e2f2834 Fix wrong init method being called (#846) 2019-02-20 11:05:55 -08:00
Ben Doherty
52ebfb1665 Add Init and Shutdown methods to MaterialBuilder (#840) 2019-02-20 10:44:12 -08:00
Adrian Perez
07eda48196 Missing include 2019-02-20 09:41:18 -08:00
Romain Guy
b2f19a1879 Remove incorrect approximations 2019-02-19 18:41:31 -08:00
Mathias Agopian
39b9d30d1a Minor RenderStream cleanups 2019-02-19 18:31:43 -08:00
Mathias Agopian
45beccc68b Fix build when DEBUG_RENDER_STREAM is enabled 2019-02-19 18:31:43 -08:00
Mathias Agopian
45e7580dc6 rename synchronous driver calls
synchronous driver calls are split in 2 calls, respectively:
fooS() and fooR() instead of fooSynchronous() and foo().

This is a tiny step towards decoupling drivers from the
renderstream, which is a pipedream of mine.
2019-02-19 18:31:43 -08:00
Romain Guy
6f9df5bfab Update incorrect equations of importance sampling 2019-02-19 17:59:39 -08:00
Philip Rideout
91ce2f412b Bump MATERIAL_VERSION. 2019-02-19 15:54:58 -08:00
Philip Rideout
e60744a6e4 Introduce MATERIAL_VERSION and panic.
Material archives already contain two version chunks (post process and
normal) but the renderer was ignoring these. The change makes it so that
matc writes a new MaterialEnums value into these chunks, and the engine
panics when receiving a material version that it does not expect.

This also adds a --version option to matc. No changes were necessary
to matinfo because it already prints out these values.

Fixes #796.
2019-02-19 15:54:58 -08:00
Ben Doherty
de4abe3295 Replace MoltenVK with Metal for iOS sample (#825) 2019-02-19 12:25:24 -08:00
Philip Rideout
b6ccdc0529 Update stb and add tnt/README.
Fixes #832.
2019-02-19 12:18:29 -08:00
Mathias Agopian
28c8f6818e glGenerateMipmap honors base/max level 2019-02-15 17:12:56 -08:00
Mathias Agopian
8f42e1a812 fix linux debug build
It looks like out static libc++abi that we use on linux needs
pthread, even if the exe doesn't use it. 
Adding libutils to this test fixes the build on my local linux machine.

The real fix is probably something else, bug I don't quite
understand these shenanigans.
2019-02-15 16:47:28 -08:00
Mathias Agopian
803229bcdc fix another out-of-bounds access 2019-02-15 16:39:48 -08:00
Mathias Agopian
c64dae95fa set textures max level properly
the texture's max level wasn't set properly when uploading
data for level 0 (it was for other levels).

this would cause uninitialized levels to be accessed by the GPU.
2019-02-15 16:19:22 -08:00
Philip Rideout
630b14d273 DriverAPI: add generateMipmaps and canGenerateMipmaps.
Fixes #808.  See also comments in #749.
2019-02-15 16:16:20 -08:00
Ben Doherty
08a71bf2f0 Install requirements for linking against filameshio (#818) 2019-02-15 12:08:28 -08:00
Ben Doherty
2e917fc8d0 Build all run-time variants on Windows for CI release and continuous (#816) 2019-02-15 12:08:08 -08:00
Philip Rideout
26ce90483a MeshAssimp: fix glTF material hash function.
I noticed this while working on the new lighter weight loader.
2019-02-15 10:32:33 -08:00
Romain Guy
5b7ad2511e Rename specularIrradiance function in shaders 2019-02-15 10:10:55 +00:00
Romain Guy
42acac02c0 Update documentation
Add titles and use energy preservation vs conservation to describe
two different concepts.
2019-02-15 09:26:52 +00:00
Ben Doherty
d0247f7867 Fix build errors in Metal driver (#823) 2019-02-14 21:31:05 -08:00
Philip Rideout
529f65d63c Introduce addEntities method to Scene.
This is an efficient method that allows clients to add a slew of
entities to the scene. This is particularly useful for the upcoming
gltfio library, which is agnostic of the Scene and exposes a flat
list of entities.
2019-02-14 20:55:21 -08:00
Philip Rideout
3b373e5d05 Fix nans in math::slerp. 2019-02-14 20:54:56 -08:00
Mathias Agopian
6fbecef857 fix out-of-bound access 2019-02-14 18:10:46 -08:00
Mathias Agopian
e98b413eb5 don't default initialize driver::Viewport/RenderPassFlags
instead we initialize them to zero in RenderPassParams.
2019-02-14 18:08:40 -08:00
Mathias Agopian
147e4d2189 Flags must be zero by default 2019-02-14 18:08:40 -08:00
Mathias Agopian
26468d9532 Split RenderPassParams into multiple structs
We split out Viewport and RenderPassFlags.
2019-02-14 18:08:40 -08:00
Mathias Agopian
6bcceefb04 always use the static version of libc++abi
This is make it a lot easier to distributes binaries like cmgen or
matc.
2019-02-14 18:05:54 -08:00
Mathias Agopian
8a850ff908 improve readme for building on linux 2019-02-14 18:05:12 -08:00
Ben Doherty
7099682204 Metal driver implementation (#795) 2019-02-14 16:04:28 -08:00
Ben Doherty
c5090ead8e Fix Incomplete framebuffer assert thrown for iOS (#815) 2019-02-14 13:07:59 -08:00
Philip Rideout
2e1acaee71 Fix potential zero stride in populateTangentQuaternions.
Fixes #794
2019-02-14 09:00:12 -08:00
Mathias Agopian
a0f8602d02 getResource() now returns a reference instead of pointer 2019-02-13 17:43:28 -08:00
Mathias Agopian
e9c37a356e Minor clean-up
- fix swapped lhs/rhs parameter names
- remove unused field 'samples' in RenderTarget
- make cache matching function more readable
2019-02-13 17:43:28 -08:00
Mathias Agopian
7915bee0df Rendertargets now have a viewport 2019-02-13 17:43:28 -08:00
Mathias Agopian
ab18e07995 handle better rendertargets with heterogenous attachments
- when possible we resize the attachments 
- we also round to 32 pixels to take avantage of
  pools the driver may have.
- when attachment can't be resized and don't have
  the same size, we do best effort -- i.e. resize
  the ones that we can.
2019-02-13 17:43:28 -08:00
Mathias Agopian
f821718171 Improve rendertarget managment
- RTs are now cached and reused
- Their life time is handled more like a normal
  resource.
2019-02-13 17:43:28 -08:00
Mathias Agopian
a1f46652d6 major implementation and api rework
- discard flags are computed correctly
- culling works correctly
- rendertargets are better supported
2019-02-13 17:43:28 -08:00
Mathias Agopian
ac679e0da4 FrameGraph API change
Resources are now single textures (generally buffers in the future),
but no longer a render target + a set of texture.
Instead, render target need to be declared and are associated to a pass.
2019-02-13 17:43:28 -08:00
Philip Rideout
be18155996 Build web docs only when opting in.
See #807.
2019-02-13 10:28:51 -08:00
Philip Rideout
691daeb45d JNI enhancement: allow mutation of non-direct buffers.
The bug was reproduced and the fix was verified by copying the following
code snippet into one of our Android samples:

    val norm = floatArrayOf(1.0f, 0.0f, 0.0f)
    val tang = floatArrayOf(0.0f, 1.0f, 0.0f, 1.0f)
    val expected = floatArrayOf(0.5f, 0.5f, 0.5f, 0.5f)
    val resultBuffer = FloatBuffer.allocate(4)
    val qtc = VertexBuffer.QuatTangentContext()
    qtc.quatCount = 1
    qtc.quatType = VertexBuffer.QuatType.FLOAT4
    qtc.outBuffer = resultBuffer
    qtc.normals = FloatBuffer.wrap(norm)
    qtc.tangents = FloatBuffer.wrap(tang)
    VertexBuffer.populateTangentQuaternions(qtc)
    Log.e("Filament", "${expected[0]} == ${resultBuffer[0]}")

Fixes #695.
2019-02-11 14:50:14 -08:00
Philip Rideout
40fe6628d0 Expose tangent utility to Java / Kotlin.
This also improves the comments and allows 0 for output stride.
2019-02-11 12:50:19 -08:00
Caleb Leak
d2f8fa5a36 Fixed printing of wrong file names
In multiple samples when a file didn't exist, it printed the first file as being the offending argument, regardless of which actually was.
2019-02-11 09:04:21 +01:00
Caleb Leak
32287aea7f Fixed README.md giving an invalid Windows command
The `./` and file separator in the executable path prevented the program from running. The other changes are just cleanup for conformity. This is the last of the Windows doc changes as far as I can tell.
2019-02-11 00:51:03 +09:00
François Guthmann
8253006899 Typo correction
Switched arguments in prefilteredDFG_LUT call to align with function definition in the documentation and in the code.
2019-02-08 10:24:15 -08:00
Ben Doherty
e5eb29dc92 Add desktop JNI bindings for filamat (#791) 2019-02-08 09:59:35 -08:00
Ben Doherty
a2caea7e88 Metal / Vulkan swapchain (#792) 2019-02-08 09:59:05 -08:00
prideout
5ee359cf40 Move math namespace to fix #746. 2019-02-07 09:23:07 -08:00
Ben Doherty
6089be6de6 Add Metal handles (#790) 2019-02-06 16:05:58 -08:00
prideout
72a987057e Move MeshReader into filamesh namespace.
This class will not extend well to glTF so this cordons it off into the
filamesh namespace, which is an already-existing namespace that we use
for the things related to the filamesh file format.

For glTF we might create a new library with its own MeshReader so
this will mitigate confusion.
2019-02-06 12:59:48 -08:00
Ben Doherty
4b0f1e8247 Add Metal state creation logic (#782) 2019-02-06 12:57:19 -08:00
prideout
60d17fff2e Minor Vulkan fixup. 2019-02-06 10:17:13 -08:00
Caleb Leak
846f21ce51 Fix example running a different app than built 2019-02-06 16:16:17 +09:00
Romain Guy
4327612159 Remove unnecessary function parameter
Our visibility terms don't make use of roughness, only of
roughness^2. This change simplifies the shaders, which will
help for specular AA.
2019-02-06 10:14:05 +09:00
Philip Rideout
714b431cf9 Vulkan: use a longer swap chain to avoid stalls.
This is consistent with the Willems demos, the Overvoorde tutorials,
as well as Intel's "API without Secrets" guidance.

Fixes #778
2019-02-05 15:26:32 -08:00
Mathias Agopian
83d9ba91e5 fix a possible crash in the gl backend
we could crash by dereferencing something that's 
not a pointer when blitting to a rendertarget not
backed by a texture (i.e. renderbuffer).

also there was a case where we couldn't disambiguate
between the two cases.
2019-02-05 14:31:25 -08:00
Ben Doherty
7381475321 Compile material during build for iOS sample (#779) 2019-02-04 20:38:41 -08:00
Ben Doherty
d127a718ab Add Metal enums (#774) 2019-02-04 11:09:51 -08:00
Ben Doherty
a827f4528a Install filamat and dependencies as single static library (#775) 2019-02-04 11:08:45 -08:00
Philip Rideout
9fd69ec7a9 Add skinning demo.
Motivated by #764.
2019-02-02 09:02:32 -08:00
Philip Rideout
16088760c8 Update VulkanTexture constructor for TextureUsage. 2019-02-01 17:10:45 -08:00
Mathias Agopian
8298520f0a TextureUsage is now a bitmask, which makes it more flexible. 2019-02-01 17:10:45 -08:00
Philip Rideout
0595e8f7a6 Fix GL error seen with skinning due to UBO size.
This fixes an INVALID_OPERATION at draw call time with skinned
renderables. We do not see this error with Adreno drivers, but we saw it
with WebGL, and technically our usage was not spec compliant.
2019-02-01 16:56:06 -08:00
Ben Doherty
2972060cd0 Add scripts for combining static libraries (#769) 2019-02-01 15:38:48 -08:00
Philip Rideout
69de626ead Rename built-in shader inputs to "inputs" instead of "variables".
In the public docs and materials API, Filament "variables" are custom
interpolants (outputs of VS, inputs of FS). However we internally used
"variables" to also refer to built-in VS inputs.

CodeGenerator had a generateVariable method and a generateVariables
method, which did something completely different. :)
2019-02-01 13:20:13 -08:00
Adrian Perez
694d5a397e Typo fixes 2019-02-01 11:26:58 -08:00
Philip Rideout
92098d2610 Fix vk_imgui crash by allowing zero-sized uniform buffers.
The vk_imgui sample regressed in December or so, after some changes in
how Filament manages uniform buffers. This commit makes the Vulkan
driver more consistent with the GL driver, which does a check for
zero-sized buffers.
2019-02-01 09:55:23 -08:00
Philip Rideout
0b71691a61 Simplify VkCommandBuffer management. 2019-02-01 09:55:23 -08:00
Philip Rideout
6556345941 Vulkan: support WaitForIdle before swap chain construction. 2019-02-01 09:55:23 -08:00
Mathias Agopian
d1aecf864f allocator's free() must take 2 parameters 2019-01-31 17:36:19 -08:00
Philip Rideout
01c2d31484 Implement blit in VulkanDriver.
Fixes #749.
2019-01-31 15:23:54 -08:00
Philip Rideout
18bff7ef5e Repair generateMipmaps for cubemaps.
This functionality regressed when we replaced the OpenGL implementation
with our own.

I proved both the regression and the fix by running suzanne with the
following hacks.

```
--- a/libs/image/include/image/KtxUtility.h
+++ b/libs/image/include/image/KtxUtility.h
@@ -129,8 +129,9 @@ namespace KtxUtility {
             for (uint32_t level = 0; level < nmips; ++level) {
                 ktx.getBlob({level, 0, 0}, &data, &size);
                 PixelBufferDescriptor pbd(data, size * 6, dataformat, datatype, cb, cbuser);
-                texture->setImage(*engine, level, std::move(pbd), Texture::FaceOffsets(size));
+                if (level == 0) texture->setImage(*engine, level, std::move(pbd), Texture::FaceOffsets(size));
             }
+            texture->generateMipmaps(*engine);
             return texture;
         }

--- a/samples/app/IBL.cpp
+++ b/samples/app/IBL.cpp
@@ -54,7 +54,7 @@ IBL::~IBL() {
 bool IBL::loadFromKtx(const std::string& prefix) {
     // First check for compressed variants of the environment.
     Path iblPath(prefix + "_ibl_s3tc.ktx");
-    if (!iblPath.exists()) {
+    if (true || !iblPath.exists()) {
```
2019-01-31 13:57:30 -08:00
Philip Rideout
41a1250598 Skinning: fix buffer overrun for non-zero bone offsets.
Fixes #764
2019-01-31 12:39:16 -08:00
Philip Rideout
2800f58aa1 Add jniLibs search path to filament-android for Vulkan.
This allows Filament to find validation layers in debug builds.
2019-01-30 16:33:54 -08:00
Adrian Perez
7ba46ef5f1 Add explicit includes for types not implied in all stdlib impls 2019-01-30 16:08:57 -08:00
Benjamin Doherty
21f0aa5fb4 Enable custom allocator test for Windows 2019-01-30 16:05:49 -08:00
Mathias Agopian
8bdae79536 added rebind copy-ctor to STLAllocator
this should fix the build on windows debug
2019-01-30 16:05:49 -08:00
Mathias Agopian
0bdb6b8a8a workaround a compile error with some compilers 2019-01-30 16:05:49 -08:00
Philip Rideout
447f44539f Add warning to GenMipmaps for non-renderable formats. 2019-01-30 11:03:54 -08:00
Philip Rideout
0a9be8f9b2 Remove generateMipmaps from DriverAPI. 2019-01-30 11:03:54 -08:00
Philip Rideout
d0df2e1336 Replace glGenMipmap with our own implementation. 2019-01-30 11:03:54 -08:00
Philip Rideout
f690d5e69c Suzanne now tests generateMipmaps. 2019-01-30 11:03:54 -08:00
Philip Rideout
4ffd790fd6 GL blit now updates baseLevel / maxLevel of target texture.
This not only paves the way for our own mipmap generator routine, but
also better aligns the semantics of blit with setTextureData.

Motivated by #749.
2019-01-30 11:03:54 -08:00
Ben Doherty
c29fcc7668 Fix typo in iOS readme 2019-01-29 18:13:38 -08:00
Mathias Agopian
ae6ab66af4 fix #755: a race condition cousing a deadlock
This reverts a JobSystem optimization that attempted to avoid signaling
a condition when there was no waiters. Unfortunately, there was a
race that caused the the signaling thread to miss that the waiter flag
was set, thus not signaling.
2019-01-29 15:40:25 -08:00
Ben Doherty
7be3994c96 Add Metal shading language compilation to matc (#752) 2019-01-29 12:44:58 -07:00
Ben Doherty
836b641bff Add filamat-jni to CMake and build.sh (#740) 2019-01-29 12:34:04 -07:00
Tim van Scherpenzeel
44bfac85e9 added quiet flag 2019-01-29 11:04:58 -08:00
Romain Guy
a141abd212 Fix Kotlin compilation error 2019-01-29 09:39:00 -08:00
Romain Guy
12aba0f1b7 Code cleanup 2019-01-29 09:36:18 -08:00
Philip Rideout
40666bdd23 HwTexture now remembers the format.
We were stashing the GL format but not the Filament format.

This simplifies VulkanTexture and will allow us to implement a very
simple mipmap generator in DriverBase.

Motivated by #749.
2019-01-29 08:59:36 -08:00
Romain Guy
66d71be300 Fix HDR ImageDecoder for width < 8 or > 32767 2019-01-28 15:16:53 -08:00
Romain Guy
614a832be0 Code cleanup in ImageDecoder.cpp 2019-01-28 15:16:53 -08:00
Ben Doherty
92de93bfb8 Add Metal skeleton code (#714) 2019-01-28 15:29:37 -07:00
Romain Guy
c1b7f2ac27 Property write small .hdr files (#750)
* Cleanup ImageEncoder code

* Properly write HDR files when width < 8 or > 32767

A little oddity in the original Radiance file format encoding.
2019-01-28 14:02:28 -08:00
Philip Rideout
6110809d23 JNI fix for badly-sized PixelBufferDescriptors. (!)
Amazingly, the size field in PixelBufferDescriptor was often totally
incorrect for Java-based clients. The reason we did not notice: OpenGL
often consumes a pointer to image data without consuming a byte count
(e.g. glTexImage2D).

OpenGL infers size from dimensions + format, but Vulkan does not. This
caused texture corruption with Vulkan on Android.

This fix follows a pattern used in other places such as
FRenderer::readPixels.
2019-01-26 09:59:06 -08:00
Romain Guy
81a52411ed Clarify Fresnel term for IBL implementation of clear coat 2019-01-25 13:49:44 -08:00
cubeleo
6956154d62 mipgen: Disambiguated string with std:: prefix. (#741) 2019-01-25 09:02:11 -08:00
prideout
9940a68165 Stipulate clang 7 in README to align with Kokoro. 2019-01-24 12:06:00 -08:00
Philip Rideout
c3d957671d Work around FXAA issue with Vulkan Adreno drivers.
Fixes #732.
2019-01-24 11:48:02 -08:00
Mathias Agopian
fbb7e1f2ef Use a linear allocator for all our std::vector<> 2019-01-23 19:14:28 -08:00
Mathias Agopian
6e90d73e24 fix PassNode move ctor 2019-01-23 19:14:28 -08:00
Mathias Agopian
07c1dbb5f4 fix typo causing a memory corruption in STLAllocator<>
We were allocating n*sizeof(n) instead of n*sizeof(T). Thankfully, 
we were not using STLAllocator anywhere.
2019-01-23 19:14:28 -08:00
Philip Rideout
4e0749f0ae Add another folder to the build's "clean" task.
Gradle creates a hidden .externalNativeBuild folder when issuing CMake
for the first time. This folder contains cached command line parameters
that get passed to CMake, and these can become stale when switching
between "normal" Android builds and Vulkan-enabled Android builds, which
leads to frustrating build errors.
2019-01-23 17:12:56 -08:00
Ben Doherty
f5bd28b7df Update linux README with CXXFLAGS (#736) 2019-01-23 16:39:34 -08:00
Ben Doherty
ad4c4148f4 Add filamat-jni Gradle project (#733) 2019-01-23 13:58:43 -08:00
Mathias Agopian
a35762bdf2 compute discard flags for all attachments 2019-01-22 10:49:22 -08:00
Mathias Agopian
1ca2b1b642 calculate rendertarget's discard flags properly 2019-01-22 10:49:22 -08:00
Mathias Agopian
373e519292 slog.* << io::hex now prefixes values with 0x 2019-01-22 10:49:22 -08:00
Mathias Agopian
acea32aae8 more validation in the framegraph
- validate that a pass actually uses a resource when requesting the
  concrete (Driver) handle.

- introduce a "blit" usage for a resource, which indicates that a 
  resource will be used as the source of a blit operation. This is
  unfortunatelly needed because blit operations work on rendertargets,
  not textures for the source.
2019-01-22 10:49:22 -08:00
Mathias Agopian
150fd321bc FrameGraph API improvements
- de-dup read/writes to the same resource from the same pass

- also, when reading & writing into the same resource from the same pass,
  always order the read before the write, i.e.:
     out = builder.write(r);
     in  = builder.read(out);
  is equivalent to:
     in  = builder.read(r);
     out = builder.write(in);

  note that the following is still not allowed:
     out = builder.write(r);
     in  = builder.read(r);
  
  this is never valid, since it's reading from a resource that has
  been written to. 


- Make FrameGraphResource class attributes private and add
  comparison operators (so they could be sorted and compared).
2019-01-22 10:49:22 -08:00
prideout
1bbe203a15 Add RGB support to VulkanDriver. 2019-01-22 09:56:27 -08:00
prideout
37201e742f Add missing locks to VulkanDriver. 2019-01-18 16:50:52 -08:00
prideout
ba8adc2d49 Fix test filter syntax. 2019-01-18 16:21:26 -08:00
Ben Doherty
d3efbd810e Add Android build instructions on Windows (#726) 2019-01-18 14:47:23 -08:00
prideout
91c946cfbd Add workaround for depth invariance on NVIDIA.
Fixes #645.
2019-01-18 13:59:22 -08:00
prideout
98d39b7e7e Revert "Fix depth prepass (#722)"
This reverts commit 896c85c324.
2019-01-18 13:59:22 -08:00
Mathias Agopian
e7169cb889 fix CI build 2019-01-18 13:55:19 -08:00
Mathias Agopian
8f70f8f879 fix a few typos 2019-01-18 13:07:54 -08:00
Mathias Agopian
8c6ac11c2d Optionally use the framegraph for post-processing
There is still a lot of work to do on the frame-graph, which is why
this is off by default for now.
2019-01-18 13:07:54 -08:00
Mathias Agopian
d9bebaa8e7 framegraph now supports imported resources 2019-01-18 13:07:54 -08:00
Mathias Agopian
5baa699c7c Add support for creating concrete resources
- Tweak the API a bit.
- We can now create concrete textures and render-targets
2019-01-18 13:07:54 -08:00
Mathias Agopian
8c8cfb6528 Frame graph API
This is only the guts of the frame graph implementation. It supports
culling of passes, but doesn't create real resources yet.

API still in flux.
2019-01-18 13:07:54 -08:00
Mathias Agopian
f1c6acafff Tweak to PostProcessManager::setSource()
setSource() is a bit more generic now.
2019-01-18 13:07:54 -08:00
Philip Rideout
03161226f2 Update MoltenVK and tweak queue selection strategy.
These changes are sufficient to resurrect Vulkan-on-macOS, at least for
the vk_hellopbr sample.
2019-01-18 12:21:50 -08:00
Ben Doherty
4d0859b266 Update Android toolchains for building on Windows (#723) 2019-01-18 09:31:03 -08:00
Romain Guy
896c85c324 Fix depth prepass (#722)
The engine tries to be smart by using a single vertex shader when
rendering unskinned, non-alpha masked, non-customized materials.
This leads to a lot of issues when laying down the depth prepass.
This change simply gets rid of this optimization (which wasn't
properly profiled anyway). Correctness is more important.

Fixes #645
2019-01-17 17:57:43 -08:00
Philip Rideout
49f1464016 Fix diabolical VAO state management bug.
When clients deleted renderables that referred to index buffers that
were still active, it was possible for our shadow ELEMENT_ARRAY_BUFFER
binding to get out of sync with the actual binding.

It is somewhat amazing that this has never caused issues before. Perhaps
it is rare for clients to "recycle" index buffers across multiple
renderable lifetimes.

This fixes #718.
2019-01-17 14:44:34 -08:00
Romain Guy
c8b3544a36 Update README 2019-01-17 12:13:43 -08:00
Romain Guy
321845d04a Update README 2019-01-17 12:11:20 -08:00
Romain Guy
a31928600e Update README 2019-01-17 12:10:39 -08:00
Romain Guy
f3752a42c8 Document UV flipping behavior and add control attribute (#720)
Materials can disbale this behavior by setting flipUV: false
in the header section of the material definition.

Fixes #672
2019-01-17 11:12:16 -08:00
Philip Rideout
2f35f26148 VertexBuffer builder normalized now accepts "false". 2019-01-17 06:09:17 -08:00
Philip Rideout
d47e6f9456 Remove presubmit test. 2019-01-16 16:28:30 -08:00
Philip Rideout
6bb385f354 Repair web builds, second attempt. 2019-01-16 16:26:57 -08:00
Philip Rideout
dd7af66516 Repair kokoro web builds. 2019-01-16 15:56:37 -08:00
Philip Rideout
04f3268961 Introduce test to ensure buildability of TypeScript declarations. 2019-01-16 14:31:42 -08:00
Philip Rideout
a3c939894c Add more JavaScript bindings and TypeScript annotations.
The following type bindings are now complete:

 - RenderableManager
 - RenderableManager$Builder
 - RenderableManager$Bone
 - TransformManager
 - Box, Camera, Frustum
2019-01-16 14:31:42 -08:00
Ben Doherty
b460d2f547 Fix resizing metal layer crash with OpenGL (#713) 2019-01-16 11:55:51 -08:00
Ben Doherty
9ea81bc2fd Resize Metal layer (#710) 2019-01-15 16:51:09 -08:00
Romain Guy
cebc83e8fa Fix the Android filamesh file loader (#709)
* Fix the Android filamesh file loader

The loader was not updated to support the SNORM16 format now sometimes
used to encode UV sets in filamesh files.

Fixes #708

* Update android/samples/image-based-lighting/app/src/main/java/com/google/android/filament/ibl/MeshLoader.kt
2019-01-15 16:11:34 -08:00
Ben Doherty
b3cd6a7f59 Add initial MaterialBuilder JNI (#707)
* Add initial MaterialBuilder JNI

* Move into android/filamat-android
2019-01-15 16:07:42 -08:00
Romain Guy
c8f5190099 Fix Windows build 2019-01-15 15:13:13 -08:00
Romain Guy
28ab087f79 Revert doubleSided hack in glTF loading 2019-01-15 14:17:22 -08:00
Romain Guy
e66aeb0c94 Fix a couple of glTF issues: (#706)
- baseColorFactor.a was not taken into account
- Some glTF files do not set `doubleSided` properly, so here we assume
  that non-opaque materials are double-sided. We may need to revisit
  this decision later...
2019-01-15 10:26:20 -08:00
Philip Rideout
749817b64b Add the official TypeScript annotations for gl-matrix to third_party.
Filament supports (but does not require) gl-matrix, and our TypeScript
annotations will need to use this file to support clients that use
gl-matrix.
2019-01-15 23:22:06 +05:30
Philip Rideout
1b18724b6b Add TypeScript to Kokoro for web for testing.
This preps for an upcoming regression test that ensures our TypeScript
annotations are valid.
2019-01-15 23:21:57 +05:30
Romain Guy
ff5a2a7a99 Peek the right dimensions for the IBL in Android samples (#704)
Fixes #701
2019-01-15 09:47:41 -08:00
Philip Rideout
125f79e5e0 Allow Java / Kotlin to enable the experimental Vulkan backend.
We still do not compile the Vulkan backend for Android by default, this
simply makes it possible to use the samples on Vulkan with a one-line
change, which is useful for testing purposes.

This change also makes it so that the materials used for the samples
include SPIR-V. This makes them fatter but they are merely samples.

I still consider Vulkan on Android to be experimental, there are some
features that need to be implemented.
2019-01-15 23:00:18 +05:30
Romain Guy
fac084dfdf Update Markdeep to latest version (2018/12) 2019-01-14 15:53:14 -08:00
Romain Guy
f8ebc047e0 Fix the build 2019-01-14 15:31:17 -08:00
Romain Guy
00f6fa24f7 Code cleanup 2019-01-14 14:57:23 -08:00
Romain Guy
0394aeb23b Add specular anti-aliasing properties to materials (#697)
* Add specular anti-aliasing properties to materials

curvatureToRoughness
limitOverInterpolation

These techiques were supposed to be enabled by default on
desktop but it turns out they were broken. They must now
be enabled manually on each material instead (and work on
mobile).

* Update docs/Materials.md.html
2019-01-14 12:25:51 -08:00
Romain Guy
c4989da047 Upgrade sample projects to Android Studio 3.3 (#700) 2019-01-14 11:50:44 -08:00
Ben Doherty
60363e518d Remove Metal layer hack for MoltenVK (#693)
* Remove Metal layer hack for MoltenVK

* Remove define

* Remove call to displaySyncEnabled
2019-01-14 10:35:26 -08:00
Damianno19
2a74397101 Incorrect order of arguments in glBlendFuncSeparate function call (#698) 2019-01-12 11:56:30 -08:00
Ben Doherty
0cccbda9b9 Move call to endFrame after commit (#696) 2019-01-11 15:42:34 -08:00
Ben Doherty
0c1fdc88ec Fix iOS hello-triangle sample (#694) 2019-01-11 13:48:00 -08:00
Philip Rideout
8228deb209 Add a multi-material model and JS demo.
This is a more complex test than suzanne because it has multiple
materials and exercises the named materials functionality in
loadFilamesh.

This also exercises our glTF-to-Filamesh pipeline at build time.

See issue #663
2019-01-11 09:18:41 +05:30
Romain Guy
8029ad5cc3 Add missing getWorldFromClip() API (#692)
Fixes #671
2019-01-10 16:35:00 -08:00
Ben Doherty
045274bbdb Use glslminifier to minifiy shaders for Release builds (#690) 2019-01-10 10:23:23 -08:00
Pixelflinger
206512add0 this fix clean builds when using make 2019-01-10 09:04:58 -08:00
Philip Rideout
f876171239 filamesh tool now generates dummy UV's if necessary.
filamesh requires UV's but some glTF test models, like CesiumMilkTruck,
do not provide UV's on nonlit parts (e.g. the truck windows). This makes
it so that these assets can be converted to filamesh somewhat more
gracefully.
2019-01-10 10:27:29 +05:30
Philip Rideout
f96501215b Reduce number of texture lookups in gltf_viewer. 2019-01-10 08:17:30 +05:30
Philip Rideout
0158e7e858 JS API: loadFilamesh can now return material names.
See issue #663
2019-01-10 07:48:19 +05:30
Ben Doherty
c6444fb502 Move sampler bindings outside of material blobs (#682) 2019-01-09 11:25:51 -08:00
Ben Doherty
60d304a83b Add glslminifier tool (#683) 2019-01-09 10:59:39 -08:00
Philip Rideout
422bf8631b Small assimp fixups for glTF => filamesh conversion.
This fixes some crashes when trying to convert CesiumMilkTruck.
2019-01-09 07:57:41 +05:30
Ben Doherty
013d735242 Destroy engine's default material (#681) 2019-01-08 13:40:02 -08:00
Romain Guy
3be10d816a Cleanup recent change to ImageOps (#678)
* Cleanup recent change to ImageOps

* Add missing sign
2019-01-08 07:20:20 -08:00
Romain Guy
9ce88e6e23 Improve skygen (#679)
Bring back the normalization and gamma correction command line flags,
render the ground in the lower half of the image.
2019-01-08 07:19:50 -08:00
nicebyte
83c40e6664 Make 4-channel versions of certain image operations. (#676)
Background: with the Vulkan backend, RGB8 textures do
not work (at least not on my hadrware). This makes me unable to run some
examples, because they use normal maps in RGB8 format.

It appears that the following commit addresses the problem by adding a
special command line option to mipgen:
8dda07bf2c

However, processing normal maps with this option does not work: certain
assertions in the image library fail.

This PR changes these functions in the image library to handle 4-channel
images instead of failing.
2019-01-07 15:16:00 -08:00
gstanlo
28f2806beb Improves linear to srgb conversion functions (#675)
* Improves linear to s/rgb

Adds rounding to nearest whole integer, supports copying over an alpha channel for linear to srgb conversion. Code would previously incorrectly apply sRGB conversion to alpha.

* reformatting previous change
2019-01-04 10:46:20 -08:00
shartte
d37e21f4ea Use different capacities for lights and renderables since there's always gonna be a light, even if there are no entities (#666) 2019-01-04 08:11:37 -08:00
Ben Doherty
d113af8afb Add return 0 to main functions to avoid crashes on Windows (#674) 2019-01-03 16:59:34 -08:00
shartte
f676d3d3ea Add constexpr constructor to StaticString (#659)
Fixes a header usage problem for MSVC, which complains about StaticString not having a constexpr constructor thus making the "make" method not constexpr.
2018-12-24 08:51:18 +01:00
shartte
cd2786a2ef Fixes #653: Skin normals/tangents before applying world space transform (#656) 2018-12-24 08:50:29 +01:00
shartte
5ea35ab87e Removed outdated documentation about static lights (#662) 2018-12-22 15:57:15 +01:00
gstanlo
c21d11e20f Fixes LinearImage memory leak (#658)
LinearImage leaks memory if assigned to itself, this ensures the old LinearImage::SharedReference object will be deleted first
2018-12-21 06:42:52 +01:00
Ben Doherty
8fe11a067d Include unwindows in Frustum and DriverEnums (#649)
* Include unwindows in Frustum and DriverEnums

* Distribute unwindows.h
2018-12-17 18:20:32 -08:00
Ben Doherty
67ffa91843 Fix Windows Debug builds (#648)
* Fix Windows Debug builds

* Use NDEBUG for Noop driver files
2018-12-17 17:15:22 -08:00
Ben Doherty
55fbb300ca Update README for VS 2017 (#647) 2018-12-17 14:00:43 -08:00
Romain Guy
4901f6f72a Fix FXAA computations in mediump (#643)
* Fix FXAA computations in mediump

UV coordinates computed in highp should be passed to the FXAA function
in highp as well. This change also fixes a potential division by 0 which
was causing dir1 to have components set to inifinity, thus breaking the
texture sampling calls below. We fix this with an early exit when a
potential division by 0 is detected. The original code contained a bias
to try to avoid this problem but that bias was not always enough. It
was frequent in mediump to cancel out the bias.

* Update shaders/src/fxaa.fs

Co-Authored-By: romainguy <romainguy@curious-creature.com>
2018-12-14 22:48:26 -08:00
Mathias Agopian
cfb9c03226 Improve JobSystem, especially under contention
- only signal waitAndRelease() when the corresponding job finishes and
only if there is waitAndRelease() active -- instead of signaling 
every time a job ends.

- don't surrender time slice when attempting to steal a job and it fails
as long as some queue has jobs.

- check that we have to wait, because taking the lock

- add a benchmark

This change more than doubles the amount of jobs we can handle per
second (~965,000 jobs/s on Pixel3)
2018-12-14 16:01:17 -08:00
Mathias Agopian
d6de2bf426 get rid of JobSystem::reset()
It was only used to clear the master job, instead the master job is
cleared when waited on.
2018-12-14 14:48:33 -08:00
Ben Doherty
b5eb00bdb1 Fix shaders compilation with VS (#641) 2018-12-14 14:03:35 -08:00
Romain Guy
ede9f7fdbb Speedup Android builds
We don't need libfilamat/spirv*/glslang for now. They greatly
reduce the time it takes to build our Android targets. We
may want to create a separate CI profile for filamat actually.
2018-12-13 16:03:39 -08:00
Romain Guy
eaf790aaa7 Improve rendering to TextureView (#635)
* Improve rendering to TextureView

UiHelper wasn't calling the resize callback at init time when attaching
to a TextureView, but it was for a SurfaceView. This makes both code
paths consistent and fixes the standard samples if they are modified to
render to a TextureView.

This change also adds a new sample app that shows how to render into
a TextureView.

* Suppress warning

* Suppress another warning
2018-12-13 15:57:15 -08:00
Mathias Agopian
02b0eb3ae2 fix a potential crasher when copying the camera stream
there was a very small race, where we would dereference a pointer
that might not be set yet.
2018-12-13 10:51:28 -08:00
Mathias Agopian
e38870ebf5 Improve JobSystem::wait
JobSystem::waitAndRelease used to spin to wait for the job to finish,
usually this wasn't a problem because the spinning thread was
able to handle other jobs. However, in cases where no job was
available it would actually spin in burn cpu cycles.

we now use a (separate) condition variable to handle that case.
2018-12-13 10:50:52 -08:00
Romain Guy
8ae1b06bce Fix frame pacing on Android (#634)
The renderer was misusing eglSetPresentationTime(), causing frame
misses when a frame was completed quickly.
2018-12-13 10:42:35 -08:00
Romain Guy
380e3fa690 Simplify UiHelper API, add transparent rendering sample (#629)
* Simplify UiHelper API, add transparent rendering sample

* Rename the app

* Address review comments

Also use the proper package name
2018-12-13 09:09:09 -08:00
Mathias Agopian
2d6b43827e Improve StaticString hashing
In a lot of case the StaticString hash can be computed a compile time,
so we now take advantage of that.

Removed StaticString(const char*) ctor, and replaced it with a
StaticString::make() method.

Fixed a couple wrong uses of the old StaticString(const char*) ctor.
2018-12-12 17:47:21 -08:00
Romain Guy
d135108763 Add mipgen.md to install directory 2018-12-12 09:09:01 -08:00
Philip Rideout
73e1bfb134 Vulkan: add support for compressed cubemaps.
This simply removes an assert from the Vulkan driver, adds a
compressed environment to our desktop samples, and contains some minor
code cleanup.
2018-12-12 08:55:17 -08:00
Philip Rideout
b81349b227 Vulkan: fix DXT => BC enum mapping. 2018-12-11 18:44:03 -08:00
prideout
71df133053 Fix Vulkan validation warning about enabled features. 2018-12-11 18:43:40 -08:00
Mathias Agopian
42fd0f5dad reduce AAR's content by about 150K
We simply don't emit unwind tables, which are not needed anyways since
we're compiling without exceptions. the combined saving for all four 
targets we support is about 120K.

This seems to improve .aar's compression, for a total gain of 152 KiB. 

We also disable stack-protector in the jni code, since it wasn't
enabled in libfilament.a anyways. However, we now compile all debug 
builds with -fstack-protector
2018-12-11 18:24:16 -08:00
Romain Guy
ff74255e6e Use clang70 in CI (#622)
* Use clang70 in CI

* Use version 7 not 7.0

* Use libc++ 7.0.0
2018-12-11 17:46:45 -08:00
Pixelflinger
2529a34c36 code size optimizations
- make Profiler::readCounters() not inline as it didn't need to be, 
it's not performance critical and it's sufficiently large.

- don't inline hasExtensions(), same reason.
2018-12-11 17:44:03 -08:00
Romain Guy
b291e11b90 Try to switch to clang60 in CI 2018-12-11 16:30:36 -08:00
Romain Guy
85a649b239 Apparently we can't use -static-libstdc++ in CI on Debug builds 2018-12-11 15:53:24 -08:00
Romain Guy
b96867e03a Link statically against libc++abi 2018-12-11 15:51:05 -08:00
Romain Guy
23e2e2a9bd Always link libc++ statically on Linux 2018-12-11 15:40:44 -08:00
Pixelflinger
e624dff037 set cpu affinity of JobSystem's threads
this is to try to prevent threads from bouncing
between cores
2018-12-11 13:46:05 -08:00
Romain Guy
025f4a54f5 Use root utils namespace in Systrace.h 2018-12-11 13:45:37 -08:00
Philip Rideout
b375d029d2 Work around CMake issue on win32 with asm-only libs. 2018-12-11 11:23:33 -08:00
Philip Rideout
40298f3cc0 Add C++ sample for compressed textures.
This is similar to its WebGL and Android counterparts, we simply did not
have a version for desktop. This uses resgen to package the model's
textures (albedo, normal, roughness, metallic, ao) into a library that
is linked only to this sample.

This is a good test because it applies multiple textures to the model.
Moreover Aaron was asking me for a C++ example that uses compressed
textures.

For now this selects the OpenGL backend. We can change it to use Vulkan
after we add support for 3-band formats to VulkanDriver.
2018-12-11 11:23:33 -08:00
Romain Guy
a38c40cf11 Turn on shaders optimization by default (#614)
* Turn on shaders optimization by default

Release builds of Filament only work well with optimize shaders,
turning optimizations on by default will help avoid mismatches.

This change also adds -g to disable all optimizations, for debug
builds.

* Use -g on debug builds

* Use -g on debug builds

* Update tutorial_redball.md to remove matc's -O

* Update tutorial_suzanne.md to remove matc's -O

* Use -g in debug builds
2018-12-11 09:36:37 -08:00
shartte
3c8b7e537c Fixes an overflow issue when exactly 256 bones are used (#617) 2018-12-11 09:35:06 -08:00
Mathias Agopian
ab3dddeb78 add missing @public-api comment 2018-12-10 21:36:20 -08:00
Mathias Agopian
cd00c4bbe8 Add getUserTimeModulo() to materials
This calculates the modulo of the user time by a given value, using
the high precision user time. This is useful for animations without
having to worry about resetting the time.
2018-12-10 21:36:20 -08:00
Mathias Agopian
1dfc7fd5ae parallelize light and renderable culling
the code was structured so light culling and renderable culling could
be done in parallel, but this wasn't implemented.
Clean-up some methods to turn them to static and run light culling
in parallel with renderable culling.
2018-12-10 21:34:00 -08:00
Mathias Agopian
f9cc118bdb Always wake up a job queue when a job is ran
We used to only wake up a job-queue if there was already some jobs
running, the idea was that the current thread would handle the new job
as soon as calling wait(). However, there is no guarantee that wait() 
will be called anytime soon.

cv.signal() is not very expensive on Android/Linux, as we're using
a custom implementation.
2018-12-10 21:33:38 -08:00
Mathias Agopian
418aebb2a0 Run Froxelization during shadow pass
We can start the froxelization earlier so it happens during the
shadow pass.
2018-12-10 21:33:18 -08:00
Philip Rideout
96c0e999ae Vulkan: support 2D compressed textures. 2018-12-10 18:05:09 -08:00
Philip Rideout
8dda07bf2c mipgen: support generation of 4-band KTX files
This is useful because our Vulkan backend currently does not accept
3-band texture data. (although we intend to fix that soon)
2018-12-10 18:04:52 -08:00
Mathias Agopian
76b15e895a [MATERIALS BREAK] higher period clock
THIS CHANGE BREAKS MATERIALS.

This adds getUserTime() in shaders/materials, which returns the time
in second since Renderer::resetUserTime() was called.
Two values are provided, the time in second encoded as a float and
the difference between that and the double value, which together allows
to perform high precision time computation when needed.

This change allows longer running animations in materials. Using only
the float value, give millisecond resolution for more than 4h.
2018-12-10 16:28:07 -08:00
Philip Rideout
e3d0630704 Vulkan: fix mipmapping for 2D textures.
The dimensions passed into the VkBuffer-to-VkImage copy utility
specify a subregion for the copy, not the dimensions of the base level.

We were handling mipmapped cubemaps correctly, but mipmapped 2D images
were incorrect.
2018-12-10 16:23:55 -08:00
Romain Guy
e41dd027ab Enable optimization passes on materials with external samplers (#605)
* Enable optimization passes on materials with external samplers

Because external samplers are not properly supported by SPIRV and
associated library (spirv-cross and spirv-tools) we currently disable
all optimizations when we encounter a material with external samplers.

This however causes issues on some misbehaved drivers (not running
the optimizations has a side effect which causes a crash). To enable
the optimization pass we simply rely on the Vulkan codegen target to
substitute samplerExternal with sampler2D. We then analyze the output
GLSL (post-optimization) and revert the relevants sampler2D declarations
to samplerExternal declarations.

This fixup only occurs after optimization and for mobile targets and
if external samplers were declared.

* Address review comments
2018-12-10 12:02:59 -08:00
Romain Guy
3c89f901af Remove key fetch 2018-12-07 17:37:42 -08:00
Romain Guy
6ae21d3825 Add View::setFrontFaceWindingInverted() API (#602)
* Add View::setFrontFaceWindingInverted() API

This API can be used to flip all meshes in a render pass
inside out. This is useful for mirrored rendering.

This change also disables face culling on the default skybox
renderable. Since it is unlit, there is no downside to this
and the mesh being in the device vertex domain it can never
be backfacing unless front face winding is inverted.

* Track face winding state in Vulkan
2018-12-07 16:36:03 -08:00
Romain Guy
866c694977 Fix Linux build 2018-12-07 16:33:06 -08:00
Romain Guy
c11d6e549a Use the proper domain for the key 2018-12-07 16:19:27 -08:00
Romain Guy
4789e81ebc Require API level 21, not 24 (#599)
* Require API level 21, not 24

Fixes #594

* Update README.md
2018-12-07 16:17:57 -08:00
Romain Guy
a042cc7b8b Fix apt-get key issue 2018-12-07 16:16:52 -08:00
Mathias Agopian
4d9788ffb9 improve skinning memory usage and udpates
- use the exact required size for bone data instead of always the max
of 256 bones. This also reduces the amount of data to update and
copy into the command stream.

- also get rid of the "reuse component" optimization, which is less
needed now that renderables don't have their own transform UBO.
2018-12-07 16:07:49 -08:00
Romain Guy
5bbdc673f2 Remove CMake warning 2018-12-07 15:11:24 -08:00
magicwhale
4be93cbdd6 Added warning about textures using the pbrSpecularGlossiness gltf extension in MeshAssimp (#597) 2018-12-07 14:33:00 -08:00
shartte
556baee70c Allow for the use of a shared CRT when compiling for release mode on Windows (#581) 2018-12-07 13:32:09 -08:00
magicwhale
2633edf2c4 Changed MeshAssimp to use snorm16 if uv values are in the range [-1, 1] (#592)
* grouped MeshAssimp arguments into struct

* added snormuv optimization to MeshAssimp and changed snormuv optimization range from [0, 1] to [-1, 1] in filamesh
2018-12-07 13:03:18 -08:00
Philip Rideout
1feb07ba8b Add webpack / TypeScript demo. 2018-12-07 09:50:06 -08:00
Philip Rideout
083a60938e Update web site to v1.1.0 (includes KTX fixes) 2018-12-07 09:43:30 -08:00
Philip Rideout
f4f6fb75dc Support JPEG textures in the JS API.
This restores the canvas-based decoding method that was removed in #214,
but only for JPEG images. We continue to decode PNG images in C because
canvas-decoding mucks with alpha and prevents us from reading 16-bit
PNG.
2018-12-07 08:15:54 -08:00
Philip Rideout
71e9c13b94 Add TypeScript annotations file (hand authored for now) 2018-12-06 15:43:11 -08:00
Romain Guy
2cdac665db Rename debug APIs 2018-12-06 14:23:20 -08:00
Philip Rideout
c9752d8310 Update zeux/meshoptimizer 2018-12-06 13:33:22 -08:00
Benjamin Doherty
79764e7e02 Use -mssse3 flag with clang-cl 2018-12-06 13:33:22 -08:00
Philip Rideout
33383ab7fb Update zeux/meshoptimizer 2018-12-06 13:33:22 -08:00
Philip Rideout
6f601e6021 Update KTX files and allow glFormat = LUMINANCE 2018-12-06 10:33:49 -08:00
Sebastian Hartte
aaf2909194 Correctly set glTypeSize in the tools, and use sized formats for internalFormat 2018-12-06 10:33:49 -08:00
Sebastian Hartte
339483b8e2 Consider the correct KTX header attribute to determine the data format 2018-12-06 10:33:49 -08:00
Mathias Agopian
669c962d2b Fix CommandStream logging build 2018-12-06 08:53:48 -08:00
Sebastian Hartte
cfa486275a Install the image library as well 2018-12-05 17:57:20 -08:00
Mathias Agopian
c205499695 port filament_benchmark to google benchmark framework 2018-12-05 17:19:47 -08:00
Mathias Agopian
7ab25ff4a2 improve libmath benchmark 2018-12-05 17:19:47 -08:00
Philip Rideout
8bb68b3c55 Rename MeshIO class to MeshReader.
This makes the name symmetrical with MeshWriter.
2018-12-05 17:15:52 -08:00
Philip Rideout
beaf751604 filamesh: Compress attributes individually.
This further reduces compressed suzanne from 333489 bytes to 272761.

Tested with vk_hellopbr and tutorial_suzanne.html

Issue #558
2018-12-05 17:15:52 -08:00
Philip Rideout
6c55b3b989 filamesh: Add support for COMPRESSION.
Note that the WebGL build uses filameshio, but Android does not. Our
Android samples therefore do not yet understand the compressed format.
For web, I measured the before / after:

```
BEFORE: filament.wasm = 505796, suzanne.filamesh = 521476
 AFTER: filament.wasm = 510915, suzanne.filamesh = 333489
```

Issue #558
2018-12-05 13:20:55 -08:00
magicwhale
27f8dbef21 Added support to gltf_viewer for multiple UV coordinates (#578)
gltf_viewer can now display models that use both UV0 and UV1 coordinates for textures.
2018-12-05 12:35:26 -08:00
Philip Rideout
b4b12914a1 Add bitcast to utils. 2018-12-04 17:56:37 -08:00
Philip Rideout
ff2da6e3b4 Add zeux/meshoptimizer to third_party.
This also adds it as a dependency to filameshio. This does not seem to
increase the size of the WebGL build even though filameshio is a
dependency, perhaps because we are not using it yet.
2018-12-04 16:36:56 -08:00
Romain Guy
f8ac76f62a Fix typo in CMakeLists for glslang 2018-12-04 16:26:49 -08:00
Philip Rideout
fff76bfa3e Resurrect the NOOP driver. 2018-12-04 14:34:16 -08:00
magicwhale
8aa52575fa updated assimp (#577) 2018-12-04 13:46:32 -08:00
Ben Doherty
f05b2f47a8 Fix use of UV0 and UV1 coordinates (#576)
* Fix use of UV1

* Add a test case

* Spelling
2018-12-04 13:23:01 -08:00
Ben Doherty
2b6499fb18 Deprecate MaterialBuilder::postprocessor (#569)
* Deprecate postprocessor

* Remove unimplemented method
2018-12-04 10:11:52 -08:00
Philip Rideout
1ec037aeca filamesh: Remove duplicated code. 2018-12-03 14:18:12 -08:00
Philip Rideout
a7d6af8d22 filamesh: Add support for TEXCOORD_SNORM16. 2018-12-03 14:18:12 -08:00
Philip Rideout
0af274fe0e filamesh: introduce MeshWriter class.
This simplifies main.cpp so that it only does assimp stuff.
2018-12-03 14:18:12 -08:00
गोपालः शर्माः
99301c6287 Fixed typo (#571)
* Removed extra slash

* Fixed typo
2018-12-03 12:30:55 -08:00
गोपालः शर्माः
97dfd1ea95 Removed extra slash (#570) 2018-12-03 12:13:41 -08:00
Mathias Agopian
6d68a4a4c6 libmath benchmarks 2018-12-03 11:58:30 -08:00
magicwhale
b902a90285 Changed MeshAssimp to dynamically generate materials with filamat (#563) 2018-12-03 10:15:47 -08:00
Philip Rideout
ab4e9b5787 Disable test_filameshio, it requires OpenGL. 2018-12-03 02:12:52 -08:00
Philip Rideout
6a82d942cf Fix typo in test_list.txt 2018-12-02 19:34:30 -08:00
Philip Rideout
edda436405 Documentation for new filamesh flags, etc. 2018-12-02 16:46:31 -08:00
Philip Rideout
61992f556c Add unit test for filamesh.
The motivation behind a new regression test is the fact that we will
soon be adding compression features to filamesh.
2018-12-02 16:46:31 -08:00
Philip Rideout
aa3a7085cc Factor out common filamesh / meshio code.
This creates a filamesh namespace and removes several duplicated
classes, including Box and filamesh::Header.
2018-12-02 16:46:31 -08:00
Romain Guy
aee644dc97 Turn *off* the warning 2018-12-01 13:49:51 -08:00
Philip Rideout
eb814a9ff2 Repair test_cmgen. 2018-11-30 18:02:00 -08:00
Philip Rideout
9192280339 KTX-ify some of our sample environments.
- Nuke office and desert
- Add pillars and venetian_crossroads
- Regenerate white_furnace
- Keep the diagnostic environments (uv2, uv8, and uv128) as-is
2018-11-30 17:15:10 -08:00
Romain Guy
79a2685f3c Update README.md 2018-11-30 17:01:04 -08:00
Philip Rideout
af799e734a FilamentApp can now use KTX environments.
When cmgen creates ktx files, it creates a pair: one with an _ibl suffix
and one with _skybox. This convention is now honored by FilamentApp.

Note that we already have several KTX environments in the repo, so you
can clone a fresh repo and do:

  gltf_viewer --ibl={FILAMENT}/docs/webgl/pillars_2k DamagedHelmet.gltf

Note that we have several hundred files in samples/envs, we should
consider replacing those or copying the environments in docs/webgl
(which git would internally de-dup, due to content hashing).
2018-11-30 14:09:04 -08:00
Philip Rideout
7366bdb500 More KtxUtility improvements.
This makes it easier for C++ clients to use KTX files and simplifies
the JavaScript bindings.
2018-11-30 13:16:47 -08:00
Philip Rideout
5abd60fca5 Mipgen now creates the out dir if needed. 2018-11-30 13:16:47 -08:00
Romain Guy
533e260804 Remove obsolete samples (#559) 2018-11-29 17:40:05 -08:00
Philip Rideout
20680e8170 Improve resgen speed and avoid using static.
(1)
Generating the C file (only used for WebAssembly) causes slowness in the
build so this makes it into an option. Also, we were flushing too often,
which made it even slower.

(2)
Using "static" in a header was causing symbol duplication.
2018-11-29 17:21:27 -08:00
Romain Guy
9686647a2e Add the ability to build several platforms, but not all (#557)
build.sh -p all builds everything which may be too much. -p now
accepts a list of platforms. For instance to build Android and
desktop:

./build.sh -p android,desktop release
2018-11-29 16:56:02 -08:00
Romain Guy
bd0b752337 Add RenderQuality API (#555)
View::setRenderQuality gives the ability to control the rendering quality
of a given view. In particular this allows the app to lower the quality
of the HDR color buffer by using R11G11B10F instead of RGB(A)16F.
2018-11-29 16:55:36 -08:00
Philip Rideout
da7dbbc04b Filamesh now creates the out dir if needed. 2018-11-29 16:41:09 -08:00
Philip Rideout
bcfe03c8e1 KtxUtility improvements.
This makes it easier for C++ clients to use KTX files and simplifies
the JavaScript bindings.
2018-11-29 16:39:30 -08:00
Mathias Agopian
e8895fee11 Add a binary search benchmark
this one basically shows that the stl is is a good as our "branch less"
versions. this is because clang generate branchless code in the end.
2018-11-29 11:44:52 -08:00
Mathias Agopian
42a3d5ea33 use utils::Mutex instead of std::mutex for Allocators locking policy
on Android it's about 2x faster and uses much less instructions, which
is better for i-cache pressure.
2018-11-29 11:44:52 -08:00
Mathias Agopian
785ce645e2 pool allocators benchmark
this benchmark shows that, as we expected, on Android mutexes,
spinlocks and lock-free algorithms are running at similar performance.
2018-11-29 11:44:52 -08:00
Ben Doherty
fe4907d0ff Remove use of iostream in filamat (#549) 2018-11-29 10:35:37 -08:00
Philip Rideout
97d5f0f52c Fix libshader build for Windows. 2018-11-29 07:37:56 -08:00
Philip Rideout
239317ee10 Use resgen for libshaders. 2018-11-29 07:37:56 -08:00
Philip Rideout
4278e1bd59 Remove assimp usage from some sample apps.
This shows how resgen can be used for mesh data. It also removes the
MeshAssimp dependency from samples that were meant to be small and
self-contained.
2018-11-28 19:46:37 -08:00
Philip Rideout
12754fd7eb Minor resgen improvements.
This adds a couple optional features:

1) Preserve file extensions when generating symbols.
   This is useful to distinguish foo.vs from foo.fs

2) Append null characters to data blobs.
   Useful when treating FOO_DATA as a C string.
2018-11-28 16:58:41 -08:00
Philip Rideout
0b84425bd0 Fix up tangents in MeshAssimp to help with #528.
We started to write our own implementation of mikktspace, but it
required an unindexed mesh for input. This was awkward because assimp is
already applying a pipeline of operations that includes tangent
generation and indexing. It felt reduandant to add our own pipeline on
top of that (unindexing => tangentgen => reindexing).

Since assimp's CalcTangentsProcess method is already producing
tangents that follow the orientation implied by texture coordinates,
this simply needs to be tweaked to match glTF. (flip the bitangent)

Also fixed a bug for the case where models have neither UV's nor
tangents, where we were calling norm instead of normalize. :)
2018-11-28 15:46:04 -08:00
Ben Doherty
b759074c8f Deprecate set method on MaterialBuilder (#545)
* Remove the defines entry in material definitions

* Deprecate set function

* Remove some getter methods from MaterilaBuilder

* Fix tests, add to CI
2018-11-28 15:35:19 -08:00
Ben Doherty
3a677fa832 Fix matc crash (#546) 2018-11-28 15:00:45 -08:00
magicwhale
2a5e978f2e Changed MeshAssimp to use constants defined in assimp header files 2018-11-28 12:15:24 -08:00
Mathias Agopian
cf5606e940 Fix another bug in AtomicFreeList
An assert checking invariants would sometime trigger, the problem
was a logic error that would be exposed by a race when running out
of space in the list.

The root of the problem is that in one place we were not remapping the 
-1 offset to nullptr, storing a pointer violating our invariants.

Also added more asserts!!!
2018-11-28 12:10:23 -08:00
Romain Guy
e6cb4d0dfa Update sample screenshots in README 2018-11-28 11:43:13 -08:00
Philip Rideout
91abaf575b Add tangents utility to fix #532.
I tested this by writing a quick-and-dirty Sphere demo.
2018-11-28 11:27:37 -08:00
Romain Guy
47d10687a5 Fix docs 2018-11-28 10:03:38 -08:00
magicwhale
ad1f3cf133 Added support for different min and mag filter samplers in gltf_viewer (#539)
Modified MeshAssimp.cpp to support different min and mag filter types for gltf files.
2018-11-28 10:03:07 -08:00
François Guthmann
9915ec7841 EV100 formula typo (#543)
Forgot the parenthesis when I corrected it, I'm sorry...
2018-11-28 09:31:13 -08:00
Philip Rideout
0011b1bba3 Use resgen in samples and MeshAssimp. 2018-11-28 08:35:44 -08:00
Philip Rideout
39fbcec767 Refactor resgen functionality in CMakeLists.
By defining a top-level function, we will allow the use of resgen
in multiple projects.

Also removed an redundant edge in the dependency graph.
2018-11-27 21:59:25 -08:00
Mathias Agopian
3861accb97 split CommandStream.h and add systrace option
systrace can now be enabled in the CommandStream's Dispatcher, which
allows it to work with all backends.
2018-11-27 20:21:34 -08:00
Romain Guy
808fd9819c Sort FADE materials with TRANSPARENT materials (#535)
FADE is just a variant of TRANSPARENT that only affects shading.
This change introduces the "render blending mode" which is the
blending mode that must be used when generating the render keys.
2018-11-27 16:04:34 -08:00
Mathias Agopian
05854e0d05 port the "filament_calls" benchmark to google benchmark 2018-11-27 15:07:45 -08:00
Ben Doherty
a1ed3b81a3 Move static code analysis into filamat (#534)
* Handle static code analysis automatically

* Fix matc test cases

* Only call InitializeProcess once per process
2018-11-27 14:11:27 -08:00
Romain Guy
d62a7c7d8d Add bit of documentation 2018-11-27 14:00:26 -08:00
Sebastian Hartte
6b030c9694 More documentation of the free list 2018-11-27 11:44:32 -08:00
Sebastian Hartte
df4a2bb86e Fixes #542 by moving the assert to after checking for a possible race condition 2018-11-27 11:44:32 -08:00
Ben Doherty
0548b28535 Update glslang (#526)
* Update glslang

* Update builtinResource

* Add glslang update README
2018-11-27 09:52:03 -08:00
shartte
ae74911bee Implicit conversion to float3 does not work in these cases for MSVC. (#529) 2018-11-27 09:34:55 -08:00
Philip Rideout
30092dc12b Add style guidelines for strings.
This also adds the std:: qualifier to resgen (see also PR #356)
2018-11-27 09:05:57 -08:00
Philip Rideout
f5fc6fe4d7 Tweak shader model error message.
The error message could say "need 0x2 but contains 0x2" which is still
confusing. Now that we're printing the actual required shader model
in English, we can simply say:

    The material 'foobar' was not built for desktop.
    Compiled material contains shader models 0x2.
2018-11-27 09:05:15 -08:00
Philip Rideout
19026931a4 Fix Android warning. 2018-11-26 16:55:34 -08:00
Romain Guy
588ce8fe3f More code style cleanup 2018-11-26 14:07:07 -08:00
Romain Guy
44c4362edb Code style cleanups 2018-11-26 14:04:43 -08:00
Ben Doherty
594f1abbbc Rename GlslChunk to TextChunk (#527)
* Rename Glsl -> Text

* Make MaterialTextChunk and DictionaryTextChunk more generic
2018-11-26 14:02:04 -08:00
Romain Guy
20ffb52dc2 Re-enable glTF support (#505)
* Revert "Rollback MeshAssimp enhancements."

This reverts commit b3dce967eb.

* Re-enable glTF support

* Start looking for texture ids at 1, not 0

* Detect if the importer is glTF

* glTF and regular materials both work
2018-11-26 13:14:28 -08:00
Pixelflinger
cf4410f656 Add some libutils benchmarks 2018-11-26 11:51:17 -08:00
Pixelflinger
bc0f2f26f2 Tweak Profiler API so it works in multithread
Instead of using a singleton, Profiler has to be instantiated in the
scope/thread it is used.
2018-11-26 11:51:17 -08:00
Pixelflinger
80aa9964f5 Add google benchmark to the build 2018-11-26 11:51:17 -08:00
Pixelflinger
417d606e5b fix google benchmark README so it works in CLion 2018-11-26 11:51:17 -08:00
Pixelflinger
42a55d3b08 fix google benchmark build for ANDROID SDK < 29 2018-11-26 11:51:17 -08:00
Pixelflinger
6a38c8fde6 fix google benchmark with emscripten (workaround) 2018-11-26 11:51:17 -08:00
Pixelflinger
89f739fd06 add google benchmark library 2018-11-26 11:51:17 -08:00
Ben Doherty
6d158bbc80 Remove codeGenTargetApi (#511) 2018-11-26 10:51:34 -08:00
Philip Rideout
0fda416c49 Use resgen for Filament built-in materials. 2018-11-26 10:31:09 -08:00
shartte
9ab9333fa5 Fixes various MSVC issues in public headers (#523) 2018-11-26 09:17:19 -08:00
François Guthmann
78804251e9 Corrected typo in formula (#519)
It looks like there is a minus sign missing in there, see https://www.wolframalpha.com/input/?i=(((1%2Bsqrt(x))+%2F+(1+-+sqrt(x)))+-+1.5)+%2F+(((1%2Bsqrt(x))+%2F+(1+-+sqrt(x)))+%2B+1.5)

I'm not sure what the code does though https://github.com/google/filament/blob/master/shaders/src/brdf.fs#L282
2018-11-23 10:09:54 -08:00
François Guthmann
5a402dc6a8 Corrected exposure from ev100 formula (#518)
The new formula should be the correct one according to this document (first line p86): https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
2018-11-22 10:03:29 -08:00
Philip Rideout
0807cfbaaa Fix Windows build. 2018-11-21 22:14:22 -08:00
Philip Rideout
e90b53fdce Introduce resgen tool for embedding binary blobs.
This tool can be used to replace inc files for built-in materials. The
inc files are unfriendly to IDE's and do not extend to non-material
resource types such as baked texture data.

The tool aggregates a sequence of binary blobs, each of which becomes a
"resource" whose id is the basename of the input file. It produces the
following set of files:

    resources.h ......... declares sizes and offsets for each resource
    resources.S ......... small assembly file with incbin directive
    resources.apple.S ... ditto but with different rodata name
    resources.bin ....... the aggregated binary blob
    resources.c ......... large xxd-style array (only for WASM)

We did an experiment to test the incbin directive on a variety of
platforms in PR #510.
2018-11-21 17:18:21 -08:00
Romain Guy
55dd612c64 Add screenshots to Android samples' README (#513)
This change also optimizes the size of existing images using squoosh.app.
This should make the main README a lot lighter and faster to load (it saves
several MiBs).
2018-11-21 14:16:21 -08:00
Mathias Agopian
d1b19efa55 a fast approximation of pow() and pow(x, 2.2f)
fast::pow(x, 2.2f) is about 100x faster than std::pow.
std::pow(x, 2.2f) takes roughly 1000 cycles.
2018-11-21 13:46:56 -08:00
Mathias Agopian
adbe3a75f2 don't use a deque for the frame history
deque is not worth it with few items.
2018-11-21 13:46:07 -08:00
Mathias Agopian
75aaa3d9ab don't use a deque for just a handful of elements
this eliminates a bunch of code
2018-11-21 13:46:07 -08:00
Mathias Agopian
265bae40db Improve/comment FrameSkipper
Try to make FrameSkipper a little less confusing.
2018-11-21 13:46:07 -08:00
Mathias Agopian
9e39004b1f Add wait_for and wait_until to our Condition implementation
We're using timed condition variable in one place, but the STL version
pulls in a lot of code because it does clock calculations in 
"long double" (!!!!). Since we already had an implementation
of condition_variable, we just add the timed version.
This saves several KiB of code.

Also don't use unique_lock() lock/unlock because it can throw exceptions.
2018-11-21 13:46:07 -08:00
Mathias Agopian
7b2a1b0018 Get rid of the memory pool for UniformBuffer
The Pool wasn't used much anymore, since we're explicitly copy
the data into the command stream. Moreover, it generated a lot of code
and in fact was probably less efficient than malloc itself -- 
I think this was a misguided optimization in the first place.
2018-11-21 13:46:07 -08:00
Mathias Agopian
1212728e45 get rid of std::string in OpenGLProgram
This was generating tons of code.
2018-11-21 13:46:07 -08:00
Mathias Agopian
815fb36b98 code size optimizations
- prevent unrolling of some loops. e.g. one loop generated more than
  1 KB of code!
2018-11-21 13:46:07 -08:00
Mathias Agopian
5bcc4cfff1 Improve the slow-path of creating a program
This removes a lot of heap allocations/deallocations, and reduces
code size. Most improvements come from using CString and
StaticString instead of std::string and better using move
semantics.
2018-11-21 13:46:07 -08:00
Mathias Agopian
c1a7164084 Improve usage of CString
This cuts down 7 calls to free() to 1, when
instantiating a new program. There are still many low-hanging fruits
there.
2018-11-21 13:46:07 -08:00
Mathias Agopian
9bb87b8725 minor reorganizing of the command loop 2018-11-21 13:46:07 -08:00
Philip Rideout
454c102e3c Remove non-existing option from build help. 2018-11-21 12:12:37 -08:00
Philip Rideout
ee26f58dcf Improve error reporting for ShaderModel mismatch.
Aaron pointed out that this error is easy to run into and quite cryptic
since one value is decimal and the other is hex. Users might not be
aware that one of them is a bitmask, and that this is related to how
they invoke matc or filamat.
2018-11-21 12:12:37 -08:00
prideout
776284b2b5 Raise sampler limit to 16.
In practice this limits materials to 10 samplers since Filament uses 5
for lights and skips 1 slot for the post-process sampler. This can
probably be optimized.
2018-11-20 16:05:16 -08:00
Ben Doherty
86fb7b4524 Compile filamat and dependencies for all platforms (#506)
* Compile filamat and dependencies for all platforms

* Describe changes made to CMakeLists
2018-11-20 15:31:16 -08:00
prideout
cfa9895b96 Improve error reporting for bindings overflow.
We now check for sampler overflow during material compilation rather
than waiting for run-time checks. This allows for Kokoro-based
validation of sample materials, and allows developers to catch this
issue in their asset pipeline.

We should also probably raise the upper limit (Qualcomm allows up to 16
samplers in their Vulkan implementation) but that can be a separate PR.

Fixes #507
2018-11-20 15:28:02 -08:00
Ben Doherty
b5fa822e86 Move GLSLPostProcessor and dependencies into filamat (#500)
* Move GLSLPostProcessor into filamat
2018-11-20 12:30:26 -08:00
Philip Rideout
aa0090a85b Fix build warnings. 2018-11-19 15:59:31 -08:00
Philip Rideout
0d476b9f6d Fix debug builds. 2018-11-19 15:45:40 -08:00
prideout
694eab703c Remove usage of std::string in VulkanDriver. 2018-11-19 14:18:39 -08:00
Philip Rideout
b3dce967eb Rollback MeshAssimp enhancements.
This caused regressions with some of our samples like vk_hellopbr:

- For the new 1x1 textures, RGB isn't accepted by Vulkan and Metal.
  Currently these platforms require RGBA, although we plan on adding
  reshaping functionality for the future.
- Too many texture samplers in a single shader, this causes a run time
  error. This could be alleviated by creating an atlas.
- vk_hellopbr assumes that all materials have a "metallic" param.

Going forward, we plan on creating a new library that avoids MeshAssimp,
so for now let's just disable gltf_viewer.
2018-11-19 14:18:12 -08:00
Philip Rideout
1413b4d622 Fix path in vk_texturedquad 2018-11-19 14:17:13 -08:00
magicwhale
fc0d587b40 Added support for more features in gltf_viewer sample 2018-11-19 09:27:08 -08:00
magicwhale
1d392d38bd updated assimp 2018-11-19 09:27:08 -08:00
magicwhale
bc38c8a773 Edited MeshAssimp and added gltf_viewer sample code 2018-11-19 09:27:08 -08:00
Philip Rideout
84d2fb222b Flesh out JS bindings a bit. 2018-11-16 17:21:44 -08:00
Philip Rideout
1ed8618cca Refresh website to publish new tutorial. 2018-11-16 17:21:18 -08:00
Philip Rideout
edb545919a Fix regression with non-Vulkan backends.
This fixes the "shader is not ASCII" error seen with GL backend,
introduced when we changed blob ownership semantics to accommodate
shader compression. It was due to missing null terminators.

We actually never bothered including the trailing null in blob length,
which was wrong but happened to work because the BlobDictionary held a
weak reference to chunk data. SInce it now holds an actual copy, the
lack of null caused our strings to contain garbage memory.
2018-11-16 15:43:41 -08:00
Philip Rideout
e652507315 Tutorial fixups per code review feedback. 2018-11-16 14:09:41 -08:00
Philip Rideout
ffff8437ba Add tutorial that describes compression and async loading. 2018-11-16 14:09:41 -08:00
Philip Rideout
b2a2da532a Fix Android-with-Vulkan build. 2018-11-16 12:07:23 -08:00
Philip Rideout
e3a20e0dfe Fix Linux build failure. 2018-11-16 12:07:23 -08:00
Philip Rideout
2d0b2050fc Fix iOS build failure. 2018-11-16 12:07:23 -08:00
Philip Rideout
b83c82ea9b Enable SMOLV compression. 2018-11-16 12:07:23 -08:00
Romain Guy
0938051579 Fix docs 2018-11-15 16:57:16 -08:00
Philip Rideout
e0fd196530 Exclude SMOL from Vulkan-free builds. 2018-11-15 16:55:40 -08:00
Philip Rideout
55eaad9450 Add smol-v to third_party.
Since we use this for decoding, this adds a dependency to the core
filament renderer which in practice is only used for Vulkan. However
this is a tiny library, so it's simplest just to always include it.

The next PR will add the actual compression / decompression code to
filaflat and filamat. Here are the preliminary results.

   102K =>  29K  aiDefaultMat.filamat
   102K =>  29K  aiDefaultTrans.filamat
    21K => 5.0K  bakedColor.filamat
    22K => 5.2K  bakedTexture.filamat
    21K => 5.0K  depthVisualizer.filamat
    40K =>  10K  groundShadow.filamat
   102K =>  29K  sandboxCloth.filamat
   125K =>  36K  sandboxLit.filamat
   126K =>  36K  sandboxLitFade.filamat
   126K =>  36K  sandboxLitTransparent.filamat
   109K =>  31K  sandboxSubsurface.filamat
    21K => 4.9K  sandboxUnlit.filamat
    21K => 4.9K  transparentColor.filamat

Both the "before" and "after" numbers are excluding non-Vulkan targets,
and I also changed our CMakeLists to build filamat instead of inc.
2018-11-15 16:55:40 -08:00
Philip Rideout
d94a1610a5 Fix minor Vulkan warning. 2018-11-15 14:49:17 -08:00
Philip Rideout
307645c7ce Add Vulkan support for depth offset and face culling. 2018-11-15 08:29:29 -08:00
Philip Rideout
a5cdb89107 Handle Vulkan ClipSpace in GLSL rather than C++.
Recall that Vulkan has a right-handed NDC system. Currently, our Vulkan
backend is not handling VERTEX_DOMAIN_DEVICE correctly, but we didn't
notice because the culling mode is not honored yet (a separate PR is on
the way for that).

To fix this, we considered adding a shader-based fixup only for the
device domain and keeping our Vulkanish projection matrix as-is.
However, this would cause the skybox shader to compute an incorrect
wrong eye vector due to in the inconsistent definition of clip space.

After discussion with Mathias and Ben, we decided that the most elegant
fix is for Filament to have only one canonical clip space, which for
now is the clip space that OpenGL requires.

Ben pointed out that spirv-cross has a flag for injecting shader-based
fixups. However we don't invoke spirv-cross for the Vulkan target, and
it's easy just to do this on our own.
2018-11-15 08:08:16 -08:00
Romain Guy
f1c2c39a3d Cleanup matc a little bit (#488) 2018-11-14 11:58:06 -08:00
Vallentin
81e8035cbb Fixed typos (#487) 2018-11-14 09:19:04 -08:00
Mathias Agopian
870d15b9ab Add MaterialInstance::setPolygonOffset()
The polygon offset can now be set through MaterialInstance. 
USE WITH CAUTION, this impacts performance negatively.
2018-11-13 19:27:52 -08:00
Mathias Agopian
87d66b41d5 Add polygon offset to the driver API 2018-11-13 19:27:52 -08:00
Mathias Agopian
825a72df10 The driver Draw() command now takes a PipelineState
PipelineState contains the program and raster state, more
state might be added in the future. Currently it is passed by value
and doesn't have a HwHandle, but this may change in the future.
2018-11-13 19:27:52 -08:00
Ben Doherty
74573c7ce4 Fix undefined symbols issue with web builds (#482) 2018-11-13 18:11:03 -08:00
Philip Rideout
17003106d2 Prep for new JavaScript tutorial.
This adds a few new functions to the JavaScript bindings. It also adds
our JavaScript docs into the CMake build system for machines that meet
the Python requirements.
2018-11-13 17:27:34 -08:00
Mathias Agopian
f011a212bd Minor clean-ups of Program 2018-11-13 16:02:44 -08:00
Philip Rideout
73a2ef7944 Add favicon. 2018-11-13 12:07:57 -08:00
Philip Rideout
7c2c4f3b11 Fix parquet wrap mode. 2018-11-13 12:07:47 -08:00
Philip Rideout
0faf7bbcb6 Publish Hugo site and web tutorials.
This performs the steps described in site/README in order to publish
the Hugo site to GitHub Pages:

    https://google.github.io/filament
2018-11-13 11:24:41 -08:00
Philip Rideout
904573b374 Incorporate feedback into Hugo site. 2018-11-13 10:57:20 -08:00
Philip Rideout
df3c2b74fd Add two-column mobile-friendly Hugo site.
This is a simple place to host WebGL demos and tutorials, we can prettify later. It will show up at:

    https://google.github.io/filament/

The hugo config specifies the output holder to be ../docs which is where our GitHub Pages site is located.

Note that this commit adds the *source* to the site, it does not publish the actual site. When we're ready to publish the actual site, we'll do:

```terminal
cd site ; hugo ; cd ..
git add docs ; git commit
```
2018-11-13 10:57:20 -08:00
Philip Rideout
037a0007c2 Disable depth prepass for WebGL.
WebGL does not always honor the invariant GLSL decoration, so we cannot
allow the depth prepass on web.

This fixes the black flakes seen with the Intel HD Graphics 615 in
Pixelbook laptops.
2018-11-13 09:22:08 -08:00
Mathias Agopian
bc3aee118a code size and performance optimizations (#472)
* Clean-up EntityManager a bit

- use tsl::robin_set instead of std::set (which should have been unordered::set
  anyways).

- getListeners() now returns a vector which avoids to traverse a set twice.
  Turns out that copying the set wasn't as efficient as I thought.

* Improve jobsystem a bit

We recently added a job reference counting mechanism, but we were a bit
too aggressive about taking/release references.

Also make the API more complete by adding explicit retain/release,
which is needed to allow several threads to wait on the same job.

Also improve futex code by inlining it.
2018-11-12 14:11:31 -08:00
Philip Rideout
3407302954 Minor suzanne cleanup. 2018-11-08 16:21:54 -08:00
Philip Rideout
f4806461ee Fix JavaScript leaks with BufferDescriptor.
Fixes #429
2018-11-08 16:17:29 -08:00
Philip Rideout
207d4ea4c1 Fix JS API leaks by auto-deleting builders, etc.
While this solves the builder leak, it does not solve the tiny leak
incurred every time you call `getInstance` on a component manager
without calling embind's `delete` method afterwards. Since there's no
way to auto-delete component instances, this CL fixes up our sample
code and docstrings.

Fixes #429
2018-11-08 16:17:29 -08:00
Mathias Agopian
f8f24f492f minor typo / spelling / clang-tidy fixes (#468)
* Minor clean-ups

- fix a couple usage of std::function
- fix a couple usage of std::string
- remove ALIGN_LOOP, which didn't work
- fix a couple explicit/noexcept
- virtual -> override

* Fix spelling typos and other minor clang-tidy
2018-11-08 11:50:00 -08:00
Philip Rideout
5fb0696fb7 Resurrect the JS memory leak test (#429) 2018-11-08 11:16:41 -08:00
Philip Rideout
75ffbe13be Fix typos. 2018-11-07 16:28:57 -08:00
Philip Rideout
bf77a33e1f Include filament-js README in npm package. 2018-11-07 16:14:39 -08:00
Philip Rideout
b9bfda5704 The JS API now supports compressed textures. 2018-11-07 16:12:55 -08:00
Philip Rideout
ee5b0268fd Introduce KtxUtility to make it easier to translate enum values. 2018-11-07 16:12:55 -08:00
Philip Rideout
5f05180d0f Update "Directory structure" in toplevel README.
I don't think it's useful to indent the entire tree, so this removes
the redundant root. More importantly, it adds the "web" folder. :)
2018-11-07 10:48:22 -08:00
Ben Doherty
cf7e49f96a Fix max anisotropy in Vulkan backend (#466) 2018-11-07 10:46:49 -08:00
Philip Rideout
a052d6cf49 Fix STREAM uniform buffers for web. 2018-11-06 13:50:49 -08:00
Mathias Agopian
591c9f2454 Fix a crasher when allocating the last Job
Instead of returning nullptr, the pool allocator returned an
invalid pointer.
2018-11-06 13:44:35 -08:00
Mathias Agopian
e580bfed56 Fix allocator test when --gtest_repeat is used 2018-11-06 13:21:33 -08:00
Mathias Agopian
e2896f4632 Set cache size to 64 bytes on all platforms
We used to assume 32-bytes cache lines when running on ARM 32-bit mode,
however, that was wrong because 32-bit mode doesn't change the cpu's
cache line. On all modern platforms we support, the cache line
is 64 bytes.

Set Job storage to 48 bytes on all platforms.
2018-11-06 13:21:09 -08:00
Philip Rideout
a33c64c736 Update version doc and package per code review. 2018-11-06 12:48:56 -08:00
Philip Rideout
7ea04957d2 Introduce versioning scheme and npm package definition. 2018-11-06 12:48:56 -08:00
Mathias Agopian
8c6cfdba67 Fix erroneous assert 2018-11-06 11:01:08 -08:00
Mathias Agopian
e5cfbeff4d Attempt to fix windows build
Align atomic HeadPtr to 64-bits.
2018-11-05 19:37:31 -08:00
Mathias Agopian
68c6afa72e Fix reuse after free and API inconsistency in job system (#446)
* Fix a reuse after free in the job system

Jobs were destroyed and recycled while still in use
by wait() or run(). To fix this we introduce reference-counting of
jobs.

Jobs start with a ref-count of 1, which is decremented when a job
naturally finishes. Additionally, all user-facing methods acquire
a reference for the duration of the call.

* Fix an API inconsistency with JobSystem

JobSystem's API lets the user create jobs but not destroy them.
Jobs are destroyed automatically, without a way for the caller to
know when that happens.

We now explicitly enforce that jobs are no longer valid when
wait() returns. Multiple concurrent wait() are allowed however.

This is enforced by clearing the job pointer upon returning
from JobSystem::wait(Job* job).

* Rename linked-list put/get to push/pop

* Better fix for Job use after free

There was still a race condition where a run()'ed
job could be destroyed before wait() was called,
wait would then use a destroyed object.

The available APIs now are:

run() - runs and destroys a job
runAndWait() - run, then waits for and destroys a job
runAndRetain() - runs and keep a reference to the job
wait() - waits and destroys a job

wait() can only be used with a job obtained with runAndRetain().

* Get rid of unused code

This version of parallel_for has use-after-free issues anyways,
since we changed the semantics of run/wait/etc...

* Fix decRef() memory order

decRef() must ensure that all access to the 
object have happened before destroying it.

* Fix memory order in atomic linked list's pop()

It needs acquire semantic, since we want to make
sure that no read/write are reordered before the
pop() -- which returns an object to the caller.

* Fix memory order on runningJobCount

we needed acquire semantic when about to destroy
the last job -- it's similar to decRef.

* Comment usages of std::memory_order_*

* Fix AtomicFreeList A-B-A bug

Turns out AtomicFreeList was not immune to the ABA bug. W're fixing
it here by using a 64-bits CAS, which is available on aarch64 and armv7.
2018-11-05 19:12:13 -08:00
Romain Guy
bb3e9a47e5 Update link to CIE colormetric tables
Fixes #452
2018-11-05 15:53:41 -08:00
Philip Rideout
8d410af4b3 JS API: prepare for compressed textures.
Note that we need to allow clients to find out if compressed textures
are supported BEFORE the engine is created, so that they can start
downloading the correct set of texture files. To allow this, we now
expose a getSupportedFormats function that creates a throw-away canvas
in order to query extensions (creating a temporary canvas is a technique
that we also used in the old PNG decoder that we removed in 7b36ed4)
2018-11-03 13:07:02 -07:00
Romain Guy
61112c02c1 Fix typo 2018-11-02 17:23:14 -07:00
Philip Rideout
816fb99b2f Repair WebGL, which does not support MapBufferRange. 2018-11-01 21:55:10 -07:00
Philip Rideout
9de7ffaf84 Fix typo in title tag for suzanne. 2018-11-01 17:11:58 -07:00
Philip Rideout
e3e16fe28b Remove defunct web/tests folder.
These are broken and no longer necessary now that we have web/samples.

Despite the name, these weren't real tests; they were ignored by CMake
and did not run in an automated manner. Going forward we need a better
solution for automated testing.
2018-11-01 17:05:30 -07:00
Philip Rideout
bb0c21b8ea Rename filamentjs to filament-js to follow convention. 2018-11-01 17:05:30 -07:00
Philip Rideout
c46ecc6e05 Port the Suzanne demo to JavaScript. 2018-11-01 17:05:30 -07:00
Philip Rideout
fffb2c8c97 Add samples to the new web directory. 2018-11-01 17:05:30 -07:00
Philip Rideout
a42dcd2291 JavaScript code re-org (#443)
This removes the old CPP-based web samples in favor of the new JS API.

The `web/samples` folder will be added in a subsequent commit.
2018-11-01 17:05:30 -07:00
Romain Guy
4e3a88bbab Cleanup and documentation (#445) 2018-11-01 16:36:52 -07:00
Mathias Agopian
02d45d464c Never use QCOM_tiled_rendering
It turns out that it degrades performance even in cases where we
thought it would help. It seems to always trigger a "glFlush"
and has a very large CPU overhead. It looks like
glInvalidateFramebuffer() does a better job.
2018-11-01 11:30:38 -07:00
Mathias Agopian
c758b53f00 Factor out the UBO uploading code
This is just so that in the future we could reuse that
code for other buffers as it's not specific to UBOs.
2018-11-01 11:30:38 -07:00
Mathias Agopian
4e3c2582e0 Rename loadFoo() to updateFoo() in the driverAPI
Now all buffer updating methods are called updateXXX().
2018-11-01 11:30:38 -07:00
Mathias Agopian
cc1ba4fac7 Reorder methods in OpenGLDriver to match declaration
This change just reorder the load/update buffer/textures
methods so they match the declaration in DriverAPI.inc,
and are grouped together.
2018-11-01 11:30:38 -07:00
Mathias Agopian
f52087ec1e Attempt to upload streaming ubo data more efficiently
IF an UBO is marked as STREAM, meaning that data will
change every frame and the buffer content is invalidated
as well, then we use map/unmap buffer in asynchronous
mode to copy the data into the buffer.

This assumes the buffer is sized to be significantly
larger than the average amount of data used every
frame.
2018-11-01 11:30:38 -07:00
Mathias Agopian
2ac04c27d8 Add support for ANDROID_get_frame_timestamps
We don't make use of it yet, though.
2018-11-01 11:30:38 -07:00
Mathias Agopian
211eddfbe0 Add a couple missing DEBUG_MARKER() calls
Also, store a couple useful glGet*()
2018-11-01 11:30:38 -07:00
Philip Rideout
522a8bedb8 Update filamentjs test runner. 2018-10-30 16:50:24 -07:00
Philip Rideout
8ad655766b JavaScript: concise setBuffer API 2018-10-29 18:09:45 -07:00
Philip Rideout
5da454f652 JavaScript: concise texture creation functions
This makes our createTexture* helpers more consistent with the
createMaterial helper, and extends the wrapped Engine class with new
methods.

Before, clients did something like this:

    const ao = Filament.createTextureFromPng(Filament.assets['foo.png'], engine);
    ...
    engine.destroyTexture(ao);

Now, they can do:

    const ao = engine.createTextureFromPng('foo.png');
    ...
    engine.destroyTexture(ao);

This is more symmetric and concise. In general the JS API now supports a
class of "buffer-like" objects which exploit dynamic typing in order to
accept any of the following: BufferDescriptor, asset string, or
Uint8Array.
2018-10-29 18:09:45 -07:00
Philip Rideout
0deafea0da Add requirements.txt for Python scripts. 2018-10-29 17:53:09 -07:00
Philip Rideout
69e379cf90 Test for JS leaks using emcc --memoryprofiler. 2018-10-29 17:53:09 -07:00
Philip Rideout
e8fddba494 New JS test for memory leaks.
This test recreates a renderable every few frames and dumps the heap
pointer to the console so we can check if it increases over time.

Also simplified the personal web server script so that it uses twisted
and avoid doing a chdir, seems to be more reliable this way.
2018-10-29 17:53:09 -07:00
Romain Guy
31b9801f17 Move textures to nodpi to avoid upscales (#437) 2018-10-29 17:40:34 -07:00
Philip Rideout
4860ff816f JavaScript PNG utility now has SRGB flag. 2018-10-29 17:38:02 -07:00
Philip Rideout
82e61ddc88 Fix the JS IcoSphere tangents.
We were not normalizing one of the orthonormal basis vectors, causing
the visual aberration reported in #423.

This CL also add a "back light" to the redball demo to lighten up the
dark area in the IBL.

Fixes #423
2018-10-29 17:37:42 -07:00
Romain Guy
3a9f3a1984 Update to Kotlin 1.3 (#436) 2018-10-29 17:37:21 -07:00
Philip Rideout
3b793a7994 Fix bad memory access in JS wood demo. 2018-10-26 16:29:26 -07:00
Ben Doherty
e2777b9100 Update libs/filamentjs/tests/test_parquet.js
Co-Authored-By: prideout <philiprideout@gmail.com>
2018-10-26 10:30:44 -07:00
Ben Doherty
96cb5d5951 Update libs/filamentjs/tests/test_parquet.js
Co-Authored-By: prideout <philiprideout@gmail.com>
2018-10-26 10:30:44 -07:00
Ben Doherty
e6bb8a6235 Update libs/filamentjs/tests/test_parquet.js
Co-Authored-By: prideout <philiprideout@gmail.com>
2018-10-26 10:30:44 -07:00
Ben Doherty
934b75e68b Update libs/filamentjs/tests/test_parquet.js
Co-Authored-By: prideout <philiprideout@gmail.com>
2018-10-26 10:30:44 -07:00
Philip Rideout
58f36d1a7f New JS test: draw shaderball with parquet wood texture.
Shameless recreation of the Android `textured-android` sample. I will
make this into a tutorial soon.

Also made some improvements to the test-builder Python script. Really,
this script exists only to make iteration easier; we need a better
solution for automated tests...
2018-10-26 10:30:44 -07:00
Philip Rideout
83e4402e90 JS: fix use-before-free for PNG data. 2018-10-26 10:05:18 -07:00
Philip Rideout
c6a1900beb Add JS utility for PNG files. 2018-10-26 10:05:18 -07:00
Ben Doherty
17021a1167 Retry installing llvm on Kokoro Windows if failure (#400) 2018-10-25 13:31:43 -07:00
Philip Rideout
f0fbdaec28 JS users no longer need to call loadMathExtensions() 2018-10-25 08:16:32 -07:00
Philip Rideout
b73f58e6ef Expose MeshIO to JavaScript clients. 2018-10-25 08:12:53 -07:00
Mathias Agopian
254e3db215 More per-scene renderable UBO to View... for now
If a scene was used in several views, we would update the renderable
ubo several times per frame, which is not desirable. So we now have
such a UBO per-view. This could change in the future, depending
how we want to manage it.
2018-10-24 15:11:54 -07:00
Mathias Agopian
d9df864de4 Get rid of RangeSet. 2018-10-24 15:11:54 -07:00
Mathias Agopian
995b8361b8 Don't use RangeSet anymore.
It was used only in one place, always with a single range. For now,
we just always upload the whole froxel record buffer (64K).
2018-10-24 15:11:54 -07:00
Mathias Agopian
a61af02038 Pass View& instead of View* around 2018-10-24 15:11:54 -07:00
Mathias Agopian
84bfbac5fa The lights UBO must be per-View
We used to have a UBO for lights per scene, however it's better to 
have one per view, since it depends on the camera heavily and is 
limited in size.
Not doing so, could force us to upload the same UBO multiple times
per frame, for e.g. if the same scene was used in multiple views.
2018-10-24 15:11:54 -07:00
Mathias Agopian
912b301790 Try to bring some sanity to our UBO structures
- move UBO declarations in UibGenerator, i.e. next
  to their Uniform Interface Block definition.
  This should help forgetting to update one but
  not the other.

- move UniformInterfaceBlock.h and SamplerInferfaceBlock.h under
  private/filament/.

- do the same things for samplers
2018-10-24 15:11:54 -07:00
Mathias Agopian
b707027401 Avoid a light UBO data copy
We use the command stream to store the lights
ubo data (16K max), which avoid a copy and simplifies
the implementation. we can get rid of GpuLightBuffer.
2018-10-24 15:11:54 -07:00
Philip Rideout
68dfb5ae80 Introduce reference page for JS.
The docgen script now looks for /// comments in the binding definitions,
and generates markdown from those. The reference page has three
sections: classes, free functions, and enums.
2018-10-24 10:05:08 -07:00
Philip Rideout
ab3770d281 Fix JS docgen script for Kokoro. 2018-10-24 09:33:44 -07:00
Philip Rideout
28c56eb354 build.sh: the web archive now includes JS docs
Before this CL, the web archive had two folders: "public" (which
contained web demos written in C++) and "filamentjs" (for the barebones
WASM).

After this CL, the web archive will instead have "dist" and "docs". The
dist folder will have the WASM and accompanying JS file, while the docs
folder has the tutorials and their accompanying demos.

If your machine has Python 3 installed, then "build -ap webgl" will
attempt to generate the JavaScript docs. If Python 3 isn't available,
this build step will be skipped. Note that our Kokoro macOS machines
already have Python 3 pre-installed.

Also removed the pipenv file to simplify the Kokoro Python environment.

Fixes #394.
2018-10-24 08:55:14 -07:00
Ben Doherty
30eccc78b6 Add support for iOS simulator (#398)
* Add support for iOS simulator

* Use correct case for include
2018-10-23 10:30:01 -07:00
Philip Rideout
ab24665396 Allow JS clients to configure FXAA and WebGL context. 2018-10-23 07:58:16 -07:00
Philip Rideout
9e7b589d0a Fix FXAA pixel alignment.
Fixes #397.
2018-10-19 16:42:01 -07:00
Ben Doherty
979b6f00fd Default to Java 9 on Windows Kokoro (#413) 2018-10-19 15:17:16 -07:00
Ben Doherty
0754edbf9b Fix broken iOS build (#411) 2018-10-19 12:51:53 -07:00
Philip Rideout
9916af3ab1 Simplify docgen script per code review. 2018-10-19 12:40:38 -07:00
Philip Rideout
dcfbe694b1 Add fullscreen button to embedded JS demos. 2018-10-19 12:40:38 -07:00
Philip Rideout
835cc93b71 Doc generator now uses argparse. 2018-10-19 12:40:38 -07:00
Mathias Agopian
2f14ac64a7 fix iOS build on case-sensitive filesystems 2018-10-19 11:42:54 -07:00
Mathias Agopian
e96f982c9f Fix typo in RangeSet
Fixes #407
2018-10-19 11:42:39 -07:00
Philip Rideout
605a836565 Add JavaScript utility functions to reduce boilerplate. (#406)
* JS utilities: simplified render method.

* redball tutorial now rotates camera.

* JS utilities: add createTextureFromKtx.

* JS utilities: add createIblFromKtx.

* Repair testwasm.

* Update libs/filamentjs/docs/tutorial_redball.md

Co-Authored-By: prideout <philiprideout@gmail.com>

* Update libs/filamentjs/docs/tutorial_redball.md

Co-Authored-By: prideout <philiprideout@gmail.com>

* Update libs/filamentjs/docs/tutorial_redball.md

Co-Authored-By: prideout <philiprideout@gmail.com>
2018-10-18 18:19:05 -07:00
Mathias Agopian
1cde20d822 Avoid a normalize() in the vertex shader
This is achieved by pre-scaling the normals 
transform so that the resulting normal doesn't have
any large component allowing to do the normalize()
in the fragment shader in mediump.

This must be done for skinning too.
2018-10-18 17:37:06 -07:00
Mathias Agopian
a547f11a8c fix more comment typos 2018-10-18 16:49:47 -07:00
Philip Rideout
83de0fc3e8 The redball tutorial now describes matc and cmgen.
This commit also adds a help option to `build.py` and allows
customization of the output folder.
2018-10-18 16:46:15 -07:00
Ben Doherty
3ed2dd08fb Handle device orientation changes (#399) 2018-10-18 14:43:32 -07:00
Ben Doherty
db729b157a Remove development team for iOS sample (#401) 2018-10-18 13:53:55 -07:00
Ben Doherty
29119c7248 Add iOS support to Filament (#360) 2018-10-18 12:42:13 -07:00
Philip Rideout
356c3a2c24 Flesh out the JavaScript tutorials. 2018-10-18 12:29:22 -07:00
Philip Rideout
b0853b5eb6 jsbindings: fix buffer lifetime bug.
This is a fix-up to f5319f2.
2018-10-18 12:29:22 -07:00
Philip Rideout
d324dc724a Start another literate tutorial / demo for JavaScript.
Unlike the triangle tutorial, this is more focused on materials and 3D
rendering. While much of the verbiage is still TBD, the code snippets
already produce a functional demo after being glued together by the
tangler script.
2018-10-18 12:29:22 -07:00
Romain Guy
e6435a7431 Update README 2018-10-17 16:30:30 -07:00
Philip Rideout
d3e7f40398 Add IBL to jsbinding and testwasm. 2018-10-17 16:13:53 -07:00
Philip Rideout
f5319f2492 jsbindings: fix buffer lifetime bug.
In order to match its JavaScript counterpart, the Buffer wrapper needs
to use reference counting, and the easiest way to achieve that is
with shared_ptr.
2018-10-17 16:13:53 -07:00
Philip Rideout
e00ba80561 jsbindings: add JS utilities, enhance testwasm. 2018-10-17 10:17:04 -07:00
Philip Rideout
d15e275de0 Add glMatrix to third_party.
Some of our web tests and demos will make use of this library, and it's
useful to leverage a local copy instead of a CDN during development.
2018-10-17 09:57:08 -07:00
Romain Guy
920cc7a84a Normalize normals and tangents in the vertex shader (#388)
This avoids breaking bitangents when a scale value is set in the
transform matrix
2018-10-16 17:12:54 -07:00
Mathias Agopian
3b504f2941 add Stream::getTimestamp() to java api 2018-10-16 16:52:26 -07:00
Mathias Agopian
f697b41a2b fix a few typos in comments 2018-10-16 16:50:10 -07:00
Mathias Agopian
8452c4f8f2 Add usage hints to the driver 2018-10-16 16:23:24 -07:00
Mathias Agopian
c238027e49 implemented Stream::getTimestamp()
this returns a timestamp in nanosecond corresponding
to the desired presentation time of the latest frame
bound to a filament texture.
2018-10-16 15:56:43 -07:00
Mathias Agopian
b374340ebb skinning allows 256 bones again, but disallow skews. 2018-10-16 15:56:30 -07:00
Romain Guy
c581b755fd Add helper to upload Android bitmaps to textures (#382)
* WIP Add helper to upload Android bitmaps to textures

* Add missing file

* Pass custom constants for bitmap formats

* Add sample app for texturing

* Update the README for samples

* Rename variable from callback to autoBitmap
2018-10-16 14:24:18 -07:00
Philip Rideout
9e5f44bd34 Consolidate two filamesh readers into a lib. 2018-10-16 13:31:16 -07:00
Philip Rideout
d9204052c8 Fix potential issue with detached ArrayBuffer. 2018-10-15 18:35:53 -07:00
Philip Rideout
5a8d4d818c Remove bad exception handler from wasmloader.
It is incorrect to assume that any exception thrown during onReady
must be due to a faulty download.
2018-10-15 18:35:53 -07:00
Philip Rideout
cd84980c84 Add tests for filamentjs. 2018-10-15 18:35:53 -07:00
Philip Rideout
9b8d5fdf12 Add JS bindings for Texture, PixelBufferDescriptor, et al. 2018-10-15 18:35:53 -07:00
Romain Guy
7cb01929a3 Clean up Kotlin samples (#380)
* Clean up Kotlin samples

* Further code cleanup
2018-10-15 15:28:39 -07:00
Philip Rideout
e7777ef330 Add literate JavaScript tutorial and Python tangler.
This commit contains a markdown file for a "hello triangle" tutorial
as well as a Python script that does two things:

1) Extracts JavaScript code blocks from the markdown to generate the
   code for the demo.

2) Converts the markdown into a nicely-rendered web page.

After we invoke the Python script for the first time, it will create
a set of files in the root docs folder, which will automatically be
published via GitHub Pages to the following URL.

    https://google.github.io/filament/webgl

This gives us an official place to host the latest web demos and
tutorials.

The tutorial can be previewed
[here](https://prideout.net/prototype/webgl/tutorial_triangle.html).
More JavaScript tutorials are forthcoming.
2018-10-15 12:42:13 -07:00
Philip Rideout
0326d60d0a jsbindings: simplify BufferDescriptor wrapper.
The JS BufferDescriptor wrapper is used in two directions: JS => WASM
and WASM => JS. In both cases, it needs to be sure to delete the
underlying driver::BufferDescriptor. This is safe because the contents
of the underlying descriptor are always moved to its final destination
before the wrapper is destroyed.
2018-10-15 12:16:02 -07:00
Ben Doherty
0d709b6074 Add a few new nodes to Tungsten (#326) 2018-10-15 12:02:05 -07:00
Ben Doherty
6992c8a584 Update README on linking against Filament (#379)
* Add section to README on linking against Filament
2018-10-15 11:18:45 -07:00
Philip Rideout
7c54faa8bd Add filamentjs to web release archive.
The web archive now has two subfolders: public and filamentjs.

- public contains the three C++ based web demos.
- jsbindings contains the new JS bindings and Filament-only WASM module.
2018-10-15 10:43:28 -07:00
Romain Guy
3a0f9791cc Remove outdated comment 2018-10-12 18:37:34 -07:00
Philip Rideout
473824b15e Introduce JavaScript API using embind.
This adds filamentjs to libs, which builds a Filament-only WASM file.
Unlike our existing web demos, this WASM file contains no application
code.

These bindings are by no means complete, but they are sufficient for a
"hello triangle" demo that I have working locally. Sneak peak of the
Triangle JS app code:

    https://gist.github.com/prideout/e9d6dd0e312146c8a287d2d109affa4d

This commit merely adds the bindings to the build. Demos and docs are
forthcoming.
2018-10-12 17:09:52 -07:00
Mathias Agopian
b4c77166b7 fix normals when skinning with non-uniform scales 2018-10-11 18:46:42 -07:00
5094 changed files with 543788 additions and 100468 deletions

2
.gitignore vendored
View File

@@ -9,3 +9,5 @@ dist-*
toolchains
filament/docs/html/**
.vscode
gltf_baker.ini
*tmp*.png

View File

@@ -1,7 +1,7 @@
# ==================================================================================================
# CMake
# ==================================================================================================
cmake_minimum_required(VERSION 3.1)
cmake_minimum_required(VERSION 3.10)
# ==================================================================================================
# Project declaration
@@ -16,6 +16,10 @@ option(ENABLE_JAVA "Compile Java projects, requires a JDK and the JAVA_HOME env
option(USE_EXTERNAL_GLES3 "Experimental: Compile Filament against OpenGL ES 3" OFF)
option(GENERATE_JS_DOCS "Build WebGL documentation and tutorials" OFF)
option(ENABLE_LTO "Enable link-time optimizations if supported by the compiler" OFF)
# ==================================================================================================
# OS specific
# ==================================================================================================
@@ -23,26 +27,66 @@ if (UNIX AND NOT APPLE AND NOT ANDROID AND NOT WEBGL)
set(LINUX TRUE)
endif()
if (ANDROID OR WEBGL OR IOS)
set(IS_MOBILE_TARGET TRUE)
endif()
if (WIN32)
# Link statically against c/c++ lib to avoid missing redistriburable such as
# "VCRUNTIME140.dll not found. Try reinstalling the app.", but give users
# a choice to opt for the shared runtime if they want.
option(USE_STATIC_CRT "Link against the static runtime libraries." ON)
# On Windows we need to instruct cmake to generate the .def in order to get the .lib required
# when linking against dlls. CL.EXE will not generate .lib without .def file (or without pragma
# __declspec(dllexport) in front of each functions).
set(CMAKE_WINDOWS_EXPORT_ALL_SYMBOLS ON)
if (${USE_STATIC_CRT})
set(CRT_FLAGS_RELEASE "/MT")
set(CRT_FLAGS_DEBUG "/MTd")
else()
set(CRT_FLAGS_RELEASE "/MD")
set(CRT_FLAGS_DEBUG "/MDd")
endif()
# TODO: Figure out why pdb generation messes with incremental compilaton.
# IN RELEASE_WITH_DEBUG_INFO, generate debug info in .obj, no in pdb.
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /Z7")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} /Z7")
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} ${CRT_FLAGS_RELEASE} /Z7")
set(CMAKE_C_FLAGS_RELWITHDEBINFO "${CMAKE_C_FLAGS_RELWITHDEBINFO} ${CRT_FLAGS_RELEASE} /Z7")
# In RELEASE, link statically against c/c++ lib to avoid missing redistriburable such as
# "VCRUNTIME140.dll not found. Try reinstalling the app.". Also generate PDBs.
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT /Zi")
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} /MT /Zi")
# In RELEASE, also generate PDBs.
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${CRT_FLAGS_RELEASE} /Zi")
set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${CRT_FLAGS_RELEASE} /Zi")
# In DEBUG, avoid generating a PDB file which seems to mess with incremental compilation.
# Instead generate debug info directly inside obj files.
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /Z7")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} /Z7")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${CRT_FLAGS_DEBUG} /Z7")
set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${CRT_FLAGS_DEBUG} /Z7")
endif()
# ==================================================================================================
# Check if embree is available.
# This is an optional dependency and can be installed with homebrew, apt-get, etc.
# ==================================================================================================
find_package(embree 3.0 QUIET PATHS /usr/lib64/cmake)
if (embree_FOUND AND NOT ANDROID)
message("Found embree in ${embree_DIR}")
set(MKLDNN_THREADING "TBB")
include(third_party/OpenImageDenoise/cmake/resource.cmake)
include(third_party/OpenImageDenoise/mkl-dnn/cmake/Threading.cmake)
include(third_party/OpenImageDenoise/mkl-dnn/cmake/TBB.cmake)
find_package(TBB QUIET)
if (TBB_FOUND AND "${TBB_VERSION_MAJOR}" VERSION_EQUAL 2019)
message("Found TBB ${TBB_VERSION}")
add_definitions(-DFILAMENT_HAS_EMBREE)
set(DENOISE_LIBRARY OpenImageDenoise)
else()
message("TBB 2019 not found.")
endif()
else()
message("Embree not found, pipeline features are disabled.")
endif()
# ==================================================================================================
@@ -63,7 +107,7 @@ set(TOOLS ${CMAKE_CURRENT_SOURCE_DIR}/tools)
# ==================================================================================================
# Compiler check
# ==================================================================================================
set(MIN_CLANG_VERSION "5.0")
set(MIN_CLANG_VERSION "6.0")
if (CMAKE_C_COMPILER_ID MATCHES "Clang")
if (CMAKE_C_COMPILER_VERSION VERSION_LESS MIN_CLANG_VERSION)
@@ -86,6 +130,20 @@ if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang" AND "${CMAKE_CXX_SIMULATE_ID}" S
set(CLANG_CL true)
endif()
# ==================================================================================================
# Link time optimizations (LTO)
# ==================================================================================================
if (ENABLE_LTO)
include(CheckIPOSupported)
check_ipo_supported(RESULT IPO_SUPPORT)
if (IPO_SUPPORT)
message(STATUS "LTO support is enabled")
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()
endif()
# ==================================================================================================
# General compiler flags
# ==================================================================================================
@@ -106,18 +164,9 @@ endif()
if (LINUX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++")
if (FILAMENT_REQUIRES_CXXABI)
# Required in CI environment with custom libc++ and libc++abi
link_libraries("-lc++abi")
endif()
# To distribute our binaries, we must remove the dependency on libc++ and libgcc.
if (CMAKE_BUILD_TYPE STREQUAL "Release")
link_libraries("-static-libgcc -static-libstdc++")
endif()
else()
if (FILAMENT_REQUIRES_CXXABI)
message("The option FILAMENT_REQUIRES_CXXABI is unsupported on this platform")
endif()
link_libraries("-static-libgcc -static-libstdc++")
link_libraries(libc++.a)
link_libraries(libc++abi.a)
endif()
if (CYGWIN)
@@ -147,7 +196,7 @@ endif()
# On Android RELEASE builds, we disable exceptions and RTTI to save some space (about 75 KiB
# saved by -fno-exception and 10 KiB saved by -fno-rtti).
if (ANDROID OR WEBGL)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-exceptions -fno-rtti")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-exceptions -fno-unwind-tables -fno-asynchronous-unwind-tables -fno-rtti")
endif()
# ==================================================================================================
@@ -157,6 +206,10 @@ endif()
# -fsanitize=undefined causes extremely long link times
# -fsanitize=address causes a crash with assimp, which we can't explain for now
#set(EXTRA_SANITIZE_OPTIONS "-fsanitize=undefined -fsanitize=address")
# clang-cl.exe on Windows does not support -fstack-protector.
if (NOT CLANG_CL)
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fstack-protector")
endif()
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${EXTRA_SANITIZE_OPTIONS}")
# ==================================================================================================
@@ -200,8 +253,7 @@ endif()
# By default, build with Vulkan support on desktop platforms, although clients must request to use
# it at run time. On Android, the build does not include Vulkan support unless CMake is invoked
# with -DFILAMENT_SUPPORTS_VULKAN=ON.
# Vulkan is not supported on Windows.
if (ANDROID OR WIN32 OR WEBGL)
if (ANDROID OR WIN32 OR WEBGL OR IOS)
option(FILAMENT_SUPPORTS_VULKAN "Include the Vulkan backend" OFF)
else()
option(FILAMENT_SUPPORTS_VULKAN "Include the Vulkan backend" ON)
@@ -210,6 +262,54 @@ if (FILAMENT_SUPPORTS_VULKAN)
add_definitions(-DFILAMENT_DRIVER_SUPPORTS_VULKAN)
endif()
# Build with Metal support on non-WebGL Apple platforms.
# Apple's simulator does not support Metal.
if (APPLE AND (NOT IOS OR IOS_ARCH STREQUAL "arm64") AND NOT WEBGL)
option(FILAMENT_SUPPORTS_METAL "Include the Metal backend" ON)
else()
option(FILAMENT_SUPPORTS_METAL "Include the Metal backend" OFF)
endif()
if (FILAMENT_SUPPORTS_METAL)
add_definitions(-DFILAMENT_SUPPORTS_METAL)
endif()
# Building filamat increases build times and isn't required for web, so turn it off by default.
if (NOT WEBGL)
option(FILAMENT_BUILD_FILAMAT "Build filamat and JNI buildings" ON)
else()
option(FILAMENT_BUILD_FILAMAT "Build filamat and JNI buildings" OFF)
endif()
# ==================================================================================================
# Material compilation flags
# ==================================================================================================
# Target system.
if (IS_MOBILE_TARGET)
set(MATC_TARGET mobile)
else()
set(MATC_TARGET desktop)
endif()
set(MATC_API_FLAGS )
# TODO: Add a flag to build Filament without support for OpenGL.
set(MATC_API_FLAGS ${MATC_API_FLAGS} -a opengl)
if (FILAMENT_SUPPORTS_VULKAN)
set(MATC_API_FLAGS ${MATC_API_FLAGS} -a vulkan)
endif()
if (FILAMENT_SUPPORTS_METAL)
set(MATC_API_FLAGS ${MATC_API_FLAGS} -a metal)
endif()
# Only optimize materials in Release mode (so error message lines match the source code)
if (NOT CMAKE_BUILD_TYPE MATCHES Release)
set(MATC_OPT_FLAGS -g)
endif()
set(MATC_BASE_FLAGS ${MATC_API_FLAGS} -p ${MATC_TARGET} ${MATC_OPT_FLAGS})
# ==================================================================================================
# Distribution
# ==================================================================================================
@@ -262,20 +362,76 @@ if (FILAMENT_SUPPORTS_VULKAN AND APPLE)
endif()
endif()
# ==================================================================================================
# Common Functions
# ==================================================================================================
# Sets the following variables: RESGEN_HEADER, RESGEN_SOURCE, RESGEN_FLAGS, RESGEN_SOURCE_FLAGS,
# and RESGEN_OUTPUTS. Please pass in an ARCHIVE_NAME that is unique to your project, otherwise the
# incbin directive will happily consume a blob from the wrong project without warnings or errors.
# Also be sure to include the ASM language in the CMake "project" directive for your project.
function(get_resgen_vars ARCHIVE_DIR ARCHIVE_NAME)
set(OUTPUTS
${ARCHIVE_DIR}/${ARCHIVE_NAME}.bin
${ARCHIVE_DIR}/${ARCHIVE_NAME}.S
${ARCHIVE_DIR}/${ARCHIVE_NAME}.apple.S
${ARCHIVE_DIR}/${ARCHIVE_NAME}.h
)
if (IOS)
set(ASM_ARCH_FLAG "-arch ${DIST_ARCH}")
endif()
if (APPLE)
set(ASM_SUFFIX ".apple")
endif()
set(RESGEN_HEADER "${ARCHIVE_DIR}/${ARCHIVE_NAME}.h" PARENT_SCOPE)
# Visual Studio makes it difficult to use assembly without using MASM. MASM doesn't support
# the equivalent of .incbin, so on Windows we'll just tell resgen to output a C file.
if (WEBGL OR WIN32 OR ANDROID_ON_WINDOWS)
set(RESGEN_OUTPUTS "${OUTPUTS};${ARCHIVE_DIR}/${ARCHIVE_NAME}.c" PARENT_SCOPE)
set(RESGEN_FLAGS -cx ${ARCHIVE_DIR} -p ${ARCHIVE_NAME} PARENT_SCOPE)
set(RESGEN_SOURCE "${ARCHIVE_DIR}/${ARCHIVE_NAME}.c" PARENT_SCOPE)
else()
set(RESGEN_OUTPUTS "${OUTPUTS}" PARENT_SCOPE)
set(RESGEN_FLAGS -x ${ARCHIVE_DIR} -p ${ARCHIVE_NAME} PARENT_SCOPE)
set(RESGEN_SOURCE "${ARCHIVE_DIR}/${ARCHIVE_NAME}${ASM_SUFFIX}.S" PARENT_SCOPE)
set(RESGEN_SOURCE_FLAGS "-I${ARCHIVE_DIR} ${ASM_ARCH_FLAG}" PARENT_SCOPE)
endif()
endfunction()
# ==================================================================================================
# Sub-projects
# ==================================================================================================
# Common to all platforms
add_subdirectory(${EXTERNAL}/libgtest/tnt)
add_subdirectory(${LIBRARIES}/filabridge)
add_subdirectory(${LIBRARIES}/filaflat)
add_subdirectory(${LIBRARIES}/filamat)
add_subdirectory(${LIBRARIES}/filameshio)
add_subdirectory(${LIBRARIES}/geometry)
add_subdirectory(${LIBRARIES}/gltfio)
add_subdirectory(${LIBRARIES}/ibl)
add_subdirectory(${LIBRARIES}/image)
add_subdirectory(${LIBRARIES}/rays)
add_subdirectory(${LIBRARIES}/math)
add_subdirectory(${LIBRARIES}/utils)
add_subdirectory(${FILAMENT}/filament)
add_subdirectory(${FILAMENT}/shaders)
add_subdirectory(${EXTERNAL}/robin-map/tnt)
add_subdirectory(${EXTERNAL}/smol-v/tnt)
add_subdirectory(${EXTERNAL}/benchmark/tnt)
add_subdirectory(${EXTERNAL}/meshoptimizer)
add_subdirectory(${EXTERNAL}/cgltf/tnt)
add_subdirectory(${EXTERNAL}/xatlas/tnt)
add_subdirectory(${EXTERNAL}/stb/tnt)
if (FILAMENT_BUILD_FILAMAT)
# spirv-tools must come before filamat, as filamat relies on the presence of the
# spirv-tools_SOURCE_DIR variable.
add_subdirectory(${EXTERNAL}/spirv-tools)
add_subdirectory(${EXTERNAL}/glslang/tnt)
add_subdirectory(${EXTERNAL}/spirv-cross/tnt)
add_subdirectory(${LIBRARIES}/filamat)
endif()
if (FILAMENT_SUPPORTS_VULKAN)
add_subdirectory(${LIBRARIES}/bluevk)
@@ -289,52 +445,53 @@ endif()
set (FILAMENT_SAMPLES_BINARY_DIR ${PROJECT_BINARY_DIR}/samples)
if (WEBGL)
add_subdirectory(${FILAMENT}/samples/web)
add_subdirectory(web/filament-js)
add_subdirectory(web/samples)
add_subdirectory(${LIBRARIES}/filagui)
if (GENERATE_JS_DOCS)
add_subdirectory(web/docs)
endif()
add_subdirectory(${EXTERNAL}/imgui/tnt)
add_subdirectory(${EXTERNAL}/stb/tnt)
endif()
if (NOT ANDROID AND NOT WEBGL)
add_subdirectory(${FILAMENT}/samples)
if (NOT ANDROID AND NOT WEBGL AND NOT IOS)
add_subdirectory(${LIBRARIES}/bluegl)
add_subdirectory(${LIBRARIES}/filagui)
add_subdirectory(${LIBRARIES}/imageio)
add_subdirectory(${FILAMENT}/java)
# must come first because of glslang
add_subdirectory(${EXTERNAL}/spirv-tools)
add_subdirectory(${FILAMENT}/java/filamat)
add_subdirectory(${FILAMENT}/java/filament)
add_subdirectory(${FILAMENT}/samples)
add_subdirectory(${EXTERNAL}/astcenc/tnt)
add_subdirectory(${EXTERNAL}/etc2comp)
add_subdirectory(${EXTERNAL}/getopt)
add_subdirectory(${EXTERNAL}/glslang/tnt)
add_subdirectory(${EXTERNAL}/imgui/tnt)
add_subdirectory(${EXTERNAL}/libassimp/tnt)
add_subdirectory(${EXTERNAL}/libpng/tnt)
add_subdirectory(${EXTERNAL}/libsdl2/tnt)
add_subdirectory(${EXTERNAL}/libz/tnt)
add_subdirectory(${EXTERNAL}/skylight/tnt)
add_subdirectory(${EXTERNAL}/spirv-cross/tnt)
add_subdirectory(${EXTERNAL}/stb/tnt)
add_subdirectory(${EXTERNAL}/tinyexr/tnt)
add_subdirectory(${TOOLS}/cmgen)
add_subdirectory(${TOOLS}/filamesh)
add_subdirectory(${TOOLS}/glslminifier)
add_subdirectory(${TOOLS}/matc)
add_subdirectory(${TOOLS}/matinfo)
add_subdirectory(${TOOLS}/mipgen)
add_subdirectory(${TOOLS}/normal-blending)
add_subdirectory(${TOOLS}/resgen)
add_subdirectory(${TOOLS}/roughness-prefilter)
add_subdirectory(${TOOLS}/skygen)
add_subdirectory(${TOOLS}/specular-color)
endif()
# Generate exported executables for cross-compiled builds (Android and WebGL)
if (NOT CMAKE_CROSSCOMPILING)
export(TARGETS matc cmgen filamesh mipgen FILE ${IMPORT_EXECUTABLES})
if (DENOISE_LIBRARY)
add_subdirectory(${EXTERNAL}/OpenImageDenoise/tnt)
endif()
# Generate exported executables for cross-compiled builds (Android, WebGL, and iOS)
if (NOT CMAKE_CROSSCOMPILING)
export(TARGETS matc cmgen filamesh mipgen resgen glslminifier FILE ${IMPORT_EXECUTABLES})
endif()

View File

@@ -5,7 +5,7 @@ Google code style and is derived from the Java code style, but not quite.
The guiding principles of the filament code style and code formatting can be resumed as:
- no nonsense
- use your own judgement
- use your own judgement
- break the rules **if it makes sense** e.g.: it improves readability substantially
- use the formatting of the file you're in, even if it breaks the rules
- no nonsense
@@ -41,14 +41,15 @@ private:
- included files use the `.inc` extension
- class files bear the name of the class they implement
- **no spaces** in file names
- file names must be treated as case **insensitive**, i.e. it is not allowed to have several files with the same name but a different case
- file names must be treated as case **insensitive**, i.e. it is not allowed to have several files
with the same name but a different case
- `#include` must use **fully qualified** names
- use `#include < >` for all public (exported) headers
- use `#include " "` for private headers
- all *public* include files must reside under the `include` folder
- all *source* files must reside under the `src` folder
- tests reside under the `test` folder
- public headers of a `foo` library must live in a folder named `foo`
- public headers of a `foo` library must live in a folder named `foo`
```
libfoo.so
@@ -78,11 +79,11 @@ extern int gGlobalWarming;
class FooBar {
public:
void methodName();
int sizeInBytes;
int sizeInBytes;
private:
int mAttributeName;
static int sGlobalAttribute;
staric constexpr int FOO_COUNT = 10;
static constexpr int FOO_COUNT = 10;
enum {
ONE, TWO, THREE
};
@@ -93,7 +94,7 @@ private:
### Files
- always include the copyright notice at the top of every file
- always include the copyright notice at the top of every file
- make sure the date is correct
```
@@ -161,9 +162,16 @@ private:
#include <string.h>
```
### Strings
- Never use `std::string` in the Filament core renderer. Prefer `utils::CString` or
`utils::StaticString`.
- When using `std::string` in tools, always include the `std::` qualifier to disambiguate it
from other string types.
### Misc
- Use `auto` only when the type appears on the same line or with iterators
- Use `auto` only when the type appears on the same line or with iterators and lambdas.
```
auto foo = new Foo();
for (auto& i : collection) { }

View File

@@ -20,7 +20,7 @@ again.
Contributor License Agreement (see details above).
1. Fork the desired repo, develop and test your code changes.
1. Ensure that your code adheres to the existing style in the sample to which
you are contributing. Refer to [CodeStyle.md](/CodeStyle.md) for the recommended coding
you are contributing. Refer to [CodeStyle.md](/CODE_STYLE.md) for the recommended coding
standards for this project.
1. Ensure that your code has an appropriate set of unit tests which all pass.
1. Submit a pull request.

361
README.md
View File

@@ -1,13 +1,14 @@
# Filament
<img alt="Android" src="build/img/android.png" width="20px" height="20px" hspace="2px"/>[![Android Build Status](https://filament-build.storage.googleapis.com/badges/build_status_android.svg)](https://filament-build.storage.googleapis.com/badges/build_link_android.html)
<img alt="iOS" src="build/img/macos.png" width="20px" height="20px" hspace="2px"/>[![iOS Build Status](https://filament-build.storage.googleapis.com/badges/build_status_ios.svg)](https://filament-build.storage.googleapis.com/badges/build_link_ios.html)
<img alt="Linux" src="build/img/linux.png" width="20px" height="20px" hspace="2px"/>[![Linux Build Status](https://filament-build.storage.googleapis.com/badges/build_status_linux.svg)](https://filament-build.storage.googleapis.com/badges/build_link_linux.html)
<img alt="macOS" src="build/img/macos.png" width="20px" height="20px" hspace="2px"/>[![MacOS Build Status](https://filament-build.storage.googleapis.com/badges/build_status_mac.svg)](https://filament-build.storage.googleapis.com/badges/build_link_mac.html)
<img alt="Windows" src="build/img/windows.png" width="20px" height="20px" hspace="2px"/>[![Windows Build Status](https://filament-build.storage.googleapis.com/badges/build_status_windows.svg)](https://filament-build.storage.googleapis.com/badges/build_link_windows.html)
<img alt="Web" src="build/img/web.png" width="20px" height="20px" hspace="2px"/>[![Web Build Status](https://filament-build.storage.googleapis.com/badges/build_status_web.svg)](https://filament-build.storage.googleapis.com/badges/build_link_web.html)
Filament is a real-time physically based rendering engine for Android, Linux, macOS, Windows, and
WebGL. It is designed to be as small as possible and as efficient as possible on Android.
Filament is a real-time physically based rendering engine for Android, iOS, Linux, macOS, Windows,
and WebGL. It is designed to be as small as possible and as efficient as possible on Android.
Filament is currently used in the
[Sceneform](https://developers.google.com/ar/develop/java/sceneform/) library both at runtime on
@@ -17,16 +18,19 @@ Android devices and as the renderer inside the Android Studio plugin.
[Download Filament releases](https://github.com/google/filament/releases) to access stable builds.
Make sure you always use tools from the same release as the runtime library. This is particularly
important for `matc` (material compiler).
If you prefer to live on the edge, you can download a continuous build by clicking one of the build
badges above.
## Documentation
- [Filament](https://google.github.io/filament/Filament.md.html), an in-depth explanation of
- [Filament](https://google.github.io/filament/Filament.html), an in-depth explanation of
real-time physically based rendering, the graphics capabilities and implementation of Filament.
This document explains the math and reasoning behind most of our decisions. This document is a
good introduction to PBR for graphics programmers.
- [Materials](https://google.github.io/filament//Materials.md.html), the full reference
- [Materials](https://google.github.io/filament/Materials.html), the full reference
documentation for our material system. This document explains our different material models, how
to use the material compiler `matc` and how to write custom materials.
- [Material Properties](https://google.github.io/filament/Material%20Properties.pdf), a reference
@@ -36,30 +40,41 @@ badges above.
Here are a few sample materials rendered with Filament:
![Brushed copper](docs/images/samples/brushed_copper_2.png)
![Chess set](docs/images/samples/chess1.png)
![Environment lighting](docs/images/samples/spheres.png)
![Material 1](docs/images/samples/material_01.png)
![Material 2](docs/images/samples/material_02.png)
![Material 3](docs/images/samples/material_03.png)
![Material 4](docs/images/samples/material_04.png)
![Material 6](docs/images/samples/material_06.png)
![Material 7](docs/images/samples/material_07.png)
![Material 8](docs/images/samples/material_08.png)
![Damaged Helmet](docs/images/samples/model_damaged_helmet.jpg)
![Helmet](docs/images/samples/model_helmet.jpg)
![Brushed copper](docs/images/samples/brushed_copper_2.jpg)
![Material 1](docs/images/samples/material_01.jpg)
![Material 2](docs/images/samples/material_02.jpg)
![Material 6](docs/images/samples/material_06.jpg)
![Material 8](docs/images/samples/material_08.jpg)
## Applications
Here are a few screenshots of applications that use Filament in production:
### Google Maps AR Navigation
![Google Maps AR Navigation](docs/images/samples/app_gmm_ar_nav.jpg)
### Google Search 3D/AR Viewer on Android
![Google Search 3D/AR Viewer on Android](docs/images/samples/app_google_3d_viewer.jpg)
## Features
### APIs
- Native C++ API for Android, Linux, macOS and Windows
- Native C++ API for Android, iOS, Linux, macOS and Windows
- Java/JNI API for Android, Linux, macOS and Windows
- [Python bindings](https://github.com/artometa/pyfilament)
- JavaScript API
### Backends
- OpenGL 4.1+ for Linux, macOS and Windows
- OpenGL ES 3.0+ for Android
- Vulkan 1.0 for Android, Linux, macOS (with MoltenVk) and Windows
- OpenGL ES 3.0+ for Android and iOS
- Metal for macOS and iOS
- Vulkan 1.0 for Android, Linux, macOS and iOS (with MoltenVk), and Windows
- WebGL 2.0 for all platforms
### Rendering
@@ -70,23 +85,24 @@ Here are a few sample materials rendered with Filament:
- Metallic workflow
- Clear coat
- Anisotropic lighting
- Approximated translucent (subsurface) materials (direct and indirect lighting)
- Approximated translucent (subsurface) materials
- Cloth shading
- Normal mapping & ambient occlusion mapping
- Image-based lighting
- Physically-based camera (shutter speed, sensitivity and aperture)
- Physical light units
- Point light, spot light and directional light
- SSAO
- ACES-like tone-mapping
- Temporal dithering
- FXAA or MSAA
- Dynamic resolution (on Android)
- FXAA, MSAA and specular anti-aliasing
- Dynamic resolution (on Android and iOS)
### Future
Many other features have been either prototyped or planned:
- IES light profiles
- IES light profiles/cookies
- Area lights
- Fog
- Color grading
@@ -96,45 +112,58 @@ Many other features have been either prototyped or planned:
## Directory structure
- `filament`: Filament engine and its supporting libraries and tools
- `android`: Android libraries and projects
- `build`: Custom Gradle tasks for Android builds
- `filament-android`: Filament library (AAR) for Android
- `samples`: Android-specific Filament samples
- `art`: Source for various artworks (logos, PDF manuals, etc.)
- `assets`: 3D assets to use with sample applications
- `build`: CMake build scripts
- `docs`: Documentation
- `math`: Mathematica notebooks used to explore BRDFs, equations, etc.
- `filament`: Filament engine
- `ide`: Configuration files for IDEs (CLion, etc.)
- `java`: Java bindings for Filament libraries
- `libs`: Libraries
- `bluegl`: OpenGL bindings for macOS, Linux and Windows
- `bluevk`: Vulkan bindings for macOS, Linux, Windows and Android
- `filabridge`: Library shared by the Filament engine and host tools
- `filaflat`: Serialization/deserialization library used for materials
- `filagui`: Helper library for [Dear ImGui](https://github.com/ocornut/imgui)
- `filamat`: Material generation library
- `image`: Image filtering and simple transforms
- `imageio`: Image file reading / writing, only intended for internal use
- `math`: Math library
- `utils`: Utility library (threads, memory, data structures, etc.)
- `samples`: Sample desktop applications
- `shaders`: Shaders used by `filamat` and `matc`
- `third_party`: External libraries and assets
- `environments`: Environment maps under CC0 license that can be used with `cmgen`
- `textures`: Textures under CC0 license
- `tools`: Host tools
- `cmgen`: Image-based lighting asset generator
- `filamesh`: Mesh converter
- `matc`: Material compiler
- `matinfo` Displays information about materials compiled with `matc`
- `mipgen` Generates a series of miplevels from a source image.
- `normal-blending`: Tool to blend normal maps
- `roughness-prefilter`: Pre-filters a roughness map from a normal map to reduce aliasing
- `skygen`: Physically-based sky environment texture generator
- `specular-color`: Computes the specular color of conductors based on spectral data
This repository not only contains the core Filament engine, but also its supporting libraries
and tools.
- `android`: Android libraries and projects
- `build`: Custom Gradle tasks for Android builds
- `filamat-android`: Filament material generation library (AAR) for Android
- `filament-android`: Filament library (AAR) for Android
- `samples`: Android-specific Filament samples
- `art`: Source for various artworks (logos, PDF manuals, etc.)
- `assets`: 3D assets to use with sample applications
- `build`: CMake build scripts
- `docs`: Documentation
- `math`: Mathematica notebooks used to explore BRDFs, equations, etc.
- `filament`: Filament rendering engine (minimal dependencies)
- `ide`: Configuration files for IDEs (CLion, etc.)
- `ios`: Sample projects for iOS
- `java`: Java bindings for Filament libraries
- `libs`: Libraries
- `bluegl`: OpenGL bindings for macOS, Linux and Windows
- `bluevk`: Vulkan bindings for macOS, Linux, Windows and Android
- `filabridge`: Library shared by the Filament engine and host tools
- `filaflat`: Serialization/deserialization library used for materials
- `filagui`: Helper library for [Dear ImGui](https://github.com/ocornut/imgui)
- `filamat`: Material generation library
- `filameshio`: Tiny filamesh parsing library (see also `tools/filamesh`)
- `geometry`: Mesh-related utilities
- `gltfio`: Loader and optional pipeline for glTF 2.0
- `ibl`: IBL generation tools
- `image`: Image filtering and simple transforms
- `imageio`: Image file reading / writing, only intended for internal use
- `math`: Math library
- `rays`: Simple path tracer used for baking ambient occlusion, etc.
- `utils`: Utility library (threads, memory, data structures, etc.)
- `samples`: Sample desktop applications
- `shaders`: Shaders used by `filamat` and `matc`
- `third_party`: External libraries and assets
- `environments`: Environment maps under CC0 license that can be used with `cmgen`
- `models`: Models under permissive licenses
- `textures`: Textures under CC0 license
- `tools`: Host tools
- `cmgen`: Image-based lighting asset generator
- `filamesh`: Mesh converter
- `glslminifier`: Minifies GLSL source code
- `matc`: Material compiler
- `matinfo` Displays information about materials compiled with `matc`
- `mipgen` Generates a series of miplevels from a source image
- `normal-blending`: Tool to blend normal maps
- `resgen` Aggregates binary blobs into embeddable resources
- `roughness-prefilter`: Pre-filters a roughness map from a normal map to reduce aliasing
- `skygen`: Physically-based sky environment texture generator
- `specular-color`: Computes the specular color of conductors based on spectral data
- `web`: JavaScript bindings, documentation, and samples
## Building Filament
@@ -142,8 +171,8 @@ Many other features have been either prototyped or planned:
To build Filament, you must first install the following tools:
- CMake 3.4 (or more recent)
- clang 5.0 (or more recent)
- CMake 3.10 (or more recent)
- clang 7.0 (or more recent)
- [ninja 1.8](https://github.com/ninja-build/ninja/wiki/Pre-built-Ninja-packages) (or more recent)
To build the Java based components of the project you can optionally install (recommended):
@@ -153,11 +182,16 @@ To build the Java based components of the project you can optionally install (re
Additional dependencies may be required for your operating system. Please refer to the appropriate
section below.
Building the `rays` library (used for light baking) is optional and requires the following packages:
- embree 3.0+
- libtbb-dev
To build Filament for Android you must also install the following:
- Android Studio 3.1
- Android Studio 3.3
- Android SDK
- Android NDK
- Android NDK 19 or higher
### Environment variables
@@ -170,7 +204,7 @@ When building for WebGL, you'll also need to set `EMSDK`. See [WebAssembly](#web
### IDE
We recommend using CLion to develop for Filament. Simply open the root directory's CMakeList.txt
We recommend using CLion to develop for Filament. Simply open the root directory's CMakeLists.txt
in CLion to obtain a usable project.
### Easy build
@@ -218,9 +252,10 @@ If you use CMake directly instead of the build script, pass `-DENABLE_JAVA=OFF`
Make sure you've installed the following dependencies:
- `clang-7` or higher
- `libglu1-mesa-dev`
- `libc++-dev` (`libcxx-devel` on Fedora)
- `libc++abi-dev`
- `libc++-7-dev` (`libcxx-devel` and `libcxx-static` on Fedora) or higher
- `libc++abi-7-dev` (`libcxxabi-static` on Fedora) or higher
- `ninja-build`
- `libxi-dev`
@@ -236,21 +271,14 @@ $ cd out/cmake-release
$ cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../release/filament ../..
```
If you experience link errors you must ensure that you are using `libc++abi` by passing this
extra parameter to `cmake`:
```
-DFILAMENT_REQUIRES_CXXABI=true
```
Your Linux distribution might default to `gcc` instead of `clang`, if that's the case invoke
`cmake` with the following command:
```
$ mkdir out/cmake-release
$ cd out/cmake-release
# Or use a specific version of clang, for instance /usr/bin/clang-5.0
$ CC=/usr/bin/clang CXX=/usr/bin/clang++ \
# Or use a specific version of clang, for instance /usr/bin/clang-7
$ CC=/usr/bin/clang CXX=/usr/bin/clang++ CXXFLAGS=-stdlib=libc++ \
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../release/filament ../..
```
@@ -259,10 +287,10 @@ solution is to use `update-alternatives` to both change the default compiler, an
specific version of clang:
```
$ update-alternatives --install /usr/bin/clang clang /usr/bin/clang-7 100
$ update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-7 100
$ update-alternatives --install /usr/bin/cc cc /usr/bin/clang 100
$ update-alternatives --install /usr/bin/c++ c++ /usr/bin/clang++ 100
$ update-alternatives --install /usr/bin/clang clang /usr/bin/clang-5.0 100
$ update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-5.0 100
```
Finally, invoke `ninja`:
@@ -299,6 +327,17 @@ $ cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=../release/fi
$ ninja
```
### iOS
The easiest way to build Filament for iOS is to use `build.sh` and the
`-p ios` flag. For instance to build the debug target:
```
$ ./build.sh -p ios debug
```
See [ios/samples/README.md](./ios/samples/README.md) for more information.
### Windows
The following instructions have been tested on a machine running Windows 10. They should take you
@@ -309,14 +348,20 @@ Google employees require additional steps which can be found here [go/filawin](h
Install the following components:
- [Windows 10 SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk)
- [Visual Studio 2015](https://www.visualstudio.com/downloads)
- [Clang 6](http://releases.llvm.org/download.html)
- [Visual Studio 2015 or 2017](https://www.visualstudio.com/downloads)
- [Clang 7](http://releases.llvm.org/download.html)
- [Python 3.7](https://www.python.org/ftp/python/3.7.0/python-3.7.0.exe)
- [Git 2.16.1 or later](https://github.com/git-for-windows/git/releases/download/v2.16.1.windows.4/PortableGit-2.16.1.4-64-bit.7z.exe)
- [Cmake 3.11 or later](https://cmake.org/files/v3.11/cmake-3.11.0-rc1-win64-x64.msi)
- [Cmake 3.13 or later](https://github.com/Kitware/CMake/releases/download/v3.13.4/cmake-3.13.4-win64-x64.msi)
Open an VS2015 x64 Native Tools terminal (click the start button, type "x64 native tools" and
select: "VS2015 x64 Native Tools Command Prompt").
If you're using Visual Studio 2017, you'll also need to install the [LLVM Compiler
Toolchain](https://marketplace.visualstudio.com/items?itemName=LLVMExtensions.llvm-toolchain)
extension.
Open an appropriate Native Tools terminal for the version of Visual Studio you are using:
- VS 2015: VS2015 x64 Native Tools Command Prompt
- VS 2017: x64 Native Tools Command Prompt for VS 2017
You can find these by clicking the start button and typing "x64 native tools".
Create a working directory:
```
@@ -326,11 +371,20 @@ Create a working directory:
Create the msBuild project:
```
# Visual Studio 2015:
> cmake -T"LLVM-vs2014" -G "Visual Studio 14 2015 Win64" ../..
# Visual Studio 2017
> cmake ..\.. -T"LLVM" -G "Visual Studio 15 2017 Win64" ^
-DCMAKE_CXX_COMPILER:PATH="C:\Program Files\LLVM\bin\clang-cl.exe" ^
-DCMAKE_C_COMPILER:PATH="C:\Program Files\LLVM\bin\clang-cl.exe" ^
-DCMAKE_LINKER:PATH="C:\Program Files\LLVM\bin\lld-link.exe"
```
Check out the output and make sure Clang for Windows frontend was found. You should see a line
showing the following ouput.
showing the following output. Note that for Visual Studio 2017 this line may list Microsoft's
compiler, but the build will still in fact use Clang and you can proceed.
```
Clang:C:/Program Files/LLVM/msbuild-bin/cl.exe
```
@@ -342,7 +396,7 @@ You are now ready to build:
Run it:
```
> samples\Release\lightbulb.exe ..\..\assets\models\monkey\monkey.obj
> samples\Release\material_sandbox.exe ..\..\assets\models\monkey\monkey.obj
```
#### Tips
@@ -361,11 +415,11 @@ Alternatively, you can use [Ninja](https://ninja-build.org/) to build for Window
installation is still necessary.
First, install the dependencies listed under [Windows](#Windows) as well as Ninja. Then open up a
VS2015 x64 Native Tools terminal as before. Create a build directory inside Filament and run the
Native Tools terminal as before. Create a build directory inside Filament and run the
following CMake command:
```
cmake .. -G Ninja ^
> cmake .. -G Ninja ^
-DCMAKE_CXX_COMPILER:PATH="C:\Program Files\LLVM\bin\clang-cl.exe" ^
-DCMAKE_C_COMPILER:PATH="C:\Program Files\LLVM\bin\clang-cl.exe" ^
-DCMAKE_LINKER:PATH="C:\Program Files\LLVM\bin\lld-link.exe" ^
@@ -375,7 +429,7 @@ cmake .. -G Ninja ^
You should then be able to build by invoking Ninja:
```
ninja
> ninja
```
#### Development tips
@@ -390,7 +444,7 @@ ninja
To confirm Filament was properly built, run the following command from the build directory:
```
./samples/material_sandbox --ibl=../../samples/envs/office ../../assets/models/sphere/sphere.obj
> samples\material_sandbox.exe --ibl=..\..\samples\envs\pillars ..\..\assets\models\sphere\sphere.obj
```
### Android
@@ -408,6 +462,8 @@ Filament can be built for the following architectures:
Note that the main target is the ARM 64-bit target. Our implementation is optimized first and
foremost for `arm64-v8a`.
To build Android on Windows machines, see [android/Windows.md](android/Windows.md).
#### Easy Android build
The easiest way to build Filament for Android is to use `build.sh` and the
@@ -421,24 +477,6 @@ Run `build.sh -h` for more information.
#### ARM 64-bit target (arm64-v8a)
##### Linux toolchain
```
$ $SDK/ndk-bundle/build/tools/make_standalone_toolchain.py --arch arm64 --api 24 \
--stl libc++ --force \
--install-dir toolchains/Linux/aarch64-linux-android-4.9
```
##### Darwin toolchain
```
$ $SDK/ndk-bundle/build/tools/make_standalone_toolchain.py --arch arm64 --api 24 \
--stl libc++ --force \
--install-dir toolchains/Darwin/aarch64-linux-android-4.9
```
##### Compiling
Then invoke CMake in a build directory of your choice, inside of filament's directory:
```
@@ -466,24 +504,6 @@ binaries should be found in `out/android-release/filament/lib/arm64-v8a`.
#### ARM 32-bit target (armeabi-v7a)
##### Linux toolchain
```
$ $SDK/ndk-bundle/build/tools/make_standalone_toolchain.py --arch arm --api 24 \
--stl libc++ --force \
--install-dir toolchains/Linux/arm-linux-androideabi-4.9
```
##### Darwin toolchain
```
$ $SDK/ndk-bundle/build/tools/make_standalone_toolchain.py --arch arm --api 24 \
--stl libc++ --force \
--install-dir toolchains/Darwin/arm-linux-androideabi-4.9
```
##### Compiling
Then invoke CMake in a build directory of your choice, inside of filament's directory:
```
@@ -511,24 +531,6 @@ binaries should be found in `out/android-release/filament/lib/armeabi-v7a`.
#### Intel 64-bit target (x86_64)
##### Linux toolchain
```
$ $SDK/ndk-bundle/build/tools/make_standalone_toolchain.py --arch x86_64 --api 24 \
--stl libc++ --force \
--install-dir toolchains/Linux/x86_64-linux-android-4.9
```
##### Darwin toolchain
```
$ $SDK/ndk-bundle/build/tools/make_standalone_toolchain.py --arch x86_64 --api 24 \
--stl libc++ --force \
--install-dir toolchains/Darwin/x86_64-linux-android-4.9
```
##### Compiling
Then invoke CMake in a build directory of your choice, sibling of filament's directory:
```
@@ -556,24 +558,6 @@ binaries should be found in `out/android-release/filament/lib/x86_64`.
#### Intel 32-bit target (x86)
##### Linux toolchain
```
$ $SDK/ndk-bundle/build/tools/make_standalone_toolchain.py --arch x86 --api 24 \
--stl libc++ --force \
--install-dir toolchains/Linux/i686-linux-android-4.9
```
##### Darwin toolchain
```
$ $SDK/ndk-bundle/build/tools/make_standalone_toolchain.py --arch x86 --api 24 \
--stl libc++ --force \
--install-dir toolchains/Darwin/i686-linux-android-4.9
```
##### Compiling
Then invoke CMake in a build directory of your choice, sibling of filament's directory:
```
@@ -683,16 +667,16 @@ same version that our continuous builds use.
```
cd <your chosen parent folder for the emscripten SDK>
curl -L https://github.com/juj/emsdk/archive/0d8576c.zip > emsdk.zip
curl -L https://github.com/emscripten-core/emsdk/archive/a77638d.zip > emsdk.zip
unzip emsdk.zip
mv emsdk-* emsdk
cd emsdk
./emsdk update
./emsdk install sdk-1.38.11-64bit
./emsdk activate sdk-1.38.11-64bit
./emsdk install sdk-1.38.28-64bit
./emsdk activate sdk-1.38.28-64bit
```
After this you can invoke [easy build](#easy-build) script as follows:
After this you can invoke the [easy build](#easy-build) script as follows:
```
export EMSDK=<your chosen home for the emscripten SDK>
@@ -700,18 +684,24 @@ export EMSDK=<your chosen home for the emscripten SDK>
```
The EMSDK variable is required so that the build script can find the Emscripten SDK. The build
creates a `public` folder that can be used as the root of a simple static web server. Note that you
creates a `samples` folder that can be used as the root of a simple static web server. Note that you
cannot open the HTML directly from the filesystem due to CORS. One way to deal with this is to
use Python to create a quick localhost server:
```
cd out/cmake-webgl-release/samples/web/public
cd out/cmake-webgl-release/web/samples
python3 -m http.server # Python 3
python -m SimpleHTTPServer # Python 2.7
```
Each sample app has its own handwritten html file, wasm file, and js loader. Additionally the public
folder contains meshes, textures, and the tiny `filaweb.js` library.
You can then open http://localhost:8000/suzanne.html in your web browser.
Alternatively, if you have node installed you can use the
[live-server](https://www.npmjs.com/package/live-server) package, which automatically refreshes the
web page when it detects a change.
Each sample app has its own handwritten html file. Additionally the server folder contains assets
such as meshes, textures, and materials.
## Running the native samples
@@ -726,11 +716,12 @@ filamesh ./assets/models/monkey/monkey.obj monkey.filamesh
```
Most samples accept an IBL that must be generated using the `cmgen` tool (`./tools/filamesh/cmgen`
in your build directory). These sample apps expect a path to a directory containing the RGBM files
for the IBL. To generate an IBL simply use this command:
in your build directory). These sample apps expect a path to a directory containing the '.rgb32f'
files for the IBL (which are PNGs containing `R11F_G11F_B10F` data). To generate an IBL simply use
this command:
```
cmgen -x ./ibls/ my_ibl.exr
cmgen -x ./ibls/ my_ibl.exr
```
The source environment map can be a PNG (8 or 16 bit), a PSD (16 or 32 bit), an HDR or an OpenEXR
@@ -743,7 +734,7 @@ pre-filtered environment map (one file per cubemap face and per mip level), the
texture for the skybox and a text file containing the spherical harmonics for indirect diffuse
lighting.
If you prefer a blurred background, run `cmgen` with this flag: `--extract-blur=0.5`. The numerical
If you prefer a blurred background, run `cmgen` with this flag: `--extract-blur=0.1`. The numerical
value is the desired roughness between 0 and 1.
## Rendering with Filament
@@ -751,7 +742,7 @@ value is the desired roughness between 0 and 1.
### Native Linux, macOS and Windows
You must create an `Engine`, a `Renderer` and a `SwapChain`. The `SwapChain` is created from a
native window pointer (an `NSView` on macOS or a `HDC` on Windows for instance):
native window pointer (an `NSView` on macOS or a `HWND` on Windows for instance):
```c++
Engine* engine = Engine::create();
@@ -840,9 +831,18 @@ package `com.google.android.filament.android`. All you need to do is set a rende
helper and attach your `SurfaceView` or `TextureView` to it. You are still responsible for
creating the swap chain in the `onNativeWindowChanged()` callback.
### iOS
See `ios/samples` for examples of using Filament on iOS.
Filament on iOS is largely the same as native rendering with C++. A `CAEAGLLayer` or `CAMetalLayer`
is passed to the `createSwapChain` method. Filament for iOS supports both OpenGL ES and Vulkan via
MoltenVK.
## Generating C++ documentation
To generate the documentation you must first install `doxygen`, then run the following commands:
To generate the documentation you must first install `doxygen` and `graphviz`, then run the
following commands:
```
$ cd filament/filament
@@ -865,12 +865,17 @@ as possible. The current external dependencies of the runtime library include:
- STL
- robin-map (header only library)
When building with Vulkan enabled, we have a few additional small dependencies:
- vkmemalloc
- smol-v
Host tools (such as `matc` or `cmgen`) can use external dependencies freely.
## How to make contributions
Please read and follow the steps in [CONTRIBUTING.md](/CONTRIBUTING.md). Make sure you are
familiar with the [code style](/CODE_STYLE.md).
familiar with the [code style](/CODE_STYLE.md).
## License

49
RELEASE_NOTES.md Normal file
View File

@@ -0,0 +1,49 @@
# Filament Release Notes log
This file contains one line summaries of commits that are worthy of mentioning in release notes.
A new header is inserted each time a *tag* is created.
- Added Java / Kotlin bindings for KtxLoader.
- Added JavaScript / Typescript bindings for the new `RenderTarget` class.
## sceneform-1.9pr4
- Added `gltf_bloom` Android sample to show gltfio and the `RenderTarget` API.
- Added `getMaterialInstanceAt` to the Java version of RenderableManager.
- Fix JNI bindings for setting values in parameter arrays.
- Added JNI bindings for the gltfio library.
- Fix support for parameter arrays in `.mat` files.
- Added support for `RGB_11_11_10`
- Removed support for `RGBM` (**warning:** source compatibility breakage)
- IBL cubemap can now be of any size
- `Texture::generatePrefilterMipmap` can be used for runtime generation of a reflection cubemap
## sceneform-1.9pr3
- Added `Scene.addEntities()` to the Java / Kotlin bindings.
- Improved robustness in the tangents utility for meshes that have tangents *and* normals.
- Introduced `RenderTarget` API that allows View to reference an offscreen render target.
- Added `lucy_bloom` sample to demonstrate the new `RenderTarget` API.
- Added Screen Space Ambient Occlusion support (SAO)
- New blending modes: `multiply` and `screen`
- Fixed an issue when sorting blended objects with different blending modes
- The material property `curvatureToRoughness` has been replaced with `specularAntiAliasing`.
This new specular anti-aliasing solution offers more control via two new properties:
`specularAntiAliasingVariance` and `specularAntiAliasingThreshold`. They can also be set on
material instances if needed
- Added specular ambient occlusion to compute a new AO term applied to specular reflections
(see `specularAmbientOcclusion` property in materials)
- Added multi-bounce ambient occlusion to brighten AO and preserve local color
(see `multiBounceAmbientOcclusion` property in materials)
- Micro-shadowing is now applied to material ambient occlusion
- Use a smaller 64x64 DFG LUT on mobile to reduce binary size
- Added a distance field generator to libimage.
- JavaScript MaterialInstance now supports vec4 colors.
- Further reduced `filamat` binary size by removing reliance on stdlib.
- Added a new, smaller, version of the `filamat` library, `filamat_lite`. Material optimization and
compiling for non-OpenGL backends have been removed in favor of a smaller binary size.
- Implemented hard fences for the Metal backend, enablying dynamic resolution support.
- Improved `SurfaceOrientation` robustness when using UVs to generate tangents.
- Created a `RELEASE_NOTES.md` file, to be updated with significant PRs.
## sceneform-1.9pr2

123
android/Windows.md Normal file
View File

@@ -0,0 +1,123 @@
# Building Filament for Android on Windows
## Prerequisites
In addition to the requirements for [building Filament on Windows](../README.md#windows), you'll
need the Android SDK and NDK. See [Getting Started with the
NDK](https://developer.android.com/ndk/guides/) for detailed installation instructions.
Ensure the `%ANDROID_HOME%` environment variable is set to your Android SDK installation location.
All of the following commands should be executed in a Visual Studio x64 Native Tools Command Prompt.
## Desktop Tools
First, a few Filament tools need to be compiled for desktop.
1. From Filament's root directory, create a desktop build directory and run CMake.
```
mkdir out\cmake-release
cd out\cmake-release
cmake ^
-G Ninja ^
-DCMAKE_CXX_COMPILER:PATH="C:\Program Files\LLVM\bin\clang-cl.exe" ^
-DCMAKE_C_COMPILER:PATH="C:\Program Files\LLVM\bin\clang-cl.exe" ^
-DCMAKE_LINKER:PATH="C:\Program Files\LLVM\bin\lld-link.exe" ^
-DCMAKE_INSTALL_PREFIX=..\release\filament ^
-DENABLE_JAVA=NO ^
-DCMAKE_BUILD_TYPE=Release ^
..\..
```
2. Build the required desktop host tools.
```
ninja matc resgen cmgen
```
The build should succeed and a `ImportExecutables-Release.cmake` file should automatically be
created at Filament's root directory.
## Build
1. Create the build directories.
```
mkdir out\cmake-android-release-aarch64
mkdir out\cmake-android-release-arm7
mkdir out\cmake-android-release-x86_64
mkdir out\cmake-android-release-x86
```
2. Run CMake for each architecture.
```
cd out\cmake-android-release-aarch64
cmake ^
-G Ninja ^
-DCMAKE_BUILD_TYPE=Release ^
-DCMAKE_INSTALL_PREFIX=..\android-release\filament ^
-DCMAKE_TOOLCHAIN_FILE=..\..\build\toolchain-aarch64-linux-android.cmake ^
..\..
cd out\cmake-android-release-arm7
cmake ^
-G Ninja ^
-DCMAKE_BUILD_TYPE=Release ^
-DCMAKE_INSTALL_PREFIX=..\android-release\filament ^
-DCMAKE_TOOLCHAIN_FILE=..\..\build\toolchain-arm7-linux-android.cmake ^
..\..
cd out\cmake-android-release-x86_64
cmake ^
-G Ninja ^
-DCMAKE_BUILD_TYPE=Release ^
-DCMAKE_INSTALL_PREFIX=..\android-release\filament ^
-DCMAKE_TOOLCHAIN_FILE=..\..\build\toolchain-x86_64-linux-android.cmake ^
..\..
cd out\cmake-android-release-x86
cmake ^
-G Ninja ^
-DCMAKE_BUILD_TYPE=Release ^
-DCMAKE_INSTALL_PREFIX=..\android-release\filament ^
-DCMAKE_TOOLCHAIN_FILE=..\..\build\toolchain-x86-linux-android.cmake ^
..\..
```
3. Build.
Inside of each build directory, run:
```
ninja install
```
## Generate AAR
The Gradle project used to generate the AAR is located at `<filament>\android\filament-android`.
```
cd android\filament-android
gradlew -Pfilament_dist_dir=..\..\out\android-release\filament assembleRelease
copy build\outputs\aar\filament-android-release.aar ..\..\out\
```
If you're only interested in building for a single ABI, you'll need to add an `abiFilters` override
inside the `build.gradle` file underneath `defaultConfig`:
```
ndk {
abiFilters 'arm64-v8a'
}
```
See
[NdkOptions](https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.NdkOptions.html#com.android.build.gradle.internal.dsl.NdkOptions:abiFilters)
for more information.
`filament-android-release.aar` should now be present at `<filament>\out\filament-android-release.aar`.
See [Using Filament's AAR](../README.md#using-filaments-aar) for usage instructions.

View File

@@ -33,6 +33,7 @@ List<File> getBinaries(String name, File toolsPath) {
ext.matcFullPath = getBinaries('matc', filamentToolsPath)
ext.cmgenFullPath = getBinaries('cmgen', filamentToolsPath)
ext.filameshFullPath = getBinaries('filamesh', filamentToolsPath)
ext.resgenFullPath = getBinaries('resgen', filamentToolsPath)
class LogOutputStream extends ByteArrayOutputStream {
private final Logger logger;
@@ -83,6 +84,7 @@ class MaterialCompiler extends DefaultTask {
}
inputs.outOfDate { InputFileDetails outOfDate ->
if (outOfDate.file.directory) return
def file = outOfDate.file
def out = new LogOutputStream(logger, LogLevel.LIFECYCLE)
@@ -96,7 +98,7 @@ class MaterialCompiler extends DefaultTask {
standardOutput out
errorOutput err
executable "${matcPath}"
args('-O', '-p', 'mobile', '-o', getOutputFile(file), file)
args('-a', 'all', '-p', 'mobile', '-o', getOutputFile(file), file)
}
}
@@ -155,7 +157,7 @@ class IblGenerator extends DefaultTask {
standardOutput out
errorOutput err
executable "${cmgenPath}"
args('--format=rgbm', '--extract-blur=0.08', "--extract=${outputDir.absolutePath}", file)
args('--format=rgb32f', '--extract-blur=0.08', "--extract=${outputDir.absolutePath}", file)
}
}

View File

@@ -56,7 +56,8 @@ JniCallback::~JniCallback() {
void JniCallback::invoke(void*, size_t, void* user) {
JniCallback* data = reinterpret_cast<JniCallback*>(user);
delete data;
// don't call delete here, because we don't own the storage
data->~JniCallback();
}
JniBufferCallback* JniBufferCallback::make(filament::Engine* engine,

View File

@@ -18,8 +18,8 @@
#include <jni.h>
#include "CallbackUtils.h"
#include "NioUtils.h"
#include "common/CallbackUtils.h"
#include "common/NioUtils.h"
#include <filament/Engine.h>

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
#include "NioUtils.h"
#include "common/NioUtils.h"
#include <algorithm>
@@ -26,7 +26,8 @@ struct {
jmethodID getBufferType;
} gNioUtils;
AutoBuffer::AutoBuffer(JNIEnv *env, jobject buffer, jint size) noexcept : mEnv(env) {
AutoBuffer::AutoBuffer(JNIEnv *env, jobject buffer, jint size, bool commit) noexcept : mEnv(env),
mDoCommit(commit) {
mBuffer = env->NewGlobalRef(buffer);
mType = (BufferType) env->CallStaticIntMethod(
@@ -108,27 +109,28 @@ AutoBuffer::AutoBuffer(AutoBuffer &&rhs) noexcept {
AutoBuffer::~AutoBuffer() noexcept {
JNIEnv *env = mEnv;
if (mBaseArray) {
jint mode = mDoCommit ? 0 : JNI_ABORT;
switch (mType) {
case BufferType::BYTE:
env->ReleaseByteArrayElements((jbyteArray)mBaseArray, (jbyte *) mData, JNI_ABORT);
env->ReleaseByteArrayElements((jbyteArray)mBaseArray, (jbyte *) mData, mode);
break;
case BufferType::CHAR:
env->ReleaseCharArrayElements((jcharArray)mBaseArray, (jchar *) mData, JNI_ABORT);
env->ReleaseCharArrayElements((jcharArray)mBaseArray, (jchar *) mData, mode);
break;
case BufferType::SHORT:
env->ReleaseShortArrayElements((jshortArray)mBaseArray, (jshort *) mData, JNI_ABORT);
env->ReleaseShortArrayElements((jshortArray)mBaseArray, (jshort *) mData, mode);
break;
case BufferType::INT:
env->ReleaseIntArrayElements((jintArray)mBaseArray, (jint *) mData, JNI_ABORT);
env->ReleaseIntArrayElements((jintArray)mBaseArray, (jint *) mData, mode);
break;
case BufferType::LONG:
env->ReleaseLongArrayElements((jlongArray)mBaseArray, (jlong *) mData, JNI_ABORT);
env->ReleaseLongArrayElements((jlongArray)mBaseArray, (jlong *) mData, mode);
break;
case BufferType::FLOAT:
env->ReleaseFloatArrayElements((jfloatArray)mBaseArray, (jfloat *) mData, JNI_ABORT);
env->ReleaseFloatArrayElements((jfloatArray)mBaseArray, (jfloat *) mData, mode);
break;
case BufferType::DOUBLE:
env->ReleaseDoubleArrayElements((jdoubleArray)mBaseArray, (jdouble *) mData, JNI_ABORT);
env->ReleaseDoubleArrayElements((jdoubleArray)mBaseArray, (jdouble *) mData, mode);
break;
}
env->DeleteGlobalRef(mBaseArray);

View File

@@ -32,7 +32,9 @@ public:
DOUBLE
};
AutoBuffer(JNIEnv* env, jobject buffer, jint size) noexcept;
// Clients should pass "true" for the commit argument if they intend to mutate the buffer
// contents from native code.
AutoBuffer(JNIEnv* env, jobject buffer, jint size, bool commit = false) noexcept;
AutoBuffer(AutoBuffer&& rhs) noexcept;
~AutoBuffer() noexcept;
@@ -62,4 +64,5 @@ private:
void* mData = nullptr;
jobject mBuffer = nullptr;
jarray mBaseArray = nullptr;
bool mDoCommit = false;
};

11
android/filamat-android/.gitignore vendored Normal file
View File

@@ -0,0 +1,11 @@
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
/.idea/caches
/.idea/gradle.xml
.DS_Store
/build
/captures
.externalNativeBuild

View File

@@ -0,0 +1,55 @@
cmake_minimum_required(VERSION 3.6)
set(FILAMENT_DIR ${FILAMENT_DIST_DIR})
set(FILAMAT_FLAVOR "filamat")
if(FILAMAT_LITE)
set(FILAMAT_FLAVOR "filamat_lite")
endif()
add_library(${FILAMAT_FLAVOR} STATIC IMPORTED)
set_target_properties(${FILAMAT_FLAVOR} PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/lib${FILAMAT_FLAVOR}.a)
add_library(utils STATIC IMPORTED)
set_target_properties(utils PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libutils.a)
add_library(filabridge STATIC IMPORTED)
set_target_properties(filabridge PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libfilabridge.a)
add_library(smol-v STATIC IMPORTED)
set_target_properties(smol-v PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libsmol-v.a)
add_library(shaders STATIC IMPORTED)
set_target_properties(shaders PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libshaders.a)
include_directories(${FILAMENT_DIR}/include)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-stack-protector")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-exceptions -fno-unwind-tables -fno-asynchronous-unwind-tables -fno-rtti")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ffast-math -ffp-contract=fast")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility-inlines-hidden")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility=hidden")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fomit-frame-pointer -ffunction-sections -fdata-sections")
set(CMAKE_SHARED_LINKER_FLAGS" ${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections")
set(CMAKE_SHARED_LINKER_FLAGS" ${CMAKE_SHARED_LINKER_FLAGS} -Wl,-Bsymbolic-functions")
set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} -Wl,--version-script=${CMAKE_SOURCE_DIR}/libfilamat-jni.map")
add_library(filamat-jni SHARED
src/main/cpp/MaterialBuilder.cpp
)
target_link_libraries(filamat-jni
${FILAMAT_FLAVOR}
filabridge
shaders
utils
log
smol-v
)

View File

@@ -0,0 +1,106 @@
// This script accepts the following parameters:
//
// filament_dist_dir
// Path to the Filament distribution/install directory for Android
// (produced by make/ninja install). This directory must contain lib/arm64-v8a/ etc.
//
// Example:
// ./gradlew -Pfilament_dist_dir=../../dist-android-release assembleRelease
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
group = "com.google.android.filament"
version = "0.1"
apply plugin: 'com.android.library'
def filament_path = file("../../out/android-release/filament").absolutePath
if (project.hasProperty("filament_dist_dir")) {
filament_path = file("$filament_dist_dir").absolutePath
}
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 14
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
arguments.add("-DANDROID_PIE=ON")
arguments.add("-DANDROID_PLATFORM=android-21")
arguments.add("-DANDROID_STL=c++_static")
arguments.add("-DFILAMENT_DIST_DIR=${filament_path}".toString())
cppFlags.add("-std=c++14")
if (project.hasProperty('extra_cmake_args')) {
arguments.add(extra_cmake_args)
}
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
flavorDimensions "functionality"
productFlavors {
full {
dimension "functionality"
}
lite {
dimension "functionality"
externalNativeBuild {
cmake {
arguments.add("-DFILAMAT_LITE=ON")
}
}
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
sourceSets {
main {
jni.srcDirs "src/main/cpp"
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:support-annotations:28.0.0'
}

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

172
android/filamat-android/gradlew vendored Executable file
View File

@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
android/filamat-android/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,4 @@
LIBFILAMAT {
global: Java_com_google_android_filament_*; JNI*;
local: *;
};

View File

@@ -0,0 +1 @@
_Java_com_google_android_filament_*

View File

@@ -0,0 +1,10 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user guide at https://docs.gradle.org/4.6/userguide/multi_project_builds.html
*/
rootProject.name = 'filamat-android'

View File

@@ -0,0 +1,2 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.filament.filamat" />

View File

@@ -0,0 +1,310 @@
/*
* Copyright (C) 2019 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 <jni.h>
#include <filamat/MaterialBuilder.h>
using namespace filament;
using namespace filamat;
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderInit(JNIEnv*, jclass) {
MaterialBuilder::init();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderShutdown(JNIEnv*, jclass) {
MaterialBuilder::shutdown();
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nCreateMaterialBuilder(JNIEnv*, jclass) {
return (jlong) new MaterialBuilder();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nDestroyMaterialBuilder(JNIEnv*, jclass,
jlong nativeBuilder) {
auto builder = (MaterialBuilder*) nativeBuilder;
delete builder;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nBuilderBuild(JNIEnv*, jclass,
jlong nativeBuilder) {
auto builder = (MaterialBuilder*) nativeBuilder;
return (jlong) new Package(builder->build());
}
extern "C" JNIEXPORT jbyteArray JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nGetPackageBytes(JNIEnv* env, jclass,
jlong nativePackage) {
auto package = (Package*) nativePackage;
auto size = jsize(package->getSize());
jbyteArray ret = env->NewByteArray(size);
auto data = (jbyte*) package->getData();
env->SetByteArrayRegion(ret, 0, size, data);
return ret;
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nGetPackageIsValid(JNIEnv*, jclass,
jlong nativePackage) {
auto* package = (Package*) nativePackage;
return jboolean(package->isValid());
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nDestroyPackage(JNIEnv*, jclass,
jlong nativePackage) {
Package* package = (Package*) nativePackage;
delete package;
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderName(JNIEnv* env,
jclass, jlong nativeBuilder, jstring name_) {
auto builder = (MaterialBuilder*) nativeBuilder;
const char* name = env->GetStringUTFChars(name_, nullptr);
builder->name(name);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderShading(JNIEnv*,
jclass, jlong nativeBuilder, jint shading) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->shading((MaterialBuilder::Shading) shading);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderInterpolation(JNIEnv*,
jclass, jlong nativeBuilder, jint interpolation) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->interpolation((MaterialBuilder::Interpolation) interpolation);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderUniformParameter(
JNIEnv* env, jclass, jlong nativeBuilder, jint uniformType, jstring name_) {
auto builder = (MaterialBuilder*) nativeBuilder;
const char* name = env->GetStringUTFChars(name_, nullptr);
builder->parameter((MaterialBuilder::UniformType) uniformType, name);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderUniformParameterArray(
JNIEnv* env, jclass, jlong nativeBuilder, jint uniformType, jint size, jstring name_) {
auto builder = (MaterialBuilder*) nativeBuilder;
const char* name = env->GetStringUTFChars(name_, nullptr);
builder->parameter((MaterialBuilder::UniformType) uniformType, (size_t) size, name);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderSamplerParameter(
JNIEnv* env, jclass, jlong nativeBuilder, jint samplerType, jint format,
jint precision, jstring name_) {
auto builder = (MaterialBuilder*) nativeBuilder;
const char* name = env->GetStringUTFChars(name_, nullptr);
builder->parameter((MaterialBuilder::SamplerType) samplerType,
(MaterialBuilder::SamplerFormat) format, (MaterialBuilder::SamplerPrecision) precision,
name);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderVariable(
JNIEnv* env, jclass, jlong nativeBuilder, jint variable, jstring name_) {
const char* name = env->GetStringUTFChars(name_, nullptr);
auto builder = (MaterialBuilder*) nativeBuilder;
builder->variable((MaterialBuilder::Variable) variable, name);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderRequire(JNIEnv*,
jclass, jlong nativeBuilder, jint attribute) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->require((VertexAttribute) attribute);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderMaterial(JNIEnv* env,
jclass, jlong nativeBuilder, jstring code_) {
auto builder = (MaterialBuilder*) nativeBuilder;
const char* code = env->GetStringUTFChars(code_, nullptr);
builder->material(code);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderMaterialVertex(JNIEnv* env,
jclass, jlong nativeBuilder, jstring code_) {
auto builder = (MaterialBuilder*) nativeBuilder;
const char* code = env->GetStringUTFChars(code_, nullptr);
builder->materialVertex(code);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderBlending(JNIEnv*,
jclass, jlong nativeBuilder, jint mode) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->blending((MaterialBuilder::BlendingMode) mode);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderPostLightingBlending(
JNIEnv*, jclass, jlong nativeBuilder, jint mode) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->postLightingBlending((MaterialBuilder::BlendingMode) mode);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderVertexDomain(JNIEnv*,
jclass, jlong nativeBuilder, jint vertexDomain) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->vertexDomain((MaterialBuilder::VertexDomain) vertexDomain);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderCulling(JNIEnv*,
jclass, jlong nativeBuilder, jint mode) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->culling((MaterialBuilder::CullingMode) mode);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderColorWrite(JNIEnv*,
jclass, jlong nativeBuilder, jboolean enable) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->colorWrite(enable);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderDepthWrite(JNIEnv*,
jclass, jlong nativeBuilder, jboolean depthWrite) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->depthWrite(depthWrite);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderDepthCulling(JNIEnv*,
jclass, jlong nativeBuilder, jboolean depthCulling) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->depthCulling(depthCulling);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderDoubleSided(JNIEnv*,
jclass, jlong nativeBuilder, jboolean doubleSided) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->doubleSided(doubleSided);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderMaskThreshold(JNIEnv*,
jclass, jlong nativeBuilder, jfloat maskThreshold) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->maskThreshold(maskThreshold);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderShadowMultiplier(
JNIEnv*, jclass, jlong nativeBuilder, jboolean shadowMultiplier) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->shadowMultiplier(shadowMultiplier);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderSpecularAntiAliasing(
JNIEnv*, jclass, jlong nativeBuilder, jboolean specularAntiAliasing) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->specularAntiAliasing(specularAntiAliasing);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderSpecularAntiAliasingVariance(
JNIEnv*, jclass, jlong nativeBuilder, jfloat variance) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->specularAntiAliasingVariance(variance);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderSpecularAntiAliasingThreshold(
JNIEnv*, jclass, jlong nativeBuilder, jfloat threshold) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->specularAntiAliasingThreshold(threshold);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderClearCoatIorChange(
JNIEnv*, jclass, jlong nativeBuilder, jboolean clearCoatIorChange) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->clearCoatIorChange(clearCoatIorChange);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderFlipUV(JNIEnv*,
jclass, jlong nativeBuilder, jboolean flipUV) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->flipUV(flipUV);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderMultiBounceAmbientOcclusion(
JNIEnv*, jclass, jlong nativeBuilder, jboolean multiBounceAO) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->multiBounceAmbientOcclusion(multiBounceAO);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderSpecularAmbientOcclusion(
JNIEnv*, jclass, jlong nativeBuilder, jboolean specularAO) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->specularAmbientOcclusion(specularAO);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderTransparencyMode(
JNIEnv* env, jclass, jlong nativeBuilder, jint mode) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->transparencyMode((MaterialBuilder::TransparencyMode) mode);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderPlatform(JNIEnv*,
jclass, jlong nativeBuilder, jint platform) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->platform((MaterialBuilder::Platform) platform);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderTargetApi(JNIEnv*,
jclass, jlong nativeBuilder, jint targetApi) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->targetApi((MaterialBuilder::TargetApi) targetApi);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderOptimization(JNIEnv*,
jclass, jlong nativeBuilder, jint optimization) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->optimization((MaterialBuilder::Optimization) optimization);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_filamat_MaterialBuilder_nMaterialBuilderVariantFilter(JNIEnv*,
jclass, jlong nativeBuilder, jbyte variantFilter) {
auto builder = (MaterialBuilder*) nativeBuilder;
builder->variantFilter((uint8_t) variantFilter);
}

View File

@@ -0,0 +1,457 @@
/*
* Copyright (C) 2019 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.
*/
package com.google.android.filament.filamat;
import android.support.annotation.NonNull;
import java.nio.ByteBuffer;
public class MaterialBuilder {
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
// Keep to finalize native resources
private final BuilderFinalizer mFinalizer;
private final long mNativeObject;
static {
System.loadLibrary("filamat-jni");
}
public enum Shading {
UNLIT, // no lighting applied, emissive possible
LIT, // default, standard lighting
SUBSURFACE, // subsurface lighting model
CLOTH, // cloth lighting model
SPECULAR_GLOSSINESS // legacy lighting model
}
public enum Interpolation {
SMOOTH, // default, smooth interpolation
FLAT // flat interpolation
}
public enum UniformType {
BOOL,
BOOL2,
BOOL3,
BOOL4,
FLOAT,
FLOAT2,
FLOAT3,
FLOAT4,
INT,
INT2,
INT3,
INT4,
UINT,
UINT2,
UINT3,
UINT4,
MAT3,
MAT4
}
public enum SamplerType {
SAMPLER_2D, // 2D texture
SAMPLER_CUBEMAP, // Cube map texture
SAMPLER_EXTERNAL, // External texture
}
public enum SamplerFormat {
INT,
UINT,
FLOAT,
SHADOW
}
public enum SamplerPrecision {
LOW,
MEDIUM,
HIGH,
DEFAULT
}
public enum Variable {
CUSTOM0,
CUSTOM1,
CUSTOM2,
CUSTOM3
}
public enum VertexAttribute {
POSITION, // XYZ position (float3)
TANGENTS, // tangent, bitangent and normal, encoded as a quaternion (4 floats or half floats)
COLOR, // vertex color (float4)
UV0, // texture coordinates (float2)
UV1, // texture coordinates (float2)
BONE_INDICES, // indices of 4 bones (uvec4)
BONE_WEIGHTS // weights of the 4 bones (normalized float4)
}
public enum BlendingMode {
OPAQUE, // material is opaque
TRANSPARENT, // material is transparent and color is alpha-pre-multiplied,
// affects diffuse lighting only
ADD, // material is additive (e.g.: hologram)
MASKED, // material is masked (i.e. alpha tested)
FADE, // material is transparent and color is alpha-pre-multiplied,
// affects specular lighting
MULTIPLY, // material darkens what's behind it
SCREN // material brightens what's behind it
}
public enum VertexDomain {
OBJECT, // vertices are in object space, default
WORLD, // vertices are in world space
VIEW, // vertices are in view space
DEVICE // vertices are in normalized device space
}
public enum CullingMode {
NONE,
FRONT,
BACK,
FRONT_AND_BACK
}
public enum TransparencyMode {
DEFAULT, // the transparent object is drawn honoring the raster state
TWO_PASSES_ONE_SIDE, // the transparent object is first drawn in the depth buffer,
// then in the color buffer, honoring the culling mode, but
// ignoring the depth test function
TWO_PASSES_TWO_SIDES // the transparent object is drawn twice in the color buffer,
// first with back faces only, then with front faces; the culling
// mode is ignored. Can be combined with two-sided lighting
}
public enum Platform {
DESKTOP,
MOBILE,
ALL
}
public enum TargetApi {
OPENGL (0x1),
VULKAN (0x2),
METAL (0x4),
ALL (0x7);
final int number;
private TargetApi(int number) {
this.number = number;
}
}
public enum Optimization {
NONE,
PREPROCESSOR,
SIZE,
PERFORMANCE
}
public static void init() {
nMaterialBuilderInit();
}
public static void shutdown() {
nMaterialBuilderShutdown();
}
public MaterialBuilder() {
mNativeObject = nCreateMaterialBuilder();
mFinalizer = new BuilderFinalizer(mNativeObject);
}
@NonNull
public MaterialBuilder name(@NonNull String name) {
nMaterialBuilderName(mNativeObject, name);
return this;
}
@NonNull
public MaterialBuilder shading(@NonNull Shading shading) {
nMaterialBuilderShading(mNativeObject, shading.ordinal());
return this;
}
@NonNull
public MaterialBuilder interpolation(@NonNull Interpolation interpolation) {
nMaterialBuilderInterpolation(mNativeObject, interpolation.ordinal());
return this;
}
@NonNull
public MaterialBuilder uniformParameter(@NonNull UniformType type, String name) {
nMaterialBuilderUniformParameter(mNativeObject, type.ordinal(), name);
return this;
}
@NonNull
public MaterialBuilder uniformParameterArray(@NonNull UniformType type, int size, String name) {
nMaterialBuilderUniformParameterArray(mNativeObject, type.ordinal(), size, name);
return this;
}
@NonNull
public MaterialBuilder samplerParameter(@NonNull SamplerType type, SamplerFormat format,
SamplerPrecision precision, String name) {
nMaterialBuilderSamplerParameter(
mNativeObject, type.ordinal(), format.ordinal(), precision.ordinal(), name);
return this;
}
@NonNull
public MaterialBuilder variable(@NonNull Variable variable, String name) {
nMaterialBuilderVariable(mNativeObject, variable.ordinal(), name);
return this;
}
@NonNull
public MaterialBuilder require(@NonNull VertexAttribute attribute) {
nMaterialBuilderRequire(mNativeObject, attribute.ordinal());
return this;
}
@NonNull
public MaterialBuilder material(@NonNull String code) {
nMaterialBuilderMaterial(mNativeObject, code);
return this;
}
@NonNull
public MaterialBuilder materialVertex(@NonNull String code) {
nMaterialBuilderMaterialVertex(mNativeObject, code);
return this;
}
@NonNull
public MaterialBuilder blending(@NonNull BlendingMode mode) {
nMaterialBuilderBlending(mNativeObject, mode.ordinal());
return this;
}
@NonNull
public MaterialBuilder postLightingBlending(@NonNull BlendingMode mode) {
nMaterialBuilderPostLightingBlending(mNativeObject, mode.ordinal());
return this;
}
@NonNull
public MaterialBuilder vertexDomain(@NonNull VertexDomain vertexDomain) {
nMaterialBuilderVertexDomain(mNativeObject, vertexDomain.ordinal());
return this;
}
@NonNull
public MaterialBuilder culling(@NonNull CullingMode mode) {
nMaterialBuilderCulling(mNativeObject, mode.ordinal());
return this;
}
@NonNull
public MaterialBuilder colorWrite(boolean enable) {
nMaterialBuilderColorWrite(mNativeObject, enable);
return this;
}
@NonNull
public MaterialBuilder depthWrite(boolean enable) {
nMaterialBuilderDepthWrite(mNativeObject, enable);
return this;
}
@NonNull
public MaterialBuilder depthCulling(boolean enable) {
nMaterialBuilderDepthCulling(mNativeObject, enable);
return this;
}
@NonNull
public MaterialBuilder doubleSided(boolean doubleSided) {
nMaterialBuilderDoubleSided(mNativeObject, doubleSided);
return this;
}
@NonNull
public MaterialBuilder maskThreshold(float threshold) {
nMaterialBuilderMaskThreshold(mNativeObject, threshold);
return this;
}
@NonNull
public MaterialBuilder shadowMultiplier(boolean shadowMultiplier) {
nMaterialBuilderShadowMultiplier(mNativeObject, shadowMultiplier);
return this;
}
@NonNull
public MaterialBuilder specularAntiAliasing(boolean specularAntiAliasing) {
nMaterialBuilderSpecularAntiAliasing(mNativeObject, specularAntiAliasing);
return this;
}
@NonNull
public MaterialBuilder specularAntiAliasingVariance(float variance) {
nMaterialBuilderSpecularAntiAliasingVariance(mNativeObject, variance);
return this;
}
@NonNull
public MaterialBuilder specularAntiAliasingThreshold(float threshold) {
nMaterialBuilderSpecularAntiAliasingThreshold(mNativeObject, threshold);
return this;
}
@NonNull
public MaterialBuilder clearCoatIorChange(boolean clearCoatIorChange) {
nMaterialBuilderClearCoatIorChange(mNativeObject, clearCoatIorChange);
return this;
}
@NonNull
public MaterialBuilder flipUV(boolean flipUV) {
nMaterialBuilderFlipUV(mNativeObject, flipUV);
return this;
}
@NonNull
public MaterialBuilder multiBounceAmbientOcclusion(boolean multiBounceAO) {
nMaterialBuilderMultiBounceAmbientOcclusion(mNativeObject, multiBounceAO);
return this;
}
@NonNull
public MaterialBuilder specularAmbientOcclusion(boolean specularAO) {
nMaterialBuilderSpecularAmbientOcclusion(mNativeObject, specularAO);
return this;
}
@NonNull
public MaterialBuilder transparencyMode(@NonNull TransparencyMode mode) {
nMaterialBuilderTransparencyMode(mNativeObject, mode.ordinal());
return this;
}
@NonNull
public MaterialBuilder platform(@NonNull Platform platform) {
nMaterialBuilderPlatform(mNativeObject, platform.ordinal());
return this;
}
@NonNull
public MaterialBuilder targetApi(@NonNull TargetApi api) {
nMaterialBuilderTargetApi(mNativeObject, api.number);
return this;
}
@NonNull
public MaterialBuilder optimization(@NonNull Optimization optimization) {
nMaterialBuilderOptimization(mNativeObject, optimization.ordinal());
return this;
}
@NonNull
public MaterialBuilder variantFilter(byte variantFilter) {
nMaterialBuilderVariantFilter(mNativeObject, variantFilter);
return this;
}
@NonNull
public MaterialPackage build() {
long nativePackage = nBuilderBuild(mNativeObject);
byte[] data = nGetPackageBytes(nativePackage);
MaterialPackage result =
new MaterialPackage(ByteBuffer.wrap(data), nGetPackageIsValid(nativePackage));
nDestroyPackage(nativePackage);
return result;
}
private static class BuilderFinalizer {
private final long mNativeObject;
BuilderFinalizer(long nativeObject) {
mNativeObject = nativeObject;
}
@Override
public void finalize() {
try {
super.finalize();
} catch (Throwable t) { // Ignore
} finally {
nDestroyMaterialBuilder(mNativeObject);
}
}
}
private static native void nMaterialBuilderInit();
private static native void nMaterialBuilderShutdown();
private static native long nCreateMaterialBuilder();
private static native void nDestroyMaterialBuilder(long nativeBuilder);
private static native long nBuilderBuild(long nativeBuilder);
private static native byte[] nGetPackageBytes(long nativePackage);
private static native boolean nGetPackageIsValid(long nativePackage);
private static native void nDestroyPackage(long nativePackage);
private static native void nMaterialBuilderName(long nativeBuilder, String name);
private static native void nMaterialBuilderShading(long nativeBuilder, int shading);
private static native void nMaterialBuilderInterpolation(long nativeBuilder, int interpolation);
private static native void nMaterialBuilderUniformParameter(long nativeBuilder, int type,
String name);
private static native void nMaterialBuilderUniformParameterArray(long nativeBuilder, int type,
int size, String name);
private static native void nMaterialBuilderSamplerParameter(long nativeBuilder, int type,
int format, int precision, String name);
private static native void nMaterialBuilderVariable(long nativeBuilder, int variable,
String name);
private static native void nMaterialBuilderRequire(long nativeBuilder, int attribute);
private static native void nMaterialBuilderMaterial(long nativeBuilder, String code);
private static native void nMaterialBuilderMaterialVertex(long nativeBuilder, String code);
private static native void nMaterialBuilderBlending(long nativeBuilder, int mode);
private static native void nMaterialBuilderPostLightingBlending(long nativeBuilder, int mode);
private static native void nMaterialBuilderVertexDomain(long nativeBuilder, int vertexDomain);
private static native void nMaterialBuilderCulling(long nativeBuilder, int mode);
private static native void nMaterialBuilderColorWrite(long nativeBuilder, boolean enable);
private static native void nMaterialBuilderDepthWrite(long nativeBuilder, boolean enable);
private static native void nMaterialBuilderDepthCulling(long nativeBuilder, boolean enable);
private static native void nMaterialBuilderDoubleSided(long nativeBuilder, boolean doubleSided);
private static native void nMaterialBuilderMaskThreshold(long nativeBuilder, float mode);
private static native void nMaterialBuilderShadowMultiplier(long mNativeObject,
boolean shadowMultiplier);
private static native void nMaterialBuilderSpecularAntiAliasing(long mNativeObject,
boolean specularAntiAliasing);
private static native void nMaterialBuilderSpecularAntiAliasingVariance(long mNativeObject,
float variance);
private static native void nMaterialBuilderSpecularAntiAliasingThreshold(long mNativeObject,
float threshold);
private static native void nMaterialBuilderClearCoatIorChange(long mNativeObject,
boolean clearCoatIorChange);
private static native void nMaterialBuilderFlipUV(long nativeBuilder, boolean flipUV);
private static native void nMaterialBuilderMultiBounceAmbientOcclusion(long nativeBuilder,
boolean multiBounceAO);
private static native void nMaterialBuilderSpecularAmbientOcclusion(long nativeBuilder,
boolean specularAO);
private static native void nMaterialBuilderTransparencyMode(long nativeBuilder, int mode);
private static native void nMaterialBuilderPlatform(long nativeBuilder, int platform);
private static native void nMaterialBuilderTargetApi(long nativeBuilder, int api);
private static native void nMaterialBuilderOptimization(long nativeBuilder, int optimization);
private static native void nMaterialBuilderVariantFilter(long nativeBuilder,
byte variantFilter);
}

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2019 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.
*/
package com.google.android.filament.filamat;
import android.support.annotation.NonNull;
import java.nio.ByteBuffer;
public class MaterialPackage {
private final ByteBuffer mBuffer;
private final boolean mIsValid;
MaterialPackage(@NonNull ByteBuffer buffer, boolean isValid) {
mBuffer = buffer;
mIsValid = isValid;
}
@NonNull
public ByteBuffer getBuffer() {
return mBuffer;
}
public boolean isValid() {
return mIsValid;
}
}

View File

@@ -1,5 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Google Configuration Checker Style" />
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

View File

@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.4.1)
cmake_minimum_required(VERSION 3.6)
set(FILAMENT_DIR ${FILAMENT_DIST_DIR})
@@ -6,14 +6,26 @@ add_library(filament STATIC IMPORTED)
set_target_properties(filament PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libfilament.a)
add_library(backend STATIC IMPORTED)
set_target_properties(backend PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libbackend.a)
add_library(utils STATIC IMPORTED)
set_target_properties(utils PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libutils.a)
add_library(ibl STATIC IMPORTED)
set_target_properties(ibl PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libibl.a)
add_library(filaflat STATIC IMPORTED)
set_target_properties(filaflat PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libfilaflat.a)
add_library(geometry STATIC IMPORTED)
set_target_properties(geometry PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libgeometry.a)
add_library(filabridge STATIC IMPORTED)
set_target_properties(filabridge PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libfilabridge.a)
@@ -22,13 +34,19 @@ add_library(bluevk STATIC IMPORTED)
set_target_properties(bluevk PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libbluevk.a)
include_directories(${FILAMENT_DIR}/include)
add_library(smol-v STATIC IMPORTED)
set_target_properties(smol-v PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libsmol-v.a)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-exceptions -fno-rtti")
include_directories(.. ${FILAMENT_DIR}/include)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-stack-protector")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-exceptions -fno-unwind-tables -fno-asynchronous-unwind-tables -fno-rtti")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ffast-math -ffp-contract=fast")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility-inlines-hidden")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility=hidden")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ffunction-sections -fdata-sections")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fomit-frame-pointer -ffunction-sections -fdata-sections")
set(CMAKE_SHARED_LINKER_FLAGS" ${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections")
set(CMAKE_SHARED_LINKER_FLAGS" ${CMAKE_SHARED_LINKER_FLAGS} -Wl,-Bsymbolic-functions")
@@ -49,6 +67,7 @@ add_library(filament-jni SHARED
src/main/cpp/MathUtils.cpp
src/main/cpp/RenderableManager.cpp
src/main/cpp/Renderer.cpp
src/main/cpp/RenderTarget.cpp
src/main/cpp/Scene.cpp
src/main/cpp/SkyBox.cpp
src/main/cpp/Stream.cpp
@@ -59,24 +78,29 @@ add_library(filament-jni SHARED
# Android specific
src/main/cpp/nativewindow/Android.cpp
# Private utils
src/main/cpp/CallbackUtils.cpp
src/main/cpp/Filament.cpp
src/main/cpp/NioUtils.cpp
# Common utils
../common/CallbackUtils.cpp
../common/NioUtils.cpp
)
target_link_libraries(filament-jni
filament
backend
filaflat
filabridge
geometry
ibl
utils
log
GLESv3
EGL
android
jnigraphics
)
option(FILAMENT_SUPPORTS_VULKAN "Enables Vulkan on Android" OFF)
if (FILAMENT_SUPPORTS_VULKAN)
target_link_libraries(filament-jni bluevk)
target_link_libraries(filament-jni bluevk smol-v)
endif()

View File

@@ -13,7 +13,7 @@ buildscript {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
classpath 'com.android.tools.build:gradle:3.4.1'
}
}
@@ -37,6 +37,9 @@ if (project.hasProperty("filament_dist_dir")) {
android {
compileSdkVersion 28
defaultConfig {
// Our minSdkVersion is actually 21, we lie and say 14 here so apps don't have
// to increase their minSdkVersion unnecessarily. It is however up to them to
// ensure they do not initialize Filament on API levels < 21.
minSdkVersion 14
targetSdkVersion 28
versionCode 1
@@ -47,7 +50,7 @@ android {
externalNativeBuild {
cmake {
arguments.add("-DANDROID_PIE=ON")
arguments.add("-DANDROID_PLATFORM=android-24")
arguments.add("-DANDROID_PLATFORM=android-21")
arguments.add("-DANDROID_STL=c++_static")
arguments.add("-DFILAMENT_DIST_DIR=${filament_path}".toString())
cppFlags.add("-std=c++14")
@@ -74,6 +77,12 @@ android {
sourceSets {
main {
jni.srcDirs "src/main/cpp"
// To enable validation layers with the Vulkan backend, uncomment the following lines
// to copy the appropriate files from the NDK to the device. Also be sure to use a debug
// configuration for the native build.
// jniLibs {
// srcDirs = ["${android.ndkDirectory}/sources/third_party/vulkan/src/build-android/jniLibs"]
// }
}
}

View File

@@ -1,6 +1,5 @@
#Tue Aug 28 15:45:13 PDT 2018
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env bash
#!/usr/bin/env sh
##############################################################################
##
@@ -6,42 +6,6 @@
##
##############################################################################
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS=""
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn ( ) {
echo "$*"
}
die ( ) {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
esac
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
@@ -60,6 +24,46 @@ cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
@@ -85,7 +89,7 @@ location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
@@ -150,11 +154,19 @@ if $cygwin ; then
esac
fi
# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
function splitJvmOpts() {
JVM_OPTS=("$@")
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
APP_ARGS=$(save "$@")
exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

View File

@@ -8,14 +8,14 @@
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS=
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
@@ -46,10 +46,9 @@ echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windowz variants
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
if "%@eval[2+2]" == "4" goto 4NT_args
:win9xME_args
@rem Slurp the command line arguments.
@@ -60,11 +59,6 @@ set _SKIP=2
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
goto execute
:4NT_args
@rem Get arguments from the 4NT Shell from JP Software
set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line

View File

@@ -5,17 +5,18 @@
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# JNI is an entry point that's hard to keep track of, so there's
# an annotation to mark fields and methods used by native code.
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# Keep the annotations that proguard needs to process.
-keep class com.google.android.filament.proguard.UsedBy*
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
# Just because native code accesses members of a class, does not mean that the
# class itself needs to be annotated - only annotate classes that are
# referenced themselves in native code.
-keep @com.google.android.filament.proguard.UsedBy* class * {
<init>();
}
-keepclassmembers class * {
@com.google.android.filament.proguard.UsedBy* *;
}

View File

@@ -48,7 +48,7 @@ Java_com_google_android_filament_Camera_nSetCustomProjection(JNIEnv *env, jclass
jlong nativeCamera, jdoubleArray inMatrix_, jdouble near, jdouble far) {
Camera *camera = (Camera *) nativeCamera;
jdouble *inMatrix = env->GetDoubleArrayElements(inMatrix_, NULL);
camera->setCustomProjection(*reinterpret_cast<const math::mat4 *>(inMatrix), near, far);
camera->setCustomProjection(*reinterpret_cast<const filament::math::mat4 *>(inMatrix), near, far);
env->ReleaseDoubleArrayElements(inMatrix_, inMatrix, JNI_ABORT);
}
@@ -78,7 +78,7 @@ Java_com_google_android_filament_Camera_nSetModelMatrix(JNIEnv *env, jclass,
jlong nativeCamera, jfloatArray in_) {
Camera* camera = (Camera *) nativeCamera;
jfloat *in = env->GetFloatArrayElements(in_, NULL);
camera->setModelMatrix(*reinterpret_cast<const math::mat4f*>(in));
camera->setModelMatrix(*reinterpret_cast<const filament::math::mat4f*>(in));
env->ReleaseFloatArrayElements(in_, in, JNI_ABORT);
}
@@ -87,7 +87,7 @@ Java_com_google_android_filament_Camera_nGetProjectionMatrix(JNIEnv *env, jclass
jlong nativeCamera, jdoubleArray out_) {
Camera *camera = (Camera *) nativeCamera;
jdouble *out = env->GetDoubleArrayElements(out_, NULL);
const math::mat4& m = camera->getProjectionMatrix();
const filament::math::mat4& m = camera->getProjectionMatrix();
std::copy_n(&m[0][0], 16, out);
env->ReleaseDoubleArrayElements(out_, out, 0);
}
@@ -97,7 +97,7 @@ Java_com_google_android_filament_Camera_nGetModelMatrix(JNIEnv *env, jclass,
jlong nativeCamera, jfloatArray out_) {
Camera *camera = (Camera *) nativeCamera;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
const math::mat4f& m = camera->getModelMatrix();
const filament::math::mat4f& m = camera->getModelMatrix();
std::copy_n(&m[0][0], 16, out);
env->ReleaseFloatArrayElements(out_, out, 0);
}
@@ -107,7 +107,7 @@ Java_com_google_android_filament_Camera_nGetViewMatrix(JNIEnv *env, jclass, jlon
jfloatArray out_) {
Camera *camera = (Camera *) nativeCamera;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
const math::mat4f& m = camera->getViewMatrix();
const filament::math::mat4f& m = camera->getViewMatrix();
std::copy_n(&m[0][0], 16, out);
env->ReleaseFloatArrayElements(out_, out, 0);
}
@@ -117,7 +117,7 @@ Java_com_google_android_filament_Camera_nGetPosition(JNIEnv *env, jclass, jlong
jfloatArray out_) {
Camera *camera = (Camera *) nativeCamera;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
reinterpret_cast<math::float3&>(*out) = camera->getPosition();
reinterpret_cast<filament::math::float3&>(*out) = camera->getPosition();
env->ReleaseFloatArrayElements(out_, out, 0);
}
@@ -126,7 +126,7 @@ Java_com_google_android_filament_Camera_nGetLeftVector(JNIEnv *env, jclass, jlon
jfloatArray out_) {
Camera *camera = (Camera *) nativeCamera;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
reinterpret_cast<math::float3&>(*out) = camera->getLeftVector();
reinterpret_cast<filament::math::float3&>(*out) = camera->getLeftVector();
env->ReleaseFloatArrayElements(out_, out, 0);
}
@@ -135,7 +135,7 @@ Java_com_google_android_filament_Camera_nGetUpVector(JNIEnv *env, jclass, jlong
jfloatArray out_) {
Camera *camera = (Camera *) nativeCamera;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
reinterpret_cast<math::float3&>(*out) = camera->getUpVector();
reinterpret_cast<filament::math::float3&>(*out) = camera->getUpVector();
env->ReleaseFloatArrayElements(out_, out, 0);
}
@@ -144,7 +144,7 @@ Java_com_google_android_filament_Camera_nGetForwardVector(JNIEnv *env, jclass,
jlong nativeCamera, jfloatArray out_) {
Camera *camera = (Camera *) nativeCamera;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
reinterpret_cast<math::float3&>(*out) = camera->getForwardVector();
reinterpret_cast<filament::math::float3&>(*out) = camera->getForwardVector();
env->ReleaseFloatArrayElements(out_, out, 0);
}

View File

@@ -22,9 +22,9 @@ using namespace filament;
using namespace utils;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Engine_nCreateEngine(JNIEnv*, jclass,
Java_com_google_android_filament_Engine_nCreateEngine(JNIEnv*, jclass, jlong backend,
jlong sharedContext) {
return (jlong) Engine::create(Engine::Backend::OPENGL, nullptr, (void*) sharedContext);
return (jlong) Engine::create((Engine::Backend) backend, nullptr, (void*) sharedContext);
}
extern "C" JNIEXPORT void JNICALL
@@ -44,6 +44,13 @@ extern "C" {
extern void *getNativeWindow(JNIEnv *env, jclass, jobject surface);
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Engine_nGetBackend(JNIEnv* env,
jclass klass, jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) engine->getBackend();
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Engine_nCreateSwapChain(JNIEnv* env,
jclass klass, jlong nativeEngine, jobject surface, jlong flags) {
@@ -229,6 +236,14 @@ Java_com_google_android_filament_Engine_nDestroyTexture(JNIEnv*, jclass,
engine->destroy(texture);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Engine_nDestroyRenderTarget(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeTarget) {
Engine* engine = (Engine*) nativeEngine;
RenderTarget* target = (RenderTarget*) nativeTarget;
engine->destroy(target);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Engine_nDestroyEntity(JNIEnv*, jclass,
jlong nativeEngine, jint entity_) {

View File

@@ -22,11 +22,11 @@
#include <filament/IndexBuffer.h>
#include "CallbackUtils.h"
#include "NioUtils.h"
#include "common/CallbackUtils.h"
#include "common/NioUtils.h"
using namespace filament;
using namespace driver;
using namespace backend;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_IndexBuffer_nCreateBuilder(JNIEnv *env, jclass type) {
@@ -91,8 +91,7 @@ Java_com_google_android_filament_IndexBuffer_nSetBuffer(JNIEnv *env, jclass type
BufferDescriptor desc(data, sizeInBytes, &JniBufferCallback::invoke, callback);
indexBuffer->setBuffer(*engine, std::move(desc),
(uint32_t) destOffsetInBytes, (uint32_t) sizeInBytes);
indexBuffer->setBuffer(*engine, std::move(desc), (uint32_t) destOffsetInBytes);
return 0;
}

View File

@@ -17,6 +17,9 @@
#include <jni.h>
#include <filament/IndirectLight.h>
#include <filament/Texture.h>
#include <common/NioUtils.h>
#include <common/CallbackUtils.h>
using namespace filament;
@@ -53,7 +56,16 @@ Java_com_google_android_filament_IndirectLight_nIrradiance(JNIEnv* env, jclass,
jlong nativeBuilder, jint bands, jfloatArray sh_) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
builder->irradiance((uint8_t) bands, (const math::float3*) sh);
builder->irradiance((uint8_t) bands, (const filament::math::float3*) sh);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nRadiance(JNIEnv* env, jclass,
jlong nativeBuilder, jint bands, jfloatArray sh_) {
IndirectLight::Builder* builder = (IndirectLight::Builder*) nativeBuilder;
jfloat* sh = env->GetFloatArrayElements(sh_, NULL);
builder->radiance((uint8_t) bands, (const filament::math::float3*) sh);
env->ReleaseFloatArrayElements(sh_, sh, JNI_ABORT);
}
@@ -77,11 +89,9 @@ Java_com_google_android_filament_IndirectLight_nRotation(JNIEnv *, jclass, jlong
jfloat v0, jfloat v1, jfloat v2, jfloat v3, jfloat v4, jfloat v5, jfloat v6, jfloat v7,
jfloat v8) {
IndirectLight::Builder *builder = (IndirectLight::Builder *) nativeBuilder;
builder->rotation(math::mat3f{v0, v1, v2, v3, v4, v5, v6, v7, v8});
builder->rotation(filament::math::mat3f{v0, v1, v2, v3, v4, v5, v6, v7, v8});
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nSetIntensity(JNIEnv*, jclass,
jlong nativeIndirectLight, jfloat intensity) {
@@ -97,9 +107,19 @@ Java_com_google_android_filament_IndirectLight_nGetIntensity(JNIEnv*, jclass,
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nSetRotation(JNIEnv *env, jclass type,
jlong nativeIndirectLight, jfloat v0, jfloat v1, jfloat v2, jfloat v3, jfloat v4, jfloat v5,
jfloat v6, jfloat v7, jfloat v8) {
Java_com_google_android_filament_IndirectLight_nSetRotation(JNIEnv*, jclass,
jlong nativeIndirectLight, jfloat v0, jfloat v1, jfloat v2,
jfloat v3, jfloat v4, jfloat v5, jfloat v6, jfloat v7, jfloat v8) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
indirectLight->setRotation(math::mat3f{v0, v1, v2, v3, v4, v5, v6, v7, v8});
indirectLight->setRotation(filament::math::mat3f{v0, v1, v2, v3, v4, v5, v6, v7, v8});
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_IndirectLight_nGetRotation(JNIEnv* env, jclass,
jlong nativeIndirectLight, jfloatArray outRotation_) {
IndirectLight *indirectLight = (IndirectLight *) nativeIndirectLight;
jfloat *outRotation = env->GetFloatArrayElements(outRotation_, NULL);
*reinterpret_cast<filament::math::mat3f*>(outRotation) = indirectLight->getRotation();
env->ReleaseFloatArrayElements(outRotation_, outRotation, 0);
}

View File

@@ -64,10 +64,17 @@ Java_com_google_android_filament_LightManager_nBuilderCastShadows(JNIEnv *env, j
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_LightManager_nBuilderShadowOptions(JNIEnv *env, jclass type,
jlong nativeBuilder, jint mapSize, jfloat constantBias, jfloat normalBias, jfloat shadowFar) {
jlong nativeBuilder, jint mapSize, jfloat constantBias, jfloat normalBias, jfloat shadowFar,
jfloat shadowNearHint, jfloat shadowFarHint, jboolean stable) {
LightManager::Builder *builder = (LightManager::Builder *) nativeBuilder;
builder->shadowOptions(
LightManager::ShadowOptions{(uint32_t) mapSize, constantBias, normalBias, shadowFar});
LightManager::ShadowOptions{.mapSize = (uint32_t)mapSize,
.constantBias = constantBias,
.normalBias = normalBias,
.shadowFar = shadowFar,
.shadowNearHint = shadowNearHint,
.shadowFarHint = shadowFarHint,
.stable = (bool)stable});
}
extern "C" JNIEXPORT void JNICALL
@@ -174,7 +181,7 @@ Java_com_google_android_filament_LightManager_nGetPosition(JNIEnv *env, jclass t
jlong nativeLightManager, jint i, jfloatArray out_) {
LightManager *lm = (LightManager *) nativeLightManager;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
*reinterpret_cast<math::float3 *>(out) = lm->getPosition((LightManager::Instance) i);
*reinterpret_cast<filament::math::float3 *>(out) = lm->getPosition((LightManager::Instance) i);
env->ReleaseFloatArrayElements(out_, out, 0);
}
@@ -190,7 +197,7 @@ Java_com_google_android_filament_LightManager_nGetDirection(JNIEnv *env, jclass
jlong nativeLightManager, jint i, jfloatArray out_) {
LightManager *lm = (LightManager *) nativeLightManager;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
*reinterpret_cast<math::float3 *>(out) = lm->getDirection((LightManager::Instance) i);
*reinterpret_cast<filament::math::float3 *>(out) = lm->getDirection((LightManager::Instance) i);
env->ReleaseFloatArrayElements(out_, out, 0);
}
@@ -206,7 +213,7 @@ Java_com_google_android_filament_LightManager_nGetColor(JNIEnv *env, jclass type
jlong nativeLightManager, jint i, jfloatArray out_) {
LightManager *lm = (LightManager *) nativeLightManager;
jfloat *out = env->GetFloatArrayElements(out_, NULL);
*reinterpret_cast<math::float3 *>(out) = lm->getColor((LightManager::Instance) i);
*reinterpret_cast<filament::math::float3 *>(out) = lm->getColor((LightManager::Instance) i);
env->ReleaseFloatArrayElements(out_, out, 0);
}
@@ -292,4 +299,4 @@ Java_com_google_android_filament_LightManager_nGetHaloFalloff(JNIEnv *env, jclas
jlong nativeLightManager, jint i) {
LightManager *lm = (LightManager *) nativeLightManager;
return lm->getSunHaloFalloff((LightManager::Instance) i);
}
}

View File

@@ -18,7 +18,7 @@
#include <filament/Material.h>
#include "NioUtils.h"
#include "common/NioUtils.h"
using namespace filament;
@@ -140,6 +140,22 @@ Java_com_google_android_filament_Material_nGetMaskThreshold(JNIEnv*, jclass,
return material->getMaskThreshold();
}
extern "C"
JNIEXPORT jfloat JNICALL
Java_com_google_android_filament_Material_nGetSpecularAntiAliasingVariance(JNIEnv*, jclass,
jlong nativeMaterial) {
Material* material = (Material*) nativeMaterial;
return material->getSpecularAntiAliasingVariance();
}
extern "C"
JNIEXPORT jfloat JNICALL
Java_com_google_android_filament_Material_nGetSpecularAntiAliasingThreshold(JNIEnv*, jclass,
jlong nativeMaterial) {
Material* material = (Material*) nativeMaterial;
return material->getSpecularAntiAliasingThreshold();
}
extern "C"
JNIEXPORT jint JNICALL
Java_com_google_android_filament_Material_nGetParameterCount(JNIEnv*, jclass,

View File

@@ -27,6 +27,30 @@
#include <math/vec4.h>
using namespace filament;
using namespace filament::math;
enum BooleanElement {
BOOL,
BOOL2,
BOOL3,
BOOL4
};
enum IntElement {
INT,
INT2,
INT3,
INT4
};
enum FloatElement {
FLOAT,
FLOAT2,
FLOAT3,
FLOAT4,
MAT3,
MAT4
};
template<typename T>
static void setParameter(JNIEnv* env, jlong nativeMaterialInstance, jstring name_, T v) {
@@ -47,14 +71,14 @@ extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterBool2(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_, jboolean x, jboolean y) {
setParameter(env, nativeMaterialInstance, name_, math::bool2{x, y});
setParameter(env, nativeMaterialInstance, name_, bool2{x, y});
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterBool3(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_, jboolean x, jboolean y, jboolean z) {
setParameter(env, nativeMaterialInstance, name_, math::bool3{x, y, z});
setParameter(env, nativeMaterialInstance, name_, bool3{x, y, z});
}
extern "C"
@@ -62,7 +86,7 @@ JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterBool4(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_,
jboolean x, jboolean y, jboolean z, jboolean w) {
setParameter(env, nativeMaterialInstance, name_, math::bool4{x, y, z, w});
setParameter(env, nativeMaterialInstance, name_, bool4{x, y, z, w});
}
extern "C"
@@ -76,14 +100,14 @@ extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterInt2(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_, jint x, jint y) {
setParameter(env, nativeMaterialInstance, name_, math::int2{x, y});
setParameter(env, nativeMaterialInstance, name_, int2{x, y});
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterInt3(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_, jint x, jint y, jint z) {
setParameter(env, nativeMaterialInstance, name_, math::int3{x, y, z});
setParameter(env, nativeMaterialInstance, name_, int3{x, y, z});
}
extern "C"
@@ -91,7 +115,7 @@ JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterInt4(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_,
jint x, jint y, jint z, jint w) {
setParameter(env, nativeMaterialInstance, name_, math::int4{x, y, z, w});
setParameter(env, nativeMaterialInstance, name_, int4{x, y, z, w});
}
extern "C"
@@ -105,14 +129,14 @@ extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterFloat2(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_, jfloat x, jfloat y) {
setParameter(env, nativeMaterialInstance, name_, math::float2{x, y});
setParameter(env, nativeMaterialInstance, name_, float2{x, y});
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterFloat3(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_, jfloat x, jfloat y, jfloat z) {
setParameter(env, nativeMaterialInstance, name_, math::float3{x, y, z});
setParameter(env, nativeMaterialInstance, name_, float3{x, y, z});
}
extern "C"
@@ -120,7 +144,7 @@ JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetParameterFloat4(JNIEnv *env, jclass,
jlong nativeMaterialInstance, jstring name_,
jfloat x, jfloat y, jfloat z, jfloat w) {
setParameter(env, nativeMaterialInstance, name_, math::float4{x, y, z, w});
setParameter(env, nativeMaterialInstance, name_, float4{x, y, z, w});
}
extern "C"
@@ -131,9 +155,26 @@ Java_com_google_android_filament_MaterialInstance_nSetBooleanParameterArray(JNIE
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
const char* name = env->GetStringUTFChars(name_, 0);
size_t size = (size_t) element + 1;
jboolean* v = env->GetBooleanArrayElements(v_, NULL);
instance->setParameter(name, (bool*) (v + offset * size), (size_t) (count * size));
// NOTE: In C++, bool has an implementation-defined size. Here we assume
// it has the same size as jboolean, which is 1 byte.
switch ((BooleanElement) element) {
case BOOL:
instance->setParameter(name, ((const bool*) v) + offset, count);
break;
case BOOL2:
instance->setParameter(name, ((const bool2*) v) + offset, count);
break;
case BOOL3:
instance->setParameter(name, ((const bool3*) v) + offset, count);
break;
case BOOL4:
instance->setParameter(name, ((const bool4*) v) + offset, count);
break;
}
env->ReleaseBooleanArrayElements(v_, v, 0);
env->ReleaseStringUTFChars(name_, name);
@@ -147,10 +188,23 @@ Java_com_google_android_filament_MaterialInstance_nSetIntParameterArray(JNIEnv *
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
const char* name = env->GetStringUTFChars(name_, 0);
size_t size = (size_t) element + 1;
jint* v = env->GetIntArrayElements(v_, NULL);
instance->setParameter(name, reinterpret_cast<int32_t*>(v + offset * size),
(size_t) (count * size));
switch ((IntElement) element) {
case INT:
instance->setParameter(name, ((const int32_t*) v) + offset, count);
break;
case INT2:
instance->setParameter(name, ((const int2*) v) + offset, count);
break;
case INT3:
instance->setParameter(name, ((const int3*) v) + offset, count);
break;
case INT4:
instance->setParameter(name, ((const int4*) v) + offset, count);
break;
}
env->ReleaseIntArrayElements(v_, v, 0);
env->ReleaseStringUTFChars(name_, name);
@@ -164,16 +218,29 @@ Java_com_google_android_filament_MaterialInstance_nSetFloatParameterArray(JNIEnv
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
const char* name = env->GetStringUTFChars(name_, 0);
size_t size = (size_t) element + 1;
if (size == 5) {
// mat3
size = 9;
} else if (size == 6) {
// mat4
size = 16;
}
jfloat* v = env->GetFloatArrayElements(v_, NULL);
instance->setParameter(name, v + offset * size, (size_t) (count * size));
switch ((FloatElement) element) {
case FLOAT:
instance->setParameter(name, ((const float*) v) + offset, count);
break;
case FLOAT2:
instance->setParameter(name, ((const float2*) v) + offset, count);
break;
case FLOAT3:
instance->setParameter(name, ((const float3*) v) + offset, count);
break;
case FLOAT4:
instance->setParameter(name, ((const float4*) v) + offset, count);
break;
case MAT3:
instance->setParameter(name, ((const mat3f*) v) + offset, count);
break;
case MAT4:
instance->setParameter(name, ((const mat4f*) v) + offset, count);
break;
}
env->ReleaseFloatArrayElements(v_, v, 0);
env->ReleaseStringUTFChars(name_, name);
@@ -209,3 +276,43 @@ Java_com_google_android_filament_MaterialInstance_nUnsetScissor(
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
instance->unsetScissor();
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetPolygonOffset(JNIEnv*,
jclass, jlong nativeMaterialInstance, jfloat scale, jfloat constant) {
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
instance->setPolygonOffset(scale, constant);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetMaskThreshold(JNIEnv*,
jclass, jlong nativeMaterialInstance, jfloat threshold) {
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
instance->setMaskThreshold(threshold);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetSpecularAntiAliasingVariance(JNIEnv*,
jclass, jlong nativeMaterialInstance, jfloat variance) {
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
instance->setSpecularAntiAliasingVariance(variance);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetSpecularAntiAliasingThreshold(JNIEnv*,
jclass, jlong nativeMaterialInstance, jfloat threshold) {
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
instance->setSpecularAntiAliasingThreshold(threshold);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_MaterialInstance_nSetDoubleSided(JNIEnv*,
jclass, jlong nativeMaterialInstance, jboolean doubleSided) {
MaterialInstance* instance = (MaterialInstance*) nativeMaterialInstance;
instance->setDoubleSided(doubleSided);
}

View File

@@ -19,7 +19,7 @@
#include <math/mat3.h>
#include <math/quat.h>
using namespace math;
using namespace filament::math;
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_MathUtils_nPackTangentFrame(JNIEnv *env, jclass,

View File

@@ -0,0 +1,83 @@
/*
* Copyright (C) 2019 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 <jni.h>
#include <functional>
#include <stdlib.h>
#include <string.h>
#include <filament/RenderTarget.h>
using namespace filament;
using namespace backend;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_RenderTarget_nCreateBuilder(JNIEnv *env, jclass type) {
return (jlong) new RenderTarget::Builder();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderTarget_nDestroyBuilder(JNIEnv *env, jclass type,
jlong nativeBuilder) {
RenderTarget::Builder* builder = (RenderTarget::Builder*) nativeBuilder;
delete builder;
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderTarget_nBuilderTexture(JNIEnv *env, jclass type,
jlong nativeBuilder, jlong attachment, jlong nativeTexture) {
RenderTarget::Builder* builder = (RenderTarget::Builder*) nativeBuilder;
Texture* texture = (Texture*) nativeTexture;
builder->texture(RenderTarget::AttachmentPoint(attachment), texture);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderTarget_nBuilderMipLevel(JNIEnv *env, jclass type,
jlong nativeBuilder, jlong attachment, jint level) {
RenderTarget::Builder* builder = (RenderTarget::Builder*) nativeBuilder;
builder->mipLevel(RenderTarget::AttachmentPoint(attachment), level);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderTarget_nBuilderFace(JNIEnv *env, jclass type,
jlong nativeBuilder, jlong attachment, jint face) {
RenderTarget::Builder* builder = (RenderTarget::Builder*) nativeBuilder;
RenderTarget::CubemapFace cubeface = (RenderTarget::CubemapFace) face;
builder->face(RenderTarget::AttachmentPoint(attachment), cubeface);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderTarget_nBuilderLayer(JNIEnv *env, jclass type,
jlong nativeBuilder, jlong attachment, jint layer) {
RenderTarget::Builder* builder = (RenderTarget::Builder*) nativeBuilder;
builder->layer(RenderTarget::AttachmentPoint(attachment), layer);
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_RenderTarget_nBuilderBuild(JNIEnv *env, jclass type,
jlong nativeBuilder, jlong nativeEngine) {
RenderTarget::Builder* builder = (RenderTarget::Builder*) nativeBuilder;
Engine *engine = (Engine *) nativeEngine;
return (jlong) builder->build(*engine);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_RenderTarget_nGetMipLevel(JNIEnv *env, jclass type,
jlong nativeTarget, jlong attachment) {
RenderTarget* target = (RenderTarget*) nativeTarget;
return (jint) target->getMipLevel(RenderTarget::AttachmentPoint(attachment));
}

View File

@@ -18,7 +18,7 @@
#include <jni.h>
#include <filament/RenderableManager.h>
#include "NioUtils.h"
#include "common/NioUtils.h"
using namespace filament;
using namespace utils;
@@ -197,7 +197,7 @@ Java_com_google_android_filament_RenderableManager_nSetBonesAsMatrices(JNIEnv* e
return -1;
}
rm->setBones((RenderableManager::Instance)i,
static_cast<math::mat4f const *>(data), (size_t)boneCount, (size_t)offset);
static_cast<filament::math::mat4f const *>(data), (size_t)boneCount, (size_t)offset);
return 0;
}
@@ -277,8 +277,8 @@ Java_com_google_android_filament_RenderableManager_nGetAxisAlignedBoundingBox(JN
jfloat *center = env->GetFloatArrayElements(center_, NULL);
jfloat *halfExtent = env->GetFloatArrayElements(halfExtent_, NULL);
Box const &aabb = rm->getAxisAlignedBoundingBox((RenderableManager::Instance) i);
*reinterpret_cast<math::float3 *>(center) = aabb.center;
*reinterpret_cast<math::float3 *>(halfExtent) = aabb.halfExtent;
*reinterpret_cast<filament::math::float3 *>(center) = aabb.center;
*reinterpret_cast<filament::math::float3 *>(halfExtent) = aabb.halfExtent;
env->ReleaseFloatArrayElements(center_, center, 0);
env->ReleaseFloatArrayElements(halfExtent_, halfExtent, 0);
}
@@ -299,6 +299,21 @@ Java_com_google_android_filament_RenderableManager_nSetMaterialInstanceAt(JNIEnv
materialInstance);
}
extern "C" JNIEXPORT long JNICALL
Java_com_google_android_filament_RenderableManager_nGetMaterialInstanceAt(JNIEnv*, jclass,
jlong nativeRenderableManager, jint i, jint primitiveIndex) {
RenderableManager *rm = (RenderableManager *) nativeRenderableManager;
return (long) rm->getMaterialInstanceAt((RenderableManager::Instance) i, (size_t) primitiveIndex);
}
extern "C" JNIEXPORT long JNICALL
Java_com_google_android_filament_RenderableManager_nGetMaterialAt(JNIEnv*, jclass,
jlong nativeRenderableManager, jint i, jint primitiveIndex) {
RenderableManager *rm = (RenderableManager *) nativeRenderableManager;
MaterialInstance *mi = rm->getMaterialInstanceAt((RenderableManager::Instance) i, (size_t) primitiveIndex);
return (long) mi->getMaterial();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_RenderableManager_nSetGeometryAt__JIIIJJII(JNIEnv*,
jclass, jlong nativeRenderableManager, jint i, jint primitiveIndex, jint primitiveType,

View File

@@ -20,13 +20,13 @@
#include <filament/Engine.h>
#include <filament/Renderer.h>
#include <filament/Viewport.h>
#include <filament/driver/PixelBufferDescriptor.h>
#include <backend/PixelBufferDescriptor.h>
#include "CallbackUtils.h"
#include "NioUtils.h"
#include "common/CallbackUtils.h"
#include "common/NioUtils.h"
using namespace filament;
using namespace driver;
using namespace backend;
extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Renderer_nBeginFrame(JNIEnv *, jclass, jlong nativeRenderer,
@@ -51,16 +51,16 @@ Java_com_google_android_filament_Renderer_nRender(JNIEnv *, jclass, jlong native
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Renderer_nMirrorFrame(JNIEnv *, jclass, jlong nativeRenderer,
Java_com_google_android_filament_Renderer_nCopyFrame(JNIEnv *, jclass, jlong nativeRenderer,
jlong nativeDstSwapChain,
jint dstLeft, jint dstBottom, jint dstWidth, jint dstHeight,
jint srcLeft, jint srcBottom, jint srcWidth, jint srcHeight,
jint flags) {
Renderer *renderer = (Renderer *) nativeRenderer;
SwapChain *dstSwapChain = (SwapChain *) nativeDstSwapChain;
const Viewport dstViewport {dstLeft, dstBottom, (uint32_t) dstWidth, (uint32_t) dstHeight};
const Viewport srcViewport {srcLeft, srcBottom, (uint32_t) srcWidth, (uint32_t) srcHeight};
renderer->mirrorFrame(dstSwapChain, dstViewport, srcViewport, (uint32_t) flags);
const filament::Viewport dstViewport {dstLeft, dstBottom, (uint32_t) dstWidth, (uint32_t) dstHeight};
const filament::Viewport srcViewport {srcLeft, srcBottom, (uint32_t) srcWidth, (uint32_t) srcHeight};
renderer->copyFrame(dstSwapChain, dstViewport, srcViewport, (uint32_t) flags);
}
extern "C" JNIEXPORT jint JNICALL
@@ -87,8 +87,8 @@ Java_com_google_android_filament_Renderer_nReadPixels(JNIEnv *env, jclass,
void *buffer = nioBuffer.getData();
auto *callback = JniBufferCallback::make(engine, env, handler, runnable, std::move(nioBuffer));
PixelBufferDescriptor desc(buffer, sizeInBytes, (driver::PixelDataFormat) format,
(driver::PixelDataType) type, (uint8_t) alignment, (uint32_t) left, (uint32_t) top,
PixelBufferDescriptor desc(buffer, sizeInBytes, (backend::PixelDataFormat) format,
(backend::PixelDataType) type, (uint8_t) alignment, (uint32_t) left, (uint32_t) top,
(uint32_t) stride, &JniBufferCallback::invoke, callback);
renderer->readPixels(uint32_t(xoffset), uint32_t(yoffset), uint32_t(width), uint32_t(height),
@@ -96,3 +96,15 @@ Java_com_google_android_filament_Renderer_nReadPixels(JNIEnv *env, jclass,
return 0;
}
extern "C" JNIEXPORT jdouble JNICALL
Java_com_google_android_filament_Renderer_nGetUserTime(JNIEnv*, jclass, jlong nativeRenderer) {
Renderer *renderer = (Renderer *) nativeRenderer;
return renderer->getUserTime();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Renderer_nResetUserTime(JNIEnv*, jclass, jlong nativeRenderer) {
Renderer *renderer = (Renderer *) nativeRenderer;
renderer->resetUserTime();
}

View File

@@ -44,6 +44,15 @@ Java_com_google_android_filament_Scene_nAddEntity(JNIEnv *env, jclass type, jlon
scene->addEntity((Entity&) entity);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Scene_nAddEntities(JNIEnv *env, jclass type, jlong nativeScene,
jintArray entities) {
Scene* scene = (Scene*) nativeScene;
Entity* nativeEntities = (Entity*) env->GetIntArrayElements(entities, nullptr);
scene->addEntities(nativeEntities, env->GetArrayLength(entities));
env->ReleaseIntArrayElements(entities, (jint*) nativeEntities, JNI_ABORT);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Scene_nRemove(JNIEnv *env, jclass type, jlong nativeScene,
jint entity) {

View File

@@ -19,13 +19,13 @@
#include <jni.h>
#include <filament/Stream.h>
#include <filament/driver/PixelBufferDescriptor.h>
#include <backend/PixelBufferDescriptor.h>
#include "NioUtils.h"
#include "CallbackUtils.h"
#include "common/NioUtils.h"
#include "common/CallbackUtils.h"
using namespace filament;
using namespace driver;
using namespace backend;
class StreamBuilder {
public:
@@ -145,8 +145,8 @@ Java_com_google_android_filament_Stream_nReadPixels(JNIEnv *env, jclass,
void *buffer = nioBuffer.getData();
auto *callback = JniBufferCallback::make(engine, env, handler, runnable, std::move(nioBuffer));
PixelBufferDescriptor desc(buffer, sizeInBytes, (driver::PixelDataFormat) format,
(driver::PixelDataType) type, (uint8_t) alignment, (uint32_t) left, (uint32_t) top,
PixelBufferDescriptor desc(buffer, sizeInBytes, (backend::PixelDataFormat) format,
(backend::PixelDataType) type, (uint8_t) alignment, (uint32_t) left, (uint32_t) top,
(uint32_t) stride, &JniBufferCallback::invoke, callback);
stream->readPixels(uint32_t(xoffset), uint32_t(yoffset), uint32_t(width), uint32_t(height),
@@ -154,3 +154,9 @@ Java_com_google_android_filament_Stream_nReadPixels(JNIEnv *env, jclass,
return 0;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Stream_nGetTimestamp(JNIEnv*, jclass, jlong nativeStream) {
Stream *stream = (Stream *) nativeStream;
return stream->getTimestamp();
}

View File

@@ -19,25 +19,31 @@
#include <algorithm>
#include <functional>
#include <filament/driver/BufferDescriptor.h>
#ifdef ANDROID
#include <android/bitmap.h>
#endif
#include <backend/BufferDescriptor.h>
#include <filament/Engine.h>
#include <filament/Stream.h>
#include <filament/Texture.h>
#include "CallbackUtils.h"
#include "NioUtils.h"
#include "common/CallbackUtils.h"
#include "common/NioUtils.h"
using namespace filament;
using namespace driver;
using namespace backend;
static size_t getTextureDataSize(const Texture *texture, size_t level,
Texture::Format format, Texture::Type type, size_t stride, size_t alignment) {
// Zero stride implies tight row-to-row packing.
stride = stride == 0 ? texture->getWidth(level) : std::max(size_t(1), stride >> level);
return Texture::computeTextureDataSize(format, type,
std::max(size_t(1), stride >> level), texture->getHeight(level), alignment);
stride, texture->getHeight(level), alignment);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Texture_nIsTextureFormatSupported(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nIsTextureFormatSupported(JNIEnv*, jclass,
jlong nativeEngine, jint internalFormat) {
Engine *engine = (Engine *) nativeEngine;
return (jboolean) Texture::isTextureFormatSupported(*engine,
@@ -47,68 +53,68 @@ Java_com_google_android_filament_Texture_nIsTextureFormatSupported(JNIEnv *env,
// Texture::Builder...
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Texture_nCreateBuilder(JNIEnv *env, jclass type) {
Java_com_google_android_filament_Texture_nCreateBuilder(JNIEnv*, jclass) {
return (jlong) new Texture::Builder();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nDestroyBuilder(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nDestroyBuilder(JNIEnv*, jclass,
jlong nativeBuilder) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
delete builder;
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nBuilderWidth(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nBuilderWidth(JNIEnv*, jclass,
jlong nativeBuilder, jint width) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
builder->width((uint32_t) width);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nBuilderHeight(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nBuilderHeight(JNIEnv*, jclass,
jlong nativeBuilder, jint height) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
builder->height((uint32_t) height);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nBuilderDepth(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nBuilderDepth(JNIEnv*, jclass,
jlong nativeBuilder, jint depth) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
builder->depth((uint32_t) depth);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nBuilderLevels(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nBuilderLevels(JNIEnv*, jclass,
jlong nativeBuilder, jint levels) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
builder->levels((uint8_t) levels);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nBuilderSampler(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nBuilderSampler(JNIEnv*, jclass,
jlong nativeBuilder, jint sampler) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
builder->sampler((Texture::Sampler) sampler);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nBuilderFormat(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nBuilderFormat(JNIEnv*, jclass,
jlong nativeBuilder, jint format) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
builder->format((Texture::InternalFormat) format);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nBuilderRgbm(JNIEnv *env, jclass type,
jlong nativeBuilder, jboolean enable) {
Java_com_google_android_filament_Texture_nBuilderUsage(JNIEnv*, jclass,
jlong nativeBuilder, jint flags) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
builder->rgbm(enable);
builder->usage((Texture::Usage) flags);
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_Texture_nBuilderBuild(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nBuilderBuild(JNIEnv*, jclass,
jlong nativeBuilder, jlong nativeEngine) {
Texture::Builder *builder = (Texture::Builder *) nativeBuilder;
Engine *engine = (Engine *) nativeEngine;
@@ -118,60 +124,54 @@ Java_com_google_android_filament_Texture_nBuilderBuild(JNIEnv *env, jclass type,
// Texture...
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nGetWidth(JNIEnv *env, jclass type, jlong nativeTexture,
Java_com_google_android_filament_Texture_nGetWidth(JNIEnv*, jclass, jlong nativeTexture,
jint level) {
Texture *texture = (Texture *) nativeTexture;
return (jint) texture->getWidth((size_t) level);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nGetHeight(JNIEnv *env, jclass type, jlong nativeTexture,
Java_com_google_android_filament_Texture_nGetHeight(JNIEnv*, jclass, jlong nativeTexture,
jint level) {
Texture *texture = (Texture *) nativeTexture;
return (jint) texture->getHeight((size_t) level);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nGetDepth(JNIEnv *env, jclass type, jlong nativeTexture,
Java_com_google_android_filament_Texture_nGetDepth(JNIEnv*, jclass, jlong nativeTexture,
jint level) {
Texture *texture = (Texture *) nativeTexture;
return (jint) texture->getDepth((size_t) level);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nGetLevels(JNIEnv *env, jclass type, jlong nativeTexture) {
Java_com_google_android_filament_Texture_nGetLevels(JNIEnv*, jclass, jlong nativeTexture) {
Texture *texture = (Texture *) nativeTexture;
return (jint) texture->getLevels();
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nGetTarget(JNIEnv *env, jclass type, jlong nativeTexture) {
Java_com_google_android_filament_Texture_nGetTarget(JNIEnv*, jclass, jlong nativeTexture) {
Texture *texture = (Texture *) nativeTexture;
return (jint) texture->getTarget();
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nGetInternalFormat(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nGetInternalFormat(JNIEnv*, jclass,
jlong nativeTexture) {
Texture *texture = (Texture *) nativeTexture;
return (jint) texture->getFormat();
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Texture_nGetRgbm(JNIEnv *env, jclass type, jlong nativeTexture) {
Texture *texture = (Texture *) nativeTexture;
return texture->isRgbm();
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nSetImage(JNIEnv *env, jclass type_, jlong nativeTexture,
Java_com_google_android_filament_Texture_nSetImage(JNIEnv* env, jclass, jlong nativeTexture,
jlong nativeEngine, jint level, jint xoffset, jint yoffset, jint width, jint height,
jobject storage, jint remaining,
jint left, jint bottom, jint type, jint alignment,
jint stride, jint format,
jobject handler, jobject runnable) {
Texture *texture = (Texture *) nativeTexture;
Engine *engine = (Engine *) nativeEngine;
Texture* texture = (Texture*) nativeTexture;
Engine* engine = (Engine*) nativeEngine;
size_t sizeInBytes = getTextureDataSize(texture, (size_t) level, (Texture::Format) format,
(Texture::Type) type, (size_t) stride, (size_t) alignment);
@@ -185,8 +185,8 @@ Java_com_google_android_filament_Texture_nSetImage(JNIEnv *env, jclass type_, jl
void *buffer = nioBuffer.getData();
auto *callback = JniBufferCallback::make(engine, env, handler, runnable, std::move(nioBuffer));
Texture::PixelBufferDescriptor desc(buffer, sizeInBytes, (driver::PixelDataFormat) format,
(driver::PixelDataType) type, (uint8_t) alignment, (uint32_t) left, (uint32_t) bottom,
Texture::PixelBufferDescriptor desc(buffer, sizeInBytes, (backend::PixelDataFormat) format,
(backend::PixelDataType) type, (uint8_t) alignment, (uint32_t) left, (uint32_t) bottom,
(uint32_t) stride, &JniBufferCallback::invoke, callback);
texture->setImage(*engine, (size_t) level, (uint32_t) xoffset, (uint32_t) yoffset,
@@ -196,9 +196,9 @@ Java_com_google_android_filament_Texture_nSetImage(JNIEnv *env, jclass type_, jl
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nSetImageCompressed(JNIEnv *env, jclass type_, jlong nativeTexture,
jlong nativeEngine, jint level, jint xoffset, jint yoffset, jint width, jint height,
jobject storage, jint remaining,
Java_com_google_android_filament_Texture_nSetImageCompressed(JNIEnv *env, jclass,
jlong nativeTexture, jlong nativeEngine, jint level, jint xoffset, jint yoffset,
jint width, jint height, jobject storage, jint remaining,
jint left, jint bottom, jint type, jint alignment,
jint compressedSizeInBytes, jint compressedFormat,
jobject handler, jobject runnable) {
@@ -217,7 +217,7 @@ Java_com_google_android_filament_Texture_nSetImageCompressed(JNIEnv *env, jclass
auto *callback = JniBufferCallback::make(engine, env, handler, runnable, std::move(nioBuffer));
Texture::PixelBufferDescriptor desc(buffer, sizeInBytes,
(driver::CompressedPixelDataType) compressedFormat, (uint32_t) compressedSizeInBytes,
(backend::CompressedPixelDataType) compressedFormat, (uint32_t) compressedSizeInBytes,
&JniBufferCallback::invoke, callback);
texture->setImage(*engine, (size_t) level, (uint32_t) xoffset, (uint32_t) yoffset,
@@ -227,7 +227,7 @@ Java_com_google_android_filament_Texture_nSetImageCompressed(JNIEnv *env, jclass
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nSetImageCubemap(JNIEnv *env, jclass type_,
Java_com_google_android_filament_Texture_nSetImageCubemap(JNIEnv *env, jclass,
jlong nativeTexture, jlong nativeEngine, jint level, jobject storage, jint remaining,
jint left, jint bottom, jint type, jint alignment, jint stride, jint format,
jintArray faceOffsetsInBytes_,
@@ -252,8 +252,8 @@ Java_com_google_android_filament_Texture_nSetImageCubemap(JNIEnv *env, jclass ty
void *buffer = nioBuffer.getData();
auto *callback = JniBufferCallback::make(engine, env, handler, runnable, std::move(nioBuffer));
Texture::PixelBufferDescriptor desc(buffer, sizeInBytes, (driver::PixelDataFormat) format,
(driver::PixelDataType) type, (uint8_t) alignment, (uint32_t) left, (uint32_t) bottom,
Texture::PixelBufferDescriptor desc(buffer, sizeInBytes, (backend::PixelDataFormat) format,
(backend::PixelDataType) type, (uint8_t) alignment, (uint32_t) left, (uint32_t) bottom,
(uint32_t) stride, &JniBufferCallback::invoke, callback);
texture->setImage(*engine, (size_t) level, std::move(desc), faceOffsets);
@@ -262,7 +262,7 @@ Java_com_google_android_filament_Texture_nSetImageCubemap(JNIEnv *env, jclass ty
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nSetImageCubemapCompressed(JNIEnv *env, jclass type_,
Java_com_google_android_filament_Texture_nSetImageCubemapCompressed(JNIEnv *env, jclass,
jlong nativeTexture, jlong nativeEngine, jint level, jobject storage, jint remaining,
jint left, jint bottom, jint type, jint alignment,
jint compressedSizeInBytes, jint compressedFormat, jintArray faceOffsetsInBytes_,
@@ -288,7 +288,7 @@ Java_com_google_android_filament_Texture_nSetImageCubemapCompressed(JNIEnv *env,
auto *callback = JniBufferCallback::make(engine, env, handler, runnable, std::move(nioBuffer));
Texture::PixelBufferDescriptor desc(buffer, sizeInBytes,
(driver::CompressedPixelDataType) compressedFormat, (uint32_t) compressedSizeInBytes,
(backend::CompressedPixelDataType) compressedFormat, (uint32_t) compressedSizeInBytes,
&JniBufferCallback::invoke, callback);
texture->setImage(*engine, (size_t) level, std::move(desc), faceOffsets);
@@ -297,14 +297,15 @@ Java_com_google_android_filament_Texture_nSetImageCubemapCompressed(JNIEnv *env,
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nSetExternalImage(JNIEnv*, jclass, jlong nativeTexture, jlong nativeEngine, jlong eglImage) {
Java_com_google_android_filament_Texture_nSetExternalImage(JNIEnv*, jclass, jlong nativeTexture,
jlong nativeEngine, jlong eglImage) {
Texture *texture = (Texture *) nativeTexture;
Engine *engine = (Engine *) nativeEngine;
texture->setExternalImage(*engine, (void*)eglImage);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nSetExternalStream(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nSetExternalStream(JNIEnv*, jclass,
jlong nativeTexture, jlong nativeEngine, jlong nativeStream) {
Texture *texture = (Texture *) nativeTexture;
Engine *engine = (Engine *) nativeEngine;
@@ -313,7 +314,7 @@ Java_com_google_android_filament_Texture_nSetExternalStream(JNIEnv *env, jclass
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_Texture_nGenerateMipmaps(JNIEnv *env, jclass type,
Java_com_google_android_filament_Texture_nGenerateMipmaps(JNIEnv*, jclass,
jlong nativeTexture, jlong nativeEngine) {
Texture *texture = (Texture *) nativeTexture;
Engine *engine = (Engine *) nativeEngine;
@@ -323,9 +324,155 @@ Java_com_google_android_filament_Texture_nGenerateMipmaps(JNIEnv *env, jclass ty
extern "C"
JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_Texture_nIsStreamValidForTexture(JNIEnv*, jclass,
jlong nativeTexture, jlong nativeStream) {
jlong nativeTexture, jlong) {
Texture* texture = (Texture*) nativeTexture;
Stream* stream = (Stream*) nativeStream;
return (jboolean) (texture->getTarget() == SamplerType::SAMPLER_EXTERNAL);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_Texture_nGeneratePrefilterMipmap(JNIEnv *env, jclass,
jlong nativeTexture, jlong nativeEngine, jint width, jint height,
jobject storage, jint remaining, jint left,
jint top, jint type, jint alignment, jint stride, jint format,
jintArray faceOffsetsInBytes_, jobject handler, jobject runnable, jint sampleCount,
jboolean mirror) {
Texture *texture = (Texture *) nativeTexture;
Engine *engine = (Engine *) nativeEngine;
jint *faceOffsetsInBytes = env->GetIntArrayElements(faceOffsetsInBytes_, NULL);
Texture::FaceOffsets faceOffsets;
std::copy_n(faceOffsetsInBytes, 6, faceOffsets.offsets);
env->ReleaseIntArrayElements(faceOffsetsInBytes_, faceOffsetsInBytes, JNI_ABORT);
stride = stride ? stride : width;
size_t sizeInBytes = 6 *
Texture::computeTextureDataSize((Texture::Format) format, (Texture::Type) type,
(size_t) stride, (size_t) height, (size_t) alignment);
AutoBuffer nioBuffer(env, storage, 0);
if (sizeInBytes > (remaining << nioBuffer.getShift())) {
// BufferOverflowException
return -1;
}
void *buffer = nioBuffer.getData();
auto *callback = JniBufferCallback::make(engine, env, handler, runnable, std::move(nioBuffer));
Texture::PixelBufferDescriptor desc(buffer, sizeInBytes, (backend::PixelDataFormat) format,
(backend::PixelDataType) type, (uint8_t) alignment, (uint32_t)0, (uint32_t)0,
(uint32_t) stride, &JniBufferCallback::invoke, callback);
Texture::PrefilterOptions options;
options.sampleCount = sampleCount;
options.mirror = mirror;
texture->generatePrefilterMipmap(*engine, std::move(desc), faceOffsets, &options);
return 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// ANDROID SPECIFIC BITS
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef ANDROID
#define BITMAP_CONFIG_ALPHA_8 0
#define BITMAP_CONFIG_RGB_565 1
#define BITMAP_CONFIG_RGBA_4444 2
#define BITMAP_CONFIG_RGBA_8888 3
#define BITMAP_CONFIG_RGBA_F16 4
#define BITMAP_CONFIG_HARDWARE 5
class AutoBitmap {
public:
AutoBitmap(JNIEnv* env, jobject bitmap) noexcept
: mEnv(env)
, mBitmap(env->NewGlobalRef(bitmap))
{
if (mBitmap) {
AndroidBitmap_getInfo(mEnv, mBitmap, &mInfo);
AndroidBitmap_lockPixels(mEnv, mBitmap, &mData);
}
}
~AutoBitmap() noexcept {
if (mBitmap) {
AndroidBitmap_unlockPixels(mEnv, mBitmap);
mEnv->DeleteGlobalRef(mBitmap);
}
}
AutoBitmap(AutoBitmap &&rhs) noexcept {
mEnv = rhs.mEnv;
std::swap(mData, rhs.mData);
std::swap(mBitmap, rhs.mBitmap);
std::swap(mInfo, rhs.mInfo);
}
void* getData() const noexcept {
return mData;
}
size_t getSizeInBytes() const noexcept {
return mInfo.height * mInfo.stride;
}
PixelDataFormat getFormat(int format) const noexcept {
// AndroidBitmapInfo does not capture the HARDWARE and RGBA_F16 formats
// so we switch on the Bitmap.Config values directly
switch (format) {
case BITMAP_CONFIG_ALPHA_8: return PixelDataFormat::ALPHA;
case BITMAP_CONFIG_RGB_565: return PixelDataFormat::RGB;
default: return PixelDataFormat::RGBA;
}
}
PixelDataType getType(int format) const noexcept {
switch (format) {
case BITMAP_CONFIG_RGBA_F16: return PixelDataType::HALF;
default: return PixelDataType::UBYTE;
}
}
static void invoke(void* buffer, size_t n, void* user) {
AutoBitmap* data = reinterpret_cast<AutoBitmap*>(user);
data->~AutoBitmap();
}
static AutoBitmap* make(Engine* engine, JNIEnv* env, jobject bitmap) {
void* that = engine->streamAlloc(sizeof(AutoBitmap), alignof(AutoBitmap));
return new (that) AutoBitmap(env, bitmap);
}
private:
JNIEnv* mEnv;
void* mData = nullptr;
jobject mBitmap = nullptr;
AndroidBitmapInfo mInfo;
};
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_android_TextureHelper_nSetBitmap(JNIEnv* env, jclass,
jlong nativeTexture, jlong nativeEngine, jint level, jint xoffset, jint yoffset,
jint width, jint height, jobject bitmap, jint format) {
Texture* texture = (Texture*) nativeTexture;
Engine *engine = (Engine *) nativeEngine;
auto* autoBitmap = AutoBitmap::make(engine, env, bitmap);
Texture::PixelBufferDescriptor desc(
autoBitmap->getData(),
autoBitmap->getSizeInBytes(),
autoBitmap->getFormat(format),
autoBitmap->getType(format),
&AutoBitmap::invoke, autoBitmap);
texture->setImage(*engine, (size_t) level,
(uint32_t) xoffset, (uint32_t) yoffset,
(uint32_t) width, (uint32_t) height,
std::move(desc));
}
#endif

View File

@@ -59,7 +59,7 @@ Java_com_google_android_filament_TransformManager_nCreateArray(JNIEnv* env,
if (localTransform_) {
jfloat *localTransform = env->GetFloatArrayElements(localTransform_, NULL);
tm->create(entity, (TransformManager::Instance) parent,
*reinterpret_cast<const math::mat4f *>(localTransform));
*reinterpret_cast<const filament::math::mat4f *>(localTransform));
env->ReleaseFloatArrayElements(localTransform_, localTransform, JNI_ABORT);
} else {
tm->create(entity, (TransformManager::Instance) parent);
@@ -90,7 +90,7 @@ Java_com_google_android_filament_TransformManager_nSetTransform(JNIEnv* env,
TransformManager* tm = (TransformManager*) nativeTransformManager;
jfloat *localTransform = env->GetFloatArrayElements(localTransform_, NULL);
tm->setTransform((TransformManager::Instance) i,
*reinterpret_cast<const math::mat4f *>(localTransform));
*reinterpret_cast<const filament::math::mat4f *>(localTransform));
env->ReleaseFloatArrayElements(localTransform_, localTransform, JNI_ABORT);
}
@@ -100,7 +100,7 @@ Java_com_google_android_filament_TransformManager_nGetTransform(JNIEnv* env,
jfloatArray outLocalTransform_) {
TransformManager* tm = (TransformManager*) nativeTransformManager;
jfloat *outLocalTransform = env->GetFloatArrayElements(outLocalTransform_, NULL);
*reinterpret_cast<math::mat4f *>(outLocalTransform) = tm->getTransform(
*reinterpret_cast<filament::math::mat4f *>(outLocalTransform) = tm->getTransform(
(TransformManager::Instance) i);
env->ReleaseFloatArrayElements(outLocalTransform_, outLocalTransform, 0);
}
@@ -111,7 +111,7 @@ Java_com_google_android_filament_TransformManager_nGetWorldTransform(JNIEnv* env
jfloatArray outWorldTransform_) {
TransformManager* tm = (TransformManager*) nativeTransformManager;
jfloat *outWorldTransform = env->GetFloatArrayElements(outWorldTransform_, NULL);
*reinterpret_cast<math::mat4f *>(outWorldTransform) = tm->getWorldTransform(
*reinterpret_cast<filament::math::mat4f *>(outWorldTransform) = tm->getWorldTransform(
(TransformManager::Instance) i);
env->ReleaseFloatArrayElements(outWorldTransform_, outWorldTransform, 0);
}

View File

@@ -21,11 +21,15 @@
#include <filament/VertexBuffer.h>
#include "CallbackUtils.h"
#include "NioUtils.h"
#include <math/vec3.h>
#include <math/vec4.h>
#include "common/CallbackUtils.h"
#include "common/NioUtils.h"
using namespace filament;
using namespace driver;
using namespace filament::math;
using namespace backend;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_VertexBuffer_nCreateBuilder(JNIEnv *env, jclass type) {
@@ -65,9 +69,9 @@ Java_com_google_android_filament_VertexBuffer_nBuilderAttribute(JNIEnv *env, jcl
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_VertexBuffer_nBuilderNormalized(JNIEnv *env, jclass type,
jlong nativeBuilder, jint attribute) {
jlong nativeBuilder, jint attribute, jboolean normalized) {
VertexBuffer::Builder* builder = (VertexBuffer::Builder *) nativeBuilder;
builder->normalized((VertexAttribute) attribute);
builder->normalized((VertexAttribute) attribute, normalized);
}
extern "C" JNIEXPORT jlong JNICALL
@@ -106,7 +110,47 @@ Java_com_google_android_filament_VertexBuffer_nSetBufferAt(JNIEnv *env, jclass t
BufferDescriptor desc(data, sizeInBytes, &JniBufferCallback::invoke, callback);
vertexBuffer->setBufferAt(*engine, (uint8_t) bufferIndex, std::move(desc),
(uint32_t) destOffsetInBytes, (uint32_t) sizeInBytes);
(uint32_t) destOffsetInBytes);
return 0;
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_VertexBuffer_nPopulateTangentQuaternions(JNIEnv *env,
jclass type, jint quatType, jint quatCount, jobject outBuffer, jint outRemaining,
jint outStride, jobject normals, jint normalsRemaining, jint normalsStride,
jobject tangents, jint tangentsRemaining, jint tangentsStride) {
AutoBuffer outNioBuffer(env, outBuffer, outRemaining, true);
void* outData = outNioBuffer.getData();
AutoBuffer normalsNioBuffer(env, normals, normalsRemaining);
auto normalsData = (const float3*) normalsNioBuffer.getData();
if (tangents) {
AutoBuffer tangentsNioBuffer(env, tangents, tangentsRemaining);
auto tangentsData = (const float4*) tangentsNioBuffer.getData();
VertexBuffer::populateTangentQuaternions({
.quatType = (VertexBuffer::QuatType) quatType,
.quatCount = (size_t) quatCount,
.outBuffer = outData,
.outStride = (size_t) outStride,
.normals = normalsData,
.normalsStride = (size_t) normalsStride,
.tangents = tangentsData,
.tangentsStride = (size_t) tangentsStride
});
return;
}
VertexBuffer::populateTangentQuaternions({
.quatType = (VertexBuffer::QuatType) quatType,
.quatCount = (size_t) quatCount,
.outBuffer = outData,
.outStride = (size_t) outStride,
.normals = normalsData,
.normalsStride = (size_t) normalsStride,
.tangents = nullptr,
.tangentsStride = 0
});
}

View File

@@ -94,6 +94,13 @@ Java_com_google_android_filament_View_nSetShadowsEnabled(JNIEnv*, jclass,
view->setShadowsEnabled(enabled);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetRenderTarget(JNIEnv*, jclass,
jlong nativeView, jlong nativeTarget) {
View* view = (View*) nativeView;
view->setRenderTarget((RenderTarget*) nativeTarget);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetSampleCount(JNIEnv*, jclass,
jlong nativeView, jint count) {
@@ -119,7 +126,35 @@ extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_View_nGetAntiAliasing(JNIEnv*, jclass,
jlong nativeView) {
View* view = (View*) nativeView;
return (jint)view->getAntiAliasing();
return (jint) view->getAntiAliasing();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetToneMapping(JNIEnv*, jclass,
jlong nativeView, jint type) {
View* view = (View*) nativeView;
view->setToneMapping(View::ToneMapping(type));
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_View_nGetToneMapping(JNIEnv*, jclass,
jlong nativeView) {
View* view = (View*) nativeView;
return (jint) view->getToneMapping();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetDithering(JNIEnv*, jclass,
jlong nativeView, jint dithering) {
View* view = (View*) nativeView;
view->setDithering((View::Dithering) dithering);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_View_nGetDithering(JNIEnv*, jclass,
jlong nativeView) {
View* view = (View*) nativeView;
return (jint)view->getDithering();
}
extern "C" JNIEXPORT void JNICALL
@@ -134,21 +169,31 @@ Java_com_google_android_filament_View_nSetDynamicResolutionOptions(JNIEnv*,
options.targetFrameTimeMilli = targetFrameTimeMilli;
options.headRoomRatio = headRoomRatio;
options.scaleRate = scaleRate;
options.minScale = math::float2{ minScale };
options.maxScale = math::float2{ maxScale };
options.history = (uint8_t)history;
return view->setDynamicResolutionOptions(options);
options.minScale = filament::math::float2{minScale};
options.maxScale = filament::math::float2{maxScale};
options.history = (uint8_t) history;
view->setDynamicResolutionOptions(options);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetRenderQuality(JNIEnv*, jclass,
jlong nativeView, jint hdrColorBufferQuality) {
View* view = (View*) nativeView;
View::RenderQuality renderQuality;
renderQuality.hdrColorBuffer = View::QualityLevel(hdrColorBufferQuality);
view->setRenderQuality(renderQuality);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetDynamicLightingOptions(JNIEnv *env,
Java_com_google_android_filament_View_nSetDynamicLightingOptions(JNIEnv*,
jclass, jlong nativeView, jfloat zLightNear, jfloat zLightFar) {
View* view = (View*) nativeView;
view->setDynamicLightingOptions(zLightNear, zLightFar);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetDepthPrepass(JNIEnv *env,
Java_com_google_android_filament_View_nSetDepthPrepass(JNIEnv*,
jclass, jlong nativeView, jint value) {
View* view = (View*) nativeView;
view->setDepthPrepass(View::DepthPrepass(value));
@@ -165,5 +210,39 @@ extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_View_nIsPostProcessingEnabled(JNIEnv*,
jclass, jlong nativeView) {
View* view = (View*) nativeView;
return view->isPostProcessingEnabled();
return static_cast<jboolean>(view->isPostProcessingEnabled());
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetFrontFaceWindingInverted(JNIEnv*,
jclass, jlong nativeView, jboolean inverted) {
View* view = (View*) nativeView;
view->setFrontFaceWindingInverted(inverted);
}
extern "C" JNIEXPORT jboolean JNICALL
Java_com_google_android_filament_View_nIsFrontFaceWindingInverted(JNIEnv*,
jclass, jlong nativeView) {
View* view = (View*) nativeView;
return static_cast<jboolean>(view->isFrontFaceWindingInverted());
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetAmbientOcclusion(JNIEnv*, jclass, jlong nativeView, jint ordinal) {
View* view = (View*) nativeView;
view->setAmbientOcclusion((View::AmbientOcclusion)ordinal);
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_View_nGetAmbientOcclusion(JNIEnv*, jclass, jlong nativeView) {
View* view = (View*) nativeView;
return (jint)view->getAmbientOcclusion();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_View_nSetAmbientOcclusionOptions(JNIEnv*, jclass,
jlong nativeView, jfloat radius, jfloat bias, jfloat power, jfloat resolution) {
View* view = (View*) nativeView;
View::AmbientOcclusionOptions options = { .radius = radius, .bias = bias, .power = power, .resolution = resolution};
view->setAmbientOcclusionOptions(options);
}

View File

@@ -24,6 +24,8 @@
#import <Cocoa/Cocoa.h>
#pragma clang diagnostic push
#pragma ide diagnostic ignored "NotReleasedValue"
extern "C" {
void *getNativeWindow(JNIEnv *env, jclass klass, jobject surface) {
void *win = nullptr;
@@ -40,7 +42,7 @@ void *getNativeWindow(JNIEnv *env, jclass klass, jobject surface) {
view.wantsLayer = true;
[jawldsip setLayer:view.layer];
win = (void*)view;
win = (void*) view;
releaseDrawingSurface(ds, dsi);
return win;
}
@@ -48,7 +50,7 @@ void *getNativeWindow(JNIEnv *env, jclass klass, jobject surface) {
jlong createNativeSurface(jint width, jint height) {
NSView *view = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, width, height)];
view.wantsLayer = true;
return (jlong)view;
return (jlong) view;
}
void destroyNativeSurface(jlong surface) {
@@ -57,3 +59,4 @@ void destroyNativeSurface(jlong surface) {
}
}
#pragma clang diagnostic pop

View File

@@ -25,65 +25,83 @@ static std::vector<int> jawtVersions = {
0x00010009,
};
bool acquireDrawingSurface(JNIEnv *env, jobject surface, JAWT_DrawingSurface** ods,
JAWT_DrawingSurfaceInfo** odsi) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wuninitialized"
bool acquireDrawingSurface(JNIEnv* env, jobject surface,
JAWT_DrawingSurface** ods, JAWT_DrawingSurfaceInfo** odsi) {
JAWT awt;
JAWT_DrawingSurface *ds = nullptr;
JAWT_DrawingSurfaceInfo *dsi = nullptr;
JAWT_DrawingSurface* ds = nullptr;
JAWT_DrawingSurfaceInfo* dsi = nullptr;
// Search for a valid AWT
jboolean foundJawt = false;
for(int jawtVersion : jawtVersions) {
jboolean foundJawt = JNI_FALSE;
for (int jawtVersion : jawtVersions) {
awt.version = jawtVersion;
foundJawt = JAWT_GetAWT(env, &awt);
if (foundJawt == JNI_TRUE) {
#ifndef NDEBUG
printf("Found valid AWT v%08x.\n", jawtVersion);
#endif
break;
} else {
#ifndef NDEBUG
printf("AWT v%08x not present.\n", jawtVersion);
#endif
}
}
#ifndef NDEBUG
fflush(stdout);
#endif
if (foundJawt == JNI_FALSE) {
printf("AWT Not found\n");
fflush(stdout);
return 0;
return false;
}
// Get the drawing surface
ds = awt.GetDrawingSurface(env, surface);
if (ds == NULL) {
if (ds == nullptr) {
#ifndef NDEBUG
printf("NULL drawing surface\n");
fflush(stdout);
return 0;
#endif
return false;
}
// Lock the drawing
jint lock = ds->Lock(ds);
if ((lock & JAWT_LOCK_ERROR) != 0) {
#ifndef NDEBUG
printf("Error locking surface\n");
fflush(stdout);
#endif
awt.FreeDrawingSurface(ds);
return 0;
return false;
}
// Get the drawing surface info
dsi = ds->GetDrawingSurfaceInfo(ds);
if (dsi == NULL) {
if (dsi == nullptr) {
#ifndef NDEBUG
printf("Error getting surface info\n");
fflush(stdout);
#endif
ds->Unlock(ds);
awt.FreeDrawingSurface(ds);
return 0;
return false;
}
*odsi = dsi;
*ods = ds;
return 1;
}
void releaseDrawingSurface(JAWT_DrawingSurface *ds, JAWT_DrawingSurfaceInfo *dsi) {
return true;
}
#pragma clang diagnostic pop
void releaseDrawingSurface(JAWT_DrawingSurface* ds, JAWT_DrawingSurfaceInfo* dsi) {
// Free the drawing surface info
ds->FreeDrawingSurfaceInfo(dsi);
// Unlock the drawing surface

View File

@@ -17,7 +17,7 @@
#include <jawt.h>
extern "C" {
bool acquireDrawingSurface(JNIEnv *env, jobject obj, JAWT_DrawingSurface** ds,
JAWT_DrawingSurfaceInfo** dsi);
bool acquireDrawingSurface(JNIEnv* env, jobject surface, JAWT_DrawingSurface** ods,
JAWT_DrawingSurfaceInfo** odsi);
void releaseDrawingSurface(JAWT_DrawingSurface* ds, JAWT_DrawingSurfaceInfo* dsi);
}

View File

@@ -23,17 +23,17 @@
#include<GL/glx.h>
extern "C" {
void *getNativeWindow(JNIEnv *env, jclass, jobject surface) {
void *win = nullptr;
JAWT_DrawingSurface *ds = nullptr;
JAWT_DrawingSurfaceInfo *dsi = nullptr;
void *getNativeWindow(JNIEnv* env, jclass, jobject surface) {
void* win = nullptr;
JAWT_DrawingSurface* ds = nullptr;
JAWT_DrawingSurfaceInfo* dsi = nullptr;
if (!acquireDrawingSurface(env, surface, &ds, &dsi)) {
return win;
}
JAWT_X11DrawingSurfaceInfo *dsi_x11 = (JAWT_X11DrawingSurfaceInfo *) dsi->platformInfo;
JAWT_X11DrawingSurfaceInfo* dsi_x11 = (JAWT_X11DrawingSurfaceInfo*) dsi->platformInfo;
win = (void *) dsi_x11->drawable;
win = (void*) dsi_x11->drawable;
releaseDrawingSurface(ds, dsi);
return win;
}
@@ -77,7 +77,7 @@ jlong createNativeSurface(jint width, jint height) {
XFlush(display);
// Camouflage the pbuffer as a window which are both XID anyway.
return (jlong)window;
return (jlong) window;
}
void destroyNativeSurface(jlong surface) {
@@ -88,4 +88,3 @@ void destroyNativeSurface(jlong surface) {
}
}

View File

@@ -27,42 +27,20 @@
extern "C" {
void chooseAndSetPixelFormat(HDC dc) {
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
32, // Colordepth of the framebuffer.
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
24, // Number of bits for the depthbuffer
0, // Number of bits for the stencilbuffer
0, // Number of aux buffers in the framebuffer.
PFD_MAIN_PLANE,
0,
0, 0, 0
};
int pixelFormat = ChoosePixelFormat(dc, &pfd);
SetPixelFormat(dc, pixelFormat, &pfd);
}
void* getNativeWindow(JNIEnv* env, jclass, jobject surface) {
JAWT_DrawingSurface* ds = nullptr;
JAWT_DrawingSurfaceInfo* dsi = nullptr;
void *getNativeWindow(JNIEnv *env, jclass, jobject surface) {
void *win = nullptr;
JAWT_DrawingSurface *ds = nullptr;
JAWT_DrawingSurfaceInfo *dsi = nullptr;
if (!acquireDrawingSurface(env, surface, &ds, &dsi)) {
return win;
return nullptr;
}
JAWT_Win32DrawingSurfaceInfo *dsi_win32 = (JAWT_Win32DrawingSurfaceInfo *) dsi->platformInfo;
HDC dc = dsi_win32->hdc;
chooseAndSetPixelFormat(dsi_win32->hdc);
win = (void *) dsi_win32->hdc;
JAWT_Win32DrawingSurfaceInfo* dsi_win32 = (JAWT_Win32DrawingSurfaceInfo*) dsi->platformInfo;
HWND hWnd = dsi_win32->hwnd;
releaseDrawingSurface(ds, dsi);
return win;
return (void*) hWnd;
}
@@ -77,15 +55,12 @@ jlong createNativeSurface(jint width, jint height) {
HWND window = CreateWindowA("STATIC", "dummy", 0, 0, 0, width, height, NULL, NULL, NULL, NULL);
SetWindowLong(window, GWL_STYLE, 0); //remove all window styles
HDC dc = GetDC(window);
chooseAndSetPixelFormat(dc);
return (jlong)dc;
return (jlong) window;
}
void destroyNativeSurface(jlong surface) {
HDC dc = (HDC)surface;
HWND window = WindowFromDC(dc);
ReleaseDC(window, dc);
HWND window = (HWND) surface;
DestroyWindow(window);
}

View File

@@ -0,0 +1,90 @@
/*
* Copyright (C) 2019 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.
*/
package com.google.android.filament;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Size;
final class Asserts {
private Asserts() {
}
@NonNull @Size(min = 9)
static float[] assertMat3f(@Nullable float[] out) {
if (out == null) out = new float[9];
else if (out.length < 9) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 9");
}
return out;
}
static void assertMat3fIn(@NonNull @Size(min = 9) float[] in) {
if (in.length < 9) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 9");
}
}
@NonNull @Size(min = 16)
static double[] assertMat4d(@Nullable double[] out) {
if (out == null) out = new double[16];
else if (out.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
return out;
}
static void assertMat4dIn(@NonNull @Size(min = 16) double[] in) {
if (in.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
}
@NonNull @Size(min = 16)
static float[] assertMat4f(@Nullable float[] out) {
if (out == null) out = new float[16];
else if (out.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
return out;
}
static void assertMat4fIn(@NonNull @Size(min = 16) float[] in) {
if (in.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
}
@NonNull @Size(min = 3)
static float[] assertFloat3(@Nullable float[] out) {
if (out == null) out = new float[3];
else if (out.length < 3) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 3");
}
return out;
}
@NonNull @Size(min = 4)
static float[] assertFloat4(@Nullable float[] out) {
if (out == null) out = new float[4];
else if (out.length < 4) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 4");
}
return out;
}
}

View File

@@ -219,7 +219,7 @@ public class Camera {
*/
public void setCustomProjection(@NonNull @Size(min = 16) double inMatrix[],
double near, double far) {
assertMat4dIn(inMatrix);
Asserts.assertMat4dIn(inMatrix);
nSetCustomProjection(getNativeObject(), inMatrix, near, far);
}
@@ -228,7 +228,7 @@ public class Camera {
* @param in
*/
public void setModelMatrix(@NonNull @Size(min = 16) float in[]) {
assertMat4fIn(in);
Asserts.assertMat4fIn(in);
nSetModelMatrix(getNativeObject(), in);
}
@@ -273,7 +273,7 @@ public class Camera {
*/
@NonNull @Size(min = 16)
public double[] getProjectionMatrix(@Nullable @Size(min = 16) double out[]) {
out = assertMat4d(out);
out = Asserts.assertMat4d(out);
nGetProjectionMatrix(getNativeObject(), out);
return out;
}
@@ -287,7 +287,7 @@ public class Camera {
*/
@NonNull @Size(min = 16)
public float[] getModelMatrix(@Nullable @Size(min = 16) float out[]) {
out = assertMat4f(out);
out = Asserts.assertMat4f(out);
nGetModelMatrix(getNativeObject(), out);
return out;
}
@@ -301,7 +301,7 @@ public class Camera {
*/
@NonNull @Size(min = 16)
public float[] getViewMatrix(@Nullable @Size(min = 16) float out[]) {
out = assertMat4f(out);
out = Asserts.assertMat4f(out);
nGetViewMatrix(getNativeObject(), out);
return out;
}
@@ -314,7 +314,7 @@ public class Camera {
*/
@NonNull @Size(min = 3)
public float[] getPosition(@Nullable @Size(min = 3) float out[]) {
out = assertFloat3(out);
out = Asserts.assertFloat3(out);
nGetPosition(getNativeObject(), out);
return out;
}
@@ -328,7 +328,7 @@ public class Camera {
*/
@NonNull @Size(min = 3)
public float[] getLeftVector(@Nullable @Size(min = 3) float out[]) {
out = assertFloat3(out);
out = Asserts.assertFloat3(out);
nGetLeftVector(getNativeObject(), out);
return out;
}
@@ -342,7 +342,7 @@ public class Camera {
*/
@NonNull @Size(min = 3)
public float[] getUpVector(@Nullable @Size(min = 3) float out[]) {
out = assertFloat3(out);
out = Asserts.assertFloat3(out);
nGetUpVector(getNativeObject(), out);
return out;
}
@@ -356,7 +356,7 @@ public class Camera {
*/
@NonNull @Size(min = 3)
public float[] getForwardVector(@Nullable @Size(min = 3) float out[]) {
out = assertFloat3(out);
out = Asserts.assertFloat3(out);
nGetForwardVector(getNativeObject(), out);
return out;
}
@@ -406,45 +406,6 @@ public class Camera {
mNativeObject = 0;
}
@NonNull @Size(min = 16)
private static double[] assertMat4d(@Nullable double[] out) {
if (out == null) out = new double[16];
else if (out.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
return out;
}
@NonNull @Size(min = 16)
private static float[] assertMat4f(@Nullable float[] out) {
if (out == null) out = new float[16];
else if (out.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
return out;
}
private static void assertMat4dIn(@NonNull @Size(min = 16) double[] in) {
if (in.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
}
private static void assertMat4fIn(@NonNull @Size(min = 16) float[] in) {
if (in.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
}
@NonNull @Size(min = 3)
private static float[] assertFloat3(@Nullable float[] out) {
if (out == null) out = new float[3];
else if (out.length < 3) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 3");
}
return out;
}
private static native void nSetProjection(long nativeCamera, int projection, double left, double right, double bottom, double top, double near, double far);
private static native void nSetProjectionFov(long nativeCamera, double fovInDegrees, double aspect, double near, double far, int fov);
private static native void nSetLensProjection(long nativeCamera, double focalLength, double near, double far);

View File

@@ -16,6 +16,8 @@
package com.google.android.filament;
import com.google.android.filament.proguard.UsedByReflection;
import android.support.annotation.NonNull;
public class Engine {
@@ -24,6 +26,13 @@ public class Engine {
@NonNull private final LightManager mLightManager;
@NonNull private final RenderableManager mRenderableManager;
public enum Backend {
DEFAULT, // Automatically selects an appropriate driver for the platform.
OPENGL, // Selects the OpenGL ES driver.
VULKAN, // Selects the experimental Vulkan driver.
NOOP, // Selects the no-op driver for testing purposes.
}
private Engine(long nativeEngine) {
mNativeObject = nativeEngine;
mTransformManager = new TransformManager(nGetTransformManager(nativeEngine));
@@ -33,7 +42,14 @@ public class Engine {
@NonNull
public static Engine create() {
long nativeEngine = nCreateEngine(0);
long nativeEngine = nCreateEngine(0, 0);
if (nativeEngine == 0) throw new IllegalStateException("Couldn't create Engine");
return new Engine(nativeEngine);
}
@NonNull
public static Engine create(@NonNull Backend backend) {
long nativeEngine = nCreateEngine(backend.ordinal(), 0);
if (nativeEngine == 0) throw new IllegalStateException("Couldn't create Engine");
return new Engine(nativeEngine);
}
@@ -46,7 +62,7 @@ public class Engine {
@NonNull
public static Engine create(@NonNull Object sharedContext) {
if (Platform.get().validateSharedContext(sharedContext)) {
long nativeEngine = nCreateEngine(
long nativeEngine = nCreateEngine(0,
Platform.get().getSharedContextNativeHandle(sharedContext));
if (nativeEngine == 0) throw new IllegalStateException("Couldn't create Engine");
return new Engine(nativeEngine);
@@ -63,6 +79,10 @@ public class Engine {
clearNativeObject();
}
public Backend getBackend() {
return Backend.values()[(int) nGetBackend(getNativeObject())];
}
// SwapChain
/**
@@ -71,13 +91,19 @@ public class Engine {
* - Other: none
*/
public SwapChain createSwapChain(@NonNull Object surface) {
return createSwapChain(surface, 0);
return createSwapChain(surface, SwapChain.CONFIG_DEFAULT);
}
/**
* Valid surface types:
* - Android: Surface
* - Other: none
*
* Flags: see CONFIG flags in SwapChain.
*
* @see SwapChain#CONFIG_DEFAULT
* @see SwapChain#CONFIG_TRANSPARENT
* @see SwapChain#CONFIG_READABLE
*/
public SwapChain createSwapChain(@NonNull Object surface, long flags) {
if (Platform.get().validateSurface(surface)) {
@@ -221,6 +247,11 @@ public class Engine {
texture.clearNativeObject();
}
public void destroyRenderTarget(@NonNull RenderTarget target) {
nDestroyRenderTarget(getNativeObject(), target.getNativeObject());
target.clearNativeObject();
}
public void destroyEntity(@Entity int entity) {
nDestroyEntity(getNativeObject(), entity);
}
@@ -246,6 +277,7 @@ public class Engine {
Fence.waitAndDestroy(createFence(Fence.Type.HARD), Fence.Mode.FLUSH);
}
@UsedByReflection("TextureHelper.java")
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed Engine");
@@ -257,8 +289,9 @@ public class Engine {
mNativeObject = 0;
}
private static native long nCreateEngine(long sharedContext);
private static native long nCreateEngine(long backend, long sharedContext);
private static native void nDestroyEngine(long nativeEngine);
private static native long nGetBackend(long nativeEngine);
private static native long nCreateSwapChain(long nativeEngine, Object nativeWindow, long flags);
private static native long nCreateSwapChainFromRawPointer(long nativeEngine, long pointer, long flags);
private static native void nDestroySwapChain(long nativeEngine, long nativeSwapChain);
@@ -281,6 +314,7 @@ public class Engine {
private static native void nDestroyMaterialInstance(long nativeEngine, long nativeMaterialInstance);
private static native void nDestroySkybox(long nativeEngine, long nativeSkybox);
private static native void nDestroyTexture(long nativeEngine, long nativeTexture);
private static native void nDestroyRenderTarget(long nativeEngine, long nativeTarget);
private static native void nDestroyEntity(long nativeEngine, int entity);
private static native long nGetTransformManager(long nativeEngine);
private static native long nGetLightManager(long nativeEngine);

View File

@@ -16,6 +16,8 @@
package com.google.android.filament;
import com.google.android.filament.proguard.UsedByReflection;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
@@ -66,6 +68,11 @@ public class EntityManager {
return nIsAlive(mNativeObject, entity);
}
@UsedByReflection("AssetLoader.java")
long getNativeObject() {
return mNativeObject;
}
private static native long nGetEntityManager();
private static native void nCreateArray(long nativeEntityManager, int n, int[] entities);
private static native int nCreate(long nativeEntityManager);

View File

@@ -16,14 +16,18 @@
package com.google.android.filament;
import com.google.android.filament.proguard.UsedByReflection;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Size;
public class IndirectLight {
long mNativeObject;
private IndirectLight(long indirectLight) {
@UsedByReflection("KtxLoader.java")
IndirectLight(long indirectLight) {
mNativeObject = indirectLight;
}
@@ -61,6 +65,24 @@ public class IndirectLight {
return this;
}
@NonNull
public Builder radiance(@IntRange(from=1, to=3) int bands, @NonNull float[] sh) {
switch (bands) {
case 1: if (sh.length < 3)
throw new ArrayIndexOutOfBoundsException(
"1 band SH, array must be at least 1 x float3"); else break;
case 2: if (sh.length < 4 * 3)
throw new ArrayIndexOutOfBoundsException(
"2 bands SH, array must be at least 4 x float3"); else break;
case 3: if (sh.length < 9 * 3)
throw new ArrayIndexOutOfBoundsException(
"3 bands SH, array must be at least 9 x float3"); else break;
default: throw new IllegalArgumentException("bands must be 1, 2 or 3");
}
nRadiance(mNativeBuilder, bands, sh);
return this;
}
@NonNull
public Builder irradiance(@NonNull Texture cubemap) {
nIrradianceAsTexture(mNativeBuilder, cubemap.getNativeObject());
@@ -74,7 +96,7 @@ public class IndirectLight {
}
@NonNull
public Builder rotation(@NonNull @Size(min = 9) float rotation[]) {
public Builder rotation(@NonNull @Size(min = 9) float[] rotation) {
nRotation(mNativeBuilder,
rotation[0], rotation[1], rotation[2],
rotation[3], rotation[4], rotation[5],
@@ -114,13 +136,21 @@ public class IndirectLight {
return nGetIntensity(getNativeObject());
}
public void setRotation(@NonNull @Size(min = 9) float rotation[]) {
public void setRotation(@NonNull @Size(min = 9) float[] rotation) {
Asserts.assertMat3fIn(rotation);
nSetRotation(getNativeObject(),
rotation[0], rotation[1], rotation[2],
rotation[3], rotation[4], rotation[5],
rotation[6], rotation[7], rotation[8]);
}
@NonNull @Size(min = 9)
public float[] getRotation(@Nullable @Size(min = 9) float[] rotation) {
rotation = Asserts.assertMat3f(rotation);
nGetRotation(getNativeObject(), rotation);
return rotation;
}
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed IndirectLight");
@@ -138,6 +168,7 @@ public class IndirectLight {
private static native long nBuilderBuild(long nativeBuilder, long nativeEngine);
private static native void nBuilderReflections(long nativeBuilder, long nativeTexture);
private static native void nIrradiance(long nativeBuilder, int bands, float[] sh);
private static native void nRadiance(long nativeBuilder, int bands, float[] sh);
private static native void nIrradianceAsTexture(long nativeBuilder, long nativeTexture);
private static native void nIntensity(long nativeBuilder, float envIntensity);
private static native void nRotation(long nativeBuilder, float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8) ;
@@ -145,5 +176,5 @@ public class IndirectLight {
private static native void nSetIntensity(long nativeIndirectLight, float intensity);
private static native float nGetIntensity(long nativeIndirectLight);
private static native void nSetRotation(long nativeIndirectLight, float v0, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8);
private static native void nGetRotation(long nativeIndirectLight, float[] outRotation);
}

View File

@@ -53,6 +53,9 @@ public class LightManager {
public float constantBias = 0.05f;
public float normalBias = 0.4f;
public float shadowFar = 0.0f;
public float shadowNearHint = 1.0f;
public float shadowFarHint = 100.0f;
public boolean stable = true;
}
public static final float EFFICIENCY_INCANDESCENT = 0.0220f;
@@ -79,7 +82,8 @@ public class LightManager {
@NonNull
public Builder shadowOptions(@NonNull ShadowOptions options) {
nBuilderShadowOptions(mNativeBuilder,
options.mapSize, options.constantBias, options.normalBias, options.shadowFar);
options.mapSize, options.constantBias, options.normalBias, options.shadowFar,
options.shadowNearHint, options.shadowFarHint, options.stable);
return this;
}
@@ -183,7 +187,7 @@ public class LightManager {
@NonNull
public float[] getPosition(@EntityInstance int i, @Nullable @Size(min = 3) float[] out) {
out = assertFloat3(out);
out = Asserts.assertFloat3(out);
nGetPosition(mNativeObject, i, out);
return out;
}
@@ -194,7 +198,7 @@ public class LightManager {
@NonNull
public float[] getDirection(@EntityInstance int i, @Nullable @Size(min = 3) float[] out) {
out = assertFloat3(out);
out = Asserts.assertFloat3(out);
nGetDirection(mNativeObject, i, out);
return out;
}
@@ -205,7 +209,7 @@ public class LightManager {
@NonNull
public float[] getColor(@EntityInstance int i, @Nullable @Size(min = 3) float[] out) {
out = assertFloat3(out);
out = Asserts.assertFloat3(out);
nGetColor(mNativeObject, i, out);
return out;
}
@@ -258,15 +262,6 @@ public class LightManager {
return nGetSunHaloFalloff(mNativeObject, i);
}
@NonNull @Size(min = 3)
private static float[] assertFloat3(@Nullable float[] out) {
if (out == null) out = new float[3];
else if (out.length < 3) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 3");
}
return out;
}
private static native boolean nHasComponent(long nativeLightManager, int entity);
private static native int nGetInstance(long nativeLightManager, int entity);
private static native void nDestroy(long nativeLightManager, int entity);
@@ -275,7 +270,7 @@ public class LightManager {
private static native void nDestroyBuilder(long nativeBuilder);
private static native boolean nBuilderBuild(long nativeBuilder, long nativeEngine, int entity);
private static native void nBuilderCastShadows(long nativeBuilder, boolean enable);
private static native void nBuilderShadowOptions(long nativeBuilder, int mapSize, float constantBias, float normalBias, float shadowFar);
private static native void nBuilderShadowOptions(long nativeBuilder, int mapSize, float constantBias, float normalBias, float shadowFar, float shadowNearHint, float shadowFarhint, boolean stable);
private static native void nBuilderCastLight(long nativeBuilder, boolean enabled);
private static native void nBuilderPosition(long nativeBuilder, float x, float y, float z);
private static native void nBuilderDirection(long nativeBuilder, float x, float y, float z);

View File

@@ -19,6 +19,7 @@ package com.google.android.filament;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Size;
import com.google.android.filament.proguard.UsedByNative;
import java.nio.Buffer;
import java.util.ArrayList;
@@ -37,7 +38,8 @@ public class Material {
UNLIT,
LIT,
SUBSURFACE,
CLOTH
CLOTH,
SPECULAR_GLOSSINESS
}
public enum Interpolation {
@@ -68,6 +70,7 @@ public class Material {
FRONT_AND_BACK
}
@UsedByNative("Material.cpp")
public static class Parameter {
public enum Type {
BOOL,
@@ -100,8 +103,8 @@ public class Material {
DEFAULT
}
// Used by native code
@SuppressWarnings("unused")
@UsedByNative("Material.cpp")
private static final int SAMPLER_OFFSET = Type.MAT4.ordinal() + 1;
@NonNull
@@ -121,8 +124,8 @@ public class Material {
this.count = count;
}
// Used by native code
@SuppressWarnings("unused")
@UsedByNative("Material.cpp")
private static void add(@NonNull List<Parameter> parameters, @NonNull String name,
@IntRange(from = 0) int type, @IntRange(from = 0) int precision,
@IntRange(from = 1) int count) {
@@ -131,8 +134,9 @@ public class Material {
}
}
private Material(long nativeMaterial, long nativeDefaultInstance) {
Material(long nativeMaterial) {
mNativeObject = nativeMaterial;
long nativeDefaultInstance = nGetDefaultInstance(nativeMaterial);
mDefaultInstance = new MaterialInstance(this, nativeDefaultInstance);
}
@@ -151,8 +155,7 @@ public class Material {
public Material build(@NonNull Engine engine) {
long nativeMaterial = nBuilderBuild(engine.getNativeObject(), mBuffer, mSize);
if (nativeMaterial == 0) throw new IllegalStateException("Couldn't create Material");
long nativeDefaultInstance = nGetDefaultInstance(nativeMaterial);
return new Material(nativeMaterial, nativeDefaultInstance);
return new Material(nativeMaterial);
}
}
@@ -212,6 +215,14 @@ public class Material {
return nGetMaskThreshold(getNativeObject());
}
public float getSpecularAntiAliasingVariance() {
return nGetSpecularAntiAliasingVariance(getNativeObject());
}
public float getSpecularAntiAliasingThreshold() {
return nGetSpecularAntiAliasingThreshold(getNativeObject());
}
public Set<VertexBuffer.VertexAttribute> getRequiredAttributes() {
if (mRequiredAttributes == null) {
int bitSet = nGetRequiredAttributes(getNativeObject());
@@ -353,6 +364,8 @@ public class Material {
private static native boolean nIsDepthCullingEnabled(long nativeMaterial);
private static native boolean nIsDoubleSided(long nativeMaterial);
private static native float nGetMaskThreshold(long nativeMaterial);
private static native float nGetSpecularAntiAliasingVariance(long nativeMaterial);
private static native float nGetSpecularAntiAliasingThreshold(long nativeMaterial);
private static native int nGetParameterCount(long nativeMaterial);
private static native void nGetParameters(long nativeMaterial,

View File

@@ -21,8 +21,9 @@ import android.support.annotation.NonNull;
import android.support.annotation.Size;
public class MaterialInstance {
private final Material mMaterial;
private Material mMaterial;
private long mNativeObject;
private long mNativeMaterial;
public enum BooleanElement {
BOOL,
@@ -52,8 +53,16 @@ public class MaterialInstance {
mNativeObject = nativeMaterialInstance;
}
MaterialInstance(long nativeMaterial, long nativeMaterialInstance) {
mNativeMaterial = nativeMaterial;
mNativeObject = nativeMaterialInstance;
}
@NonNull
public Material getMaterial() {
if (mMaterial == null) {
mMaterial = new Material(mNativeMaterial);
}
return mMaterial;
}
@@ -130,12 +139,14 @@ public class MaterialInstance {
public void setParameter(@NonNull String name, @NonNull Colors.RgbType type,
float r, float g, float b) {
setParameter(name, FloatElement.FLOAT3, Colors.toLinear(type, r, g, b), 0, 1);
float[] color = Colors.toLinear(type, r, g, b);
nSetParameterFloat3(getNativeObject(), name, color[0], color[1], color[2]);
}
public void setParameter(@NonNull String name, @NonNull Colors.RgbaType type,
float r, float g, float b, float a) {
setParameter(name, FloatElement.FLOAT4, Colors.toLinear(type, r, g, b, a), 0, 1);
float[] color = Colors.toLinear(type, r, g, b, a);
nSetParameterFloat4(getNativeObject(), name, color[0], color[1], color[2], color[3]);
}
public void setScissor(@IntRange(from = 0) int left, @IntRange(from = 0) int bottom,
@@ -147,6 +158,26 @@ public class MaterialInstance {
nUnsetScissor(getNativeObject());
}
public void setPolygonOffset(float scale, float constant) {
nSetPolygonOffset(getNativeObject(), scale, constant);
}
public void setMaskThreshold(float threshold) {
nSetMaskThreshold(getNativeObject(), threshold);
}
public void setSpecularAntiAliasingVariance(float variance) {
nSetSpecularAntiAliasingVariance(getNativeObject(), variance);
}
public void setSpecularAntiAliasingThreshold(float threshold) {
nSetSpecularAntiAliasingThreshold(getNativeObject(), threshold);
}
public void setDoubleSided(boolean doubleSided) {
nSetDoubleSided(getNativeObject(), doubleSided);
}
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed MaterialInstance");
@@ -204,4 +235,16 @@ public class MaterialInstance {
@IntRange(from = 0) int width, @IntRange(from = 0) int height);
private static native void nUnsetScissor(long nativeMaterialInstance);
private static native void nSetPolygonOffset(long nativeMaterialInstance,
float scale, float constant);
private static native void nSetMaskThreshold(long nativeMaterialInstance, float threshold);
private static native void nSetSpecularAntiAliasingVariance(long nativeMaterialInstance,
float variance);
private static native void nSetSpecularAntiAliasingThreshold(long nativeMaterialInstance,
float threshold);
private static native void nSetDoubleSided(long nativeMaterialInstance, boolean doubleSided);
}

View File

@@ -17,6 +17,7 @@
package com.google.android.filament;
import android.support.annotation.NonNull;
import com.google.android.filament.proguard.UsedByNative;
import java.nio.Buffer;
import java.nio.ByteBuffer;
@@ -26,6 +27,7 @@ import java.nio.IntBuffer;
import java.nio.LongBuffer;
import java.nio.ShortBuffer;
@UsedByNative("NioUtils.cpp")
final class NioUtils {
enum BufferType {
@@ -41,18 +43,22 @@ final class NioUtils {
private NioUtils() {
}
@UsedByNative("NioUtils.cpp")
static long getBasePointer(@NonNull Buffer b, long address, int sizeShift) {
return address != 0 ? address + (b.position() << sizeShift) : 0;
}
@UsedByNative("NioUtils.cpp")
static Object getBaseArray(@NonNull Buffer b) {
return b.hasArray() ? b.array() : null;
}
@UsedByNative("NioUtils.cpp")
static int getBaseArrayOffset(@NonNull Buffer b, int sizeShift) {
return b.hasArray() ? ((b.arrayOffset() + b.position()) << sizeShift) : 0;
}
@UsedByNative("NioUtils.cpp")
static int getBufferType(@NonNull Buffer b) {
if (b instanceof ByteBuffer) {
return BufferType.BYTE.ordinal();

View File

@@ -0,0 +1,145 @@
/*
* Copyright (C) 2019 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.
*/
package com.google.android.filament;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.nio.Buffer;
import java.nio.BufferOverflowException;
public class RenderTarget {
private long mNativeObject;
private final Texture[] mTextures = new Texture[2];
private RenderTarget(long nativeRenderTarget, Builder builder) {
mNativeObject = nativeRenderTarget;
mTextures[0] = builder.mTextures[0];
mTextures[1] = builder.mTextures[1];
}
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed RenderTarget");
}
return mNativeObject;
}
public enum AttachmentPoint {
COLOR,
DEPTH,
}
public static class Builder {
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"})
private final BuilderFinalizer mFinalizer;
private final long mNativeBuilder;
private final Texture[] mTextures = new Texture[2];
public Builder() {
mNativeBuilder = nCreateBuilder();
mFinalizer = new BuilderFinalizer(mNativeBuilder);
}
@NonNull
public Builder texture(@NonNull AttachmentPoint attachment, @Nullable Texture texture) {
mTextures[attachment.ordinal()] = texture;
nBuilderTexture(mNativeBuilder, attachment.ordinal(), texture != null ? texture.getNativeObject() : 0);
return this;
}
@NonNull
public Builder mipLevel(@NonNull AttachmentPoint attachment, @IntRange(from = 0) int level) {
nBuilderMipLevel(mNativeBuilder, attachment.ordinal(), level);
return this;
}
@NonNull
public Builder face(@NonNull AttachmentPoint attachment, Texture.CubemapFace face) {
nBuilderFace(mNativeBuilder, attachment.ordinal(), face.ordinal());
return this;
}
@NonNull
public Builder layer(@NonNull AttachmentPoint attachment, @IntRange(from = 0) int layer) {
nBuilderLayer(mNativeBuilder, attachment.ordinal(), layer);
return this;
}
@NonNull
public RenderTarget build(@NonNull Engine engine) {
long nativeRenderTarget = nBuilderBuild(mNativeBuilder, engine.getNativeObject());
if (nativeRenderTarget == 0)
throw new IllegalStateException("Couldn't create RenderTarget");
return new RenderTarget(nativeRenderTarget, this);
}
private static class BuilderFinalizer {
private final long mNativeObject;
BuilderFinalizer(long nativeObject) {
mNativeObject = nativeObject;
}
@Override
public void finalize() {
try {
super.finalize();
} catch (Throwable t) { // Ignore
} finally {
nDestroyBuilder(mNativeObject);
}
}
}
}
@Nullable
public Texture getTexture(@NonNull AttachmentPoint attachment) {
return mTextures[attachment.ordinal()];
}
@IntRange(from = 0)
public int getMipLevel(@NonNull AttachmentPoint attachment) {
return nGetMipLevel(getNativeObject(), attachment.ordinal());
}
public Texture.CubemapFace getFace(AttachmentPoint attachment) {
return Texture.CubemapFace.values()[nGetFace(getNativeObject(), attachment.ordinal())];
}
@IntRange(from = 0)
public int getLayer(@NonNull AttachmentPoint attachment) {
return nGetLayer(getNativeObject(), attachment.ordinal());
}
void clearNativeObject() {
mNativeObject = 0;
}
private static native long nCreateBuilder();
private static native long nDestroyBuilder(long nativeBuilder);
private static native long nBuilderTexture(long nativeBuilder, int attachment, long nativeTexture);
private static native long nBuilderMipLevel(long nativeBuilder, int attachment, int level);
private static native long nBuilderFace(long nativeBuilder, int attachment, int face);
private static native long nBuilderLayer(long nativeBuilder, int attachment, int layer);
private static native long nBuilderBuild(long nativeBuilder, long nativeEngine);
private static native int nGetMipLevel(long nativeRenderTarget, int attachment);
private static native int nGetFace(long nativeRenderTarget, int attachment);
private static native int nGetLayer(long nativeRenderTarget, int attachment);
}

View File

@@ -282,6 +282,14 @@ public class RenderableManager {
nSetMaterialInstanceAt(mNativeObject, i, primitiveIndex, materialInstance.getNativeObject());
}
// creates a MaterialInstance Java wrapper object for a particular material instance
public @NonNull MaterialInstance getMaterialInstanceAt(@EntityInstance int i,
@IntRange(from = 0) int primitiveIndex) {
long nativeMatInstance = nGetMaterialInstanceAt(mNativeObject, i, primitiveIndex);
long nativeMaterial = nGetMaterialAt(mNativeObject, i, primitiveIndex);
return new MaterialInstance(nativeMaterial, nativeMatInstance);
}
// set/change the geometry (vertex/index buffers) of a given primitive
public void setGeometryAt(@EntityInstance int i, @IntRange(from = 0) int primitiveIndex,
@NonNull PrimitiveType type, @NonNull VertexBuffer vertices,
@@ -356,6 +364,8 @@ public class RenderableManager {
private static native void nGetAxisAlignedBoundingBox(long nativeRenderableManager, int i, float[] center, float[] halfExtent);
private static native int nGetPrimitiveCount(long nativeRenderableManager, int i);
private static native void nSetMaterialInstanceAt(long nativeRenderableManager, int i, int primitiveIndex, long nativeMaterialInstance);
private static native long nGetMaterialInstanceAt(long nativeRenderableManager, int i, int primitiveIndex);
private static native long nGetMaterialAt(long nativeRenderableManager, int i, int primitiveIndex);
private static native void nSetGeometryAt(long nativeRenderableManager, int i, int primitiveIndex, int primitiveType, long nativeVertexBuffer, long nativeIndexBuffer, int offset, int count);
private static native void nSetGeometryAt(long nativeRenderableManager, int i, int primitiveIndex, int primitiveType, int offset, int count);
private static native void nSetBlendOrderAt(long nativeRenderableManager, int i, int primitiveIndex, int blendOrder);

View File

@@ -56,15 +56,22 @@ public class Renderer {
/**
* This method MUST be called before endFrame.
*/
public void mirrorFrame(
public void copyFrame(
@NonNull SwapChain dstSwapChain, @NonNull Viewport dstViewport,
@NonNull Viewport srcViewport, int flags) {
nMirrorFrame(getNativeObject(), dstSwapChain.getNativeObject(),
nCopyFrame(getNativeObject(), dstSwapChain.getNativeObject(),
dstViewport.left, dstViewport.bottom, dstViewport.width, dstViewport.height,
srcViewport.left, srcViewport.bottom, srcViewport.width, srcViewport.height,
flags);
}
@Deprecated
public void mirrorFrame(
@NonNull SwapChain dstSwapChain, @NonNull Viewport dstViewport,
@NonNull Viewport srcViewport, int flags) {
copyFrame(dstSwapChain, dstViewport, srcViewport, flags);
}
/**
* This method MUST be called before endFrame.
*/
@@ -89,6 +96,14 @@ public class Renderer {
}
}
double getUserTime() {
return nGetUserTime(getNativeObject());
}
void resetUserTime() {
nResetUserTime(getNativeObject());
}
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed Renderer");
@@ -103,7 +118,7 @@ public class Renderer {
private static native boolean nBeginFrame(long nativeRenderer, long nativeSwapChain);
private static native void nEndFrame(long nativeRenderer);
private static native void nRender(long nativeRenderer, long nativeView);
private static native void nMirrorFrame(long nativeRenderer, long nativeDstSwapChain,
private static native void nCopyFrame(long nativeRenderer, long nativeDstSwapChain,
int dstLeft, int dstBottom, int dstWidth, int dstHeight,
int srcLeft, int srcBottom, int srcWidth, int srcHeight,
int flags);
@@ -112,4 +127,6 @@ public class Renderer {
Buffer storage, int remaining,
int left, int top, int type, int alignment, int stride, int format,
Object handler, Runnable callback);
private static native double nGetUserTime(long nativeRenderer);
private static native void nResetUserTime(long nativeRenderer);
}

View File

@@ -52,6 +52,10 @@ public class Scene {
nAddEntity(getNativeObject(), entity);
}
public void addEntities(@Entity int[] entities) {
nAddEntities(getNativeObject(), entities);
}
public void removeEntity(@Entity int entity) {
nRemove(getNativeObject(), entity);
}
@@ -85,6 +89,7 @@ public class Scene {
private static native void nSetSkybox(long nativeScene, long nativeSkybox);
private static native void nSetIndirectLight(long nativeScene, long nativeIndirectLight);
private static native void nAddEntity(long nativeScene, int entity);
private static native void nAddEntities(long nativeScene, int[] entities);
private static native void nRemove(long nativeScene, int entity);
private static native int nGetRenderableCount(long nativeScene);
private static native int nGetLightCount(long nativeScene);

View File

@@ -16,13 +16,16 @@
package com.google.android.filament;
import com.google.android.filament.proguard.UsedByReflection;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
public class Skybox {
private long mNativeObject;
private Skybox(long nativeSkybox) {
@UsedByReflection("KtxLoader.java")
Skybox(long nativeSkybox) {
mNativeObject = nativeSkybox;
}

View File

@@ -128,6 +128,10 @@ public class Stream {
}
}
public long getTimestamp() {
return nGetTimestamp(getNativeObject());
}
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed Stream");
@@ -153,6 +157,7 @@ public class Stream {
Buffer storage, int remaining,
int left, int top, int type, int alignment, int stride, int format,
Object handler, Runnable callback);
private static native long nGetTimestamp(long nativeStream);
private static native boolean nIsNative(long nativeStream);
}

View File

@@ -22,6 +22,7 @@ public class SwapChain {
private final Object mSurface;
private long mNativeObject;
public static final long CONFIG_DEFAULT = 0x0;
public static final long CONFIG_TRANSPARENT = 0x1;
public static final long CONFIG_READABLE = 0x2;

View File

@@ -16,6 +16,8 @@
package com.google.android.filament;
import com.google.android.filament.proguard.UsedByReflection;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
@@ -30,6 +32,7 @@ import static com.google.android.filament.Texture.Type.COMPRESSED;
public class Texture {
private long mNativeObject;
@UsedByReflection("KtxLoader.java")
Texture(long nativeTexture) {
mNativeObject = nativeTexture;
}
@@ -60,7 +63,7 @@ public class Texture {
RG16F, RG16UI, RG16I,
R11F_G11F_B10F,
RGBA8, SRGB8_A8, RGBA8_SNORM,
UNUSED, // The RGBM InternalFormat has been replaced with a flag (Texture.Builder.rgbm)
UNUSED, // used to be rgbm
RGB10_A2, RGBA8UI, RGBA8I,
DEPTH32F, DEPTH24_STENCIL8, DEPTH32F_STENCIL8,
@@ -118,7 +121,7 @@ public class Texture {
RGB_INTEGER,
RGBA,
RGBA_INTEGER,
RGBM,
UNUSED,
DEPTH_COMPONENT,
DEPTH_STENCIL,
STENCIL_INDEX,
@@ -134,7 +137,8 @@ public class Texture {
INT,
HALF,
FLOAT,
COMPRESSED
COMPRESSED,
UINT_10F_11F_11F_REV
}
public static class PixelBufferDescriptor {
@@ -252,7 +256,6 @@ public class Texture {
break;
case RGBA:
case RGBA_INTEGER:
case RGBM:
n = 4;
break;
}
@@ -273,6 +276,10 @@ public class Texture {
case FLOAT:
bpp *= 4;
break;
case UINT_10F_11F_11F_REV:
// Special case, format must be RGB and uses 4 bytes
bpp = 4;
break;
}
int bpr = bpp * stride;
@@ -281,6 +288,11 @@ public class Texture {
}
}
public static class PrefilterOptions {
public int sampleCount = 8;
public boolean mirror = true;
}
public static boolean isTextureFormatSupported(@NonNull Engine engine,
@NonNull InternalFormat format) {
return nIsTextureFormatSupported(engine.getNativeObject(), format.ordinal());
@@ -333,9 +345,14 @@ public class Texture {
return this;
}
/**
* Sets the usage flags, which is necessary when attaching to {@link RenderTarget}.
*
* The flags argument much be a combination of {@link Usage} flags.
*/
@NonNull
public Builder rgbm(@NonNull boolean enabled) {
nBuilderRgbm(mNativeBuilder, enabled);
public Builder usage(int flags) {
nBuilderUsage(mNativeBuilder, flags);
return this;
}
@@ -365,6 +382,15 @@ public class Texture {
}
}
public static class Usage {
public static final int COLOR_ATTACHMENT = 0x1;
public static final int DEPTH_ATTACHMENT = 0x2;
public static final int STENCIL_ATTACHMENT = 0x4;
public static final int UPLOADABLE = 0x8;
public static final int SAMPLEABLE = 0x10;
public static final int DEFAULT = UPLOADABLE | SAMPLEABLE;
}
public static final int BASE_LEVEL = 0;
public int getWidth(@IntRange(from = 0) int level) {
@@ -470,6 +496,34 @@ public class Texture {
nGenerateMipmaps(getNativeObject(), engine.getNativeObject());
}
public void generatePrefilterMipmap(@NonNull Engine engine,
@NonNull PixelBufferDescriptor buffer, @NonNull @Size(min = 6) int[] faceOffsetsInBytes,
PrefilterOptions options) {
int width = getWidth(0);
int height= getHeight(0);
int sampleCount = 8;
boolean mirror = true;
if (options != null) {
sampleCount = options.sampleCount;
mirror = options.mirror;
}
int result = nGeneratePrefilterMipmap(getNativeObject(), engine.getNativeObject(),
width, height,
buffer.storage, buffer.storage.remaining(),
buffer.left, buffer.top, buffer.type.ordinal(), buffer.alignment,
buffer.stride, buffer.format.ordinal(), faceOffsetsInBytes,
buffer.handler, buffer.callback,
sampleCount, mirror);
if (result < 0) {
throw new BufferOverflowException();
}
}
@UsedByReflection("TextureHelper.java")
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed Texture");
@@ -492,7 +546,7 @@ public class Texture {
private static native void nBuilderLevels(long nativeBuilder, int levels);
private static native void nBuilderSampler(long nativeBuilder, int sampler);
private static native void nBuilderFormat(long nativeBuilder, int format);
private static native void nBuilderRgbm(long nativeBuilder, boolean enabled);
private static native void nBuilderUsage(long nativeBuilder, int flags);
private static native long nBuilderBuild(long nativeBuilder, long nativeEngine);
private static native int nGetWidth(long nativeTexture, int level);
@@ -524,7 +578,8 @@ public class Texture {
int alignment, int compressedSizeInBytes, int compressedFormat,
int[] faceOffsetsInBytes, Object handler, Runnable callback);
private static native void nSetExternalImage(long nativeObject, long nativeObject1, long eglImage);
private static native void nSetExternalImage(
long nativeObject, long nativeEngine, long eglImage);
private static native void nSetExternalStream(long nativeTexture,
long nativeEngine, long nativeStream);
@@ -532,4 +587,9 @@ public class Texture {
private static native void nGenerateMipmaps(long nativeTexture, long nativeEngine);
private static native boolean nIsStreamValidForTexture(long nativeTexture, long nativeStream);
private static native int nGeneratePrefilterMipmap(long nativeIndirectLight, long nativeEngine,
int width, int height, Buffer storage, int remaining, int left, int top,
int type, int alignment, int stride, int format, int[] faceOffsetsInBytes,
Object handler, Runnable callback, int sampleCount, boolean mirror);
}

View File

@@ -57,7 +57,13 @@ public class TextureSampler {
int mSampler = 0; // bit field used by native
/**
* Min filter: LINEAR_MIPMAP_LINEAR
* Mag filter: LINEAR
* Wrap mode: REPEAT
*/
public TextureSampler() {
this(MinFilter.LINEAR_MIPMAP_LINEAR, MagFilter.LINEAR, WrapMode.REPEAT);
}
public TextureSampler(@NonNull MagFilter minMag) {

View File

@@ -57,9 +57,7 @@ public class TransformManager {
public void setTransform(@EntityInstance int i,
@NonNull @Size(min = 16) float[] localTransform) {
if (localTransform.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
Asserts.assertMat4fIn(localTransform);
nSetTransform(mNativeObject, i, localTransform);
}
@@ -67,7 +65,7 @@ public class TransformManager {
@Size(min = 16)
public float[] getTransform(@EntityInstance int i,
@Nullable @Size(min = 16) float[] outLocalTransform) {
outLocalTransform = assertMat4f(outLocalTransform);
outLocalTransform = Asserts.assertMat4f(outLocalTransform);
nGetTransform(mNativeObject, i, outLocalTransform);
return outLocalTransform;
}
@@ -76,7 +74,7 @@ public class TransformManager {
@Size(min = 16)
public float[] getWorldTransform(@EntityInstance int i,
@Nullable @Size(min = 16) float[] outWorldTransform) {
outWorldTransform = assertMat4f(outWorldTransform);
outWorldTransform = Asserts.assertMat4f(outWorldTransform);
nGetWorldTransform(mNativeObject, i, outWorldTransform);
return outWorldTransform;
}
@@ -89,15 +87,6 @@ public class TransformManager {
nCommitLocalTransformTransaction(mNativeObject);
}
@NonNull @Size(min = 16)
private static float[] assertMat4f(@Nullable float[] out) {
if (out == null) out = new float[16];
else if (out.length < 16) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 16");
}
return out;
}
private static native boolean nHasComponent(long nativeTransformManager, int entity);
private static native int nGetInstance(long nativeTransformManager, int entity);
private static native int nCreate(long nativeTransformManager, int entity);

View File

@@ -69,6 +69,23 @@ public class VertexBuffer {
HALF4,
}
public enum QuatType {
HALF4, // 2 bytes per component as half-floats (8 bytes per quat)
SHORT4, // 2 bytes per component as normalized integers (8 bytes per quat)
FLOAT4, // 4 bytes per component as floats (16 bytes per quat)
}
public static class QuatTangentContext {
public QuatType quatType; // desired quaternion type (required)
public int quatCount; // number of quaternions (required)
public Buffer outBuffer; // pre-allocated output buffer (required)
public int outStride; // desired stride in bytes (optional)
public Buffer normals; // source normals (required)
public int normalsStride; // normals stride in bytes (optional)
public Buffer tangents; // source tangents (optional)
public int tangentsStride; // tangents stride in bytes (optional)
}
public static class Builder {
@SuppressWarnings({"FieldCanBeLocal", "UnusedDeclaration"}) // Keep to finalize native resources
private final BuilderFinalizer mFinalizer;
@@ -108,7 +125,13 @@ public class VertexBuffer {
@NonNull
public Builder normalized(@NonNull VertexAttribute attribute) {
nBuilderNormalized(mNativeBuilder, attribute.ordinal());
nBuilderNormalized(mNativeBuilder, attribute.ordinal(), true);
return this;
}
@NonNull
public Builder normalized(@NonNull VertexAttribute attribute, boolean enabled) {
nBuilderNormalized(mNativeBuilder, attribute.ordinal(), enabled);
return this;
}
@@ -166,6 +189,14 @@ public class VertexBuffer {
}
}
public static void populateTangentQuaternions(@NonNull QuatTangentContext context) {
nPopulateTangentQuaternions(context.quatType.ordinal(), context.quatCount,
context.outBuffer, context.outBuffer.remaining(), context.outStride,
context.normals, context.normals.remaining(), context.normalsStride,
context.tangents, context.tangents != null ? context.tangents.remaining() : 0,
context.tangentsStride);
}
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed VertexBuffer");
@@ -183,11 +214,16 @@ public class VertexBuffer {
private static native void nBuilderBufferCount(long nativeBuilder, int bufferCount);
private static native void nBuilderAttribute(long nativeBuilder, int attribute,
int bufferIndex, int attributeType, int byteOffset, int byteStride);
private static native void nBuilderNormalized(long nativeBuilder, int attribute);
private static native void nBuilderNormalized(long nativeBuilder, int attribute,
boolean normalized);
private static native long nBuilderBuild(long nativeBuilder, long nativeEngine);
private static native int nGetVertexCount(long nativeVertexBuffer);
private static native int nSetBufferAt(long nativeVertexBuffer, long nativeEngine,
int bufferIndex, Buffer buffer, int remaining, int destOffsetInBytes, int count,
Object handler, Runnable callback);
private static native void nPopulateTangentQuaternions(int quatType, int quatCount,
Buffer outBuffer, int outRemaining, int outStride, Buffer normals, int normalsRemaining,
int normalsStride, Buffer tangents, int tangentsRemaining, int tangentsStride);
}

View File

@@ -30,7 +30,10 @@ public class View {
private Camera mCamera;
private Viewport mViewport = new Viewport(0, 0, 0, 0);
private DynamicResolutionOptions mDynamicResolution;
private RenderQuality mRenderQuality;
private DepthPrepass mDepthPrepass = DepthPrepass.DEFAULT;
private AmbientOcclusionOptions mAmbientOcclusionOptions;
private RenderTarget mRenderTarget;
public static class DynamicResolutionOptions {
public boolean enabled = false;
@@ -41,13 +44,46 @@ public class View {
public float minScale = 0.5f;
public float maxScale = 1.0f;
public int history = 9;
};
}
public static class AmbientOcclusionOptions {
public float radius = 0.3f;
public float bias = 0.005f;
public float power = 0.0f;
public float resolution = 0.5f;
}
public enum QualityLevel {
LOW,
MEDIUM,
HIGH,
ULTRA
}
public static class RenderQuality {
public QualityLevel hdrColorBuffer = QualityLevel.HIGH;
}
public enum AmbientOcclusion {
NONE,
SSAO
}
public enum AntiAliasing {
NONE,
FXAA
}
public enum ToneMapping {
LINEAR,
ACES
}
public enum Dithering {
NONE,
TEMPORAL
}
public enum DepthPrepass {
DEFAULT(-1),
DISABLED(0),
@@ -112,7 +148,7 @@ public class View {
@NonNull @Size(min = 4)
public float[] getClearColor(@NonNull @Size(min = 4) float[] out) {
out = assertFloat4(out);
out = Asserts.assertFloat4(out);
nGetClearColor(getNativeObject(), out);
return out;
}
@@ -131,6 +167,16 @@ public class View {
nSetShadowsEnabled(getNativeObject(), enabled);
}
public void setRenderTarget(@Nullable RenderTarget target) {
mRenderTarget = target;
nSetRenderTarget(getNativeObject(), target != null ? target.getNativeObject() : 0);
}
@Nullable
public RenderTarget getRenderTarget() {
return mRenderTarget;
}
public void setSampleCount(int count) {
nSetSampleCount(getNativeObject(), count);
}
@@ -148,6 +194,24 @@ public class View {
return AntiAliasing.values()[nGetAntiAliasing(getNativeObject())];
}
public void setToneMapping(@NonNull ToneMapping type) {
nSetToneMapping(getNativeObject(), type.ordinal());
}
@NonNull
public ToneMapping getToneMapping() {
return ToneMapping.values()[nGetToneMapping(getNativeObject())];
}
public void setDithering(@NonNull Dithering dithering) {
nSetDithering(getNativeObject(), dithering.ordinal());
}
@NonNull
public Dithering getDithering() {
return Dithering.values()[nGetDithering(getNativeObject())];
}
public void setDynamicResolutionOptions(@NonNull DynamicResolutionOptions options) {
mDynamicResolution = options;
nSetDynamicResolutionOptions(getNativeObject(),
@@ -169,13 +233,26 @@ public class View {
return mDynamicResolution;
}
public void setRenderQuality(@NonNull RenderQuality renderQuality) {
mRenderQuality = renderQuality;
nSetRenderQuality(getNativeObject(), renderQuality.hdrColorBuffer.ordinal());
}
@NonNull
public RenderQuality getRenderQuality() {
if (mRenderQuality == null) {
mRenderQuality = new RenderQuality();
}
return mRenderQuality;
}
@NonNull
public DepthPrepass getDepthPrepass() {
return mDepthPrepass;
}
public void setDepthPrepass(@NonNull DepthPrepass depthPrepass) {
mDepthPrepass = mDepthPrepass;
mDepthPrepass = depthPrepass;
nSetDepthPrepass(getNativeObject(), depthPrepass.value);
}
@@ -187,10 +264,40 @@ public class View {
nSetPostProcessingEnabled(getNativeObject(), enabled);
}
public boolean isFrontFaceWindingInverted() {
return nIsFrontFaceWindingInverted(getNativeObject());
}
public void setFrontFaceWindingInverted(boolean inverted) {
nSetFrontFaceWindingInverted(getNativeObject(), inverted);
}
public void setDynamicLightingOptions(float zLightNear, float zLightFar) {
nSetDynamicLightingOptions(getNativeObject(), zLightNear, zLightFar);
}
public void setAmbientOcclusion(@NonNull AmbientOcclusion ao) {
nSetAmbientOcclusion(getNativeObject(), ao.ordinal());
}
@NonNull
public AmbientOcclusion getAmbientOcclusion() {
return AmbientOcclusion.values()[nGetAmbientOcclusion(getNativeObject())];
}
public void setAmbientOcclusionOptions(@NonNull AmbientOcclusionOptions options) {
mAmbientOcclusionOptions = options;
nSetAmbientOcclusionOptions(getNativeObject(), options.radius, options.bias, options.power, options.resolution);
}
@NonNull
public AmbientOcclusionOptions getAmbientOcclusionOptions() {
if (mAmbientOcclusionOptions == null) {
mAmbientOcclusionOptions = new AmbientOcclusionOptions();
}
return mAmbientOcclusionOptions;
}
long getNativeObject() {
if (mNativeObject == 0) {
throw new IllegalStateException("Calling method on destroyed View");
@@ -202,15 +309,6 @@ public class View {
mNativeObject = 0;
}
@NonNull @Size(min = 4)
private static float[] assertFloat4(@Nullable float[] out) {
if (out == null) out = new float[4];
else if (out.length < 4) {
throw new ArrayIndexOutOfBoundsException("Array length must be at least 4");
}
return out;
}
private static native void nSetName(long nativeView, String name);
private static native void nSetScene(long nativeView, long nativeScene);
private static native void nSetCamera(long nativeView, long nativeCamera);
@@ -220,16 +318,27 @@ public class View {
private static native void nSetClearTargets(long nativeView, boolean color, boolean depth, boolean stencil);
private static native void nSetVisibleLayers(long nativeView, int select, int value);
private static native void nSetShadowsEnabled(long nativeView, boolean enabled);
private static native void nSetRenderTarget(long nativeView, long nativeRenderTarget);
private static native void nSetSampleCount(long nativeView, int count);
private static native int nGetSampleCount(long nativeView);
private static native void nSetAntiAliasing(long nativeView, int type);
private static native int nGetAntiAliasing(long nativeView);
private static native void nSetToneMapping(long nativeView, int type);
private static native int nGetToneMapping(long nativeView);
private static native void nSetDithering(long nativeView, int dithering);
private static native int nGetDithering(long nativeView);
private static native void nSetDynamicResolutionOptions(long nativeView,
boolean enabled, boolean homogeneousScaling,
float targetFrameTimeMilli, float headRoomRatio, float scaleRate,
float minScale, float maxScale, int history);
private static native void nSetRenderQuality(long nativeView, int hdrColorBufferQuality);
private static native void nSetDynamicLightingOptions(long nativeView, float zLightNear, float zLightFar);
private static native void nSetDepthPrepass(long nativeView, int value);
private static native void nSetPostProcessingEnabled(long nativeView, boolean enabled);
private static native boolean nIsPostProcessingEnabled(long nativeView);
private static native void nSetFrontFaceWindingInverted(long nativeView, boolean inverted);
private static native boolean nIsFrontFaceWindingInverted(long nativeView);
private static native void nSetAmbientOcclusion(long nativeView, int ordinal);
private static native int nGetAmbientOcclusion(long nativeView);
private static native void nSetAmbientOcclusionOptions(long nativeView, float radius, float bias, float power, float resolution);
}

View File

@@ -0,0 +1,96 @@
/*
* 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.
*/
package com.google.android.filament.android;
import android.graphics.Bitmap;
import android.support.annotation.IntRange;
import android.support.annotation.NonNull;
import com.google.android.filament.Engine;
import com.google.android.filament.Texture;
import java.lang.reflect.Method;
public final class TextureHelper {
// Keep in sync with Texture.cpp
private static final int BITMAP_CONFIG_ALPHA_8 = 0;
private static final int BITMAP_CONFIG_RGB_565 = 1;
private static final int BITMAP_CONFIG_RGBA_4444 = 2;
private static final int BITMAP_CONFIG_RGBA_8888 = 3;
private static final int BITMAP_CONFIG_RGBA_F16 = 4;
private static final int BITMAP_CONFIG_HARDWARE = 5;
private static Method sEngineGetNativeObject;
private static Method sTextureGetNativeObject;
static {
try {
sEngineGetNativeObject = Engine.class.getDeclaredMethod("getNativeObject");
sTextureGetNativeObject = Texture.class.getDeclaredMethod("getNativeObject");
sEngineGetNativeObject.setAccessible(true);
sTextureGetNativeObject.setAccessible(true);
} catch (NoSuchMethodException e) {
// Cannot happen
}
}
private TextureHelper() {
}
public static void setBitmap(@NonNull Engine engine,
@NonNull Texture texture, @IntRange(from = 0) int level, @NonNull Bitmap bitmap) {
setBitmap(engine, texture,
level, 0, 0, texture.getWidth(level), texture.getHeight(level), bitmap);
}
public static void setBitmap(@NonNull Engine engine,
@NonNull Texture texture, @IntRange(from = 0) int level,
@IntRange(from = 0) int xoffset, @IntRange(from = 0) int yoffset,
@IntRange(from = 0) int width, @IntRange(from = 0) int height,
@NonNull Bitmap bitmap) {
int format = toNativeFormat(bitmap.getConfig());
if (format == BITMAP_CONFIG_RGBA_4444 || format == BITMAP_CONFIG_HARDWARE) {
throw new IllegalArgumentException("Unsupported config: ARGB_4444 or HARDWARE");
}
try {
long nativeTexture = (Long) sTextureGetNativeObject.invoke(texture);
long nativeEngine = (Long) sEngineGetNativeObject.invoke(engine);
nSetBitmap(nativeTexture, nativeEngine, level, xoffset, yoffset, width, height,
bitmap, format);
} catch (Exception e) {
// Ignored
}
}
private static int toNativeFormat(Bitmap.Config config) {
switch (config) {
case ALPHA_8: return BITMAP_CONFIG_ALPHA_8;
case RGB_565: return BITMAP_CONFIG_RGB_565;
case ARGB_4444: return BITMAP_CONFIG_RGBA_4444;
case ARGB_8888: return BITMAP_CONFIG_RGBA_8888;
case RGBA_F16: return BITMAP_CONFIG_RGBA_F16;
case HARDWARE: return BITMAP_CONFIG_HARDWARE;
}
return BITMAP_CONFIG_RGBA_8888;
}
private static native void nSetBitmap(long nativeTexture, long nativeEngine,
int level, int xoffset, int yoffset, int width, int height, Bitmap bitmap, int format);
}

View File

@@ -16,15 +16,111 @@
package com.google.android.filament.android;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.TextureView;
import com.google.android.filament.SwapChain;
/**
* UiHelper is a simple class that can manage either a SurfaceView or a TextureView so it can
* be used to render into with Filament.
*
* Here is a simple example with a SurfaceView. The code would be exactly the same with a
* TextureView:
*
* <pre>
* public class FilamentActivity extends Activity {
* private UiHelper mUiHelper;
* private SurfaceView mSurfaceView;
*
* // Filament specific APIs
* private Engine mEngine;
* private Renderer mRenderer;
* private View mView; // com.google.android.filament.View, not android.view.View
* private SwapChain mSwapChain;
*
* public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
*
* // Create a SurfaceView and add it to the activity
* mSurfaceView = new SurfaceView(this);
* setContentView(mSurfaceView);
*
* // Create the Filament UI helper
* mUiHelper = new UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK);
*
* // Attach the SurfaceView to the helper, you could do the same with a TextureView
* mUiHelper.attachTo(mSurfaceView);
*
* // Set a rendering callback that we will use to invoke Filament
* mUiHelper.setRenderCallback(new UiHelper.RendererCallback() {
* public void onNativeWindowChanged(Surface surface) {
* if (mSwapChain != null) mEngine.destroySwapChain(mSwapChain);
* mSwapChain = mEngine.createSwapChain(surface, mUiHelper.getSwapChainFlags());
* }
*
* // The native surface went away, we must stop rendering.
* public void onDetachedFromSurface() {
* if (mSwapChain != null) {
* mEngine.destroySwapChain(mSwapChain);
*
* // Required to ensure we don't return before Filament is done executing the
* // destroySwapChain command, otherwise Android might destroy the Surface
* // too early
* mEngine.flushAndWait();
*
* mSwapChain = null;
* }
* }
*
* // The native surface has changed size. This is always called at least once
* // after the surface is created (after onNativeWindowChanged() is invoked).
* public void onResized(int width, int height) {
* // Compute camera projection and set the viewport on the view
* }
* });
*
* mEngine = Engine.create();
* mRenderer = mEngine.createRenderer();
* mView = mEngine.createView();
* // Create scene, camera, etc.
* }
*
* public void onDestroy() {
* super.onDestroy();
* // Always detach the surface before destroying the engine
* mUiHelper.detach();
*
* // This ensures that all the commands we've sent to Filament have
* // been processed before we attempt to destroy anything
* Fence.waitAndDestroy(mEngine.createFence(Fence.Type.SOFT), Fence.Mode.FLUSH);
*
* mEngine.destroy();
* }
*
* // This is an example of a render function. You will most likely invoke this from
* // a Choreographer callback to trigger rendering at vsync.
* public void render() {
* if (mUiHelper.isReadyToRender) {
* // If beginFrame() returns false you should skip the frame
* // This means you are sending frames too quickly to the GPU
* if (mRenderer.beginFrame(swapChain)) {
* mRenderer.render(mView);
* mRenderer.endFrame();
* }
* }
* }
* }
* </pre>
*/
public class UiHelper {
private static final String LOG_TAG = "UiHelper";
private static final boolean LOGGING = false;
@@ -36,27 +132,46 @@ public class UiHelper {
private RendererCallback mRenderCallback;
private boolean mHasSwapChain;
private RenderSurface mRenderSurface;
private boolean mOpaque = true;
/**
* Enum used to decide whether UiHelper should perform extra error checking.
*
* @see UiHelper#UiHelper(ContextErrorPolicy)
*/
public enum ContextErrorPolicy {
CHECK, DONT_CHECK
/** Check for extra errors. */
CHECK,
/** Do not check for extra errors. */
DONT_CHECK
}
/**
* Interface used to know when the native surface is created, destroyed or resized.
*
* @see #setRenderCallback(RendererCallback)
*/
public interface RendererCallback {
// called when the underlying native window has changed
// NOTE: this could be called from UiHelper's constructor.
/**
* Called when the underlying native window has changed.
*/
void onNativeWindowChanged(Surface surface);
// called when the surface is going away. after this call isReadyToRender() returns false.
// you MUST have stopped drawing when returning.
// This is called from detach() or if the surface disappears on its own.
/**
* Called when the surface is going away. After this call <code>isReadyToRender()</code>
* returns false. You MUST have stopped drawing when returning.
* This is called from detach() or if the surface disappears on its own.
*/
void onDetachedFromSurface();
// called when the underlying native window has been resized
/**
* Called when the underlying native window has been resized.
*/
void onResized(int width, int height);
}
// --------------------------------------------------------------------------------------------
private interface RenderSurface {
void resize(int width, int height);
void detach();
@@ -108,39 +223,46 @@ public class UiHelper {
mSurface = surface;
}
}
// --------------------------------------------------------------------------------------------
private RenderSurface mRenderSurface;
/**
* Creates a UiHelper which will help manage the EGL context
* and EGL surfaces. UiHelper handles SurfaceView and TextureView.
*
* When this call returns, OpenGL ES is ready to use.
* Creates a UiHelper which will help manage the native surface provided by a
* SurfaceView or a TextureView.
*/
public UiHelper() {
this(ContextErrorPolicy.CHECK);
}
/**
* Creates a UiHelper which will help manage the native surface provided by a
* SurfaceView or a TextureView.
*
* @param policy The error checking policy to use.
*/
public UiHelper(ContextErrorPolicy policy) {
// TODO: do something with policy
}
public UiHelper(int sampleCount, RendererCallback renderCallback) {
this();
setRenderCallback(renderCallback);
}
public void setRenderCallback(RendererCallback renderCallback) {
/**
* Sets the renderer callback that will be notified when the native surface is
* created, destroyed or resized.
*
* @param renderCallback The callback to register.
*/
public void setRenderCallback(@Nullable RendererCallback renderCallback) {
mRenderCallback = renderCallback;
}
/**
* Returns the current render callback associated with this UiHelper.
*/
@Nullable
public RendererCallback getRenderCallback() {
return mRenderCallback;
}
/**
* Free resources associated to the native window specified in attachTo().
* Free resources associated to the native window specified in {@link #attachTo(SurfaceView)}
* or {@link #attachTo(TextureView)}.
*/
public void detach() {
destroySwapChain();
@@ -148,13 +270,6 @@ public class UiHelper {
mRenderSurface = null;
}
@Override
protected void finalize() throws Throwable {
super.finalize();
// TODO: check that detach() has been called
// TODO: call Surface.release() if not already done
}
/**
* Checks whether we are ready to render into the attached surface.
*
@@ -168,7 +283,7 @@ public class UiHelper {
}
/**
* Set the size of the underlying buffers
* Set the size of the render target buffers of the native surface.
*/
public void setDesiredSize(int width, int height) {
mDesiredWidth = width;
@@ -178,51 +293,97 @@ public class UiHelper {
}
}
/**
* Returns the requested width for the native surface.
*/
public int getDesiredWidth() {
return mDesiredWidth;
}
/**
* Returns the requested height for the native surface.
*/
public int getDesiredHeight() {
return mDesiredHeight;
}
/**
* Returns true if the render target is opaque.
*/
public boolean isOpaque() {
return mOpaque;
}
/**
* Controls whether the render target (SurfaceView or TextureView) is opaque or not.
* The render target is considered opaque by default.
*
* Must be called before calling {@link #attachTo(SurfaceView)}
* or {@link #attachTo(TextureView)}.
*
* @param opaque Indicates whether the render target should be opaque. True by default.
*/
public void setOpaque(boolean opaque) {
mOpaque = opaque;
}
/**
* Returns the flags to pass to
* {@link com.google.android.filament.Engine#createSwapChain(Object, long)} to honor all
* the options set on this UiHelper.
*/
public long getSwapChainFlags() {
return isOpaque() ? SwapChain.CONFIG_DEFAULT : SwapChain.CONFIG_TRANSPARENT;
}
/**
* Associate UiHelper with a SurfaceView.
*
* As soon as SurfaceView is ready (i.e. has a Surface), we'll create the
* EGL resources needed, and call user callbacks if needed.
*/
public void attachTo(SurfaceView view) {
final SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (LOGGING) Log.d(LOG_TAG, "surfaceCreated()");
createSwapChain(holder.getSurface());
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Note: this is always called at least once after surfaceCreated()
if (LOGGING) Log.d(LOG_TAG, "surfaceChanged(" + width + ", " + height + ")");
mRenderCallback.onResized(width, height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (LOGGING) Log.d(LOG_TAG, "surfaceDestroyed()");
destroySwapChain();
}
};
public void attachTo(@NonNull SurfaceView view) {
if (attach(view)) {
if (!isOpaque()) {
view.setZOrderOnTop(true);
view.getHolder().setFormat(PixelFormat.TRANSLUCENT);
}
mRenderSurface = new SurfaceViewHandler(view);
final SurfaceHolder.Callback callback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (LOGGING) Log.d(LOG_TAG, "surfaceCreated()");
createSwapChain(holder.getSurface());
}
@Override
public void surfaceChanged(
SurfaceHolder holder, int format, int width, int height) {
// Note: this is always called at least once after surfaceCreated()
if (LOGGING) Log.d(LOG_TAG, "surfaceChanged(" + width + ", " + height + ")");
mRenderCallback.onResized(width, height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (LOGGING) Log.d(LOG_TAG, "surfaceDestroyed()");
destroySwapChain();
}
};
SurfaceHolder holder = view.getHolder();
holder.addCallback(callback);
holder.setFixedSize(mDesiredWidth, mDesiredHeight);
// in case the SurfaceView's surface already existed
final Surface surface = holder.getSurface();
if (surface != null && surface.isValid()) {
callback.surfaceCreated(holder);
int format = isOpaque() ? PixelFormat.OPAQUE : PixelFormat.TRANSLUCENT;
callback.surfaceChanged(holder, format,
holder.getSurfaceFrame().width(), holder.getSurfaceFrame().height());
}
}
}
@@ -233,49 +394,64 @@ public class UiHelper {
* As soon as TextureView is ready (i.e. has a buffer), we'll create the
* EGL resources needed, and call user callbacks if needed.
*/
public void attachTo(TextureView view) {
final TextureView.SurfaceTextureListener listener = new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureAvailable()");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
surfaceTexture.setDefaultBufferSize(mDesiredWidth, mDesiredHeight);
}
Surface surface = new Surface(surfaceTexture);
TextureViewHandler textureViewHandler = (TextureViewHandler)mRenderSurface;
textureViewHandler.setSurface(surface);
createSwapChain(surface);
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureSizeChanged()");
mRenderCallback.onResized(width, height);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureDestroyed()");
destroySwapChain();
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) { }
};
public void attachTo(@NonNull TextureView view) {
if (attach(view)) {
view.setOpaque(isOpaque());
mRenderSurface = new TextureViewHandler(view);
TextureView.SurfaceTextureListener listener = new TextureView.SurfaceTextureListener() {
@Override
public void onSurfaceTextureAvailable(
SurfaceTexture surfaceTexture, int width, int height) {
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureAvailable()");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
if (mDesiredWidth > 0 && mDesiredHeight > 0) {
surfaceTexture.setDefaultBufferSize(mDesiredWidth, mDesiredHeight);
}
}
Surface surface = new Surface(surfaceTexture);
TextureViewHandler textureViewHandler = (TextureViewHandler) mRenderSurface;
textureViewHandler.setSurface(surface);
createSwapChain(surface);
// Call this the first time because onSurfaceTextureSizeChanged()
// isn't called at initialization time
mRenderCallback.onResized(width, height);
}
@Override
public void onSurfaceTextureSizeChanged(
SurfaceTexture surfaceTexture, int width, int height) {
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureSizeChanged()");
mRenderCallback.onResized(width, height);
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
if (LOGGING) Log.d(LOG_TAG, "onSurfaceTextureDestroyed()");
destroySwapChain();
return true;
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) { }
};
view.setSurfaceTextureListener(listener);
// in case the View's SurfaceTexture already existed
if (view.isAvailable()) {
final SurfaceTexture surfaceTexture = view.getSurfaceTexture();
SurfaceTexture surfaceTexture = view.getSurfaceTexture();
listener.onSurfaceTextureAvailable(surfaceTexture, mDesiredWidth, mDesiredHeight);
}
}
}
private boolean attach(Object nativeWindow) {
private boolean attach(@NonNull Object nativeWindow) {
if (mNativeWindow != null) {
// we are already attached to a native window
if (mNativeWindow == nativeWindow) {
@@ -288,8 +464,8 @@ public class UiHelper {
return true;
}
private void createSwapChain(Surface sur) {
mRenderCallback.onNativeWindowChanged(sur);
private void createSwapChain(@NonNull Surface surface) {
mRenderCallback.onNativeWindowChanged(surface);
mHasSwapChain = true;
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright (C) 2019 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.
*/
package com.google.android.filament.proguard;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Annotation used for marking methods and fields that are called from native
* code. Useful for keeping components that would otherwise be removed by
* Proguard. Use the value parameter to mention a file that calls this method.
*
* Note that adding this annotation to a method is not enough to guarantee that
* it is kept - either its class must be referenced elsewhere in the program, or
* the class must be annotated with this as well.
*
* Usage example:<br />
* {@code
* @UsedByNative("NativeCrashHandler.cpp")
public static void reportCrash(int signal, int code, int address) {
...
}
}
*/
@Target({
ElementType.METHOD,
ElementType.FIELD,
ElementType.TYPE,
ElementType.CONSTRUCTOR})
public @interface UsedByNative {
String value();
}

View File

@@ -0,0 +1,47 @@
/*
* Copyright (C) 2019 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.
*/
package com.google.android.filament.proguard;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Annotation used for marking methods and fields that are called by reflection. Useful for keeping
* components that would otherwise be removed by Proguard. Use the value parameter to mention a file
* that calls this method.
*
* Note that adding this annotation to a method is not enough to guarantee that
* it is kept - either its class must be referenced elsewhere in the program, or
* the class must be annotated with this as well.
*
* Usage example:<br />
* {@code
* @UsedByReflection("PeopleListItemView.java")
public PeopleListItemViewV11(Context context) {
super(context);
}
}
*/
@Target({
ElementType.METHOD,
ElementType.FIELD,
ElementType.TYPE,
ElementType.CONSTRUCTOR})
public @interface UsedByReflection {
String value();
}

11
android/gltfio-android/.gitignore vendored Normal file
View File

@@ -0,0 +1,11 @@
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
/.idea/caches
/.idea/gradle.xml
.DS_Store
/build
/captures
.externalNativeBuild

View File

@@ -0,0 +1,89 @@
cmake_minimum_required(VERSION 3.6)
set(FILAMENT_DIR ${FILAMENT_DIST_DIR})
add_library(filament SHARED IMPORTED)
set_target_properties(filament PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libfilament.a)
add_library(backend SHARED IMPORTED)
set_target_properties(backend PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libbackend.a)
add_library(utils SHARED IMPORTED)
set_target_properties(utils PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libutils.a)
add_library(filaflat SHARED IMPORTED)
set_target_properties(filaflat PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libfilaflat.a)
add_library(image STATIC IMPORTED)
set_target_properties(image PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libimage.a)
add_library(ibl STATIC IMPORTED)
set_target_properties(ibl PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libibl.a)
add_library(geometry SHARED IMPORTED)
set_target_properties(geometry PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libgeometry.a)
add_library(filabridge SHARED IMPORTED)
set_target_properties(filabridge PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libfilabridge.a)
add_library(gltfio SHARED IMPORTED)
set_target_properties(gltfio PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libgltfio_core.a)
add_library(gltfio_resources SHARED IMPORTED)
set_target_properties(gltfio_resources PROPERTIES IMPORTED_LOCATION
${FILAMENT_DIR}/lib/${ANDROID_ABI}/libgltfio_resources.a)
include_directories(${FILAMENT_DIR}/include
..
../../libs/utils/include)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-stack-protector")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fno-exceptions -fno-unwind-tables -fno-asynchronous-unwind-tables -fno-rtti")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -ffast-math -ffp-contract=fast")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility-inlines-hidden")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fvisibility=hidden")
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -fomit-frame-pointer -ffunction-sections -fdata-sections")
set(CMAKE_SHARED_LINKER_FLAGS " ${CMAKE_SHARED_LINKER_FLAGS} -Wl,--gc-sections")
set(CMAKE_SHARED_LINKER_FLAGS " ${CMAKE_SHARED_LINKER_FLAGS} -Wl,-Bsymbolic-functions")
set(CMAKE_SHARED_LINKER_FLAGS_RELEASE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE} -Wl,--version-script=${CMAKE_SOURCE_DIR}/libgltfio-jni.map")
add_library(gltfio-jni SHARED
src/main/cpp/AssetLoader.cpp
src/main/cpp/FilamentAsset.cpp
src/main/cpp/KtxLoader.cpp
src/main/cpp/MaterialProvider.cpp
src/main/cpp/ResourceLoader.cpp
../common/CallbackUtils.cpp
../common/NioUtils.cpp
)
set_target_properties(gltfio-jni PROPERTIES LINK_DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/libgltfio-jni.symbols)
# The ordering in the following list is important because CMake does not have dependency information.
target_link_libraries(gltfio-jni
gltfio
gltfio_resources
filament
filabridge
backend
filaflat
geometry
image
ibl
utils
GLESv3
EGL
m
log
)

View File

@@ -0,0 +1,90 @@
// This script accepts the following parameters:
//
// filament_dist_dir
// Path to the Filament distribution/install directory for Android
// (produced by make/ninja install). This directory must contain lib/arm64-v8a/ etc.
//
// Example:
// ./gradlew -Pfilament_dist_dir=../../dist-android-release assembleRelease
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
group = "com.google.android.filament"
version = "0.1"
apply plugin: 'com.android.library'
def filament_path = file("../../out/android-release/filament").absolutePath
if (project.hasProperty("filament_dist_dir")) {
filament_path = file("$filament_dist_dir").absolutePath
}
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 14
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
externalNativeBuild {
cmake {
arguments.add("-DANDROID_PIE=ON")
arguments.add("-DANDROID_PLATFORM=android-21")
arguments.add("-DANDROID_STL=c++_static")
arguments.add("-DFILAMENT_DIST_DIR=${filament_path}".toString())
cppFlags.add("-std=c++14")
if (project.hasProperty('extra_cmake_args')) {
arguments.add(extra_cmake_args)
}
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
externalNativeBuild {
cmake {
path "CMakeLists.txt"
}
}
sourceSets {
main {
jni.srcDirs "src/main/cpp"
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:support-annotations:28.0.0'
implementation 'com.google.android.filament:filament-android'
}

Binary file not shown.

View File

@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

172
android/gltfio-android/gradlew vendored Executable file
View File

@@ -0,0 +1,172 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
android/gltfio-android/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,84 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,4 @@
LIBGLTFIO {
global: Java_com_google_android_filament_*; JNI*;
local: *;
};

View File

@@ -0,0 +1 @@
_Java_com_google_android_filament_*

View File

@@ -0,0 +1,12 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user guide at https://docs.gradle.org/4.6/userguide/multi_project_builds.html
*/
includeBuild '../filament-android'
rootProject.name = 'gltfio-android'

View File

@@ -0,0 +1,18 @@
<!--
Copyright (C) 2019 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.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.filament.gltfio" />

View File

@@ -0,0 +1,85 @@
/*
* Copyright (C) 2019 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 <jni.h>
#include <filament/Engine.h>
#include <utils/EntityManager.h>
#include <gltfio/AssetLoader.h>
#include <gltfio/MaterialProvider.h>
#include "common/NioUtils.h"
using namespace filament;
using namespace gltfio;
using namespace utils;
extern void registerCallbackUtils(JNIEnv*);
extern void registerNioUtils(JNIEnv*);
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
JNIEnv* env;
if (vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
registerCallbackUtils(env);
registerNioUtils(env);
return JNI_VERSION_1_6;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_AssetLoader_nCreateAssetLoader(JNIEnv*, jclass,
jlong nativeEngine, jlong nativeProvider, jlong nativeEntities) {
Engine* engine = (Engine*) nativeEngine;
MaterialProvider* materials = (MaterialProvider*) nativeProvider;
EntityManager* entities = (EntityManager*) nativeEntities;
return (jlong) AssetLoader::create({engine, materials, nullptr, entities});
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_AssetLoader_nDestroyAssetLoader(JNIEnv*, jclass,
jlong nativeLoader) {
AssetLoader* loader = (AssetLoader*) nativeLoader;
AssetLoader::destroy(&loader);
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_AssetLoader_nCreateAssetFromBinary(JNIEnv* env, jclass,
jlong nativeLoader, jobject javaBuffer, jint remaining) {
AssetLoader* loader = (AssetLoader*) nativeLoader;
AutoBuffer buffer(env, javaBuffer, remaining);
return (jlong) loader->createAssetFromBinary((const uint8_t *) buffer.getData(),
buffer.getSize());
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_AssetLoader_nEnableDiagnostics(JNIEnv*, jclass,
jlong nativeLoader, jboolean enable) {
AssetLoader* loader = (AssetLoader*) nativeLoader;
loader->enableDiagnostics(enable);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_AssetLoader_nDestroyAsset(JNIEnv*, jclass,
jlong nativeLoader, jlong nativeAsset) {
AssetLoader* loader = (AssetLoader*) nativeLoader;
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
loader->destroyAsset(asset);
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright (C) 2019 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 <jni.h>
#include <gltfio/FilamentAsset.h>
using namespace filament;
using namespace filament::math;
using namespace gltfio;
using namespace utils;
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetRoot(JNIEnv*, jclass, jlong nativeAsset) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
return asset->getRoot().getId();
}
extern "C" JNIEXPORT jint JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetEntityCount(JNIEnv*, jclass,
jlong nativeAsset) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
return asset->getEntityCount();
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetEntities(JNIEnv* env, jclass,
jlong nativeAsset, jintArray result) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
Entity* entities = (Entity*) env->GetIntArrayElements(result, nullptr);
std::copy_n(asset->getEntities(), asset->getEntityCount(), entities);
env->ReleaseIntArrayElements(result, (jint*) entities, 0);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_FilamentAsset_nGetBoundingBox(JNIEnv* env, jclass,
jlong nativeAsset, jfloatArray result) {
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
float* values = (float*) env->GetFloatArrayElements(result, nullptr);
const filament::Aabb box = asset->getBoundingBox();
const float3 center = box.center();
const float3 extent = box.extent();
values[0] = center.x;
values[1] = center.y;
values[2] = center.z;
values[3] = extent.x;
values[4] = extent.y;
values[5] = extent.z;
env->ReleaseFloatArrayElements(result, (jfloat*) values, 0);
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright (C) 2019 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 <jni.h>
#include <filament/Engine.h>
#include <filament/IndirectLight.h>
#include <filament/Skybox.h>
#include <image/KtxUtility.h>
#include "common/NioUtils.h"
using namespace filament;
using namespace filament::math;
using namespace image;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_KtxLoader_nCreateTexture(JNIEnv* env, jclass,
jlong nativeEngine, jobject javaBuffer, jint remaining, jboolean srgb) {
Engine* engine = (Engine*) nativeEngine;
AutoBuffer buffer(env, javaBuffer, remaining);
KtxBundle* bundle = new KtxBundle((const uint8_t*) buffer.getData(), buffer.getSize());
return (jlong) KtxUtility::createTexture(engine, *bundle, srgb, [](void* userdata) {
KtxBundle* bundle = (KtxBundle*) userdata;
delete bundle;
}, bundle);
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_KtxLoader_nCreateIndirectLight(JNIEnv* env, jclass,
jlong nativeEngine, jobject javaBuffer, jint remaining, jboolean srgb) {
Engine* engine = (Engine*) nativeEngine;
AutoBuffer buffer(env, javaBuffer, remaining);
KtxBundle* bundle = new KtxBundle((const uint8_t*) buffer.getData(), buffer.getSize());
Texture* cubemap = KtxUtility::createTexture(engine, *bundle, srgb, [](void* userdata) {
KtxBundle* bundle = (KtxBundle*) userdata;
delete bundle;
}, bundle);
float3 harmonics[9];
bundle->getSphericalHarmonics(harmonics);
IndirectLight* indirectLight = IndirectLight::Builder()
.reflections(cubemap)
.irradiance(3, harmonics)
.intensity(30000)
.build(*engine);
return (jlong) indirectLight;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_KtxLoader_nCreateSkybox(JNIEnv* env, jclass,
jlong nativeEngine, jobject javaBuffer, jint remaining, jboolean srgb) {
Engine* engine = (Engine*) nativeEngine;
AutoBuffer buffer(env, javaBuffer, remaining);
KtxBundle* bundle = new KtxBundle((const uint8_t*) buffer.getData(), buffer.getSize());
Texture* cubemap = KtxUtility::createTexture(engine, *bundle, srgb, [](void* userdata) {
KtxBundle* bundle = (KtxBundle*) userdata;
delete bundle;
}, bundle);
return (jlong) Skybox::Builder().environment(cubemap).showSun(true).build(*engine);
}

View File

@@ -0,0 +1,36 @@
/*
* Copyright (C) 2019 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 <jni.h>
#include <gltfio/MaterialProvider.h>
using namespace filament;
using namespace gltfio;
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_MaterialProvider_nCreateMaterialProvider(JNIEnv*, jclass,
jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) createUbershaderLoader(engine);
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_MaterialProvider_nDestroyMaterialProvider(JNIEnv*, jclass,
jlong nativeProvider) {
auto provider = (MaterialProvider*) nativeProvider;
delete provider;
}

View File

@@ -0,0 +1,67 @@
/*
* Copyright (C) 2019 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 <jni.h>
#include <filament/Engine.h>
#include <gltfio/ResourceLoader.h>
#include <utils/Log.h>
#include "common/NioUtils.h"
using namespace filament;
using namespace gltfio;
using namespace utils;
static void destroy(void* data, size_t size, void *userData) {
AutoBuffer* buffer = (AutoBuffer*) userData;
delete buffer;
}
extern "C" JNIEXPORT jlong JNICALL
Java_com_google_android_filament_gltfio_ResourceLoader_nCreateResourceLoader(JNIEnv*, jclass,
jlong nativeEngine) {
Engine* engine = (Engine*) nativeEngine;
return (jlong) new ResourceLoader({ engine, utils::Path(), true, true });
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_ResourceLoader_nDestroyResourceLoader(JNIEnv*, jclass,
jlong nativeLoader) {
ResourceLoader* loader = (ResourceLoader*) nativeLoader;
delete loader;
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_ResourceLoader_nAddResourceData(JNIEnv* env, jclass,
jlong nativeLoader, jstring url, jobject javaBuffer, jint remaining) {
ResourceLoader* loader = (ResourceLoader*) nativeLoader;
AutoBuffer* buffer = new AutoBuffer(env, javaBuffer, remaining);
const char* curl = env->GetStringUTFChars(url, nullptr);
loader->addResourceData(curl,
ResourceLoader::BufferDescriptor(buffer->getData(), buffer->getSize(), &destroy,
buffer));
}
extern "C" JNIEXPORT void JNICALL
Java_com_google_android_filament_gltfio_ResourceLoader_nLoadResources(JNIEnv*, jclass,
jlong nativeLoader, jlong nativeAsset) {
ResourceLoader* loader = (ResourceLoader*) nativeLoader;
FilamentAsset* asset = (FilamentAsset*) nativeAsset;
loader->loadResources(asset);
}

View File

@@ -0,0 +1,103 @@
/*
* Copyright (C) 2019 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.
*/
package com.google.android.filament.gltfio;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.android.filament.Engine;
import com.google.android.filament.EntityManager;
import com.google.android.filament.IndirectLight;
import com.google.android.filament.Skybox;
import com.google.android.filament.Texture;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.nio.Buffer;
public class AssetLoader {
private long mNativeObject;
static Method sEngineGetNativeObject;
static Method sEntityManagerGetNativeObject;
static Constructor<Texture> sTextureConstructor;
static Constructor<IndirectLight> sIndirectLightConstructor;
static Constructor<Skybox> sSkyboxConstructor;
public static void init() {
System.loadLibrary("gltfio-jni");
try {
sEngineGetNativeObject = Engine.class.getDeclaredMethod("getNativeObject");
sEngineGetNativeObject.setAccessible(true);
sEntityManagerGetNativeObject = EntityManager.class.getDeclaredMethod("getNativeObject");
sEntityManagerGetNativeObject.setAccessible(true);
sTextureConstructor = Texture.class.getDeclaredConstructor(long.class);
sTextureConstructor.setAccessible(true);
sIndirectLightConstructor = IndirectLight.class.getDeclaredConstructor(long.class);
sIndirectLightConstructor.setAccessible(true);
sSkyboxConstructor = Skybox.class.getDeclaredConstructor(long.class);
sSkyboxConstructor.setAccessible(true);
} catch (NoSuchMethodException e) {
// Cannot happen
}
}
public AssetLoader(@NonNull Engine engine, @NonNull MaterialProvider generator,
@NonNull EntityManager entities) {
try {
long nativeEngine = (long) sEngineGetNativeObject.invoke(engine);
long nativeMaterials = generator.getNativeObject();
long nativeEntities = (long) sEntityManagerGetNativeObject.invoke(entities);
mNativeObject = nCreateAssetLoader(nativeEngine, nativeMaterials, nativeEntities);
} catch (Exception e) {
// Ignored
}
if (mNativeObject == 0) {
throw new IllegalStateException("Unable to parse glTF asset.");
}
}
public void destroy() {
nDestroyAssetLoader(mNativeObject);
mNativeObject = 0;
}
@Nullable
public FilamentAsset createAssetFromBinary(@NonNull Buffer buffer) {
long nativeAsset = nCreateAssetFromBinary(mNativeObject, buffer, buffer.remaining());
return new FilamentAsset(nativeAsset);
}
public void enableDiagnostics(boolean enable) {
nEnableDiagnostics(mNativeObject, enable);
}
public void destroyAsset(@Nullable FilamentAsset asset) {
nDestroyAsset(mNativeObject, asset.getNativeObject());
asset.clearNativeObject();
}
private static native long nCreateAssetLoader(long nativeEngine, long nativeGenerator, long nativeEntities);
private static native void nDestroyAssetLoader(long nativeLoader);
private static native long nCreateAssetFromBinary(long nativeLoader, Buffer buffer, int remaining);
private static native void nEnableDiagnostics(long nativeLoader, boolean enable);
private static native void nDestroyAsset(long nativeLoader, long nativeAsset);
}

View File

@@ -0,0 +1,59 @@
/*
* Copyright (C) 2019 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.
*/
package com.google.android.filament.gltfio;
import android.support.annotation.NonNull;
import com.google.android.filament.Box;
import com.google.android.filament.Entity;
public class FilamentAsset {
private long mNativeObject;
FilamentAsset(long nativeObject) {
mNativeObject = nativeObject;
}
long getNativeObject() {
return mNativeObject;
}
public @Entity int getRoot() {
return nGetRoot(mNativeObject);
}
public @Entity int[] getEntities() {
int[] result = new int[nGetEntityCount(mNativeObject)];
nGetEntities(mNativeObject, result);
return result;
}
public @NonNull Box getBoundingBox() {
float[] box = new float[6];
nGetBoundingBox(mNativeObject, box);
return new Box(box[0], box[1], box[2], box[3], box[4], box[5]);
}
void clearNativeObject() {
mNativeObject = 0;
}
private static native int nGetRoot(long nativeAsset);
private static native int nGetEntityCount(long nativeAsset);
private static native void nGetEntities(long nativeAsset, int[] result);
private static native void nGetBoundingBox(long nativeAsset, float[] box);
}

Some files were not shown because too many files have changed in this diff Show More