diff --git a/Assets/Editor/ObjectIcons/AreaTrigger.bmp b/Assets/Editor/ObjectIcons/AreaTrigger.bmp deleted file mode 100644 index 779e9bd30f..0000000000 --- a/Assets/Editor/ObjectIcons/AreaTrigger.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4cf08659d31a337ceb28de2765b0177abf404f3e671f5277dd7a280f2fd6c60d -size 3128 diff --git a/Assets/Editor/ObjectIcons/AudioAreaAmbience.bmp b/Assets/Editor/ObjectIcons/AudioAreaAmbience.bmp deleted file mode 100644 index 052eb463cb..0000000000 --- a/Assets/Editor/ObjectIcons/AudioAreaAmbience.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:706b12b37518596b01fc6c5cdb3aadc5fdbe76b668e9989ba2bb03ee23376dbf -size 3126 diff --git a/Assets/Editor/ObjectIcons/AudioAreaEntity.bmp b/Assets/Editor/ObjectIcons/AudioAreaEntity.bmp deleted file mode 100644 index b490f91bc4..0000000000 --- a/Assets/Editor/ObjectIcons/AudioAreaEntity.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7e67540926b2d55c70ac5867266ac9688437fc139b459f165f9d52d9b351851c -size 3128 diff --git a/Assets/Editor/ObjectIcons/AudioAreaRandom.bmp b/Assets/Editor/ObjectIcons/AudioAreaRandom.bmp deleted file mode 100644 index 73a0a21256..0000000000 --- a/Assets/Editor/ObjectIcons/AudioAreaRandom.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:96ec04e8126bcffb7fe391dc55ea1aa6a82419825c8305117f9b0ae72b40e63e -size 3126 diff --git a/Assets/Editor/ObjectIcons/Camera.bmp b/Assets/Editor/ObjectIcons/Camera.bmp deleted file mode 100644 index fd89801011..0000000000 --- a/Assets/Editor/ObjectIcons/Camera.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4168676b803b7e3b03a90fb69502204a418b6598941c75f0c36e589a31455db5 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Checkpoint.bmp b/Assets/Editor/ObjectIcons/Checkpoint.bmp deleted file mode 100644 index fd31d3c446..0000000000 --- a/Assets/Editor/ObjectIcons/Checkpoint.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b11c94da25b704a36f2b437dae98c04a5cea54f02022567306e2cf82837bf7a1 -size 3128 diff --git a/Assets/Editor/ObjectIcons/ClipVolume.bmp b/Assets/Editor/ObjectIcons/ClipVolume.bmp deleted file mode 100644 index dba0aa32ba..0000000000 --- a/Assets/Editor/ObjectIcons/ClipVolume.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8ca14c966de6d392beb4d154221b622a417163fcdf92eb049638bf8495c13774 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Clock.bmp b/Assets/Editor/ObjectIcons/Clock.bmp deleted file mode 100644 index 1557a7e8dc..0000000000 --- a/Assets/Editor/ObjectIcons/Clock.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6d11fd9413f06706bc706a97f39cc72b1ae6ff7cb6c506cf2fcda98660e2a92f -size 3128 diff --git a/Assets/Editor/ObjectIcons/Clouds.bmp b/Assets/Editor/ObjectIcons/Clouds.bmp deleted file mode 100644 index 4530661aac..0000000000 --- a/Assets/Editor/ObjectIcons/Clouds.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1f5fd7032f82fbb7364cd0a96989918defd63f26a899836c61b039541cf3b3af -size 3128 diff --git a/Assets/Editor/ObjectIcons/Comment.bmp b/Assets/Editor/ObjectIcons/Comment.bmp deleted file mode 100644 index 78a8d8f4fa..0000000000 --- a/Assets/Editor/ObjectIcons/Comment.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9201d97225c19b8fc2fc208ab913ab100a94328b64b026ab65be9c4cd9c4e28a -size 3128 diff --git a/Assets/Editor/ObjectIcons/DeadBody.bmp b/Assets/Editor/ObjectIcons/DeadBody.bmp deleted file mode 100644 index ffebc73608..0000000000 --- a/Assets/Editor/ObjectIcons/DeadBody.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a2937837233d9f313b2500232c74952cee3f4e7497ee0e1099b301ef2fa49bf8 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Decal.bmp b/Assets/Editor/ObjectIcons/Decal.bmp deleted file mode 100644 index 4b33fe7422..0000000000 --- a/Assets/Editor/ObjectIcons/Decal.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ffbe8438c19ac2a9b6614beb78f0d651184dbe5cf2998063257dc7272c9c2c10 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Dialog.bmp b/Assets/Editor/ObjectIcons/Dialog.bmp deleted file mode 100644 index 0722f5f1e4..0000000000 --- a/Assets/Editor/ObjectIcons/Dialog.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:63640478bd3258aa310dd639014cde714780ebaa168aa784093e74fc0da23a4c -size 3126 diff --git a/Assets/Editor/ObjectIcons/Flash.bmp b/Assets/Editor/ObjectIcons/Flash.bmp deleted file mode 100644 index d7f02ed44b..0000000000 --- a/Assets/Editor/ObjectIcons/Flash.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b66daefbb3f11f527d9c10ff1dd54f87635e6561cc546a762ae2e72793ae6ef6 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Fog.bmp b/Assets/Editor/ObjectIcons/Fog.bmp deleted file mode 100644 index 2af489a79a..0000000000 --- a/Assets/Editor/ObjectIcons/Fog.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:42e0c1dc60809958d74145ae14030c22e351ef3b72ed6d820fdb19632b691c89 -size 3128 diff --git a/Assets/Editor/ObjectIcons/FogVolume.bmp b/Assets/Editor/ObjectIcons/FogVolume.bmp deleted file mode 100644 index 78d20bff41..0000000000 --- a/Assets/Editor/ObjectIcons/FogVolume.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2cbb23fc09d47d16b2414d622fd16b330d9f684398dcfc44e0fb44378dfd3287 -size 3128 diff --git a/Assets/Editor/ObjectIcons/GravitySphere.bmp b/Assets/Editor/ObjectIcons/GravitySphere.bmp deleted file mode 100644 index 06168d4698..0000000000 --- a/Assets/Editor/ObjectIcons/GravitySphere.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:26b6e2f28ed72b9cdb90410351e3a22fee3c0498ac315e71d966a1ffb77742fe -size 3128 diff --git a/Assets/Editor/ObjectIcons/Item.bmp b/Assets/Editor/ObjectIcons/Item.bmp deleted file mode 100644 index 15c610cad2..0000000000 --- a/Assets/Editor/ObjectIcons/Item.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bd6f39152affb52a7b3c4361032d1d7d77e7e94841613a83d7e2cdea9eaab553 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Ladder.bmp b/Assets/Editor/ObjectIcons/Ladder.bmp deleted file mode 100644 index dbd4a288e7..0000000000 --- a/Assets/Editor/ObjectIcons/Ladder.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:077502953026981b6e8cc5e40ab58722fc514947f175021508e6af8058340f32 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Light.bmp b/Assets/Editor/ObjectIcons/Light.bmp deleted file mode 100644 index 6a3347e78c..0000000000 --- a/Assets/Editor/ObjectIcons/Light.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c9ecfc056ab66b3221be3175889d182229c0e49bf9604abd7946fe58cc7d29a9 -size 3128 diff --git a/Assets/Editor/ObjectIcons/LightPropagationVolume.bmp b/Assets/Editor/ObjectIcons/LightPropagationVolume.bmp deleted file mode 100644 index 4ad9437883..0000000000 --- a/Assets/Editor/ObjectIcons/LightPropagationVolume.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:206820d3bb5d6a4d26bf87fc0b91a36adcbd0f154149b7cb5f5ce067f5ee4d67 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Lightning.bmp b/Assets/Editor/ObjectIcons/Lightning.bmp deleted file mode 100644 index 5c02d0368c..0000000000 --- a/Assets/Editor/ObjectIcons/Lightning.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d7c81a8000339695f73277bcebaedb0cfeacdff547f51c1ff7f4761c75927ca4 -size 3126 diff --git a/Assets/Editor/ObjectIcons/Magnet.bmp b/Assets/Editor/ObjectIcons/Magnet.bmp deleted file mode 100644 index 68b6e4e7e4..0000000000 --- a/Assets/Editor/ObjectIcons/Magnet.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:560c3af6e8f2fb98ddc8638b0ea4786131e75b6fe0acece964bfdb28f8c3ec9f -size 3128 diff --git a/Assets/Editor/ObjectIcons/MultiTrigger.bmp b/Assets/Editor/ObjectIcons/MultiTrigger.bmp deleted file mode 100644 index e96dc6f1b7..0000000000 --- a/Assets/Editor/ObjectIcons/MultiTrigger.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8a3a64d33b65c4cd5d666c11abf03b4148acadfe69e4c80e79382b56d2906ae6 -size 3128 diff --git a/Assets/Editor/ObjectIcons/ODD.bmp b/Assets/Editor/ObjectIcons/ODD.bmp deleted file mode 100644 index 5c5a7bbd89..0000000000 --- a/Assets/Editor/ObjectIcons/ODD.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:113d0a416da49ce24dae2c47514318b75e0ca4d7dc257a9927e0db4bdad35d91 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Particles.bmp b/Assets/Editor/ObjectIcons/Particles.bmp deleted file mode 100644 index 8f71edb74f..0000000000 --- a/Assets/Editor/ObjectIcons/Particles.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6ca81d96a5450660f7e17f75565595368fb7c0071df9589bcbfda2ba54d5c0ae -size 3128 diff --git a/Assets/Editor/ObjectIcons/PrecacheCamera.bmp b/Assets/Editor/ObjectIcons/PrecacheCamera.bmp deleted file mode 100644 index 8f1dca751a..0000000000 --- a/Assets/Editor/ObjectIcons/PrecacheCamera.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:73629b1903365aa6acf35fd7846896c23c38401fac12bc23b23285e5ed9ae89d -size 3126 diff --git a/Assets/Editor/ObjectIcons/Prefab.bmp b/Assets/Editor/ObjectIcons/Prefab.bmp deleted file mode 100644 index 539a0f5a56..0000000000 --- a/Assets/Editor/ObjectIcons/Prefab.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6d7fbb76f67165492a51e6b8715ee3716040d44bd5419b12481e2c9cc627c291 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Prompt.bmp b/Assets/Editor/ObjectIcons/Prompt.bmp deleted file mode 100644 index 1e9b18a97c..0000000000 --- a/Assets/Editor/ObjectIcons/Prompt.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2482da67fbf513a9597b3919562a65d361a4c8264fcc8510ef45321b4192ce4d -size 3128 diff --git a/Assets/Editor/ObjectIcons/SavePoint.bmp b/Assets/Editor/ObjectIcons/SavePoint.bmp deleted file mode 100644 index ce602eeeb4..0000000000 --- a/Assets/Editor/ObjectIcons/SavePoint.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:06f866e66e0458ccf3e014a30fef2dfaab832d9b4b1179f98b7cdd716b358b48 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Seed.bmp b/Assets/Editor/ObjectIcons/Seed.bmp deleted file mode 100644 index 3a9452d982..0000000000 --- a/Assets/Editor/ObjectIcons/Seed.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fdcea1e14d3b01b1ed6ea123767343eddc646969ee447b4bf725c233fd7946f4 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Sound.bmp b/Assets/Editor/ObjectIcons/Sound.bmp deleted file mode 100644 index 06ab261be3..0000000000 --- a/Assets/Editor/ObjectIcons/Sound.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:14a4003a9faf9a2fb3a17d2f87825c8497aeaca364c592ab75970d00e77aa203 -size 3128 diff --git a/Assets/Editor/ObjectIcons/SpawnPoint.bmp b/Assets/Editor/ObjectIcons/SpawnPoint.bmp deleted file mode 100644 index b04a20e8c0..0000000000 --- a/Assets/Editor/ObjectIcons/SpawnPoint.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f7e109f57e5e9bc6bcaee7176a479bb6434353bc49a8021ab96e016ce27f41a1 -size 3128 diff --git a/Assets/Editor/ObjectIcons/T.bmp b/Assets/Editor/ObjectIcons/T.bmp deleted file mode 100644 index 767782c43d..0000000000 --- a/Assets/Editor/ObjectIcons/T.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4c2288c239604402f7e85d753141fbd8a82fde9f18e4f95006b039ceeec41d0c -size 3128 diff --git a/Assets/Editor/ObjectIcons/TagPoint.bmp b/Assets/Editor/ObjectIcons/TagPoint.bmp deleted file mode 100644 index 36727d9c4a..0000000000 --- a/Assets/Editor/ObjectIcons/TagPoint.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8f58cabe21df546914abc1e8f2604989d87b4a3471c1902956a4e1e1be9930b8 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Trigger.bmp b/Assets/Editor/ObjectIcons/Trigger.bmp deleted file mode 100644 index ef712e4b09..0000000000 --- a/Assets/Editor/ObjectIcons/Trigger.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e9cfb325abea577e8737b837098ff3cecd564e302b2c30925b3d35a62fa6c7c3 -size 3128 diff --git a/Assets/Editor/ObjectIcons/UiCanvasRefEntity.bmp b/Assets/Editor/ObjectIcons/UiCanvasRefEntity.bmp deleted file mode 100644 index c1ff4d3291..0000000000 --- a/Assets/Editor/ObjectIcons/UiCanvasRefEntity.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bcd9a1efaab42cdea4557265e544f2370565872115d21cc84af6e6998bb7ad01 -size 3128 diff --git a/Assets/Editor/ObjectIcons/User.bmp b/Assets/Editor/ObjectIcons/User.bmp deleted file mode 100644 index 780242c15c..0000000000 --- a/Assets/Editor/ObjectIcons/User.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:56a379a337a44617cb6ed5a20560286b8263c75871742ca04cc61cac49736a2a -size 3128 diff --git a/Assets/Editor/ObjectIcons/VVVArea.bmp b/Assets/Editor/ObjectIcons/VVVArea.bmp deleted file mode 100644 index 82712dda92..0000000000 --- a/Assets/Editor/ObjectIcons/VVVArea.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9cab80e4ce74155a3eaf771fa9b2464c1f3b36bce6de55d3f5aa180576cabec2 -size 3128 diff --git a/Assets/Editor/ObjectIcons/W.bmp b/Assets/Editor/ObjectIcons/W.bmp deleted file mode 100644 index 40448a6334..0000000000 --- a/Assets/Editor/ObjectIcons/W.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6ebc8eacd6695caafd131d5c8ca29b45fea16bc2147cdb169478e391d6f13b70 -size 3128 diff --git a/Assets/Editor/ObjectIcons/Water.bmp b/Assets/Editor/ObjectIcons/Water.bmp deleted file mode 100644 index fb7d6c7b51..0000000000 --- a/Assets/Editor/ObjectIcons/Water.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e5d24ecf0878409dc3f7ed0f447734061bb9e313e4adb767580bd961b0038236 -size 3126 diff --git a/Assets/Editor/ObjectIcons/animobject.bmp b/Assets/Editor/ObjectIcons/animobject.bmp deleted file mode 100644 index d28e4c016a..0000000000 --- a/Assets/Editor/ObjectIcons/animobject.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:514fb756bd23f0376a03ba7222a5a8479408eb68efbfcecac30957142580e494 -size 3128 diff --git a/Assets/Editor/ObjectIcons/bird.bmp b/Assets/Editor/ObjectIcons/bird.bmp deleted file mode 100644 index b6431dc2cf..0000000000 --- a/Assets/Editor/ObjectIcons/bird.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e7d72d46274c9c0863e7e34caccfdf78a7c8c77262caf1b7f4305a822ac0145c -size 3128 diff --git a/Assets/Editor/ObjectIcons/bug.bmp b/Assets/Editor/ObjectIcons/bug.bmp deleted file mode 100644 index 86cb76bed0..0000000000 --- a/Assets/Editor/ObjectIcons/bug.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d238a0d17e3469c499249bd907b5aba0b924fb8539259a1b92af64e39820b619 -size 3128 diff --git a/Assets/Editor/ObjectIcons/character.bmp b/Assets/Editor/ObjectIcons/character.bmp deleted file mode 100644 index a37997e7bf..0000000000 --- a/Assets/Editor/ObjectIcons/character.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4b7bd2ee00f000d13ef096bd4d430fbca5cd35f3d641d44f4698c1270423b484 -size 3128 diff --git a/Assets/Editor/ObjectIcons/death.bmp b/Assets/Editor/ObjectIcons/death.bmp deleted file mode 100644 index 98c673af1d..0000000000 --- a/Assets/Editor/ObjectIcons/death.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9d93aa4486316a2ba269f860d64f741da15359fec6111da1049331a5a75dee02 -size 3128 diff --git a/Assets/Editor/ObjectIcons/door.bmp b/Assets/Editor/ObjectIcons/door.bmp deleted file mode 100644 index 3c95318ef9..0000000000 --- a/Assets/Editor/ObjectIcons/door.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4be7c244d9350a46c18161222ace0eaea1213dd1e7ed5ba02fa94ee5a98dc728 -size 3128 diff --git a/Assets/Editor/ObjectIcons/elevator.bmp b/Assets/Editor/ObjectIcons/elevator.bmp deleted file mode 100644 index b256426aef..0000000000 --- a/Assets/Editor/ObjectIcons/elevator.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6c1cf46f0825ecf1d3331bdca3d5f6a0d348aa6346af9fb1fdb3b75cfc5564dd -size 3128 diff --git a/Assets/Editor/ObjectIcons/environmentProbe.bmp b/Assets/Editor/ObjectIcons/environmentProbe.bmp deleted file mode 100644 index 0a23ebb9f4..0000000000 --- a/Assets/Editor/ObjectIcons/environmentProbe.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:27c8ae2924af50058207e7a1e1f4e35799f27abd7cb2e0778b8903ce00e99732 -size 4152 diff --git a/Assets/Editor/ObjectIcons/explosion.bmp b/Assets/Editor/ObjectIcons/explosion.bmp deleted file mode 100644 index 27213da651..0000000000 --- a/Assets/Editor/ObjectIcons/explosion.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a93e2e2164781ed0de1be34bbbd0c85d630a31efd3fe568ea7f3c026646209c8 -size 3128 diff --git a/Assets/Editor/ObjectIcons/fish.bmp b/Assets/Editor/ObjectIcons/fish.bmp deleted file mode 100644 index 9c1d0b2d21..0000000000 --- a/Assets/Editor/ObjectIcons/fish.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:590e0458bbc0d528ba71cd048b6019ebb8d1764a55cc3b9b3e2b1446182cfaa9 -size 3128 diff --git a/Assets/Editor/ObjectIcons/forbiddenarea.bmp b/Assets/Editor/ObjectIcons/forbiddenarea.bmp deleted file mode 100644 index b41c47bf72..0000000000 --- a/Assets/Editor/ObjectIcons/forbiddenarea.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6a8eac076d5094c722513bcdb6b71def9116ae063d453017d7bb0b38068c3a7e -size 3128 diff --git a/Assets/Editor/ObjectIcons/hazard.bmp b/Assets/Editor/ObjectIcons/hazard.bmp deleted file mode 100644 index 4779f3730a..0000000000 --- a/Assets/Editor/ObjectIcons/hazard.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:71c3e9e9ccf404c3c17f71f806cd6ee0e4b48f6f2e172b52aeca78cc28668ac3 -size 3128 diff --git a/Assets/Editor/ObjectIcons/health.bmp b/Assets/Editor/ObjectIcons/health.bmp deleted file mode 100644 index 01833903c3..0000000000 --- a/Assets/Editor/ObjectIcons/health.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3ded11545905ac937fe6e28929e57c10abe55befa74b44260dee5b206cdf3d15 -size 3128 diff --git a/Assets/Editor/ObjectIcons/ledge.bmp b/Assets/Editor/ObjectIcons/ledge.bmp deleted file mode 100644 index 3d6784fb44..0000000000 --- a/Assets/Editor/ObjectIcons/ledge.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c43daede42eb72eca0f80454b0e70de1e03156b5f098bcc8dbc080117c34380a -size 3128 diff --git a/Assets/Editor/ObjectIcons/mine.bmp b/Assets/Editor/ObjectIcons/mine.bmp deleted file mode 100644 index 8f4394a2dd..0000000000 --- a/Assets/Editor/ObjectIcons/mine.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:da1bb03a55949c6dc80ac18e3cf87c962e30fe2eacfd4fac74cc93db58552ac5 -size 3128 diff --git a/Assets/Editor/ObjectIcons/physicsobject.bmp b/Assets/Editor/ObjectIcons/physicsobject.bmp deleted file mode 100644 index 00bb3f2380..0000000000 --- a/Assets/Editor/ObjectIcons/physicsobject.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:74cdfbf6f61029fa6f1262f78c2787afb9dddc0218911b53349962c4ed548bbf -size 3128 diff --git a/Assets/Editor/ObjectIcons/prefabbuilding.bmp b/Assets/Editor/ObjectIcons/prefabbuilding.bmp deleted file mode 100644 index e416cbafe1..0000000000 --- a/Assets/Editor/ObjectIcons/prefabbuilding.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:98aaf6d6e532f5a3f31cdc08676432e30b4e52fd4f376331f4610379f288a191 -size 3128 diff --git a/Assets/Editor/ObjectIcons/proceduralbuilding.bmp b/Assets/Editor/ObjectIcons/proceduralbuilding.bmp deleted file mode 100644 index e416cbafe1..0000000000 --- a/Assets/Editor/ObjectIcons/proceduralbuilding.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:98aaf6d6e532f5a3f31cdc08676432e30b4e52fd4f376331f4610379f288a191 -size 3128 diff --git a/Assets/Editor/ObjectIcons/proceduralobject.bmp b/Assets/Editor/ObjectIcons/proceduralobject.bmp deleted file mode 100644 index e416cbafe1..0000000000 --- a/Assets/Editor/ObjectIcons/proceduralobject.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:98aaf6d6e532f5a3f31cdc08676432e30b4e52fd4f376331f4610379f288a191 -size 3128 diff --git a/Assets/Editor/ObjectIcons/proximitytrigger.bmp b/Assets/Editor/ObjectIcons/proximitytrigger.bmp deleted file mode 100644 index a776094539..0000000000 --- a/Assets/Editor/ObjectIcons/proximitytrigger.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ac364f478ca4dfa0186069fb69d19b8005a8d1da74cff34ced76bb85cf4402e7 -size 3128 diff --git a/Assets/Editor/ObjectIcons/river.bmp b/Assets/Editor/ObjectIcons/river.bmp deleted file mode 100644 index bf831c356a..0000000000 --- a/Assets/Editor/ObjectIcons/river.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:910d8f788514dc2d66c58027cb841a16e7d5194ee1f1ff3ccfcf5badd86c768a -size 3128 diff --git a/Assets/Editor/ObjectIcons/road.bmp b/Assets/Editor/ObjectIcons/road.bmp deleted file mode 100644 index 91a8b0916f..0000000000 --- a/Assets/Editor/ObjectIcons/road.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9e92c9792886fab49007891c38addf2f62719d6563a36cd81250de13c50fbf61 -size 3128 diff --git a/Assets/Editor/ObjectIcons/rope.bmp b/Assets/Editor/ObjectIcons/rope.bmp deleted file mode 100644 index d7f7fddb67..0000000000 --- a/Assets/Editor/ObjectIcons/rope.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:738525640cf00402ebd807ce9a35d6d7ed67be39cde7def7930b136596977a2e -size 3128 diff --git a/Assets/Editor/ObjectIcons/sequence.bmp b/Assets/Editor/ObjectIcons/sequence.bmp deleted file mode 100644 index 8e76c924f1..0000000000 --- a/Assets/Editor/ObjectIcons/sequence.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e339afca6ba8ffa2463bf6b367615e66bb953fced380d739996d52c2971feab5 -size 3128 diff --git a/Assets/Editor/ObjectIcons/shake.bmp b/Assets/Editor/ObjectIcons/shake.bmp deleted file mode 100644 index 5275a0aac9..0000000000 --- a/Assets/Editor/ObjectIcons/shake.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f3130dcb95136d806aff1882d3933eb3f7ee88aaa9876423b53dbf73f02c8cd3 -size 3128 diff --git a/Assets/Editor/ObjectIcons/smartobject.bmp b/Assets/Editor/ObjectIcons/smartobject.bmp deleted file mode 100644 index 5ecf9a273e..0000000000 --- a/Assets/Editor/ObjectIcons/smartobject.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e908579e0a62d74a1402ee786876e88eadb0ef0de0542617d02291947504078b -size 3128 diff --git a/Assets/Editor/ObjectIcons/spawngroup.bmp b/Assets/Editor/ObjectIcons/spawngroup.bmp deleted file mode 100644 index 00626fc17f..0000000000 --- a/Assets/Editor/ObjectIcons/spawngroup.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:28111b13e60816f31f3916131d4632ce2d0c48c1a7712421593f79dff79c99d0 -size 3128 diff --git a/Assets/Editor/ObjectIcons/spectator.bmp b/Assets/Editor/ObjectIcons/spectator.bmp deleted file mode 100644 index 6798c841c0..0000000000 --- a/Assets/Editor/ObjectIcons/spectator.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9a2885b3eb0845b48571f1af08d9e685b52361c78c31485c64f8e1efb38e8cc4 -size 3128 diff --git a/Assets/Editor/ObjectIcons/switch.bmp b/Assets/Editor/ObjectIcons/switch.bmp deleted file mode 100644 index 50f4e790b2..0000000000 --- a/Assets/Editor/ObjectIcons/switch.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9bdce356a35d214c4d806ba568d2de72af636410eb433be5c0390eae67d8478a -size 3128 diff --git a/Assets/Editor/ObjectIcons/territory.bmp b/Assets/Editor/ObjectIcons/territory.bmp deleted file mode 100644 index edd8b5178e..0000000000 --- a/Assets/Editor/ObjectIcons/territory.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:dc350e4d3226531a35ac810fa5ebe1894bfdcafac605334afffcdd3a14416f94 -size 3128 diff --git a/Assets/Editor/ObjectIcons/tornado.bmp b/Assets/Editor/ObjectIcons/tornado.bmp deleted file mode 100644 index e30b642441..0000000000 --- a/Assets/Editor/ObjectIcons/tornado.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c54df0fb1c9b8abeee30adc5e983bfd7dd524c551909b26466a9d8b6422a094a -size 3128 diff --git a/Assets/Editor/ObjectIcons/vehicle.bmp b/Assets/Editor/ObjectIcons/vehicle.bmp deleted file mode 100644 index f65e5bb7bf..0000000000 --- a/Assets/Editor/ObjectIcons/vehicle.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:50e0b4d6a86953c33b0c3ace60bb53d119fa5acd193f4d9aa2c0934f3074cb19 -size 3128 diff --git a/Assets/Editor/ObjectIcons/voxel.bmp b/Assets/Editor/ObjectIcons/voxel.bmp deleted file mode 100644 index dba0aa32ba..0000000000 --- a/Assets/Editor/ObjectIcons/voxel.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8ca14c966de6d392beb4d154221b622a417163fcdf92eb049638bf8495c13774 -size 3128 diff --git a/Assets/Editor/ObjectIcons/wave.bmp b/Assets/Editor/ObjectIcons/wave.bmp deleted file mode 100644 index 0465b41c38..0000000000 --- a/Assets/Editor/ObjectIcons/wave.bmp +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:573d22719ad010351a58733b63315a9a0fc07545dde71f3931f37371dfe44ce3 -size 3128 diff --git a/Assets/Editor/Scripts/Shelves/icons/Albedo.png b/Assets/Editor/Scripts/Shelves/icons/Albedo.png deleted file mode 100644 index f3225255c7..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Albedo.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a91ea78d1ffd91490f20efcf76ad8790e450836240b8a77dda719da963235c85 -size 2987 diff --git a/Assets/Editor/Scripts/Shelves/icons/Diffuse_Lighting.png b/Assets/Editor/Scripts/Shelves/icons/Diffuse_Lighting.png deleted file mode 100644 index 4709ee81d0..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Diffuse_Lighting.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2d8eadc0bdc63391e88936b0acfd0616c2d7bce550ea82cee1f967f971ace8a6 -size 2905 diff --git a/Assets/Editor/Scripts/Shelves/icons/Diffuse_Texture_Res_360.png b/Assets/Editor/Scripts/Shelves/icons/Diffuse_Texture_Res_360.png deleted file mode 100644 index 25c686e46a..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Diffuse_Texture_Res_360.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9cdb92de995635eadfbb6dceb25f44a737dde744e09f0fcfe7016de981dce786 -size 2975 diff --git a/Assets/Editor/Scripts/Shelves/icons/Empty_Wireframe.png b/Assets/Editor/Scripts/Shelves/icons/Empty_Wireframe.png deleted file mode 100644 index b4329c1beb..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Empty_Wireframe.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:268a5b239b9988be0ae13a2f42a99ac39ac2db9988f92604154630b661b89999 -size 2865 diff --git a/Assets/Editor/Scripts/Shelves/icons/Exit.png b/Assets/Editor/Scripts/Shelves/icons/Exit.png deleted file mode 100644 index 3706ddc01c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Exit.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:030f4dc71dac36f220cd7e7c07eb24bda2df3c1e14b054e48fc6274573734bdb -size 2898 diff --git a/Assets/Editor/Scripts/Shelves/icons/Fuzziness.png b/Assets/Editor/Scripts/Shelves/icons/Fuzziness.png deleted file mode 100644 index 6ca7e20209..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Fuzziness.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e0fa6d24bbb7f969a71b9e761f2dc4ec990a7e522201af9b13b2651d0565e1f0 -size 3607 diff --git a/Assets/Editor/Scripts/Shelves/icons/Gloss.png b/Assets/Editor/Scripts/Shelves/icons/Gloss.png deleted file mode 100644 index 5063b7f01e..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Gloss.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d5b949330e86f02662bb3b25db123fd77be31c910ad7e1e21223a543820ce46a -size 2959 diff --git a/Assets/Editor/Scripts/Shelves/icons/Normal_Texture_Res_360.png b/Assets/Editor/Scripts/Shelves/icons/Normal_Texture_Res_360.png deleted file mode 100644 index 3ca3270344..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Normal_Texture_Res_360.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:49086e4fa1736415d79d7d1d5ed8484b49582db8c27957148ef2a6d7f5dec189 -size 3176 diff --git a/Assets/Editor/Scripts/Shelves/icons/PrefabAddLibrary.png b/Assets/Editor/Scripts/Shelves/icons/PrefabAddLibrary.png deleted file mode 100644 index 899b8cbc57..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/PrefabAddLibrary.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e0d9c3f0be3c978deaa053d458a49908e99d8d0f7e87169b5b03b7f500e37f55 -size 3248 diff --git a/Assets/Editor/Scripts/Shelves/icons/PrefabAddSelection.png b/Assets/Editor/Scripts/Shelves/icons/PrefabAddSelection.png deleted file mode 100644 index 6144e48a2b..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/PrefabAddSelection.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5d98fa218cf0c13100584611e1c4d536bdd9cf78a4a10dd1a0a49e4265b5292d -size 503 diff --git a/Assets/Editor/Scripts/Shelves/icons/PrefabBreak.png b/Assets/Editor/Scripts/Shelves/icons/PrefabBreak.png deleted file mode 100644 index 9982a71078..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/PrefabBreak.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e538188411092f7a172ef364035df77dc228bc91d43cfc35ffbbd824e716800e -size 3231 diff --git a/Assets/Editor/Scripts/Shelves/icons/PrefabConvert.png b/Assets/Editor/Scripts/Shelves/icons/PrefabConvert.png deleted file mode 100644 index cdbd6d2ac7..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/PrefabConvert.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:52b2c98b0f50fcfdd8334bcde259aef0a0533055f6caa1a1606536f5d2eca23f -size 3079 diff --git a/Assets/Editor/Scripts/Shelves/icons/PrefabCreate.png b/Assets/Editor/Scripts/Shelves/icons/PrefabCreate.png deleted file mode 100644 index 1aad8f3446..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/PrefabCreate.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:40905f7865cd5a71bfdace3943ccdd8fe532ee111419fb023befac357256eb07 -size 490 diff --git a/Assets/Editor/Scripts/Shelves/icons/PrefabIsolate.png b/Assets/Editor/Scripts/Shelves/icons/PrefabIsolate.png deleted file mode 100644 index 4c1a1766b5..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/PrefabIsolate.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:31f8f9a5ff20b33bdf86af8da579717cda40e097db6f893ec4e2fffab720f90e -size 3211 diff --git a/Assets/Editor/Scripts/Shelves/icons/Scattering.png b/Assets/Editor/Scripts/Shelves/icons/Scattering.png deleted file mode 100644 index 3c2c5cff38..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Scattering.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9ec02e421b4e832f73576d1f1bf2b6bc60879521f3a8abbb554925982574c374 -size 3146 diff --git a/Assets/Editor/Scripts/Shelves/icons/Solid_Wireframe.png b/Assets/Editor/Scripts/Shelves/icons/Solid_Wireframe.png deleted file mode 100644 index e439baed1b..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Solid_Wireframe.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bcc61dfe03d5bae6060c1fc6814b7be299705803fdb9058cabe6227f386ddeef -size 2872 diff --git a/Assets/Editor/Scripts/Shelves/icons/Spec_Amount.png b/Assets/Editor/Scripts/Shelves/icons/Spec_Amount.png deleted file mode 100644 index 7561feb7c0..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Spec_Amount.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a67c8e063331c5c6ce256892abdde113f405c60854115ba87f6798d06f57eb02 -size 2892 diff --git a/Assets/Editor/Scripts/Shelves/icons/Spec_Lighting.png b/Assets/Editor/Scripts/Shelves/icons/Spec_Lighting.png deleted file mode 100644 index f08a036519..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Spec_Lighting.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:927d3b2f83e6e962a492ea625240bb5f336e30aa2052d1f8699b76a86a5e475d -size 2897 diff --git a/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_1024.png b/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_1024.png deleted file mode 100644 index 2d4b08f5fb..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_1024.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a3861aa38f3e521127a48f08e6c24e12e61c15450bb4d10ef27a0a95c2c420c0 -size 2889 diff --git a/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_256.png b/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_256.png deleted file mode 100644 index 4b1ceef8ab..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_256.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:5ecc3596974c0c9f1703d51e60de2ca00a479012d98f11316966686cc891f982 -size 2922 diff --git a/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_512.png b/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_512.png deleted file mode 100644 index 4f328adf91..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/Texel_Per_Meter_512.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ce1ca5c1d89cd6d7a0cf35142be114904ec469afab2fa69a12afe6824055b67b -size 2913 diff --git a/Assets/Editor/Scripts/Shelves/icons/all.png b/Assets/Editor/Scripts/Shelves/icons/all.png deleted file mode 100644 index 1b6e3b12d6..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/all.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ffcf54b92f48aa06f38e94826a76f350b425ad9d46c0e2170455730123a69a6d -size 3693 diff --git a/Assets/Editor/Scripts/Shelves/icons/beams.png b/Assets/Editor/Scripts/Shelves/icons/beams.png deleted file mode 100644 index 9263cc070a..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/beams.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:68c4333ba27b39baed2696fa90040cc4e669dbc5e9fab43b11abd854d5482474 -size 613 diff --git a/Assets/Editor/Scripts/Shelves/icons/blanker.png b/Assets/Editor/Scripts/Shelves/icons/blanker.png deleted file mode 100644 index 277a067134..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/blanker.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:adac9f1fc606475d1d86ca8f5b2376570ebc70161e4b5240ede3cb8f176b8f41 -size 2810 diff --git a/Assets/Editor/Scripts/Shelves/icons/bounding_box.png b/Assets/Editor/Scripts/Shelves/icons/bounding_box.png deleted file mode 100644 index 854a9f957c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/bounding_box.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f00fa9904ce4687aaf21f1553d03bf1d47390d007fd38513ad959f324a4b6ebb -size 3618 diff --git a/Assets/Editor/Scripts/Shelves/icons/brushes.png b/Assets/Editor/Scripts/Shelves/icons/brushes.png deleted file mode 100644 index 283af0629c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/brushes.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ed21a97324849633d156ec03f949a3cf21b8b682a3a6ad1dcfac6eee9df7a497 -size 734 diff --git a/Assets/Editor/Scripts/Shelves/icons/cloud.png b/Assets/Editor/Scripts/Shelves/icons/cloud.png deleted file mode 100644 index 8f28b28613..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/cloud.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:11599538b6bc197e92f07db149ccdfee50ddea630f095865bac9782254a7c06f -size 387 diff --git a/Assets/Editor/Scripts/Shelves/icons/cloud_dark.png b/Assets/Editor/Scripts/Shelves/icons/cloud_dark.png deleted file mode 100644 index 28d1d0281b..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/cloud_dark.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:559ec911f9cac84de411e92d746913c3828ebf1d1f8c7bab794fb9c768c1581d -size 387 diff --git a/Assets/Editor/Scripts/Shelves/icons/cloud_dark_rain.png b/Assets/Editor/Scripts/Shelves/icons/cloud_dark_rain.png deleted file mode 100644 index 7119b0387f..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/cloud_dark_rain.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:88d11b32db70a437fd8ff8c845b4ff26182d28f5b7a2f6b3de4fce61dffff98d -size 489 diff --git a/Assets/Editor/Scripts/Shelves/icons/collisions.png b/Assets/Editor/Scripts/Shelves/icons/collisions.png deleted file mode 100644 index af947db919..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/collisions.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0510fa11c090234a2008703917834ad0455bc6e5e9a2d2375ebd0fc279b41851 -size 3491 diff --git a/Assets/Editor/Scripts/Shelves/icons/create_ao_volume_box.png b/Assets/Editor/Scripts/Shelves/icons/create_ao_volume_box.png deleted file mode 100644 index 558a3eba64..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/create_ao_volume_box.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:24fc2750f740f0b85ca720beedb564f2a01bbeed229cb89c6d8f395d5cf5d439 -size 844 diff --git a/Assets/Editor/Scripts/Shelves/icons/create_both_vis_box_envprobe.png b/Assets/Editor/Scripts/Shelves/icons/create_both_vis_box_envprobe.png deleted file mode 100644 index d4b1023cdb..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/create_both_vis_box_envprobe.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:000effa8925a61313fdf420830857172bc69c38cb8a14737a389b9c9df1b36df -size 745 diff --git a/Assets/Editor/Scripts/Shelves/icons/create_envprobe.png b/Assets/Editor/Scripts/Shelves/icons/create_envprobe.png deleted file mode 100644 index bdaf8fdf2c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/create_envprobe.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9d91f30f31576dc957f57d59e2b94d6e45c9aef28f321240c31639c148f62aea -size 803 diff --git a/Assets/Editor/Scripts/Shelves/icons/create_portal_box.png b/Assets/Editor/Scripts/Shelves/icons/create_portal_box.png deleted file mode 100644 index 416952b279..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/create_portal_box.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6452c7e2baef1d8d285a96e72d053a8af80430e52a149ce14795c946d55896fb -size 807 diff --git a/Assets/Editor/Scripts/Shelves/icons/create_vis_box.png b/Assets/Editor/Scripts/Shelves/icons/create_vis_box.png deleted file mode 100644 index 74ac6eac4d..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/create_vis_box.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e0d5e21ccaec784d3118a2609e5f26caca4a26901a92db0821e2e0f18e555534 -size 833 diff --git a/Assets/Editor/Scripts/Shelves/icons/create_vis_box_and_portal_box.png b/Assets/Editor/Scripts/Shelves/icons/create_vis_box_and_portal_box.png deleted file mode 100644 index 5da50020d9..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/create_vis_box_and_portal_box.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e5717c6fde94577b831b8d83104733f86ed82f030664624d62cb4a6d26dd5646 -size 822 diff --git a/Assets/Editor/Scripts/Shelves/icons/create_vis_box_env_probe_and_portal.png b/Assets/Editor/Scripts/Shelves/icons/create_vis_box_env_probe_and_portal.png deleted file mode 100644 index cd39aade30..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/create_vis_box_env_probe_and_portal.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:07e831e8cab5e1e222b4a4d6a64932bbb8a9a5fcb7cae020432905a7c1e53402 -size 782 diff --git a/Assets/Editor/Scripts/Shelves/icons/cubemap.png b/Assets/Editor/Scripts/Shelves/icons/cubemap.png deleted file mode 100644 index d55d04b978..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/cubemap.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:9775b4823563dbff4c3410c1751f022e2985f91202e6d691f86172ef1f820f4b -size 3353 diff --git a/Assets/Editor/Scripts/Shelves/icons/decals.png b/Assets/Editor/Scripts/Shelves/icons/decals.png deleted file mode 100644 index b9e4c92bd7..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/decals.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c12d69b2d85c339bbff06011fff7c2468a2b2e6c67726ad7fb0ab82384eb39df -size 918 diff --git a/Assets/Editor/Scripts/Shelves/icons/default_material.png b/Assets/Editor/Scripts/Shelves/icons/default_material.png deleted file mode 100644 index 9fda69eaab..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/default_material.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:98146b9b75602ddc8a46529fe0427303491dfe4584cadb914d3774377593c7ef -size 3809 diff --git a/Assets/Editor/Scripts/Shelves/icons/default_material_with_normals.png b/Assets/Editor/Scripts/Shelves/icons/default_material_with_normals.png deleted file mode 100644 index cbb0f9bbf2..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/default_material_with_normals.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a1c7e790dad53937ed0845cb89c5651c7932a696d7d34d85df6fc8c4b09c7245 -size 3106 diff --git a/Assets/Editor/Scripts/Shelves/icons/designer.png b/Assets/Editor/Scripts/Shelves/icons/designer.png deleted file mode 100644 index 9018385ebb..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/designer.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e790bb52b7f7d52e79b2c5b84ee4a4587a721c7e3c70d2d7e0eb683b478b51f7 -size 1015 diff --git a/Assets/Editor/Scripts/Shelves/icons/diff_acc.png b/Assets/Editor/Scripts/Shelves/icons/diff_acc.png deleted file mode 100644 index df3eac041c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/diff_acc.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b341792fb1c13db8144f74c3895942251c07e67e87ac374c09df21e3459b3610 -size 3930 diff --git a/Assets/Editor/Scripts/Shelves/icons/display_info.png b/Assets/Editor/Scripts/Shelves/icons/display_info.png deleted file mode 100644 index 22572bc6e5..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/display_info.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0fc2408c2f1801de3f625dcbdf960104195c1d47d7e240f4ec9391a7b645399c -size 3623 diff --git a/Assets/Editor/Scripts/Shelves/icons/dual_layer_mask.png b/Assets/Editor/Scripts/Shelves/icons/dual_layer_mask.png deleted file mode 100644 index c47a0f7350..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/dual_layer_mask.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:80bca215bbcec9d9e1e33abfbf0b17d6032327a175d6f9d4d76bfefd5c7f2480 -size 3517 diff --git a/Assets/Editor/Scripts/Shelves/icons/dynamiclights.png b/Assets/Editor/Scripts/Shelves/icons/dynamiclights.png deleted file mode 100644 index 541d8f9304..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/dynamiclights.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ef3cae03d5f38bdf9e82ff29b1a77133a44e5e859cfdb063c449ee5609902367 -size 780 diff --git a/Assets/Editor/Scripts/Shelves/icons/entities.png b/Assets/Editor/Scripts/Shelves/icons/entities.png deleted file mode 100644 index 0bf2eda8cc..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/entities.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:42de1878f5cef5c3f80dd56e042584eeb8759cacd58a0b22115644ed38800836 -size 870 diff --git a/Assets/Editor/Scripts/Shelves/icons/eye_adaptation_speed.png b/Assets/Editor/Scripts/Shelves/icons/eye_adaptation_speed.png deleted file mode 100644 index a485e39655..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/eye_adaptation_speed.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f1b4a6d4cca72740f14e97239bf8490d23ccb3d9283d4ff558f0302d9fa773ad -size 1017 diff --git a/Assets/Editor/Scripts/Shelves/icons/fog.png b/Assets/Editor/Scripts/Shelves/icons/fog.png deleted file mode 100644 index 68137429de..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/fog.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4dea1c985077475184c32562609e27b7919cd1c08776174a83f38f095a11f3d4 -size 394 diff --git a/Assets/Editor/Scripts/Shelves/icons/fogvolumes.png b/Assets/Editor/Scripts/Shelves/icons/fogvolumes.png deleted file mode 100644 index 8c305abb4a..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/fogvolumes.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:bbf140c23e75f1c1035defd58ec8522230abdb5fc7538953ed88eb3bc06c9ca3 -size 349 diff --git a/Assets/Editor/Scripts/Shelves/icons/freeze_particles.png b/Assets/Editor/Scripts/Shelves/icons/freeze_particles.png deleted file mode 100644 index 963374b096..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/freeze_particles.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:52986df9e8a866606cbfbe8a9702f15483a6f3bfa0b15563e64a5c6d208dab55 -size 4076 diff --git a/Assets/Editor/Scripts/Shelves/icons/full_shading.png b/Assets/Editor/Scripts/Shelves/icons/full_shading.png deleted file mode 100644 index 4decb4c800..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/full_shading.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:339d6542b6a259feeb7dc8ebc536ca6fed44a91faaf021b1453a735b39d98450 -size 3021 diff --git a/Assets/Editor/Scripts/Shelves/icons/gamma.png b/Assets/Editor/Scripts/Shelves/icons/gamma.png deleted file mode 100644 index 43b16f55a6..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/gamma.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b93bb51dd54685b9dd1a37b535c7cb456110b45c62ae64eaaceb61a58b99f254 -size 1418 diff --git a/Assets/Editor/Scripts/Shelves/icons/gi.png b/Assets/Editor/Scripts/Shelves/icons/gi.png deleted file mode 100644 index 51fb05190c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/gi.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:cbc47ed9888c792af55b4e0ab5d5c7a7b8a582fdb202fa035e21b974c7df1022 -size 885 diff --git a/Assets/Editor/Scripts/Shelves/icons/lens_flare.png b/Assets/Editor/Scripts/Shelves/icons/lens_flare.png deleted file mode 100644 index 2da269b7c7..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/lens_flare.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e2cbf9570c227884d49ac2a702377821891d06eaa91b6bf92861088508927796 -size 670 diff --git a/Assets/Editor/Scripts/Shelves/icons/lighting_only.png b/Assets/Editor/Scripts/Shelves/icons/lighting_only.png deleted file mode 100644 index bd4590053c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/lighting_only.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:695dcdc3004705d1489b5b2a0a750bf6d30940d343a62bc8ff06bc103d3ae6f7 -size 2870 diff --git a/Assets/Editor/Scripts/Shelves/icons/lods.png b/Assets/Editor/Scripts/Shelves/icons/lods.png deleted file mode 100644 index a6ad158679..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/lods.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:266450829046d2be9557c86f8061f1b50d8f55795436b608689d6c117c5b970d -size 1156 diff --git a/Assets/Editor/Scripts/Shelves/icons/lsao.png b/Assets/Editor/Scripts/Shelves/icons/lsao.png deleted file mode 100644 index 127b421a30..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/lsao.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:7a253c696ce28fb7699b6879c35e874d906033b59e89224d307bf029dd9257e6 -size 3926 diff --git a/Assets/Editor/Scripts/Shelves/icons/lsao_toggle.png b/Assets/Editor/Scripts/Shelves/icons/lsao_toggle.png deleted file mode 100644 index c264be14bd..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/lsao_toggle.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:734ca55bc936d229c56abb4f141a746fe64affc570570d182308f6f0d8f21638 -size 3952 diff --git a/Assets/Editor/Scripts/Shelves/icons/lsro.png b/Assets/Editor/Scripts/Shelves/icons/lsro.png deleted file mode 100644 index ff4099a887..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/lsro.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a100211ce724c005cd2fadecb4ca3c36feacad4f7cb4bbccd8761ae622d59aa3 -size 1153 diff --git a/Assets/Editor/Scripts/Shelves/icons/normals.png b/Assets/Editor/Scripts/Shelves/icons/normals.png deleted file mode 100644 index 1f723ef0d1..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/normals.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:58e65981a6b66482ac3443f644fe210d9c90d01b4a5ab381796d37bf6d5be289 -size 3215 diff --git a/Assets/Editor/Scripts/Shelves/icons/normals_x.png b/Assets/Editor/Scripts/Shelves/icons/normals_x.png deleted file mode 100644 index 98a705b559..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/normals_x.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1be96cc2682443b03bfc4696403d5c3d98eec709878acac0b690dbb635d04ea9 -size 3227 diff --git a/Assets/Editor/Scripts/Shelves/icons/normals_y.png b/Assets/Editor/Scripts/Shelves/icons/normals_y.png deleted file mode 100644 index 8c109bee9b..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/normals_y.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:2eaf04f15e42ac910dc7c29fb61034dc5126a80832b6a0bc0a842b549c23eaf7 -size 3118 diff --git a/Assets/Editor/Scripts/Shelves/icons/normals_z.png b/Assets/Editor/Scripts/Shelves/icons/normals_z.png deleted file mode 100644 index 078ceded6c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/normals_z.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:0c8ec3131755522c3f1a4fc45cef0b9ace4641316d890d3f6f042557f220d6ba -size 3152 diff --git a/Assets/Editor/Scripts/Shelves/icons/ocean.png b/Assets/Editor/Scripts/Shelves/icons/ocean.png deleted file mode 100644 index 04c4fff0fc..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/ocean.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1407119e10f378a6ae375f3951dbfe42505560f75a88687f4c03e0ac2e85a05e -size 700 diff --git a/Assets/Editor/Scripts/Shelves/icons/particles.png b/Assets/Editor/Scripts/Shelves/icons/particles.png deleted file mode 100644 index daecfbc256..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/particles.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:d9875276bc1b8055f306d0bf95b0ba3f6c8f9a49447a68f75334e86b360f4359 -size 713 diff --git a/Assets/Editor/Scripts/Shelves/icons/particles_bounds.png b/Assets/Editor/Scripts/Shelves/icons/particles_bounds.png deleted file mode 100644 index 04321c8ed5..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/particles_bounds.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:231f6c7939361f71b9926f551bbf2eb93ca4ec8394318dcfed0fa413ccd58e66 -size 4073 diff --git a/Assets/Editor/Scripts/Shelves/icons/particles_off.png b/Assets/Editor/Scripts/Shelves/icons/particles_off.png deleted file mode 100644 index ed7fe76f44..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/particles_off.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:b6e656417153394c5466a207bd6ff21072c6ef82fe6972380ceda7fa6e60c478 -size 4053 diff --git a/Assets/Editor/Scripts/Shelves/icons/particles_overdraw.png b/Assets/Editor/Scripts/Shelves/icons/particles_overdraw.png deleted file mode 100644 index 86a8a72b52..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/particles_overdraw.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:8f021d07012f712d8ab70af609974e1cb0933d571bbe0f184e0e7479ee172834 -size 3004 diff --git a/Assets/Editor/Scripts/Shelves/icons/particles_screen_coverage.png b/Assets/Editor/Scripts/Shelves/icons/particles_screen_coverage.png deleted file mode 100644 index fd20e416b2..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/particles_screen_coverage.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:387a799eeb739b6183f3d47186c122ea51c8998664bd0cff76e28f8de2cf49ee -size 4024 diff --git a/Assets/Editor/Scripts/Shelves/icons/placeholder.png b/Assets/Editor/Scripts/Shelves/icons/placeholder.png deleted file mode 100644 index f3225255c7..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/placeholder.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a91ea78d1ffd91490f20efcf76ad8790e450836240b8a77dda719da963235c85 -size 2987 diff --git a/Assets/Editor/Scripts/Shelves/icons/prefab.png b/Assets/Editor/Scripts/Shelves/icons/prefab.png deleted file mode 100644 index 84d2b08397..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/prefab.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:332071c8b20030de53ec194dfe853b29f45a0de04d99dcd1b1c4b32dcf2946a5 -size 683 diff --git a/Assets/Editor/Scripts/Shelves/icons/reflections.png b/Assets/Editor/Scripts/Shelves/icons/reflections.png deleted file mode 100644 index 0fc82618b8..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/reflections.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ee9fdf1b6ab47cfc72c3794a46b6886b9993e691a7d097b3d109127ddcde46ac -size 640 diff --git a/Assets/Editor/Scripts/Shelves/icons/reset.png b/Assets/Editor/Scripts/Shelves/icons/reset.png deleted file mode 100644 index 8cc13235ae..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/reset.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:120be39c58db0bab5450db22604f94cf31eb68a480f06daf3d4f76828461385b -size 4076 diff --git a/Assets/Editor/Scripts/Shelves/icons/selfocc.png b/Assets/Editor/Scripts/Shelves/icons/selfocc.png deleted file mode 100644 index f3a1ece6a3..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/selfocc.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:83e8233f9f0594151e734583f9fd3835250f370dac8b648554f1060d79efa43b -size 2935 diff --git a/Assets/Editor/Scripts/Shelves/icons/shaded_wireframe.png b/Assets/Editor/Scripts/Shelves/icons/shaded_wireframe.png deleted file mode 100644 index 79d4148d9c..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/shaded_wireframe.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f514eebcdcd02d8195d8b51966ad84cfb8162c3811facc6da9fc0a71e10443bc -size 3041 diff --git a/Assets/Editor/Scripts/Shelves/icons/shadows.png b/Assets/Editor/Scripts/Shelves/icons/shadows.png deleted file mode 100644 index 06fd30ee05..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/shadows.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:281c6d85ab6d7e706f73865a7beb523bf64e505d8fd2b3c367f6ad56b008a77e -size 818 diff --git a/Assets/Editor/Scripts/Shelves/icons/showlines.png b/Assets/Editor/Scripts/Shelves/icons/showlines.png deleted file mode 100644 index b4329c1beb..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/showlines.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:268a5b239b9988be0ae13a2f42a99ac39ac2db9988f92604154630b661b89999 -size 2865 diff --git a/Assets/Editor/Scripts/Shelves/icons/sky.png b/Assets/Editor/Scripts/Shelves/icons/sky.png deleted file mode 100644 index 86d018f2d8..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/sky.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:3598e1bdc4c47d6be99ad6ff10e91b307bb4a94286fff57a0c339d6aaed2e0a3 -size 620 diff --git a/Assets/Editor/Scripts/Shelves/icons/spec_acc.png b/Assets/Editor/Scripts/Shelves/icons/spec_acc.png deleted file mode 100644 index b66acb25ca..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/spec_acc.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ee2c46410495a75862d8f5d2e69cce11c94745680ef03b50ba7b17af9c137656 -size 3334 diff --git a/Assets/Editor/Scripts/Shelves/icons/spec_lum.png b/Assets/Editor/Scripts/Shelves/icons/spec_lum.png deleted file mode 100644 index 7561feb7c0..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/spec_lum.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:a67c8e063331c5c6ce256892abdde113f405c60854115ba87f6798d06f57eb02 -size 2892 diff --git a/Assets/Editor/Scripts/Shelves/icons/spec_occ.png b/Assets/Editor/Scripts/Shelves/icons/spec_occ.png deleted file mode 100644 index 624f8481ad..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/spec_occ.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:23a7074e8ced66649cc8c2f69db33559bd600658709aaf287a9d9de9c98a05f6 -size 3182 diff --git a/Assets/Editor/Scripts/Shelves/icons/ssao.png b/Assets/Editor/Scripts/Shelves/icons/ssao.png deleted file mode 100644 index 376a0a2157..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/ssao.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:134cbfd478080236c3f5ea2ee32319e63ee21ff48f187b709ab9dc0f3688c2dd -size 3932 diff --git a/Assets/Editor/Scripts/Shelves/icons/ssdo.png b/Assets/Editor/Scripts/Shelves/icons/ssdo.png deleted file mode 100644 index 517658c1f5..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/ssdo.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c200aad6ad59b7d466edc44026ffca2272ca3b20944070210db1108f21f1cb60 -size 3972 diff --git a/Assets/Editor/Scripts/Shelves/icons/ssdo_toggle.png b/Assets/Editor/Scripts/Shelves/icons/ssdo_toggle.png deleted file mode 100644 index 881b07cb2f..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/ssdo_toggle.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c897d61016bc32c7072273a081e624880b90beb89e90f20b25e689f5198d1f63 -size 3966 diff --git a/Assets/Editor/Scripts/Shelves/icons/sun.big.png b/Assets/Editor/Scripts/Shelves/icons/sun.big.png deleted file mode 100644 index 0a5363ddca..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/sun.big.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c49214e755a68e48bba8b8be9183777c24c3443aa734e4969e74bc42d5979cb7 -size 539 diff --git a/Assets/Editor/Scripts/Shelves/icons/tangents.png b/Assets/Editor/Scripts/Shelves/icons/tangents.png deleted file mode 100644 index 7a1f5c0a3a..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/tangents.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e8a5f21232c186fed9bd9a0d62bd4023dca1d496e151ad0fee5b593fc67645bf -size 1115 diff --git a/Assets/Editor/Scripts/Shelves/icons/terrain.png b/Assets/Editor/Scripts/Shelves/icons/terrain.png deleted file mode 100644 index b32c4cde98..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/terrain.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:821ef3daa0cdf246985c0bc1bd988edeceadb672dd81f4813320e8d50ca0e41c -size 461 diff --git a/Assets/Editor/Scripts/Shelves/icons/time_scale_double.png b/Assets/Editor/Scripts/Shelves/icons/time_scale_double.png deleted file mode 100644 index 03ae1a21ea..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/time_scale_double.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:86ebd1c792b9024662a179995ba65d181157a9887112f12571fbfe05a3dc8a79 -size 3145 diff --git a/Assets/Editor/Scripts/Shelves/icons/time_scale_frozen.png b/Assets/Editor/Scripts/Shelves/icons/time_scale_frozen.png deleted file mode 100644 index a1756ce9fa..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/time_scale_frozen.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4fbe9783be75404b2364726b09f9013360522d2e71f479476a715b6577def003 -size 3386 diff --git a/Assets/Editor/Scripts/Shelves/icons/time_scale_half.png b/Assets/Editor/Scripts/Shelves/icons/time_scale_half.png deleted file mode 100644 index c3f9f03d98..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/time_scale_half.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:1a6740a0e38ea99c83c1460a33f62c3dead3ab85f05bf446426fb39a75aa76f8 -size 3137 diff --git a/Assets/Editor/Scripts/Shelves/icons/time_scale_quarter.png b/Assets/Editor/Scripts/Shelves/icons/time_scale_quarter.png deleted file mode 100644 index a8a9b8cdd8..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/time_scale_quarter.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:4b0baf9f76bcc0bcd38fea907b79edde3bcb66e78b221094473a8abd0b222734 -size 3175 diff --git a/Assets/Editor/Scripts/Shelves/icons/time_scale_tenth.png b/Assets/Editor/Scripts/Shelves/icons/time_scale_tenth.png deleted file mode 100644 index 0aba084827..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/time_scale_tenth.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f71d44c06aa67ab94b190bd74516ce73c534a7d6421415437db262659b2ff32a -size 3124 diff --git a/Assets/Editor/Scripts/Shelves/icons/tod.png b/Assets/Editor/Scripts/Shelves/icons/tod.png deleted file mode 100644 index 0d5c4682c2..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/tod.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6028cef57651c79f5eb83c52eb0ab63eb42dbf4014dcb0f60c4c15ab8fe3cafd -size 977 diff --git a/Assets/Editor/Scripts/Shelves/icons/translucency.png b/Assets/Editor/Scripts/Shelves/icons/translucency.png deleted file mode 100644 index 8487c5916f..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/translucency.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:07457d1315f4cf1bd931187d849a1e842c931640edb53abb2a4f5b2d8d65716b -size 3110 diff --git a/Assets/Editor/Scripts/Shelves/icons/transparency.png b/Assets/Editor/Scripts/Shelves/icons/transparency.png deleted file mode 100644 index 4f41c6491b..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/transparency.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e59571a1490d7dd4696bc118bd4ccc8e08a663afac1ce3f2d88bb5d7d6fdb196 -size 558 diff --git a/Assets/Editor/Scripts/Shelves/icons/valid_albedo.png b/Assets/Editor/Scripts/Shelves/icons/valid_albedo.png deleted file mode 100644 index c3a76d6dfa..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/valid_albedo.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ce233f32949099694d4294b95252068c4486edba163a466ebdb20a54a2338f0f -size 3120 diff --git a/Assets/Editor/Scripts/Shelves/icons/valid_spec_lum.png b/Assets/Editor/Scripts/Shelves/icons/valid_spec_lum.png deleted file mode 100644 index 13f8404057..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/valid_spec_lum.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:f5f365970f6f9138d6e78a2053338eb1275c562fb700670ab00e800e6a43280d -size 3199 diff --git a/Assets/Editor/Scripts/Shelves/icons/vegetation.png b/Assets/Editor/Scripts/Shelves/icons/vegetation.png deleted file mode 100644 index 4492e38ce8..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/vegetation.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:48a435a0632d7d0a8bdfee418423d8c411c4eab9b1da0fac257f32451a233d8f -size 747 diff --git a/Assets/Editor/Scripts/Shelves/icons/vertex_normals.png b/Assets/Editor/Scripts/Shelves/icons/vertex_normals.png deleted file mode 100644 index 80c51660c0..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/vertex_normals.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:101e61f7e5b40aaa48bed685f854fc01c58aec66ca8becc5386f6f0c22c020ad -size 1114 diff --git a/Assets/Editor/Scripts/Shelves/icons/vis_area.png b/Assets/Editor/Scripts/Shelves/icons/vis_area.png deleted file mode 100644 index 0d16d4a477..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/vis_area.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:ae9997b5b999a6b66e56d6024617f718ea06fd389a98a97465a5d76780a1da75 -size 3915 diff --git a/Assets/Editor/Scripts/Shelves/icons/water_volume.png b/Assets/Editor/Scripts/Shelves/icons/water_volume.png deleted file mode 100644 index 2be9a96264..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/water_volume.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e88a2a6e4d14bced3d3e48c25d4bfe075d8587898cd61fbd0e3ab99e4391e663 -size 602 diff --git a/Assets/Editor/Scripts/Shelves/icons/wind.png b/Assets/Editor/Scripts/Shelves/icons/wind.png deleted file mode 100644 index 54ed666138..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/wind.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:caa003d65336c2e2a8987122ace98e0300e5d8afe1864dffef0d1651b136ccc1 -size 720 diff --git a/Assets/Editor/Scripts/Shelves/icons/wireframe.png b/Assets/Editor/Scripts/Shelves/icons/wireframe.png deleted file mode 100644 index 85a71daccc..0000000000 --- a/Assets/Editor/Scripts/Shelves/icons/wireframe.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fd5356c97575c12fa7038443c0216a316c234e4e50e2e439ff8dde4504e56243 -size 2848 diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/CMakeLists.txt index 1b42d0d871..29b30a12b4 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/CMakeLists.txt @@ -7,6 +7,7 @@ # add_subdirectory(asset_processor_tests) +add_subdirectory(fbx_tests) if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) ## AP Python Tests ## diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt index 8b9de91906..0170d73af0 100644 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/CMakeLists.txt @@ -97,7 +97,7 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) PATH ${CMAKE_CURRENT_LIST_DIR}/asset_bundler_batch_tests.py EXCLUDE_TEST_RUN_TARGET_FROM_IDE TEST_SERIAL - TIMEOUT 1500 + TIMEOUT 2400 TEST_SUITE periodic RUNTIME_DEPENDENCIES AZ::AssetProcessor diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py index 13b899dfdd..2c805f0291 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_builder_tests.py @@ -113,7 +113,7 @@ class TestsAssetBuilder_WindowsAndMac(object): if listening_port: corrupted_slice_command.append(f'-port={listening_port}') if workspace.project: - corrupted_slice_command.append(f'-gamename={workspace.project}') + corrupted_slice_command.append(f'--project-path={workspace.project}') corrupted_slice_output = utils.safe_subprocess(corrupted_slice_command) # Verify corrupted slice produced error diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py index 768dd985fd..7f85e5e317 100755 --- a/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/asset_processor_tests/asset_bundler_batch_tests.py @@ -902,7 +902,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): second_input_arg = asset_lists_to_string(second_asset_list) # --secondAssetList output_arg = asset_lists_to_string(output_file) # --output - def generate_compare_command(platform_arg: str) -> object: + def generate_compare_command(platform_arg: str, project_name : str) -> object: """Creates a string containing a full Compare command. This string can be executed as-is.""" cmd = [helper["bundler_batch"], "compare", f"--firstassetFile={first_input_arg}", f"--output={output_arg}"] if platform_arg is not None: @@ -918,6 +918,8 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): if comp_type == "4": # Extra arguments for pattern comparison cmd.extend([f"--filePatternType={pattern_type}", f"--filePattern={pattern}"]) + if workspace.project: + cmd.append(f'--project-path={project_name}') return cmd # End generate_compare_command() @@ -936,6 +938,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): # End verify_asset_list_contents() def run_compare_command_and_verify(platform_arg: str, expect_pc_output: bool, expect_mac_output: bool) -> None: + # Expected asset list to equal result of comparison expected_pc_asset_list = None expected_mac_asset_list = None @@ -957,7 +960,7 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): output_mac_asset_list = helper.platform_file_name(last_output_arg, platform) # Build execution command - cmd = generate_compare_command(platform_arg) + cmd = generate_compare_command(platform_arg, workspace.project) # Execute command subprocess.check_call(cmd) @@ -992,10 +995,12 @@ class TestsAssetBundlerBatch_WindowsAndMac(object): f"--comparisonRulesFile={rule_file}", f"--comparisonType={args[1]}", r"--addComparison", + f"--project-path={workspace.project}", ] if args[1] == "4": # If pattern comparison, append a few extra arguments cmd.extend(["--filePatternType=0", "--filePattern=*.dat"]) + subprocess.check_call(cmd) assert os.path.exists(rule_file), f"Rule file {args[0]} was not created at location: {rule_file}" diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/CMakeLists.txt new file mode 100644 index 0000000000..4a26500ee2 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/CMakeLists.txt @@ -0,0 +1,21 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +if(PAL_TRAIT_BUILD_TESTS_SUPPORTED AND PAL_TRAIT_BUILD_HOST_TOOLS) + ly_add_pytest( + NAME SceneProcessingTests.PythonAssetBuilderTests + TEST_SUITE main + PATH ${CMAKE_CURRENT_LIST_DIR}/pythonassetbuildertests.py + PYTEST_MARKS "not SUITE_sandbox" # don't run sandbox tests in this file + EXCLUDE_TEST_RUN_TARGET_FROM_IDE + RUNTIME_DEPENDENCIES + AZ::AssetProcessorBatch + AZ::AssetProcessor + ) + +endif() diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/a_simple_box_with_script.fbx b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/a_simple_box_with_script.fbx new file mode 100644 index 0000000000..e31b4a96f2 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/a_simple_box_with_script.fbx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f82aecb36faf5cf9f2730e5ad264db38a3a469f8f48aff9b74682d1a32b098f0 +size 11644 diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/a_simple_box_with_script.fbx.assetinfo b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/a_simple_box_with_script.fbx.assetinfo new file mode 100644 index 0000000000..07018ab521 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/a_simple_box_with_script.fbx.assetinfo @@ -0,0 +1,9 @@ +{ + "values": + [ + { + "$type": "ScriptProcessorRule", + "scriptFilename": "TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/python_builder.py" + } + ] +} diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/b_simple_box_no_script.fbx b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/b_simple_box_no_script.fbx new file mode 100644 index 0000000000..e31b4a96f2 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/b_simple_box_no_script.fbx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f82aecb36faf5cf9f2730e5ad264db38a3a469f8f48aff9b74682d1a32b098f0 +size 11644 diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/b_simple_box_no_script.fbx.assetinfo b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/b_simple_box_no_script.fbx.assetinfo new file mode 100644 index 0000000000..72d756d655 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/b_simple_box_no_script.fbx.assetinfo @@ -0,0 +1,15 @@ +{ + "values": [ + { + "$type": "{07B356B7-3635-40B5-878A-FAC4EFD5AD86} MeshGroup", + "name": "b_simple_box_no_script", + "nodeSelectionList": { + "selectedNodes": [ + {}, + "RootNode", + "RootNode.Cube" + ] + } + } + ] +} \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/python_builder.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/python_builder.py new file mode 100644 index 0000000000..7ad5894a86 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/assets/TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene/python_builder.py @@ -0,0 +1,45 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" +import datetime, uuid, os +import azlmbr.scene as sceneApi +import azlmbr.scene.graph + +def output_test_data(scene): + source_filename = os.path.basename(scene.sourceFilename) + source_filename = source_filename.replace('.','_') + + log_output_file_name = f"{source_filename}.log" + + log_output_folder = os.path.dirname(scene.sourceFilename) + log_output_location = os.path.join(log_output_folder, log_output_file_name) + + # Saving a file to the temp folder is the easiest way to have this test communicate + # with the outer python test. + with open(log_output_location, "w") as f: + # Just write something to the file, but the filename is the main information + # used for the test. + f.write(f"scene.sourceFilename: {scene.sourceFilename}\n") + return True + +mySceneJobHandler = None + +def on_update_manifest(args): + scene = args[0] + result = output_test_data(scene) + global mySceneJobHandler + mySceneJobHandler.disconnect() + mySceneJobHandler = None + return result + +def main(): + global mySceneJobHandler + mySceneJobHandler = sceneApi.ScriptBuildingNotificationBusHandler() + mySceneJobHandler.connect() + mySceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/pythonassetbuildertests.py b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/pythonassetbuildertests.py new file mode 100644 index 0000000000..6a568349d2 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/assetpipeline/fbx_tests/pythonassetbuildertests.py @@ -0,0 +1,94 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +# Import builtin libraries +import pytest +import logging +import os +import stat + +# Import LyTestTools +from ly_test_tools.o3de.asset_processor import AssetProcessor +from ly_test_tools.o3de import asset_processor as asset_processor_utils +import ly_test_tools.environment.file_system as fs + +# Import fixtures +from ..ap_fixtures.asset_processor_fixture import asset_processor as asset_processor +from ..ap_fixtures.ap_setup_fixture import ap_setup_fixture as ap_setup_fixture + +# Import LyShared +from ly_test_tools.o3de.ap_log_parser import APLogParser, APOutputParser +import ly_test_tools.o3de.pipeline_utils as utils + +# Use the following logging pattern to hook all test logging together: +logger = logging.getLogger(__name__) +# Configuring the logging is done in ly_test_tools at the following location: +# ~/dev/Tools/LyTestTools/ly_test_tools/log/py_logging_util.py + +# Helper: variables we will use for parameter values in the test: +targetProjects = ["AutomatedTesting"] + +@pytest.fixture +def local_resources(request, workspace, ap_setup_fixture): + ap_setup_fixture["tests_dir"] = os.path.dirname(os.path.realpath(__file__)) + + +@pytest.mark.usefixtures("asset_processor") +@pytest.mark.usefixtures("ap_setup_fixture") +@pytest.mark.usefixtures("local_resources") +@pytest.mark.parametrize("project", targetProjects) +@pytest.mark.assetpipeline +@pytest.mark.SUITE_main +class TestsPythonAssetProcessing_APBatch(object): + + @pytest.mark.BAT + @pytest.mark.assetpipeline + def test_ProcessAssetWithoutScriptAfterAssetWithScript_ScriptOnlyRunsOnExpectedAsset(self, workspace, ap_setup_fixture, asset_processor): + # This is a regression test. The situation it's testing is, the Python script to run + # defined in scene manifest files was persisting in a single builder. So if + # that builder processed file a.fbx, then b.fbx, and a.fbx has a Python script to run, + # it was also running that Python script on b.fbx. + + asset_processor.prepare_test_environment(ap_setup_fixture["tests_dir"], "TwoSceneFiles_OneWithPythonOneWithout_PythonOnlyRunsOnFirstScene") + + asset_processor_extra_params = [ + # Disabling Atom assets disables most products, using the debugOutput flag ensures one product is output. + "--debugOutput", + # By default, if job priorities are equal, jobs run in an arbitrary order. This makes sure + # jobs are run by sorting on the database source name, so they run in the same order each time + # when this test is run. + "--sortJobsByDBSourceName", + # Disabling Atom products means this asset won't need a lot of source dependencies to be processed, + # keeping the scope of this test down. + "--regset=\"/O3DE/SceneAPI/AssetImporter/SkipAtomOutput=true\"", + # The bug this regression test happened when the same builder processed FBX files with and without Python. + # This flag ensures that only one builder is launched, so that situation can be replicated. + "--regset=\"/Amazon/AssetProcessor/Settings/Jobs/maxJobs=1\""] + + result, _ = asset_processor.batch_process(extra_params=asset_processor_extra_params) + assert result, "AP Batch failed" + + expected_product_list = [ + "a_simple_box_with_script.dbgsg", + "b_simple_box_no_script.dbgsg" + ] + + missing_assets, _ = utils.compare_assets_with_cache(expected_product_list, + asset_processor.project_test_cache_folder()) + assert not missing_assets, f'The following assets were expected to be in, but not found in cache: {str(missing_assets)}' + + # The Python script loaded in the scene manifest will write a log file with the source file's name + # to the temp folder. This is the easiest way to have the internal Python there communicate with this test. + expected_path = os.path.join(asset_processor.project_test_source_folder(), "a_simple_box_with_script_fbx.log") + unexpected_path = os.path.join(asset_processor.project_test_source_folder(), "b_simple_box_no_script_fbx.log") + + # Simple check to make sure the Python script in the scene manifest ran on the file it should have ran on. + assert os.path.exists(expected_path), f"Did not find expected output test asset {expected_path}" + # If this test fails here, it means the Python script from the first processed FBX file is being run + # on the second FBX file, when it should not be. + assert not os.path.exists(unexpected_path), f"Found unexpected output test asset {unexpected_path}" + diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt index a342d95d98..d4f036faeb 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt @@ -17,7 +17,7 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED AND AutomatedT TEST_SUITE main PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_MainSuite.py TEST_SERIAL - TIMEOUT 400 + TIMEOUT 600 RUNTIME_DEPENDENCIES AssetProcessor AutomatedTesting.Assets diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py new file mode 100644 index 0000000000..ec8dc199ae --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py @@ -0,0 +1,217 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +Hydra script that creates an entity, attaches the Light component to it for test verifications. +The test verifies that each light type option is available and can be selected without errors. +""" + +import os +import sys + +import azlmbr.bus as bus +import azlmbr.editor as editor +import azlmbr.math as math +import azlmbr.paths +import azlmbr.legacy.general as general + +sys.path.append(os.path.join(azlmbr.paths.devassets, "Gem", "PythonTests")) + +import editor_python_test_tools.hydra_editor_utils as hydra +from atom_renderer.atom_utils.atom_component_helper import LIGHT_TYPES + +LIGHT_TYPE_PROPERTY = 'Controller|Configuration|Light type' +SPHERE_AND_SPOT_DISK_LIGHT_PROPERTIES = [ + ("Controller|Configuration|Shadows|Enable shadow", True), + ("Controller|Configuration|Shadows|Shadowmap size", 0), # 256 + ("Controller|Configuration|Shadows|Shadowmap size", 1), # 512 + ("Controller|Configuration|Shadows|Shadowmap size", 2), # 1024 + ("Controller|Configuration|Shadows|Shadowmap size", 3), # 2048 + ("Controller|Configuration|Shadows|Shadow filter method", 1), # PCF + ("Controller|Configuration|Shadows|Filtering sample count", 4.0), + ("Controller|Configuration|Shadows|Filtering sample count", 64.0), + ("Controller|Configuration|Shadows|PCF method", 0), # Bicubic + ("Controller|Configuration|Shadows|PCF method", 1), # Boundary search + ("Controller|Configuration|Shadows|Shadow filter method", 2), # ECM + ("Controller|Configuration|Shadows|ESM exponent", 50), + ("Controller|Configuration|Shadows|ESM exponent", 5000), + ("Controller|Configuration|Shadows|Shadow filter method", 3), # ESM+PCF +] +QUAD_LIGHT_PROPERTIES = [ + ("Controller|Configuration|Both directions", True), + ("Controller|Configuration|Fast approximation", True), +] +SIMPLE_POINT_LIGHT_PROPERTIES = [ + ("Controller|Configuration|Attenuation radius|Mode", 0), + ("Controller|Configuration|Attenuation radius|Radius", 100.0), +] +SIMPLE_SPOT_LIGHT_PROPERTIES = [ + ("Controller|Configuration|Shutters|Inner angle", 45.0), + ("Controller|Configuration|Shutters|Outer angle", 90.0), +] + + +def verify_required_component_property_value(entity_name, component, property_path, expected_property_value): + """ + Compares the property value of component against the expected_property_value. + :param entity_name: name of the entity to use (for test verification purposes). + :param component: component to check on a given entity for its current property value. + :param property_path: the path to the property inside the component. + :param expected_property_value: The value expected from the value inside property_path. + :return: None, but prints to general.log() which the test uses to verify against. + """ + property_value = editor.EditorComponentAPIBus( + bus.Broadcast, "GetComponentProperty", component, property_path).GetValue() + general.log(f"{entity_name}_test: Property value is {property_value} " + f"which matches {expected_property_value}") + + +def run(): + """ + Test Case - Light Component + 1. Creates a "light_entity" Entity and attaches a "Light" component to it. + 2. Updates the Light component to each light type option from the LIGHT_TYPES constant. + 3. The test will check the Editor log to ensure each light type was selected. + 4. Prints the string "Light component test (non-GPU) completed" after completion. + + Tests will fail immediately if any of these log lines are found: + 1. Trace::Assert + 2. Trace::Error + 3. Traceback (most recent call last): + + :return: None + """ + # Create a "light_entity" entity with "Light" component. + light_entity_name = "light_entity" + light_component = "Light" + light_entity = hydra.Entity(light_entity_name) + light_entity.create_entity(math.Vector3(-1.0, -2.0, 3.0), [light_component]) + general.log( + f"{light_entity_name}_test: Component added to the entity: " + f"{hydra.has_components(light_entity.id, [light_component])}") + + # Populate the light_component_id_pair value so that it can be used to select all Light component options. + light_component_id_pair = None + component_type_id_list = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'FindComponentTypeIdsByEntityType', [light_component], 0) + if len(component_type_id_list) < 1: + general.log(f"ERROR: A component class with name {light_component} doesn't exist") + light_component_id_pair = None + elif len(component_type_id_list) > 1: + general.log(f"ERROR: Found more than one component classes with same name: {light_component}") + light_component_id_pair = None + entity_component_id_pair = azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, 'GetComponentOfType', light_entity.id, component_type_id_list[0]) + if entity_component_id_pair.IsSuccess(): + light_component_id_pair = entity_component_id_pair.GetValue() + + # Test each Light component option can be selected and it's properties updated. + # Point (sphere) light type checks. + light_type_property_test( + light_type=LIGHT_TYPES['sphere'], + light_properties=SPHERE_AND_SPOT_DISK_LIGHT_PROPERTIES, + light_component_id_pair=light_component_id_pair, + light_entity_name=light_entity_name, + light_entity=light_entity + ) + + # Spot (disk) light type checks. + light_type_property_test( + light_type=LIGHT_TYPES['spot_disk'], + light_properties=SPHERE_AND_SPOT_DISK_LIGHT_PROPERTIES, + light_component_id_pair=light_component_id_pair, + light_entity_name=light_entity_name, + light_entity=light_entity + ) + + # Capsule light type checks. + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + LIGHT_TYPES['capsule'] + ) + verify_required_component_property_value( + entity_name=light_entity_name, + component=light_entity.components[0], + property_path=LIGHT_TYPE_PROPERTY, + expected_property_value=LIGHT_TYPES['capsule'] + ) + + # Quad light type checks. + light_type_property_test( + light_type=LIGHT_TYPES['quad'], + light_properties=QUAD_LIGHT_PROPERTIES, + light_component_id_pair=light_component_id_pair, + light_entity_name=light_entity_name, + light_entity=light_entity + ) + + # Polygon light type checks. + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + LIGHT_TYPES['polygon'] + ) + verify_required_component_property_value( + entity_name=light_entity_name, + component=light_entity.components[0], + property_path=LIGHT_TYPE_PROPERTY, + expected_property_value=LIGHT_TYPES['polygon'] + ) + + # Point (simple punctual) light type checks. + light_type_property_test( + light_type=LIGHT_TYPES['simple_point'], + light_properties=SIMPLE_POINT_LIGHT_PROPERTIES, + light_component_id_pair=light_component_id_pair, + light_entity_name=light_entity_name, + light_entity=light_entity + ) + + # Spot (simple punctual) light type checks. + light_type_property_test( + light_type=LIGHT_TYPES['simple_spot'], + light_properties=SIMPLE_SPOT_LIGHT_PROPERTIES, + light_component_id_pair=light_component_id_pair, + light_entity_name=light_entity_name, + light_entity=light_entity + ) + + general.log("Light component test (non-GPU) completed.") + + +def light_type_property_test(light_type, light_properties, light_component_id_pair, light_entity_name, light_entity): + """ + Updates the current light type and modifies its properties, then verifies they are accurate to what was set. + :param light_type: The type of light to update, must match a value in LIGHT_TYPES + :param light_properties: List of tuples detailing properties to modify with update values. + :param light_component_id_pair: Entity + component ID pair for updating the light component on a given entity. + :param light_entity_name: the name of the Entity holding the light component. + :param light_entity: the Entity object containing the light component. + :return: None + """ + azlmbr.editor.EditorComponentAPIBus( + azlmbr.bus.Broadcast, + 'SetComponentProperty', + light_component_id_pair, + LIGHT_TYPE_PROPERTY, + light_type + ) + verify_required_component_property_value( + entity_name=light_entity_name, + component=light_entity.components[0], + property_path=LIGHT_TYPE_PROPERTY, + expected_property_value=light_type + ) + + for light_property in light_properties: + light_entity.get_set_test(0, light_property[0], light_property[1]) + + +if __name__ == "__main__": + run() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py new file mode 100644 index 0000000000..de4e28bb36 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_utils/atom_component_helper.py @@ -0,0 +1,19 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +File to assist with common hydra component functions or constants used across various Atom tests. +""" + +# Light type options for the Light component. +LIGHT_TYPES = { + 'unknown': 0, + 'sphere': 1, + 'spot_disk': 2, + 'capsule': 3, + 'quad': 4, + 'polygon': 5, + 'simple_point': 6, + 'simple_spot': 7, +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index ed5d057626..98d2ba0632 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -12,9 +12,10 @@ import os import pytest import editor_python_test_tools.hydra_test_utils as hydra +from atom_renderer.atom_utils.atom_component_helper import LIGHT_TYPES logger = logging.getLogger(__name__) -EDITOR_TIMEOUT = 300 +EDITOR_TIMEOUT = 120 TEST_DIRECTORY = os.path.join(os.path.dirname(__file__), "atom_hydra_scripts") @@ -180,3 +181,64 @@ class TestAtomEditorComponentsMain(object): null_renderer=True, cfg_args=cfg_args, ) + + def test_AtomEditorComponents_LightComponent( + self, request, editor, workspace, project, launcher_platform, level): + """ + Please review the hydra script run by this test for more specific test info. + Tests that the Light component has the expected property options available to it. + """ + cfg_args = [level] + + expected_lines = [ + "light_entity Entity successfully created", + "Entity has a Light component", + "light_entity_test: Component added to the entity: True", + f"light_entity_test: Property value is {LIGHT_TYPES['sphere']} which matches {LIGHT_TYPES['sphere']}", + "Controller|Configuration|Shadows|Enable shadow set to True", + "light_entity Controller|Configuration|Shadows|Shadowmap size: SUCCESS", + "Controller|Configuration|Shadows|Shadow filter method set to 1", # PCF + "Controller|Configuration|Shadows|Filtering sample count set to 4", + "Controller|Configuration|Shadows|Filtering sample count set to 64", + "Controller|Configuration|Shadows|PCF method set to 0", + "Controller|Configuration|Shadows|PCF method set to 1", + "Controller|Configuration|Shadows|Shadow filter method set to 2", # ESM + "Controller|Configuration|Shadows|ESM exponent set to 50.0", + "Controller|Configuration|Shadows|ESM exponent set to 5000.0", + "Controller|Configuration|Shadows|Shadow filter method set to 3", # ESM+PCF + f"light_entity_test: Property value is {LIGHT_TYPES['spot_disk']} which matches {LIGHT_TYPES['spot_disk']}", + f"light_entity_test: Property value is {LIGHT_TYPES['capsule']} which matches {LIGHT_TYPES['capsule']}", + f"light_entity_test: Property value is {LIGHT_TYPES['quad']} which matches {LIGHT_TYPES['quad']}", + "light_entity Controller|Configuration|Fast approximation: SUCCESS", + "light_entity Controller|Configuration|Both directions: SUCCESS", + f"light_entity_test: Property value is {LIGHT_TYPES['polygon']} which matches {LIGHT_TYPES['polygon']}", + f"light_entity_test: Property value is {LIGHT_TYPES['simple_point']} " + f"which matches {LIGHT_TYPES['simple_point']}", + "Controller|Configuration|Attenuation radius|Mode set to 0", + "Controller|Configuration|Attenuation radius|Radius set to 100.0", + f"light_entity_test: Property value is {LIGHT_TYPES['simple_spot']} " + f"which matches {LIGHT_TYPES['simple_spot']}", + "Controller|Configuration|Shutters|Outer angle set to 45.0", + "Controller|Configuration|Shutters|Outer angle set to 90.0", + "light_entity_test: Component added to the entity: True", + "Light component test (non-GPU) completed.", + ] + + unexpected_lines = [ + "Trace::Assert", + "Trace::Error", + "Traceback (most recent call last):", + ] + + hydra.launch_and_validate_results( + request, + TEST_DIRECTORY, + editor, + "hydra_AtomEditorComponents_LightComponent.py", + timeout=EDITOR_TIMEOUT, + expected_lines=expected_lines, + unexpected_lines=unexpected_lines, + halt_on_unexpected=True, + null_renderer=True, + cfg_args=cfg_args, + ) diff --git a/AutomatedTesting/Passes/MainPipeline.pass b/AutomatedTesting/Passes/MainPipeline.pass new file mode 100644 index 0000000000..aa9f3757c4 --- /dev/null +++ b/AutomatedTesting/Passes/MainPipeline.pass @@ -0,0 +1,483 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "MainPipeline", + "PassClass": "ParentPass", + "Slots": [ + { + "Name": "SwapChainOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "RenderTarget" + } + ], + "PassRequests": [ + { + "Name": "MorphTargetPass", + "TemplateName": "MorphTargetPassTemplate" + }, + { + "Name": "SkinningPass", + "TemplateName": "SkinningPassTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshOutputStream", + "AttachmentRef": { + "Pass": "MorphTargetPass", + "Attachment": "MorphTargetDeltaOutput" + } + } + ] + }, + { + "Name": "RayTracingAccelerationStructurePass", + "TemplateName": "RayTracingAccelerationStructurePassTemplate" + }, + { + "Name": "DiffuseProbeGridUpdatePass", + "TemplateName": "DiffuseProbeGridUpdatePassTemplate", + "ExecuteAfter": [ + "RayTracingAccelerationStructurePass" + ] + }, + { + "Name": "DepthPrePass", + "TemplateName": "DepthMSAAParentTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshes", + "AttachmentRef": { + "Pass": "SkinningPass", + "Attachment": "SkinnedMeshOutputStream" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "MotionVectorPass", + "TemplateName": "MotionVectorParentTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshes", + "AttachmentRef": { + "Pass": "SkinningPass", + "Attachment": "SkinnedMeshOutputStream" + } + }, + { + "LocalSlot": "Depth", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "LightCullingPass", + "TemplateName": "LightCullingParentTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshes", + "AttachmentRef": { + "Pass": "SkinningPass", + "Attachment": "SkinnedMeshOutputStream" + } + }, + { + "LocalSlot": "DepthMSAA", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthMSAA" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "ShadowPass", + "TemplateName": "ShadowParentTemplate", + "Connections": [ + { + "LocalSlot": "SkinnedMeshes", + "AttachmentRef": { + "Pass": "SkinningPass", + "Attachment": "SkinnedMeshOutputStream" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "OpaquePass", + "TemplateName": "OpaqueParentTemplate", + "Connections": [ + { + "LocalSlot": "DirectionalShadowmap", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "DirectionalShadowmap" + } + }, + { + "LocalSlot": "DirectionalESM", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "DirectionalESM" + } + }, + { + "LocalSlot": "ProjectedShadowmap", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "ProjectedShadowmap" + } + }, + { + "LocalSlot": "ProjectedESM", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "ProjectedESM" + } + }, + { + "LocalSlot": "TileLightData", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "TileLightData" + } + }, + { + "LocalSlot": "LightListRemapped", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "LightListRemapped" + } + }, + { + "LocalSlot": "DepthLinear", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthLinear" + } + }, + { + "LocalSlot": "DepthStencil", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthMSAA" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "TransparentPass", + "TemplateName": "TransparentParentTemplate", + "Connections": [ + { + "LocalSlot": "DirectionalShadowmap", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "DirectionalShadowmap" + } + }, + { + "LocalSlot": "DirectionalESM", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "DirectionalESM" + } + }, + { + "LocalSlot": "ProjectedShadowmap", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "ProjectedShadowmap" + } + }, + { + "LocalSlot": "ProjectedESM", + "AttachmentRef": { + "Pass": "ShadowPass", + "Attachment": "ProjectedESM" + } + }, + { + "LocalSlot": "TileLightData", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "TileLightData" + } + }, + { + "LocalSlot": "LightListRemapped", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "LightListRemapped" + } + }, + { + "LocalSlot": "InputLinearDepth", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthLinear" + } + }, + { + "LocalSlot": "DepthStencil", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + }, + { + "LocalSlot": "InputOutput", + "AttachmentRef": { + "Pass": "OpaquePass", + "Attachment": "Output" + } + } + ] + }, + { + "Name": "DeferredFogPass", + "TemplateName": "DeferredFogPassTemplate", + "Enabled": false, + "Connections": [ + { + "LocalSlot": "InputLinearDepth", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "DepthLinear" + } + }, + { + "LocalSlot": "InputDepthStencil", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + }, + { + "LocalSlot": "RenderTargetInputOutput", + "AttachmentRef": { + "Pass": "TransparentPass", + "Attachment": "InputOutput" + } + } + ], + "PassData": { + "$type": "FullscreenTrianglePassData", + "ShaderAsset": { + "FilePath": "Shaders/ScreenSpace/DeferredFog.shader" + }, + "PipelineViewTag": "MainCamera" + } + }, + { + "Name": "ReflectionCopyFrameBufferPass", + "TemplateName": "ReflectionCopyFrameBufferPassTemplate", + "Enabled": false, + "Connections": [ + { + "LocalSlot": "Input", + "AttachmentRef": { + "Pass": "DeferredFogPass", + "Attachment": "RenderTargetInputOutput" + } + } + ] + }, + { + "Name": "PostProcessPass", + "TemplateName": "PostProcessParentTemplate", + "Connections": [ + { + "LocalSlot": "LightingInput", + "AttachmentRef": { + "Pass": "DeferredFogPass", + "Attachment": "RenderTargetInputOutput" + } + }, + { + "LocalSlot": "Depth", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + }, + { + "LocalSlot": "MotionVectors", + "AttachmentRef": { + "Pass": "MotionVectorPass", + "Attachment": "MotionVectorOutput" + } + }, + { + "LocalSlot": "SwapChainOutput", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + }, + { + "Name": "AuxGeomPass", + "TemplateName": "AuxGeomPassTemplate", + "Enabled": true, + "Connections": [ + { + "LocalSlot": "ColorInputOutput", + "AttachmentRef": { + "Pass": "PostProcessPass", + "Attachment": "Output" + } + }, + { + "LocalSlot": "DepthInputOutput", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + } + ], + "PassData": { + "$type": "RasterPassData", + "DrawListTag": "auxgeom", + "PipelineViewTag": "MainCamera" + } + }, + { + "Name": "DebugOverlayPass", + "TemplateName": "DebugOverlayParentTemplate", + "Connections": [ + { + "LocalSlot": "TileLightData", + "AttachmentRef": { + "Pass": "LightCullingPass", + "Attachment": "TileLightData" + } + }, + { + "LocalSlot": "RawLightingInput", + "AttachmentRef": { + "Pass": "PostProcessPass", + "Attachment": "RawLightingOutput" + } + }, + { + "LocalSlot": "LuminanceMipChainInput", + "AttachmentRef": { + "Pass": "PostProcessPass", + "Attachment": "LuminanceMipChainOutput" + } + }, + { + "LocalSlot": "InputOutput", + "AttachmentRef": { + "Pass": "AuxGeomPass", + "Attachment": "ColorInputOutput" + } + } + ] + }, + { + "Name": "LyShinePass", + "TemplateName": "LyShineParentTemplate", + "Connections": [ + { + "LocalSlot": "ColorInputOutput", + "AttachmentRef": { + "Pass": "DebugOverlayPass", + "Attachment": "InputOutput" + } + }, + { + "LocalSlot": "DepthInputOutput", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + } + ] + }, + { + "Name": "UIPass", + "TemplateName": "UIParentTemplate", + "Connections": [ + { + "LocalSlot": "InputOutput", + "AttachmentRef": { + "Pass": "LyShinePass", + "Attachment": "ColorInputOutput" + } + }, + { + "LocalSlot": "DepthInputOutput", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + } + ] + }, + { + "Name": "CopyToSwapChain", + "TemplateName": "FullscreenCopyTemplate", + "Connections": [ + { + "LocalSlot": "Input", + "AttachmentRef": { + "Pass": "UIPass", + "Attachment": "InputOutput" + } + }, + { + "LocalSlot": "Output", + "AttachmentRef": { + "Pass": "Parent", + "Attachment": "SwapChainOutput" + } + } + ] + } + ] + } + } +} \ No newline at end of file diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 357c27fd72..4ea36728ad 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -472,6 +472,12 @@ void EditorViewportWidget::Update() m_Camera.SetZRange(cameraState.m_nearClip, cameraState.m_farClip); } + // Ensure the FOV matches our internally stored setting if we're using the Editor camera + if (!m_viewEntityId.IsValid() && !GetIEditor()->IsInGameMode()) + { + SetFOV(GetFOV()); + } + // Reset the camera update flag now that we're finished updating our viewport context m_updateCameraPositionNextTick = false; @@ -2624,8 +2630,6 @@ void EditorViewportWidget::DestroyRenderContext() ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::SetDefaultCamera() { - // Ensure the FOV matches our internally stored setting - SetFOV(GetFOV()); if (IsDefaultCamera()) { return; diff --git a/Code/Editor/ToolBox.cpp b/Code/Editor/ToolBox.cpp index 77cb479873..82817e1ff7 100644 --- a/Code/Editor/ToolBox.cpp +++ b/Code/Editor/ToolBox.cpp @@ -321,42 +321,13 @@ bool CToolBoxManager::SetMacroTitle(int index, const QString& title, bool bToolb } ////////////////////////////////////////////////////////////////////////// -void CToolBoxManager::Load(ActionManager* actionManager) +void CToolBoxManager::Load([[maybe_unused]] ActionManager* actionManager) { Clear(); QString path; GetSaveFilePath(path); Load(path, nullptr, true, nullptr); - - if (actionManager) - { - auto engineSourceAssetPath = AZ::IO::FixedMaxPath(AZ::Utils::GetEnginePath()) / "Assets"; - LoadShelves((engineSourceAssetPath / "Editor" / "Scripts").c_str(), - (engineSourceAssetPath / "Editor" / "Scripts" / "Shelves").c_str(), actionManager); - } -} - -void CToolBoxManager::LoadShelves(QString scriptPath, QString shelvesPath, ActionManager* actionManager) -{ - IFileUtil::FileArray files; - CFileUtil::ScanDirectory(shelvesPath, "*.xml", files); - - const int shelfCount = files.size(); - for (int idx = 0; idx < shelfCount; ++idx) - { - if (Path::GetExt(files[idx].filename) != "xml") - { - continue; - } - - QString shelfName(PathUtil::GetFileName(files[idx].filename.toUtf8().data())); - - AmazonToolbar toolbar(shelfName, shelfName); - Load(shelvesPath + QString("/") + files[idx].filename, &toolbar, false, actionManager); - - m_toolbars.push_back(toolbar); - } } void CToolBoxManager::Load(QString xmlpath, AmazonToolbar* pToolbar, bool bToolbox, ActionManager* actionManager) diff --git a/Code/Editor/ToolBox.h b/Code/Editor/ToolBox.h index 691b9cd089..0c91305c79 100644 --- a/Code/Editor/ToolBox.h +++ b/Code/Editor/ToolBox.h @@ -129,7 +129,6 @@ public: void Save() const; // Load macros configuration from registry. void Load(ActionManager* actionManager = nullptr); - void LoadShelves(QString scriptPath, QString shelvesPath, ActionManager* actionManager); //! Get the number of managed macros. int GetMacroCount(bool bToolbox) const; diff --git a/Code/Framework/AzCore/AzCore/Jobs/Job.cpp b/Code/Framework/AzCore/AzCore/Jobs/Job.cpp new file mode 100644 index 0000000000..d3a2a77d92 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Jobs/Job.cpp @@ -0,0 +1,312 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#include +#include +#include +#include +#include +#include + +namespace AZ +{ + Job::Job(bool isAutoDelete, AZ::JobContext* context, bool isCompletion, AZ::s8 priority) + { + if (context) + { + m_context = context; + } + else + { + m_context = JobContext::GetParentContext(); + } + + unsigned int countAndFlags = 1; + if (isAutoDelete) + { + countAndFlags |= (unsigned int)FLAG_AUTO_DELETE; + } + if (isCompletion) + { + countAndFlags |= (unsigned int)FLAG_COMPLETION; + } + countAndFlags |= (unsigned int)((priority << FLAG_PRIORITY_START_BIT) & FLAG_PRIORITY_MASK); + SetDependentCountAndFlags(countAndFlags); + StoreDependent(NULL); + + #ifdef AZ_DEBUG_JOB_STATE + SetState(STATE_SETUP); + #endif // AZ_DEBUG_JOB_STATE + } + + void Job::Start() + { + //jobs are created with a count set to 1, we remove that count to allow the job to start + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(m_state == STATE_SETUP, ("Jobs must be in the setup state before they can be started")); + SetState(STATE_STARTED); + #endif + DecrementDependentCount(); + } + + void Job::Reset(bool isClearDependent) + { + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert((m_state == STATE_SETUP) || (m_state == STATE_PROCESSING), "Jobs must not be running when they are reset"); + SetState(STATE_SETUP); + #endif + unsigned int countAndFlags = GetDependentCountAndFlags(); + AZ_Assert((countAndFlags & (unsigned int)FLAG_AUTO_DELETE) == 0, "You can't call reset on AutoDelete jobs!"); + // Remove the FLAG_DEPENDENTCOUNT_MASK and FLAG_CHILD_JOBS flags + countAndFlags = (countAndFlags & (~(FLAG_DEPENDENTCOUNT_MASK) & ~(FLAG_CHILD_JOBS))) | 1; + SetDependentCountAndFlags(countAndFlags); + if (isClearDependent) + { + StoreDependent(NULL); + } + else + { + Job* dependent = GetDependent(); + if (dependent) + { + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(dependent->m_state == STATE_SETUP, ("Dependent must be in setup state before it can be re-initialized")); + #endif + dependent->IncrementDependentCount(); + } + } + } + + void Job::SetDependent(Job* dependent) + { + AZ_Assert(!GetDependent(), ("Job already has a dependent, should be cleared after the job is done")); + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(m_state == STATE_SETUP, ("Dependent can only be set before the jobs are started")); + AZ_Assert(dependent->m_state == STATE_SETUP, ("Dependent must be in the setup state")); + #endif + dependent->IncrementDependentCount(); + StoreDependent(dependent); + } + + void Job::SetDependentStarted(Job* dependent) + { + AZ_Assert(!GetDependent(), ("Job already has a dependent, should be cleared after the job is done")); + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(m_state == STATE_SETUP, ("Dependent can only be set before the jobs are started")); + //We don't require the dependent to be in STATE_SETUP, the user can call this from a context where they + //know the dependent has not started yet, although it is in STATE_STARTED already, e.g. if SetDependent + //is called from a job which the dependent is already dependent on. + //Note that if the user gets this wrong, the dependent may start before this job is finished, and the asserts + //may not even trigger due to race conditions. Hence why this function is 'experts only'. + AZ_Assert((dependent->m_state == STATE_SETUP) || (dependent->m_state == STATE_STARTED) + || (dependent->m_state == STATE_SUSPENDED), "Dependent must be in the setup, started, or suspended state"); + #endif + dependent->IncrementDependentCount(); + StoreDependent(dependent); + } + + void Job::SetDependentChild(Job* dependent) + { + AZ_Assert(!GetDependent(), ("Job already has a dependent, should be cleared after the job is done")); + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(m_state == STATE_SETUP, ("Dependent can only be set before the jobs are started")); + AZ_Assert(dependent->m_state == STATE_PROCESSING, "Dependent must be processing to add a child"); + #endif + dependent->IncrementDependentCountAndSetChildFlag(); + StoreDependent(dependent); + } + + void Job::SetContinuation(Job* continuationJob) + { + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(m_state == STATE_PROCESSING, "Continuation jobs can only be set while we are processing, otherwise a regular dependent should be used"); + #endif + Job* dependent = GetDependent(); + if (dependent) //nothing to do if there is no dependent... doesn't usually happen, except with synchronous processing and assists + { + continuationJob->SetDependentStarted(dependent); + } + } + + void Job::StartAsChild(Job* childJob) + { + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(m_state == STATE_PROCESSING, "Child jobs can only be added while we are processing"); + #endif + childJob->SetDependentChild(this); + childJob->Start(); + } + + void Job::WaitForChildren() + { + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(m_state == STATE_PROCESSING, "We must be currently processing in order to suspend"); + #endif + if (GetDependentCount() != 0) + { + #ifdef AZ_DEBUG_JOB_STATE + SetState(STATE_SUSPENDED); + #endif // AZ_DEBUG_JOB_STATE + m_context->GetJobManager().SuspendJobUntilReady(this); + #ifdef AZ_DEBUG_JOB_STATE + SetState(STATE_PROCESSING); + #endif // AZ_DEBUG_JOB_STATE + } + AZ_Assert(GetDependentCount() == 0, "Suspended job has resumed, but still has non-zero dependent count, bug in JobManager?"); + } + + bool Job::IsCancelled() const + { + JobCancelGroup* cancelGroup = m_context->GetCancelGroup(); + if (cancelGroup && cancelGroup->IsCancelled()) + { + if (!IsCompletion()) // always run completion jobs, as they can be holding a synchronization primitive + { + return true; + } + } + return false; + } + + bool Job::IsAutoDelete() const + { + return (GetDependentCountAndFlags() & (unsigned int)FLAG_AUTO_DELETE) ? true : false; + } + + bool Job::IsCompletion() const + { + return (GetDependentCountAndFlags() & (unsigned int)FLAG_COMPLETION) ? true : false; + } + + void Job::StartAndAssistUntilComplete() + { + m_context->GetJobManager().StartJobAndAssistUntilComplete(this); + } + + void Job::StartAndWaitForCompletion() + { + //check if we are in a worker thread or a general user thread + Job* currentJob = m_context->GetJobManager().GetCurrentJob(); + if (currentJob) + { + //worker thread, so just suspend this current job until the empty job completes + currentJob->StartAsChild(this); + currentJob->WaitForChildren(); + } + else + { + StartAndAssistUntilComplete(); + } + } + + unsigned int Job::GetDependentCount() const + { + return (GetDependentCountAndFlags() & FLAG_DEPENDENTCOUNT_MASK); + } + + void Job::IncrementDependentCount() + { + AZ_Assert(GetDependentCount() < FLAG_DEPENDENTCOUNT_MASK, "Dependent count overflow"); + #ifdef AZCORE_JOBS_IMPL_SYNCHRONOUS + ++m_dependentCountAndFlags; + #else + m_dependentCountAndFlags.fetch_add(1, AZStd::memory_order_acq_rel); + #endif + } + + void Job::IncrementDependentCountAndSetChildFlag() + { + AZ_Assert(GetDependentCount() < FLAG_DEPENDENTCOUNT_MASK, "Dependent count overflow"); + #ifdef AZCORE_JOBS_IMPL_SYNCHRONOUS + int oldCount = m_dependentCountAndFlags & FLAG_DEPENDENTCOUNT_MASK; + m_dependentCountAndFlags = (m_dependentCountAndFlags & ~FLAG_DEPENDENTCOUNT_MASK) | (oldCount + 1) | FLAG_CHILD_JOBS; + #else + //use a single atomic operation to increment the count and set the child flag if possible + unsigned int oldCountAndFlags, newCountAndFlags; + do + { + oldCountAndFlags = m_dependentCountAndFlags.load(AZStd::memory_order_acquire); + int oldCount = oldCountAndFlags & FLAG_DEPENDENTCOUNT_MASK; + newCountAndFlags = (oldCountAndFlags & ~FLAG_DEPENDENTCOUNT_MASK) | (oldCount + 1) | FLAG_CHILD_JOBS; + } while (!m_dependentCountAndFlags.compare_exchange_weak(oldCountAndFlags, newCountAndFlags, AZStd::memory_order_acq_rel, AZStd::memory_order_acquire)); + #endif + } + + void Job::DecrementDependentCount() + { + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert((m_state == STATE_SETUP) || (m_state == STATE_STARTED) + || (m_state == STATE_PROCESSING) || (m_state == STATE_SUSPENDED), //child jobs + "Job dependent count should not be decremented after job is already pending"); + #endif + AZ_Assert(GetDependentCount() > 0, ("Job dependent count is already zero")); + #ifdef AZCORE_JOBS_IMPL_SYNCHRONOUS + unsigned int countAndFlags = m_dependentCountAndFlags--; + #else + unsigned int countAndFlags = m_dependentCountAndFlags.fetch_sub(1, AZStd::memory_order_acq_rel); + #endif + unsigned int count = countAndFlags & FLAG_DEPENDENTCOUNT_MASK; + if (count == 1) + { + if (!(countAndFlags & FLAG_CHILD_JOBS)) + { + #ifdef AZ_DEBUG_JOB_STATE + AZ_Assert(m_state == STATE_STARTED, "Job has not been started but the dependent count is zero, must be a dependency error"); + SetState(STATE_PENDING); + #endif + m_context->GetJobManager().AddPendingJob(this); + } + } + } + + AZ::s8 Job::GetPriority() const + { + return (GetDependentCountAndFlags() >> FLAG_PRIORITY_START_BIT) & 0xff; + } + +#ifdef AZCORE_JOBS_IMPL_SYNCHRONOUS + void Job::StoreDependent(Job* job) + { + m_dependent = job; + } + + Job* Job::GetDependent() const + { + return m_dependent; + } + + void Job::SetDependentCountAndFlags(unsigned int countAndFlags) + { + m_dependentCountAndFlags = countAndFlags; + } + + unsigned int Job::GetDependentCountAndFlags() const + { + return m_dependentCountAndFlags; + } +#else + void Job::StoreDependent(Job* job) + { + m_dependent.store(job, AZStd::memory_order_release); + } + + Job* Job::GetDependent() const + { + return m_dependent.load(AZStd::memory_order_acquire); + } + + void Job::SetDependentCountAndFlags(unsigned int countAndFlags) + { + m_dependentCountAndFlags.store(countAndFlags, AZStd::memory_order_release); + } + + unsigned int Job::GetDependentCountAndFlags() const + { + return m_dependentCountAndFlags.load(AZStd::memory_order_acquire); + } +#endif +} diff --git a/Code/Framework/AzCore/AzCore/Jobs/Job.h b/Code/Framework/AzCore/AzCore/Jobs/Job.h index 18c639e2c2..b6632dd063 100644 --- a/Code/Framework/AzCore/AzCore/Jobs/Job.h +++ b/Code/Framework/AzCore/AzCore/Jobs/Job.h @@ -5,15 +5,14 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZCORE_JOBS_JOB_H -#define AZCORE_JOBS_JOB_H 1 - -#include -#include -#include -#include -#include +#pragma once +#include +#include +#include +#include +#include + #include #if defined(_DEBUG) @@ -234,319 +233,22 @@ namespace AZ //would require atomic ops to set/read it, so not really worth it. int m_state; }; - - //============================================================================================================ - //============================================================================================================ - //============================================================================================================ - - inline Job::Job(bool isAutoDelete, JobContext* context, bool isCompletion, AZ::s8 priority) - { - if (context) - { - m_context = context; - } - else - { - m_context = JobContext::GetParentContext(); - } - - unsigned int countAndFlags = 1; - if (isAutoDelete) - { - countAndFlags |= (unsigned int)FLAG_AUTO_DELETE; - } - if (isCompletion) - { - countAndFlags |= (unsigned int)FLAG_COMPLETION; - } - countAndFlags |= (unsigned int)((priority << FLAG_PRIORITY_START_BIT) & FLAG_PRIORITY_MASK); - SetDependentCountAndFlags(countAndFlags); - StoreDependent(NULL); - -#ifdef AZ_DEBUG_JOB_STATE - SetState(STATE_SETUP); -#endif // AZ_DEBUG_JOB_STATE - } - - AZ_FORCE_INLINE void Job::Start() - { - //jobs are created with a count set to 1, we remove that count to allow the job to start -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(m_state == STATE_SETUP, ("Jobs must be in the setup state before they can be started")); - SetState(STATE_STARTED); -#endif - DecrementDependentCount(); - } - - inline void Job::Reset(bool isClearDependent) - { -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert((m_state == STATE_SETUP) || (m_state == STATE_PROCESSING), "Jobs must not be running when they are reset"); - SetState(STATE_SETUP); -#endif - unsigned int countAndFlags = GetDependentCountAndFlags(); - AZ_Assert((countAndFlags & (unsigned int)FLAG_AUTO_DELETE) == 0, "You can't call reset on AutoDelete jobs!"); - // Remove the FLAG_DEPENDENTCOUNT_MASK and FLAG_CHILD_JOBS flags - countAndFlags = (countAndFlags & (~(FLAG_DEPENDENTCOUNT_MASK) & ~(FLAG_CHILD_JOBS))) | 1; - SetDependentCountAndFlags(countAndFlags); - if (isClearDependent) - { - StoreDependent(NULL); - } - else - { - Job* dependent = GetDependent(); - if (dependent) - { -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(dependent->m_state == STATE_SETUP, ("Dependent must be in setup state before it can be re-initialized")); -#endif - dependent->IncrementDependentCount(); - } - } - } - - AZ_FORCE_INLINE void Job::SetDependent(Job* dependent) - { - AZ_Assert(!GetDependent(), ("Job already has a dependent, should be cleared after the job is done")); -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(m_state == STATE_SETUP, ("Dependent can only be set before the jobs are started")); - AZ_Assert(dependent->m_state == STATE_SETUP, ("Dependent must be in the setup state")); -#endif - dependent->IncrementDependentCount(); - StoreDependent(dependent); - } - - AZ_FORCE_INLINE void Job::SetDependentStarted(Job* dependent) - { - AZ_Assert(!GetDependent(), ("Job already has a dependent, should be cleared after the job is done")); -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(m_state == STATE_SETUP, ("Dependent can only be set before the jobs are started")); - //We don't require the dependent to be in STATE_SETUP, the user can call this from a context where they - //know the dependent has not started yet, although it is in STATE_STARTED already, e.g. if SetDependent - //is called from a job which the dependent is already dependent on. - //Note that if the user gets this wrong, the dependent may start before this job is finished, and the asserts - //may not even trigger due to race conditions. Hence why this function is 'experts only'. - AZ_Assert((dependent->m_state == STATE_SETUP) || (dependent->m_state == STATE_STARTED) - || (dependent->m_state == STATE_SUSPENDED), "Dependent must be in the setup, started, or suspended state"); -#endif - dependent->IncrementDependentCount(); - StoreDependent(dependent); - } - - AZ_FORCE_INLINE void Job::SetDependentChild(Job* dependent) - { - AZ_Assert(!GetDependent(), ("Job already has a dependent, should be cleared after the job is done")); -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(m_state == STATE_SETUP, ("Dependent can only be set before the jobs are started")); - AZ_Assert(dependent->m_state == STATE_PROCESSING, "Dependent must be processing to add a child"); -#endif - dependent->IncrementDependentCountAndSetChildFlag(); - StoreDependent(dependent); - } - - AZ_FORCE_INLINE void Job::SetContinuation(Job* continuationJob) - { -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(m_state == STATE_PROCESSING, "Continuation jobs can only be set while we are processing, otherwise a regular dependent should be used"); -#endif - Job* dependent = GetDependent(); - if (dependent) //nothing to do if there is no dependent... doesn't usually happen, except with synchronous processing and assists - { - continuationJob->SetDependentStarted(dependent); - } - } - - AZ_FORCE_INLINE void Job::StartAsChild(Job* childJob) - { -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(m_state == STATE_PROCESSING, "Child jobs can only be added while we are processing"); -#endif - childJob->SetDependentChild(this); - childJob->Start(); - } - - AZ_FORCE_INLINE void Job::WaitForChildren() - { -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(m_state == STATE_PROCESSING, "We must be currently processing in order to suspend"); -#endif - if (GetDependentCount() != 0) - { -#ifdef AZ_DEBUG_JOB_STATE - SetState(STATE_SUSPENDED); -#endif // AZ_DEBUG_JOB_STATE - m_context->GetJobManager().SuspendJobUntilReady(this); -#ifdef AZ_DEBUG_JOB_STATE - SetState(STATE_PROCESSING); -#endif // AZ_DEBUG_JOB_STATE - } - AZ_Assert(GetDependentCount() == 0, "Suspended job has resumed, but still has non-zero dependent count, bug in JobManager?"); - } - - AZ_FORCE_INLINE bool Job::IsCancelled() const - { - JobCancelGroup* cancelGroup = m_context->GetCancelGroup(); - if (cancelGroup && cancelGroup->IsCancelled()) - { - if (!IsCompletion()) // always run completion jobs, as they can be holding a synchronization primitive - { - return true; - } - } - return false; - } - - AZ_FORCE_INLINE bool Job::IsAutoDelete() const - { - return (GetDependentCountAndFlags() & (unsigned int)FLAG_AUTO_DELETE) ? true : false; - } - - AZ_FORCE_INLINE bool Job::IsCompletion() const - { - return (GetDependentCountAndFlags() & (unsigned int)FLAG_COMPLETION) ? true : false; - } - - AZ_FORCE_INLINE void Job::StartAndAssistUntilComplete() - { - m_context->GetJobManager().StartJobAndAssistUntilComplete(this); - } - - inline void Job::StartAndWaitForCompletion() - { - //check if we are in a worker thread or a general user thread - Job* currentJob = m_context->GetJobManager().GetCurrentJob(); - if (currentJob) - { - //worker thread, so just suspend this current job until the empty job completes - currentJob->StartAsChild(this); - currentJob->WaitForChildren(); - } - else - { - StartAndAssistUntilComplete(); - } - } - - AZ_FORCE_INLINE JobContext* Job::GetContext() const + + ////////////////////////////////////////////////////////////////////////////////////////////////////// + // Inline implementations + inline JobContext* Job::GetContext() const { return m_context; } - AZ_FORCE_INLINE unsigned int Job::GetDependentCount() const - { - return (GetDependentCountAndFlags() & FLAG_DEPENDENTCOUNT_MASK); - } - - AZ_FORCE_INLINE void Job::IncrementDependentCount() - { - AZ_Assert(GetDependentCount() < FLAG_DEPENDENTCOUNT_MASK, "Dependent count overflow"); -#ifdef AZCORE_JOBS_IMPL_SYNCHRONOUS - ++m_dependentCountAndFlags; -#else - m_dependentCountAndFlags.fetch_add(1, AZStd::memory_order_acq_rel); -#endif - } - - inline void Job::IncrementDependentCountAndSetChildFlag() - { - AZ_Assert(GetDependentCount() < FLAG_DEPENDENTCOUNT_MASK, "Dependent count overflow"); -#ifdef AZCORE_JOBS_IMPL_SYNCHRONOUS - int oldCount = m_dependentCountAndFlags & FLAG_DEPENDENTCOUNT_MASK; - m_dependentCountAndFlags = (m_dependentCountAndFlags & ~FLAG_DEPENDENTCOUNT_MASK) | (oldCount + 1) | FLAG_CHILD_JOBS; -#else - //use a single atomic operation to increment the count and set the child flag if possible - unsigned int oldCountAndFlags, newCountAndFlags; - do - { - oldCountAndFlags = m_dependentCountAndFlags.load(AZStd::memory_order_acquire); - int oldCount = oldCountAndFlags & FLAG_DEPENDENTCOUNT_MASK; - newCountAndFlags = (oldCountAndFlags & ~FLAG_DEPENDENTCOUNT_MASK) | (oldCount + 1) | FLAG_CHILD_JOBS; - } while (!m_dependentCountAndFlags.compare_exchange_weak(oldCountAndFlags, newCountAndFlags, AZStd::memory_order_acq_rel, AZStd::memory_order_acquire)); -#endif - } - - inline void Job::DecrementDependentCount() - { #ifdef AZ_DEBUG_JOB_STATE - AZ_Assert((m_state == STATE_SETUP) || (m_state == STATE_STARTED) - || (m_state == STATE_PROCESSING) || (m_state == STATE_SUSPENDED), //child jobs - "Job dependent count should not be decremented after job is already pending"); -#endif - AZ_Assert(GetDependentCount() > 0, ("Job dependent count is already zero")); -#ifdef AZCORE_JOBS_IMPL_SYNCHRONOUS - unsigned int countAndFlags = m_dependentCountAndFlags--; -#else - unsigned int countAndFlags = m_dependentCountAndFlags.fetch_sub(1, AZStd::memory_order_acq_rel); -#endif - unsigned int count = countAndFlags & FLAG_DEPENDENTCOUNT_MASK; - if (count == 1) - { - if (!(countAndFlags & FLAG_CHILD_JOBS)) - { -#ifdef AZ_DEBUG_JOB_STATE - AZ_Assert(m_state == STATE_STARTED, "Job has not been started but the dependent count is zero, must be a dependency error"); - SetState(STATE_PENDING); -#endif - m_context->GetJobManager().AddPendingJob(this); - } - } - } - - inline AZ::s8 Job::GetPriority() const - { - return (GetDependentCountAndFlags() >> FLAG_PRIORITY_START_BIT) & 0xff; - } - -#ifdef AZ_DEBUG_JOB_STATE - AZ_FORCE_INLINE void Job::SetState(int state) + inline void Job::SetState(int state) { m_state = state; } #endif -#ifdef AZCORE_JOBS_IMPL_SYNCHRONOUS - AZ_FORCE_INLINE void Job::StoreDependent(Job* job) - { - m_dependent = job; - } - AZ_FORCE_INLINE Job* Job::GetDependent() const - { - return m_dependent; - } - - AZ_FORCE_INLINE void Job::SetDependentCountAndFlags(unsigned int countAndFlags) - { - m_dependentCountAndFlags = countAndFlags; - } - - AZ_FORCE_INLINE unsigned int Job::GetDependentCountAndFlags() const - { - return m_dependentCountAndFlags; - } -#else - AZ_FORCE_INLINE void Job::StoreDependent(Job* job) - { - m_dependent.store(job, AZStd::memory_order_release); - } - - AZ_FORCE_INLINE Job* Job::GetDependent() const - { - return m_dependent.load(AZStd::memory_order_acquire); - } - - AZ_FORCE_INLINE void Job::SetDependentCountAndFlags(unsigned int countAndFlags) - { - m_dependentCountAndFlags.store(countAndFlags, AZStd::memory_order_release); - } - - AZ_FORCE_INLINE unsigned int Job::GetDependentCountAndFlags() const - { - return m_dependentCountAndFlags.load(AZStd::memory_order_acquire); - } -#endif } -#endif -#pragma once + diff --git a/Code/Framework/AzCore/AzCore/Serialization/EditContext.h b/Code/Framework/AzCore/AzCore/Serialization/EditContext.h index 019683ee81..492550f266 100644 --- a/Code/Framework/AzCore/AzCore/Serialization/EditContext.h +++ b/Code/Framework/AzCore/AzCore/Serialization/EditContext.h @@ -236,6 +236,17 @@ namespace AZ */ ClassBuilder* ClassElement(Crc32 elementIdCrc, const char* description); + + /** + * Declare element with attributes that belong to the class SerializeContext::Class, this is a logical structure, you can have one or more GroupElementToggles. + * T must be a boolean variable that will enable and disable each DataElement attached to this structure. + * \param description - Descriptive name of the field that will typically appear in a tooltip. + * \param memberVariable - reference to the member variable so we can bind to serialization data. + */ + template + ClassBuilder* GroupElementToggle(const char* description, T memberVariable); + + /** * Declare element with an associated UI handler that does not represent a specific class member variable. * \param uiId - name of a UI handler used to display the element @@ -515,6 +526,15 @@ namespace AZ return this; } + //========================================================================= + // ClassElement + //========================================================================= + template + inline EditContext::ClassBuilder* EditContext::ClassBuilder::GroupElementToggle(const char* name, T memberVariable) + { + return DataElement(AZ::Edit::ClassElements::Group, memberVariable, name, name, ""); + } + //========================================================================= // UIElement //========================================================================= diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index 667ae49387..e3d2987a3c 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -221,6 +221,7 @@ set(FILES Jobs/Internal/JobManagerWorkStealing.cpp Jobs/Internal/JobManagerWorkStealing.h Jobs/Internal/JobNotify.h + Jobs/Job.cpp Jobs/Job.h Jobs/JobCancelGroup.h Jobs/JobCompletion.h diff --git a/Code/Framework/AzCore/AzCore/std/hash.cpp b/Code/Framework/AzCore/AzCore/std/hash.cpp index c2f7a104d4..b5277de2f4 100644 --- a/Code/Framework/AzCore/AzCore/std/hash.cpp +++ b/Code/Framework/AzCore/AzCore/std/hash.cpp @@ -21,6 +21,7 @@ namespace AZStd 1610612741ul, 3221225473ul, 4294967291ul }; + // Bucket size suitable to hold n elements. AZStd::size_t hash_next_bucket_size(AZStd::size_t n) { const AZStd::size_t* first = prime_list; diff --git a/Code/Framework/AzCore/AzCore/std/hash_table.h b/Code/Framework/AzCore/AzCore/std/hash_table.h index 5b76b6cb82..c364720b3b 100644 --- a/Code/Framework/AzCore/AzCore/std/hash_table.h +++ b/Code/Framework/AzCore/AzCore/std/hash_table.h @@ -134,6 +134,7 @@ namespace AZStd void rehash(HashTable* table, size_type numBucketsMin) { size_type num_buckets = 0; + numBucketsMin = (AZStd::max)(numBucketsMin, (size_type)ceilf((float)m_list.size() / m_max_load_factor)); if (numBucketsMin != 0) @@ -143,7 +144,7 @@ namespace AZStd if (num_buckets == m_numBuckets) { - return; // no point + return; // no need yet to rehash } m_numBuckets = num_buckets; @@ -165,32 +166,43 @@ namespace AZStd while (!m_list.empty()) { cur = m_list.begin(); + typename list_type::iterator insertIter, curEnd(cur); + const typename HashTable::key_type& valueKey = Traits::key_from_value(*cur); - typename list_type::iterator newIter, iter(cur); size_type numValues = 1; - for (++iter; iter != last && table->m_keyEqual(Traits::key_from_value(*cur), Traits::key_from_value(*iter)); ++iter, ++numValues) + // Get the number of same consecutive elements in the table with same key, + // this allows range insertion of elements at once + for (++curEnd; curEnd != last && table->m_keyEqual(valueKey, Traits::key_from_value(*curEnd)); ++curEnd, ++numValues) { } - ; - const typename HashTable::key_type& valueKey = Traits::key_from_value(*cur); size_type newBucketIndex = table->bucket_from_hash(table->m_hasher(valueKey)); + + // newBucket.first holds the total number of elements in the bucket + // newBucket.second contains the pointer to the first element in the bucket vector_value_type& newBucket = newBuckets[newBucketIndex]; size_type numElements = newBucket.first; - newIter = newBucket.second; + insertIter = newBucket.second; + + // If we don't have elements in the bucket yet, transfer the elements directly if (numElements == 0) { - newList.splice(newList.begin(), m_list, cur, iter); + newList.splice(newList.begin(), m_list, cur, curEnd); newBucket.second = newList.begin(); } else { - if (!table->find_insert_position(valueKey, table->m_keyEqual, newIter, numElements, integral_constant())) + // Since there are elements already in the bucket, update `insertIter` to where the elements will need to be inserted. + if (!table->find_insert_position(valueKey, table->m_keyEqual, insertIter, numElements, integral_constant())) { - continue; + // An element was found but we don't allow for duplicate elements in this table. + // This happens when there was an insertion of two elements that are equal but have different hashes, + // which is undefined behavior for a hash table: ISO C++ N4713, section 23.14.15 - 5.3 + AZ_Assert(false, "Found a duplicate element when rehashing. " + "Review the hashing function for this type and make sure two equal elements always have the same hash"); } - newList.splice(newIter, m_list, cur, iter); + newList.splice(insertIter, m_list, cur, curEnd); } newBucket.first += numValues; @@ -251,15 +263,15 @@ namespace AZStd m_vector.set_allocator(typename vector_type::allocator_type(&m_allocator)); } - allocator_type m_allocator; ///< The single instance of the allocator shared between list and vector containers. - list_type m_list; ///< List with elements. - vector_type m_vector; ///< Buckets with list iterators. + allocator_type m_allocator; //!< The single instance of the allocator shared between list and vector containers. + list_type m_list; //!< List with elements. + vector_type m_vector; //!< Buckets with list iterators. private: - vector_value_type* m_buckets; ///< Current buckets array. (can point to the m_vector or m_startBucket). - size_type m_numBuckets; ///< Current number of buckets. - float m_max_load_factor; - vector_value_type m_startBucket; ///< Start bucket used for before we start dynamically allocate memory from m_vector. + vector_value_type* m_buckets; //!< Current buckets array. (can point to the m_vector or m_startBucket). + size_type m_numBuckets; //!< Current number of buckets. + float m_max_load_factor; //!< Maximum load (elements/buckets) before rehashing. + vector_value_type m_startBucket; //!< Start bucket used for before we start dynamically allocate memory from m_vector. }; /** @@ -321,8 +333,8 @@ namespace AZStd template AZ_FORCE_INLINE void rehash(HashTable*, size_type) {} - vector_type m_vector; ///< Buckets with list iterators. - list_type m_list; ///< List with elements. + vector_type m_vector; //!< Buckets with list iterators. + list_type m_list; //!< List with elements. }; } @@ -972,28 +984,32 @@ namespace AZStd rhs.clear(); } + // find_insert_position sets insertIter to where the element should be inserted + // and returns true if the element should be inserted, otherwise false template - bool find_insert_position(const ComparableToKey& keyCmp, const KeyEq& keyEq, iterator& iter, size_type numElements, const true_type& /* is multi elements */) + bool find_insert_position(const ComparableToKey& keyCmp, const KeyEq& keyEq, iterator& insertIter, size_type numElements, const true_type& /* is multi elements */) { - for (size_type i = 0; i < numElements; ++i, ++iter) + for (size_type i = 0; i < numElements; ++i, ++insertIter) { - if (keyEq(keyCmp, Traits::key_from_value(*iter))) + if (keyEq(keyCmp, Traits::key_from_value(*insertIter))) { - ++iter; + ++insertIter; break; } } + // always return true since multi elements (like multiset) allow repeated elements return true; } template - bool find_insert_position(const ComparableToKey& keyCmp, const KeyEq& keyEq, iterator& iter, size_type numElements, const false_type& /* !is multi elements */) + bool find_insert_position(const ComparableToKey& keyCmp, const KeyEq& keyEq, iterator& insertIter, size_type numElements, const false_type& /* !is multi elements */) { - for (size_type i = 0; i < numElements; ++i, ++iter) + for (size_type i = 0; i < numElements; ++i, ++insertIter) { - if (keyEq(keyCmp, Traits::key_from_value(*iter))) + if (keyEq(keyCmp, Traits::key_from_value(*insertIter))) { + // Element already exists, it shouldn't be inserted as we don't allow more than one repeated element for this specialization return false; } } diff --git a/Code/Framework/AzCore/Tests/AZStd/Hashed.cpp b/Code/Framework/AzCore/Tests/AZStd/Hashed.cpp index f2558289ea..4e4dfc1f89 100644 --- a/Code/Framework/AzCore/Tests/AZStd/Hashed.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/Hashed.cpp @@ -287,6 +287,55 @@ namespace UnitTest } } + TEST_F(HashedContainers, HashTable_InsertionDuplicateOnRehash) + { + struct TwoPtrs + { + void* m_ptr1; + void* m_ptr2; + + bool operator==(const TwoPtrs& other) const + { + if (m_ptr1 == other.m_ptr1) + { + return m_ptr2 == other.m_ptr2; + } + else if (m_ptr1 == other.m_ptr2) + { + return m_ptr2 == other.m_ptr1; + } + return false; + } + }; + + // This hashing function produces different hashes for two equal values, + // which violates the requirement for hashing functions. + // The test makes sure that this does not reproduce an issue that caused the insert() function to loop infinitely. + struct TwoPtrsHasher + { + size_t operator()(const TwoPtrs& p) const + { + size_t hash{ 0 }; + AZStd::hash_combine(hash, p.m_ptr1, p.m_ptr2); + return hash; + } + }; + using PairSet = AZStd::unordered_set; + PairSet set; + set.insert({ (void*)1, (void*)2 }); + set.insert({ (void*)3, (void*)4 }); + set.insert({ (void*)5, (void*)6 }); + set.insert({ (void*)7, (void*)8 }); + // Elements with different hashes, but equal + set.insert({ (void*)0x000001ceddd9ca20, (void*)0x000001ceddd9cba0 }); // hash(148335135725641) + set.insert({ (void*)0x000001ceddd9cba0, (void*)0x000001ceddd9ca20 }); // hash(148335135764189) + AZ_TEST_START_TRACE_SUPPRESSION; + // This will trigger the assertion of duplicated elements found + // A bucket size of 23 since is where the collision between different hashes happens + set.rehash(23); + AZ_TEST_STOP_TRACE_SUPPRESSION(1); // 1 assertion + } + TEST_F(HashedContainers, HashTable_Fixed) { array elements = { diff --git a/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp b/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp index 156719b8a7..e25c3dbcf7 100644 --- a/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp +++ b/Code/Framework/AzCore/Tests/Asset/AssetManagerLoadingTests.cpp @@ -1150,7 +1150,7 @@ namespace UnitTest #if AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS TEST_F(AssetJobsFloodTest, DISABLED_ContainerFilterTest_ContainersWithAndWithoutFiltering_Success) #else - TEST_F(AssetJobsFloodTest, ContainerFilterTest_ContainersWithAndWithoutFiltering_Success) + TEST_F(AssetJobsFloodTest, DISABLED_ContainerFilterTest_ContainersWithAndWithoutFiltering_Success) #endif // !AZ_TRAIT_DISABLE_FAILED_ASSET_MANAGER_TESTS { m_assetHandlerAndCatalog->AssetCatalogRequestBus::Handler::BusConnect(); diff --git a/Code/Framework/AzNetworking/AzNetworking/Framework/INetworkInterface.h b/Code/Framework/AzNetworking/AzNetworking/Framework/INetworkInterface.h index d47f76ceb8..09aa62f7d7 100644 --- a/Code/Framework/AzNetworking/AzNetworking/Framework/INetworkInterface.h +++ b/Code/Framework/AzNetworking/AzNetworking/Framework/INetworkInterface.h @@ -103,6 +103,14 @@ namespace AzNetworking //! @return boolean true on success virtual bool Disconnect(ConnectionId connectionId, DisconnectReason reason) = 0; + //! Sets whether this connection interface can disconnect by virtue of a timeout + //! @param timeoutEnabled If this connection interface will automatically disconnect due to a timeout + virtual void SetTimeoutEnabled(bool timeoutEnabled) = 0; + + //! Whether this connection interface will disconnect by virtue of a time out (does not account for cvars affecting all connections) + //! @return boolean true if this connection will not disconnect on timeout (does not account for cvars affecting all connections) + virtual bool IsTimeoutEnabled() const = 0; + //! Const access to the metrics tracked by this network interface. //! @return const reference to the metrics tracked by this network interface const NetworkInterfaceMetrics& GetMetrics() const; diff --git a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.cpp b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.cpp index f9569b5c7e..62335a9b39 100644 --- a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.cpp @@ -174,6 +174,16 @@ namespace AzNetworking return connection->Disconnect(reason, TerminationEndpoint::Local); } + void TcpNetworkInterface::SetTimeoutEnabled(bool timeoutEnabled) + { + m_timeoutEnabled = timeoutEnabled; + } + + bool TcpNetworkInterface::IsTimeoutEnabled() const + { + return m_timeoutEnabled; + } + void TcpNetworkInterface::QueueNewConnection(const PendingConnection& pendingConnection) { m_pendingConnections.PushBackItem(pendingConnection); @@ -306,7 +316,7 @@ namespace AzNetworking { tcpConnection->SendReliablePacket(CorePackets::HeartbeatPacket()); } - else if (net_TcpTimeoutConnections) + else if (net_TcpTimeoutConnections && m_networkInterface.IsTimeoutEnabled()) { tcpConnection->Disconnect(DisconnectReason::Timeout, TerminationEndpoint::Local); return TimeoutResult::Delete; diff --git a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.h b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.h index 1d590da2aa..b9ea88974d 100644 --- a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.h +++ b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.h @@ -99,6 +99,8 @@ namespace AzNetworking bool WasPacketAcked(ConnectionId connectionId, PacketId packetId) override; bool StopListening() override; bool Disconnect(ConnectionId connectionId, DisconnectReason reason) override; + void SetTimeoutEnabled(bool timeoutEnabled) override; + bool IsTimeoutEnabled() const override; //! @} //! Queues a new incoming connection for this network interface. @@ -154,6 +156,7 @@ namespace AzNetworking AZ::Name m_name; TrustZone m_trustZone; uint16_t m_port = 0; + bool m_timeoutEnabled = true; IConnectionListener& m_connectionListener; TcpConnectionSet m_connectionSet; TcpSocketManager m_tcpSocketManager; diff --git a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.cpp b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.cpp index a3ddb856d2..48b3ad57e1 100644 --- a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.cpp @@ -397,6 +397,16 @@ namespace AzNetworking return connection->Disconnect(reason, TerminationEndpoint::Local); } + void UdpNetworkInterface::SetTimeoutEnabled(bool timeoutEnabled) + { + m_timeoutEnabled = timeoutEnabled; + } + + bool UdpNetworkInterface::IsTimeoutEnabled() const + { + return m_timeoutEnabled; + } + bool UdpNetworkInterface::IsEncrypted() const { return m_socket->IsEncrypted(); @@ -729,7 +739,7 @@ namespace AzNetworking { udpConnection->SendUnreliablePacket(CorePackets::HeartbeatPacket()); } - else if (net_UdpTimeoutConnections) + else if (net_UdpTimeoutConnections && m_networkInterface.IsTimeoutEnabled()) { udpConnection->Disconnect(DisconnectReason::Timeout, TerminationEndpoint::Local); return TimeoutResult::Delete; diff --git a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.h b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.h index 7a391c152e..949914da91 100644 --- a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.h +++ b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.h @@ -104,6 +104,8 @@ namespace AzNetworking bool WasPacketAcked(ConnectionId connectionId, PacketId packetId) override; bool StopListening() override; bool Disconnect(ConnectionId connectionId, DisconnectReason reason) override; + void SetTimeoutEnabled(bool timeoutEnabled) override; + bool IsTimeoutEnabled() const override; //! @} //! Returns true if this is an encrypted socket, false if not. @@ -179,6 +181,7 @@ namespace AzNetworking TrustZone m_trustZone; uint16_t m_port = 0; bool m_allowIncomingConnections = false; + bool m_timeoutEnabled = true; IConnectionListener& m_connectionListener; UdpConnectionSet m_connectionSet; TimeoutQueue m_connectionTimeoutQueue; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp index 39faf06f08..2e697a7398 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.cpp @@ -546,7 +546,7 @@ namespace AzToolsFramework for (auto& element : nodeEditData->m_elements) { - if (element.IsClassElement() && element.m_elementId == AZ::Edit::ClassElements::Group) + if (element.m_elementId == AZ::Edit::ClassElements::Group) { groupData = (element.m_description && element.m_description[0]) ? &element : nullptr; continue; @@ -1112,13 +1112,14 @@ namespace AzToolsFramework const AZ::Edit::ElementData* groupData = nullptr; for (const AZ::Edit::ElementData& elementData : parentEditData->m_elements) { - if (node->m_elementEditData == &elementData) // this element matches this node + // this element matches this node + if ((node->m_elementEditData == &elementData) && (elementData.m_elementId != AZ::Edit::ClassElements::Group)) { // Record the last found group data node->m_groupElementData = groupData; break; } - else if (elementData.IsClassElement() && elementData.m_elementId == AZ::Edit::ClassElements::Group) + else if (elementData.m_elementId == AZ::Edit::ClassElements::Group) { if (!elementData.m_description || !elementData.m_description[0]) { // close the group diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp index b9578d4e3a..5ea36bb30e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.cpp @@ -12,6 +12,7 @@ #include #include +#include AZ_PUSH_DISABLE_WARNING(4244 4251 4800, "-Wunknown-warning-option") // 4244: conversion from 'int' to 'float', possible loss of data // 4251: class '...' needs to have dll-interface to be used by clients of class 'QInputEvent' @@ -141,6 +142,11 @@ namespace AzToolsFramework m_treeDepth = 0; delete m_dropDownArrow; + if (m_toggleSwitch != nullptr) + { + m_handler->DestroyGUI(m_toggleSwitch); + m_toggleSwitch = nullptr; + } if (m_childWidget) { @@ -387,6 +393,13 @@ namespace AzToolsFramework setUpdatesEnabled(true); } + void PropertyRowWidget::InitializeToggleGroup(const char* groupName, PropertyRowWidget* pParent, int depth, InstanceDataNode* node, int labelWidth) + { + Initialize(groupName, pParent, depth, labelWidth); + ChangeSourceNode(node); + CreateGroupToggleSwitch(); + } + void PropertyRowWidget::Initialize(const char* groupName, PropertyRowWidget* pParent, int depth, int labelWidth) { Initialize(pParent, nullptr, depth, labelWidth); @@ -1102,6 +1115,19 @@ namespace AzToolsFramework } } + void PropertyRowWidget::CreateGroupToggleSwitch() + { + if (m_toggleSwitch == nullptr) + { + m_handlerName = AZ::Edit::UIHandlers::CheckBox; + PropertyTypeRegistrationMessages::Bus::BroadcastResult(m_handler, &PropertyTypeRegistrationMessages::Bus::Events::ResolvePropertyHandler, m_handlerName, azrtti_typeid()); + m_toggleSwitch = m_handler->CreateGUI(this); + m_middleLayout->insertWidget(0, m_toggleSwitch, 1); + auto checkBoxCtrl = static_cast(m_toggleSwitch); + QObject::connect(checkBoxCtrl, &AzToolsFramework::PropertyCheckBoxCtrl::valueChanged, this, &PropertyRowWidget::OnClickedToggleButton); + } + } + void PropertyRowWidget::SetIndentSize(int w) { m_indent->changeSize(w, 1, QSizePolicy::Fixed, QSizePolicy::Fixed); @@ -1110,6 +1136,18 @@ namespace AzToolsFramework m_leftHandSideLayout->activate(); } + void PropertyRowWidget::OnClickedToggleButton(bool checked) + { + if (m_expanded != checked) + { + DoExpandOrContract(!IsExpanded(), 0 != (QGuiApplication::keyboardModifiers() & Qt::ControlModifier)); + } + } + + void PropertyRowWidget::ChangeSourceNode(InstanceDataNode* node) + { + m_sourceNode = node; + } void PropertyRowWidget::SetExpanded(bool expanded) { diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx index 8248eb4b86..ebf7c67b21 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/PropertyRowWidget.hxx @@ -50,6 +50,7 @@ namespace AzToolsFramework virtual void Initialize(PropertyRowWidget* pParent, InstanceDataNode* dataNode, int depth, int labelWidth = 200); virtual void Initialize(const char* groupName, PropertyRowWidget* pParent, int depth, int labelWidth = 200); + virtual void InitializeToggleGroup(const char* groupName, PropertyRowWidget* pParent, int depth, InstanceDataNode* node, int labelWidth = 200); virtual void Clear(); // for pooling // --- NOT A UNIQUE IDENTIFIER --- @@ -143,11 +144,14 @@ namespace AzToolsFramework QVBoxLayout* GetLeftHandSideLayoutParent() { return m_leftHandSideLayoutParent; } QToolButton* GetIndicatorButton() { return m_indicatorButton; } QLabel* GetNameLabel() { return m_nameLabel; } + QWidget* GetToggle() { return m_toggleSwitch; } + const QWidget* GetToggle() const { return m_toggleSwitch; } void SetIndentSize(int w); void SetAsCustom(bool custom) { m_custom = custom; } bool CanChildrenBeReordered() const; bool CanBeReordered() const; + protected: int CalculateLabelWidth() const; @@ -177,6 +181,8 @@ namespace AzToolsFramework QLabel* m_defaultLabel; // if there is no handler, we use a m_defaultLabel label InstanceDataNode* m_sourceNode; + QWidget* m_toggleSwitch = nullptr; + QString m_currentFilterString; struct ChangeNotification @@ -241,6 +247,8 @@ namespace AzToolsFramework void mouseDoubleClickEvent(QMouseEvent* event) override; void UpdateDropDownArrow(); + void CreateGroupToggleSwitch(); + void ChangeSourceNode(InstanceDataNode* node); void UpdateDefaultLabel(InstanceDataNode* node); void createContainerButtons(); @@ -259,6 +267,7 @@ namespace AzToolsFramework private slots: void OnClickedExpansionButton(); + void OnClickedToggleButton(bool checked); void OnClickedAddElementButton(); void OnClickedRemoveElementButton(); void OnClickedClearContainerButton(); diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp index ae3bcd6849..36462bca66 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.cpp @@ -169,6 +169,8 @@ namespace AzToolsFramework InstanceDataHierarchyList m_instances; ///< List of instance sets to display, other one can aggregate other instances. InstanceDataHierarchy::ValueComparisonFunction m_valueComparisonFunction; ReflectedPropertyEditor::WidgetList m_widgets; + ReflectedPropertyEditor::WidgetList m_specialGroupWidgets; + InstanceDataNode* groupSourceNode = nullptr; RowContainerType m_widgetsInDisplayOrder; UserWidgetToDataMap m_userWidgetsToData; VisibilityCallback m_visibilityCallback; @@ -501,6 +503,7 @@ namespace AzToolsFramework // if the node is in a group then create the widget for the group if (groupElementData) { + bool isToggleGroup = false; const char* groupName = groupElementData->m_description; PropertyRowWidget*& widgetEntry = m_groupWidgets[{parent, groupName}]; @@ -509,14 +512,34 @@ namespace AzToolsFramework { widgetEntry = CreateOrPullFromPool(); widgetEntry->SetFilterString(m_editor->GetFilterString()); - widgetEntry->Initialize(groupName, parent, depth, m_propertyLabelWidth); + + // Initialized normally if the group does not have a member variable attached to it, + // otherwise initialize it as a group that will have a toggle switch. + if (groupElementData->IsClassElement()) + { + widgetEntry->Initialize(groupName, parent, depth, m_propertyLabelWidth); + } + else + { + widgetEntry->InitializeToggleGroup(groupName, parent, depth, groupSourceNode, m_propertyLabelWidth); + QWidget* toggleSwitch = widgetEntry->GetToggle(); + PropertyHandlerBase* pHandler = widgetEntry->GetHandler(); + m_userWidgetsToData[toggleSwitch] = groupSourceNode; + m_specialGroupWidgets[groupSourceNode] = widgetEntry; + pHandler->ConsumeAttributes_Internal(toggleSwitch, groupSourceNode); + pHandler->ReadValuesIntoGUI_Internal(toggleSwitch, groupSourceNode); + widgetEntry->OnValuesUpdated(); + isToggleGroup = true; + } + widgetEntry->SetLeafIndentation(m_leafIndentation); widgetEntry->SetTreeIndentation(m_treeIndentation); widgetEntry->setObjectName(groupName); for (const AZ::Edit::AttributePair& attribute : groupElementData->m_attributes) { - PropertyAttributeReader reader(node->GetParent()->FirstInstance(), attribute.second); + InstanceDataNode* readerNode = (isToggleGroup) ? groupSourceNode : node; + PropertyAttributeReader reader(readerNode->GetParent()->FirstInstance(), attribute.second); QString descriptionOut; bool foundDescription = false; widgetEntry->ConsumeAttribute(attribute.first, reader, true, &descriptionOut, &foundDescription); @@ -608,7 +631,7 @@ namespace AzToolsFramework // creates and populates the GUI to edit the property if not already created void ReflectedPropertyEditor::Impl::CreateEditorWidget(PropertyRowWidget* pWidget) { - if (!pWidget->HasChildWidgetAlready()) + if (!pWidget->HasChildWidgetAlready() && !pWidget->GetToggle()) { PropertyHandlerBase* pHandler = pWidget->GetHandler(); if (pHandler) @@ -735,36 +758,44 @@ namespace AzToolsFramework } } } - - pWidget = CreateOrPullFromPool(); - pWidget->show(); - - pWidget->SetFilterString(m_editor->GetFilterString()); - pWidget->Initialize(pParent, node, depth, m_propertyLabelWidth); - - if (labelOverride != "") + if (!node->GetElementEditMetadata() || (node->GetElementEditMetadata()->m_elementId != AZ::Edit::ClassElements::Group)) { - pWidget->SetNameLabel(labelOverride.data()); + pWidget = CreateOrPullFromPool(); + pWidget->show(); + + pWidget->SetFilterString(m_editor->GetFilterString()); + pWidget->Initialize(pParent, node, depth, m_propertyLabelWidth); + + if (labelOverride != "") + { + pWidget->SetNameLabel(labelOverride.data()); + } + + pWidget->setObjectName(pWidget->label()); + pWidget->SetSelectionEnabled(m_selectionEnabled); + pWidget->SetLeafIndentation(m_leafIndentation); + pWidget->SetTreeIndentation(m_treeIndentation); + + m_widgets[node] = pWidget; + m_widgetsInDisplayOrder.insert(widgetDisplayOrder, pWidget); + + if (pParent) + { + pParent->AddedChild(pWidget); + } + + if (pParent || !m_hideRootProperties) + { + depth += 1; + } + pParent = pWidget; } - pWidget->setObjectName(pWidget->label()); - pWidget->SetSelectionEnabled(m_selectionEnabled); - pWidget->SetLeafIndentation(m_leafIndentation); - pWidget->SetTreeIndentation(m_treeIndentation); - - m_widgets[node] = pWidget; - m_widgetsInDisplayOrder.insert(widgetDisplayOrder, pWidget); - - if (pParent) + // Save the last InstanceDataNode that is a Group ClassElement so that we can use it as the source node for its widget. + if (node->GetElementEditMetadata() && (node->GetElementEditMetadata()->m_elementId == AZ::Edit::ClassElements::Group)) { - pParent->AddedChild(pWidget); + groupSourceNode = node; } - - if (pParent || !m_hideRootProperties) - { - depth += 1; - } - pParent = pWidget; } } @@ -1356,9 +1387,13 @@ namespace AzToolsFramework return; } - // get the property editor + // Get the property editor from either the widget map or the special toggle group widgets auto rowWidget = m_widgets.find(it->second); - if (rowWidget != m_widgets.end()) + if (rowWidget == m_widgets.end()) + { + rowWidget = m_specialGroupWidgets.find(it->second); + } + if (rowWidget != m_widgets.end() || rowWidget != m_specialGroupWidgets.end()) { InstanceDataNode* node = rowWidget->first; PropertyRowWidget* widget = rowWidget->second; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx index b95c2b927a..b10e153162 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/PropertyEditor/ReflectedPropertyEditor.hxx @@ -51,6 +51,8 @@ namespace AzToolsFramework typedef AZStd::unordered_map WidgetList; + ReflectedPropertyEditor::WidgetList m_specialGroupWidgets; + ReflectedPropertyEditor(QWidget* pParent); virtual ~ReflectedPropertyEditor(); @@ -62,6 +64,7 @@ namespace AzToolsFramework bool AddInstance(void* instance, const AZ::Uuid& classId, void* aggregateInstance = nullptr, void* compareInstance = nullptr); void SetCompareInstance(void* instance, const AZ::Uuid& classId); void ClearInstances(); + void ReadValuesIntoGui(QWidget* widget, InstanceDataNode* node); template bool AddInstance(T* instance, void* aggregateInstance = nullptr, void* compareInstance = nullptr) { diff --git a/Code/Framework/AzToolsFramework/Tests/InstanceDataHierarchy.cpp b/Code/Framework/AzToolsFramework/Tests/InstanceDataHierarchy.cpp index 61b512abb6..1b11479bff 100644 --- a/Code/Framework/AzToolsFramework/Tests/InstanceDataHierarchy.cpp +++ b/Code/Framework/AzToolsFramework/Tests/InstanceDataHierarchy.cpp @@ -21,6 +21,7 @@ #include #include #include +#include using namespace AZ; @@ -727,6 +728,153 @@ namespace UnitTest }; + class GroupTestComponent : public AZ::Component + { + public: + AZ_COMPONENT(GroupTestComponent, "{C088C81D-D59D-43F1-85F8-B2E591BABA36}") + + GroupTestComponent() = default; + + struct SubData + { + AZ_TYPE_INFO(SubData, "{983316B5-17C0-476E-9CEB-CA749B3ABE5D}"); + AZ_CLASS_ALLOCATOR(SubData, AZ::SystemAllocator, 0); + + SubData() {} + explicit SubData(int v) : m_int(v) {} + explicit SubData(bool b) : m_bool(b) {} + explicit SubData(float f) : m_float(f) {} + ~SubData() = default; + + float m_float = 0.f; + int m_int = 0; + bool m_bool = true; + }; + + static void Reflect(AZ::ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("SubInt", &SubData::m_int) + ->Field("SubToggle", &SubData::m_bool) + ->Field("SubFloat", &SubData::m_float) + ; + + serializeContext->Class() + ->Version(1) + ->Field("Float", &GroupTestComponent::m_float) + ->Field("GroupToggle", &GroupTestComponent::m_groupToggle) + ->Field("GroupFloat", &GroupTestComponent::m_groupFloat) + ->Field("ToggleGroupInt", &GroupTestComponent::m_toggleGroupInt) + ->Field("SubDataNormal", &GroupTestComponent::m_subGroupForNormal) + ->Field("SubDataToggle", &GroupTestComponent::m_subGroupForToggle) + ; + + if (AZ::EditContext* edit = serializeContext->GetEditContext()) + { + edit->Class("Group Test Component", "Testing normal groups and toggle groups") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->DataElement(0, &GroupTestComponent::m_float, "Float Field", "A float field") + ->ClassElement(AZ::Edit::ClassElements::Group, "Normal Group") + ->DataElement(0, &GroupTestComponent::m_groupFloat, "Float Field", "A float field") + ->DataElement(0, &GroupTestComponent::m_subGroupForNormal, "Struct Field", "A sub data type") + ->GroupElementToggle("Group Toggle", &GroupTestComponent::m_groupToggle) + ->DataElement(0, &GroupTestComponent::m_toggleGroupInt, "Normal Integer", "An Integer") + ->DataElement(0, &GroupTestComponent::m_subGroupForToggle, "Struct Field", "A sub data type") + ; + + edit->Class("SubGroup Test Component", "Testing nested normal groups and toggle groups") + ->ClassElement(AZ::Edit::ClassElements::EditorData, "") + ->ClassElement(AZ::Edit::ClassElements::Group, "Normal SubGroup") + ->DataElement(0, &SubData::m_int, "SubGroup Int Field", "An int") + ->GroupElementToggle("SubGroup Toggle", &SubData::m_bool) + ->DataElement(0, &SubData::m_float, "SubGroup Float Field", "An int") + ; + } + } + } + + void Activate() override + { + } + + void Deactivate() override + { + } + + float m_float = 0.f; + float m_groupFloat = 0.f; + int m_toggleGroupInt = 0; + AZStd::string m_string; + bool m_groupToggle = false; + + SubData m_subGroupForNormal; + SubData m_subGroupForToggle; + }; + + class InstanceDataHierarchyGroupTestFixture : public AllocatorsFixture + { + public: + InstanceDataHierarchyGroupTestFixture() = default; + + AZStd::unique_ptr m_serializeContext; + AZStd::unique_ptr testEntity1; + AzToolsFramework::InstanceDataHierarchy* instanceDataHierarchy; + AzToolsFramework::InstanceDataNode* componentNode1 = nullptr; + + void SetUp() override + { + AllocatorsFixture::SetUp(); + + using AzToolsFramework::InstanceDataHierarchy; + using AzToolsFramework::InstanceDataNode; + + AZ::AllocatorInstance::Create(); + + m_serializeContext.reset(aznew AZ::SerializeContext()); + m_serializeContext.get()->CreateEditContext(); + Entity::Reflect(m_serializeContext.get()); + GroupTestComponent::Reflect(m_serializeContext.get()); + + testEntity1.reset(new AZ::Entity()); + testEntity1->CreateComponent(); + + instanceDataHierarchy = aznew InstanceDataHierarchy(); + instanceDataHierarchy->AddRootInstance(testEntity1.get()); + instanceDataHierarchy->Build(m_serializeContext.get(), 0); + + // Adding the nodes to a node stack + auto rootNode = instanceDataHierarchy->GetRootNode(); + AZStd::stack nodeStack; + nodeStack.push(rootNode); + while (!nodeStack.empty()) + { + InstanceDataNode* node = nodeStack.top(); + nodeStack.pop(); + if (node->GetClassMetadata()->m_typeId == AZ::AzTypeInfo::Uuid()) + { + componentNode1 = node; + break; + } + for (InstanceDataNode& child : node->GetChildren()) + { + nodeStack.push(&child); + } + } + } + + void TearDown() override + { + m_serializeContext.reset(); + testEntity1.reset(); + delete instanceDataHierarchy; + AZ::AllocatorInstance::Destroy(); + AllocatorsFixture::TearDown(); + } + }; + class InstanceDataHierarchyKeyedContainerTest : public AllocatorsFixture { @@ -1315,4 +1463,108 @@ namespace UnitTest run(); } + // Test to validate that the only ClassElement::Group nodes are ToggleGroups + TEST_F(InstanceDataHierarchyGroupTestFixture, GroupToggleIsClassElementGroup) + { + using AzToolsFramework::InstanceDataHierarchy; + using AzToolsFramework::InstanceDataNode; + + for (auto child : componentNode1->GetChildren()) + { + AZStd::string childName(child.GetElementMetadata()->m_name); + if (childName.compare("GroupToggle") == 0) + { + EXPECT_EQ(child.GetElementEditMetadata()->m_elementId, AZ::Edit::ClassElements::Group); + } + if ((childName.compare("SubDataNormal") == 0) || (childName.compare("SubDataToggle") == 0)) + { + for (auto subChild : child.GetChildren()) + { + childName = subChild.GetElementMetadata()->m_name; + if (childName.compare("SubToggle") == 0) + { + EXPECT_EQ(subChild.GetElementEditMetadata()->m_elementId, AZ::Edit::ClassElements::Group); + } + else + { + EXPECT_NE(subChild.GetElementEditMetadata()->m_elementId, AZ::Edit::ClassElements::Group); + } + } + } + } + } + + // Test to ensure that each node has been assigned under the proper group and the group hierarchy is structured correctly + TEST_F(InstanceDataHierarchyGroupTestFixture, ValidatingGroupAndSubGroupHierarchy) + { + using AzToolsFramework::InstanceDataHierarchy; + using AzToolsFramework::InstanceDataNode; + + for (auto child : componentNode1->GetChildren()) + { + AZStd::string childName(child.GetElementMetadata()->m_name); + if (childName.compare("GroupFloat") == 0) + { + EXPECT_EQ(child.GetGroupElementMetadata()->m_description, "Normal Group"); + } + if (childName.compare("ToggleGroupInt") == 0) + { + EXPECT_EQ(child.GetGroupElementMetadata()->m_description, "Group Toggle"); + } + if ((childName.compare("SubDataNormal") == 0) || (childName.compare("SubDataToggle") == 0)) + { + for (auto subChild : child.GetChildren()) + { + childName = subChild.GetElementMetadata()->m_name; + if (childName.compare("SubInt") == 0) + { + EXPECT_EQ(subChild.GetGroupElementMetadata()->m_description, "Normal SubGroup"); + } + if (childName.compare("SubFloat") == 0) + { + EXPECT_EQ(subChild.GetGroupElementMetadata()->m_description, "SubGroup Toggle"); + } + } + } + } + } + + class InstanceDataHierarchyGroupTestFixtureParameterized + : public InstanceDataHierarchyGroupTestFixture + , public ::testing::WithParamInterface + { + }; + + INSTANTIATE_TEST_CASE_P( + InstanceDataHierarchyGroupTestFixture, + InstanceDataHierarchyGroupTestFixtureParameterized, + ::testing::Values("GroupFloat", "GroupToggle", "ToggleGroupInt", "SubInt", "SubToggle", "SubFloat")); + + // Test to validate that each node in a group and Subgroup has the correct parent + TEST_P(InstanceDataHierarchyGroupTestFixtureParameterized, ValidatingGroupAndSubGroupParents) + { + using AzToolsFramework::InstanceDataHierarchy; + using AzToolsFramework::InstanceDataNode; + + const char* paramName = GetParam(); + for (auto child : componentNode1->GetChildren()) + { + AZStd::string childName(child.GetElementMetadata()->m_name); + if (childName.compare(paramName) == 0) + { + EXPECT_EQ(child.GetParent()->GetClassMetadata()->m_name, "GroupTestComponent"); + } + if ((childName.compare("SubDataNormal") == 0) || (childName.compare("SubDataToggle") == 0)) + { + for (auto subChild : child.GetChildren()) + { + childName = subChild.GetElementMetadata()->m_name; + if (childName.compare(paramName) == 0) + { + EXPECT_EQ(subChild.GetParent()->GetClassMetadata()->m_name, "SubData"); + } + } + } + } + } } // namespace UnitTest diff --git a/Code/Framework/CMakeLists.txt b/Code/Framework/CMakeLists.txt index 45ccb22b14..61f65de5a4 100644 --- a/Code/Framework/CMakeLists.txt +++ b/Code/Framework/CMakeLists.txt @@ -6,7 +6,6 @@ # # -add_subdirectory(AzAutoGen) add_subdirectory(AtomCore) add_subdirectory(AzCore) add_subdirectory(AzQtComponents) diff --git a/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.cpp b/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.cpp index 21089ef020..3a7bc6ef3e 100644 --- a/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.cpp +++ b/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.cpp @@ -3072,6 +3072,7 @@ namespace AssetProcessor QElapsedTimer elapsedTimer; elapsedTimer.start(); + for (auto jobIter = m_jobsToProcess.begin(); jobIter != m_jobsToProcess.end();) { JobDetails& job = *jobIter; @@ -3082,7 +3083,7 @@ namespace AssetProcessor jobIter = m_jobsToProcess.erase(jobIter); m_numOfJobsToAnalyze--; - // Update the remaining job status occasionally + // Update the remaining job status occasionally if (elapsedTimer.elapsed() >= MILLISECONDS_BETWEEN_PROCESS_JOBS_STATUS_UPDATE) { Q_EMIT NumRemainingJobsChanged(m_activeFiles.size() + m_filesToExamine.size() + m_numOfJobsToAnalyze); @@ -3102,7 +3103,8 @@ namespace AssetProcessor // Process the first job if no jobs were analyzed. auto jobIter = m_jobsToProcess.begin(); JobDetails& job = *jobIter; - AZ_Warning(AssetProcessor::DebugChannel, false, " Cyclic job dependency detected. Processing job (%s, %s, %s, %s) to unblock.", + AZ_Warning( + AssetProcessor::DebugChannel, false, " Cyclic job dependency detected. Processing job (%s, %s, %s, %s) to unblock.", job.m_jobEntry.m_databaseSourceName.toUtf8().data(), job.m_jobEntry.m_jobKey.toUtf8().data(), job.m_jobEntry.m_platformInfo.m_identifier.c_str(), job.m_jobEntry.m_builderGuid.ToString().c_str()); ProcessJob(job); diff --git a/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.h b/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.h index 5fc7a73035..376af5d773 100644 --- a/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.h +++ b/Code/Tools/AssetProcessor/native/AssetManager/assetProcessorManager.h @@ -207,6 +207,11 @@ namespace AssetProcessor //! or a job dependency and we can only resolve these dependencies once all the create jobs are completed. struct JobToProcessEntry { + bool operator<(const JobToProcessEntry& other) + { + return m_sourceFileInfo.m_pathRelativeToScanFolder < other.m_sourceFileInfo.m_pathRelativeToScanFolder; + } + SourceFileInfo m_sourceFileInfo; AZStd::vector m_jobsToAnalyze; // a vector of pairs of diff --git a/Code/Tools/AssetProcessor/native/assetprocessor.h b/Code/Tools/AssetProcessor/native/assetprocessor.h index 2397f3b1ff..1c13eca200 100644 --- a/Code/Tools/AssetProcessor/native/assetprocessor.h +++ b/Code/Tools/AssetProcessor/native/assetprocessor.h @@ -244,6 +244,11 @@ namespace AssetProcessor m_jobEntry.m_builderGuid == rhs.m_jobEntry.m_builderGuid); } + static bool DatabaseSourceLexCompare(const JobDetails& left, const JobDetails& right) + { + return left.m_jobEntry.m_databaseSourceName <= right.m_jobEntry.m_databaseSourceName; + } + JobDetails() = default; }; diff --git a/Code/Tools/AssetProcessor/native/resourcecompiler/RCQueueSortModel.cpp b/Code/Tools/AssetProcessor/native/resourcecompiler/RCQueueSortModel.cpp index c39a0c66e9..774876234d 100644 --- a/Code/Tools/AssetProcessor/native/resourcecompiler/RCQueueSortModel.cpp +++ b/Code/Tools/AssetProcessor/native/resourcecompiler/RCQueueSortModel.cpp @@ -197,10 +197,20 @@ namespace AssetProcessor { return priorityLeft > priorityRight; } + + // Optionally stabilize queue order on the source name. + // This is used in automated tests, to allow tests to have a stable + // order that jobs with otherwise equal priority run, so tests process + // assets in the same order each time they are run. + if (m_sortQueueOnDBSourceName) + { + return leftJob->GetJobEntry().m_databaseSourceName < rightJob->GetJobEntry().m_databaseSourceName; + } // if we get all the way down here it means we're dealing with two assets which are not // in any compile groups, not a priority platform, not a priority type, priority platform, etc. // we can arrange these any way we want, but must pick at least a stable order. + return leftJob->GetJobEntry().m_jobRunKey < rightJob->GetJobEntry().m_jobRunKey; } diff --git a/Code/Tools/AssetProcessor/native/resourcecompiler/RCQueueSortModel.h b/Code/Tools/AssetProcessor/native/resourcecompiler/RCQueueSortModel.h index fbeacd8b8c..7fc60fdd60 100644 --- a/Code/Tools/AssetProcessor/native/resourcecompiler/RCQueueSortModel.h +++ b/Code/Tools/AssetProcessor/native/resourcecompiler/RCQueueSortModel.h @@ -50,6 +50,10 @@ namespace AssetProcessor void AddJobIdEntry(AssetProcessor::RCJob* rcJob); void RemoveJobIdEntry(AssetProcessor::RCJob* rcJob); + void SetQueueSortOnDBSourceName() + { + m_sortQueueOnDBSourceName = true; + } // implement QSortFilteRProxyModel: bool filterAcceptsRow(int source_row, const QModelIndex& source_parent) const override; @@ -68,6 +72,11 @@ namespace AssetProcessor QSet m_currentlyConnectedPlatforms; bool m_dirtyNeedsResort = false; // instead of constantly resorting, we resort only when someone wants to pull an element from us + // By default, jobs with equal priority and escalation sort on the job run key. This flag changes + // jobs to sort on the database source name. This is used for testing, to guarantee jobs run in the same + // order for those tests each time they are run. + bool m_sortQueueOnDBSourceName = false; + // --------------------------------------------------------- // AssetProcessorPlatformBus::Handler void AssetProcessorPlatformConnected(const AZStd::string platform) override; diff --git a/Code/Tools/AssetProcessor/native/resourcecompiler/rccontroller.cpp b/Code/Tools/AssetProcessor/native/resourcecompiler/rccontroller.cpp index 11ef68de29..660144095b 100644 --- a/Code/Tools/AssetProcessor/native/resourcecompiler/rccontroller.cpp +++ b/Code/Tools/AssetProcessor/native/resourcecompiler/rccontroller.cpp @@ -163,6 +163,11 @@ namespace AssetProcessor return ((!m_RCQueueSortModel.GetNextPendingJob()) && (m_RCJobListModel.jobsInFlight() == 0)); } + void RCController::SetQueueSortOnDBSourceName() + { + m_RCQueueSortModel.SetQueueSortOnDBSourceName(); + } + void RCController::JobSubmitted(JobDetails details) { AssetProcessor::QueueElementID checkFile(details.m_jobEntry.m_databaseSourceName, details.m_jobEntry.m_platformInfo.m_identifier.c_str(), details.m_jobEntry.m_jobKey); diff --git a/Code/Tools/AssetProcessor/native/resourcecompiler/rccontroller.h b/Code/Tools/AssetProcessor/native/resourcecompiler/rccontroller.h index c555c7a585..51ae6b4a26 100644 --- a/Code/Tools/AssetProcessor/native/resourcecompiler/rccontroller.h +++ b/Code/Tools/AssetProcessor/native/resourcecompiler/rccontroller.h @@ -54,10 +54,11 @@ namespace AssetProcessor void StartJob(AssetProcessor::RCJob* rcJob); int NumberOfPendingCriticalJobsPerPlatform(QString platform); - void SetSystemRoot(const QDir& systemRoot); int NumberOfPendingJobsPerPlatform(QString platform); bool IsIdle(); - bool IsPriorityCopyJob(AssetProcessor::RCJob* rcJob); + + void SetQueueSortOnDBSourceName(); + Q_SIGNALS: void FileCompiled(JobEntry entry, AssetBuilderSDK::ProcessJobResponse response); void FileFailed(JobEntry entry); diff --git a/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.cpp b/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.cpp index 5e2de8e4cd..b90364e1c5 100644 --- a/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.cpp +++ b/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.cpp @@ -49,8 +49,6 @@ static const qint64 s_ReservedDiskSpaceInBytes = 256 * 1024; //! Maximum number of temp folders allowed static const int s_MaximumTempFolders = 10000; -const char AdditionalScanFolders[] = "additionalScanFolders"; - ApplicationManagerBase::ApplicationManagerBase(int* argc, char*** argv, QObject* parent) : ApplicationManager(argc, argv, parent) { @@ -155,55 +153,90 @@ void ApplicationManagerBase::InitAssetProcessorManager() const AzFramework::CommandLine* commandLine = nullptr; AzFramework::ApplicationRequests::Bus::BroadcastResult(commandLine, &AzFramework::ApplicationRequests::GetCommandLine); - if(commandLine->HasSwitch("zeroAnalysisMode")) + struct APCommandLineSwitch + { + APCommandLineSwitch(const char* switchTitle, const char* helpText) + : m_switch(switchTitle) + , m_helpText(helpText) + { + + } + const char* m_switch; + const char* m_helpText; + }; + + const APCommandLineSwitch Command_waitOnLaunch("waitOnLaunch", "Briefly pauses Asset Processor during initializiation. Useful if you want to attach a debugger."); + const APCommandLineSwitch Command_zeroAnalysisMode("zeroAnalysisMode", "Enables using file modification time when examining source assets for processing."); + const APCommandLineSwitch Command_enableQueryLogging("enableQueryLogging", "Enables logging database queries."); + const APCommandLineSwitch Command_dependencyScanPattern("dependencyScanPattern", "Scans assets that match the given pattern for missing product dependencies."); + const APCommandLineSwitch Command_dsp("dsp", Command_dependencyScanPattern.m_helpText); + const APCommandLineSwitch Command_fileDependencyScanPattern("fileDependencyScanPattern", "Used with dependencyScanPattern to farther filter the scan."); + const APCommandLineSwitch Command_fdsp("fdsp", Command_fileDependencyScanPattern.m_helpText); + const APCommandLineSwitch Command_additionalScanFolders("additionalScanFolders", "Used with dependencyScanPattern to farther filter the scan."); + const APCommandLineSwitch Command_dependencyScanMaxIteration("dependencyScanMaxIteration", "Used to limit the number of recursive searches per line when running dependencyScanPattern."); + const APCommandLineSwitch Command_warningLevel("warningLevel", "Configure the error and warning reporting level for AssetProcessor. Pass in 1 for fatal errors, 2 for fatal errors and warnings."); + const APCommandLineSwitch Command_acceptInput("acceptInput", "Enable external control messaging via the ControlRequestHandler, used with automated tests."); + const APCommandLineSwitch Command_debugOutput("debugOutput", "When enabled, builders that support it will output debug information as product assets. Used primarily with scene files."); + const APCommandLineSwitch Command_sortJobsByDBSourceName("sortJobsByDBSourceName", "When enabled, sorts pending jobs with equal priority and dependencies by database source name instead of job ID. Useful for automated tests to process assets in the same order each time."); + const APCommandLineSwitch Command_truncatefingerprint("truncatefingerprint", "Truncates the fingerprint used for processed assets. Useful if you plan to compress product assets to share on another machine because some compression formats like zip will truncate file mod timestamps."); + const APCommandLineSwitch Command_help("help", "Displays this message."); + const APCommandLineSwitch Command_h("h", Command_help.m_helpText); + + if (commandLine->HasSwitch(Command_waitOnLaunch.m_switch)) + { + // Useful for attaching the debugger, this forces a short pause. + AZStd::this_thread::sleep_for(AZStd::chrono::seconds(20)); + } + + if (commandLine->HasSwitch(Command_zeroAnalysisMode.m_switch)) { m_assetProcessorManager->SetEnableModtimeSkippingFeature(true); } - if(commandLine->HasSwitch("enableQueryLogging")) + if (commandLine->HasSwitch(Command_enableQueryLogging.m_switch)) { m_assetProcessorManager->SetQueryLogging(true); } - if (commandLine->HasSwitch("dependencyScanPattern")) + if (commandLine->HasSwitch(Command_dependencyScanPattern.m_switch)) { - m_dependencyScanPattern = commandLine->GetSwitchValue("dependencyScanPattern", 0).c_str(); + m_dependencyScanPattern = commandLine->GetSwitchValue(Command_dependencyScanPattern.m_switch, 0).c_str(); } - else if (commandLine->HasSwitch("dsp")) + else if (commandLine->HasSwitch(Command_dsp.m_switch)) { - m_dependencyScanPattern = commandLine->GetSwitchValue("dsp", 0).c_str(); + m_dependencyScanPattern = commandLine->GetSwitchValue(Command_dsp.m_switch, 0).c_str(); } m_fileDependencyScanPattern = "*"; - if (commandLine->HasSwitch("fileDependencyScanPattern")) + if (commandLine->HasSwitch(Command_fileDependencyScanPattern.m_switch)) { - m_fileDependencyScanPattern = commandLine->GetSwitchValue("fileDependencyScanPattern", 0).c_str(); + m_fileDependencyScanPattern = commandLine->GetSwitchValue(Command_fileDependencyScanPattern.m_switch, 0).c_str(); } - else if (commandLine->HasSwitch("fdsp")) + else if (commandLine->HasSwitch(Command_fdsp.m_switch)) { - m_fileDependencyScanPattern = commandLine->GetSwitchValue("fdsp", 0).c_str(); + m_fileDependencyScanPattern = commandLine->GetSwitchValue(Command_fdsp.m_switch, 0).c_str(); } - if (commandLine->HasSwitch(AdditionalScanFolders)) + if (commandLine->HasSwitch(Command_additionalScanFolders.m_switch)) { - for (size_t idx = 0; idx < commandLine->GetNumSwitchValues(AdditionalScanFolders); idx++) + for (size_t idx = 0; idx < commandLine->GetNumSwitchValues(Command_additionalScanFolders.m_switch); idx++) { - AZStd::string value = commandLine->GetSwitchValue(AdditionalScanFolders, idx); + AZStd::string value = commandLine->GetSwitchValue(Command_additionalScanFolders.m_switch, idx); m_dependencyAddtionalScanFolders.emplace_back(AZStd::move(value)); } } - if (commandLine->HasSwitch("dependencyScanMaxIteration")) + if (commandLine->HasSwitch(Command_dependencyScanMaxIteration.m_switch)) { - AZStd::string maxIterationAsString = commandLine->GetSwitchValue("dependencyScanMaxIteration", 0); + AZStd::string maxIterationAsString = commandLine->GetSwitchValue(Command_dependencyScanMaxIteration.m_switch, 0); m_dependencyScanMaxIteration = AZStd::stoi(maxIterationAsString); } - if (commandLine->HasSwitch("warningLevel")) + if (commandLine->HasSwitch(Command_warningLevel.m_switch)) { using namespace AssetProcessor; - const AZStd::string& levelString = commandLine->GetSwitchValue("warningLevel", 0); + const AZStd::string& levelString = commandLine->GetSwitchValue(Command_warningLevel.m_switch, 0); WarningLevel warningLevel = WarningLevel::Default; switch(AZStd::stoi(levelString)) @@ -217,26 +250,30 @@ void ApplicationManagerBase::InitAssetProcessorManager() } AssetProcessor::JobDiagnosticRequestBus::Broadcast(&AssetProcessor::JobDiagnosticRequestBus::Events::SetWarningLevel, warningLevel); } - if (commandLine->HasSwitch("acceptInput")) + if (commandLine->HasSwitch(Command_acceptInput.m_switch)) { InitControlRequestHandler(); } - if (commandLine->HasSwitch("debugOutput")) + if (commandLine->HasSwitch(Command_debugOutput.m_switch)) { m_assetProcessorManager->SetBuilderDebugFlag(true); } - constexpr char truncateFingerprintSwitch[] = "truncatefingerprint"; - if(commandLine->HasSwitch(truncateFingerprintSwitch)) + if (commandLine->HasSwitch(Command_sortJobsByDBSourceName.m_switch)) + { + m_sortJobsByDBSourceName = true; + } + + if (commandLine->HasSwitch(Command_truncatefingerprint.m_switch)) { // Zip archive format uses 2 second precision truncated const int ArchivePrecision = 2000; int precision = ArchivePrecision; - if(commandLine->GetNumSwitchValues(truncateFingerprintSwitch) > 0) + if (commandLine->GetNumSwitchValues(Command_truncatefingerprint.m_switch) > 0) { - precision = AZStd::stoi(commandLine->GetSwitchValue(truncateFingerprintSwitch, 0)); + precision = AZStd::stoi(commandLine->GetSwitchValue(Command_truncatefingerprint.m_switch, 0)); if(precision < 1) { @@ -246,6 +283,31 @@ void ApplicationManagerBase::InitAssetProcessorManager() AssetUtilities::SetTruncateFingerprintTimestamp(precision); } + + if (commandLine->HasSwitch(Command_help.m_switch) || commandLine->HasSwitch(Command_h.m_switch)) + { + // Other O3DE tools have a more full featured system for registering command flags + // that includes help output, but right now the AssetProcessor just checks strings + // via HasSwitch. This means this help output has to be updated manually. + AZ_TracePrintf("AssetProcessor", "Asset Processor Command Line Flags:\n"); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_waitOnLaunch.m_switch, Command_waitOnLaunch.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_zeroAnalysisMode.m_switch, Command_zeroAnalysisMode.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_enableQueryLogging.m_switch, Command_enableQueryLogging.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_dependencyScanPattern.m_switch, Command_dependencyScanPattern.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_dsp.m_switch, Command_dsp.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_fileDependencyScanPattern.m_switch, Command_fileDependencyScanPattern.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_fdsp.m_switch, Command_fdsp.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_additionalScanFolders.m_switch, Command_additionalScanFolders.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_dependencyScanMaxIteration.m_switch, Command_dependencyScanMaxIteration.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_warningLevel.m_switch, Command_warningLevel.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_acceptInput.m_switch, Command_acceptInput.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_debugOutput.m_switch, Command_debugOutput.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_sortJobsByDBSourceName.m_switch, Command_sortJobsByDBSourceName.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_truncatefingerprint.m_switch, Command_truncatefingerprint.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_help.m_switch, Command_help.m_helpText); + AZ_TracePrintf("AssetProcessor", "\t%s : %s\n", Command_h.m_switch, Command_h.m_helpText); + AZ_TracePrintf("AssetProcessor", "\tregset : set the given registry key to the given value.\n"); + } } void ApplicationManagerBase::Rescan() @@ -281,6 +343,11 @@ void ApplicationManagerBase::InitRCController() { m_rcController = new AssetProcessor::RCController(m_platformConfiguration->GetMinJobs(), m_platformConfiguration->GetMaxJobs()); + if (m_sortJobsByDBSourceName) + { + m_rcController->SetQueueSortOnDBSourceName(); + } + QObject::connect(m_assetProcessorManager, &AssetProcessor::AssetProcessorManager::AssetToProcess, m_rcController, &AssetProcessor::RCController::JobSubmitted); QObject::connect(m_rcController, &AssetProcessor::RCController::FileCompiled, m_assetProcessorManager, &AssetProcessor::AssetProcessorManager::AssetProcessed, Qt::UniqueConnection); QObject::connect(m_rcController, &AssetProcessor::RCController::FileFailed, m_assetProcessorManager, &AssetProcessor::AssetProcessorManager::AssetFailed); @@ -1807,4 +1874,3 @@ void ApplicationManagerBase::OnActiveJobsCountChanged(unsigned int count) AssetProcessor::AssetProcessorStatusEntry entry(AssetProcessor::AssetProcessorStatus::Processing_Jobs, count); Q_EMIT AssetProcessorStatusChanged(entry); } - diff --git a/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.h b/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.h index 40106c69ec..7e6347b4d1 100644 --- a/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.h +++ b/Code/Tools/AssetProcessor/native/utilities/ApplicationManagerBase.h @@ -236,6 +236,11 @@ protected: int m_remainingAPMJobs = 0; bool m_assetProcessorManagerIsReady = false; + // When job priority and escalation is equal, jobs sort in order by job key. + // This switches that behavior to instead sort by the DB source name, which + // allows automated tests to get deterministic behavior out of Asset Processor. + bool m_sortJobsByDBSourceName = false; + unsigned int m_highestConnId = 0; AzToolsFramework::Ticker* m_ticker = nullptr; // for ticking the tickbus. diff --git a/Code/Tools/ProjectManager/Platform/Windows/ProjectBuilderWorker_windows.cpp b/Code/Tools/ProjectManager/Platform/Windows/ProjectBuilderWorker_windows.cpp index a228f58e51..8856e2312a 100644 --- a/Code/Tools/ProjectManager/Platform/Windows/ProjectBuilderWorker_windows.cpp +++ b/Code/Tools/ProjectManager/Platform/Windows/ProjectBuilderWorker_windows.cpp @@ -118,7 +118,9 @@ namespace O3DE::ProjectManager } } - if (m_configProjectProcess->exitCode() != 0 || !containsGeneratingDone) + if (m_configProjectProcess->exitStatus() != QProcess::ExitStatus::NormalExit + || m_configProjectProcess->exitCode() != 0 + || !containsGeneratingDone) { QString error = tr("Configuring project failed. See log for details."); QStringToAZTracePrint(error); @@ -180,7 +182,8 @@ namespace O3DE::ProjectManager } } - if (m_configProjectProcess->exitCode() != 0) + if (m_configProjectProcess->exitStatus() != QProcess::ExitStatus::NormalExit + || m_configProjectProcess->exitCode() != 0) { QString error = tr("Building project failed. See log for details."); QStringToAZTracePrint(error); diff --git a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp index 20d564d8b0..f098518fd3 100644 --- a/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/CreateProjectCtrl.cpp @@ -265,6 +265,6 @@ namespace O3DE::ProjectManager void CreateProjectCtrl::ReinitGemCatalogForSelectedTemplate() { const QString projectTemplatePath = m_newProjectSettingsScreen->GetProjectTemplatePath(); - m_gemCatalogScreen->ReinitForProject(projectTemplatePath + "/Template", /*isNewProject=*/true); + m_gemCatalogScreen->ReinitForProject(projectTemplatePath + "/Template"); } } // namespace O3DE::ProjectManager diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp index 53d772c217..863f611ec8 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.cpp @@ -62,10 +62,10 @@ namespace O3DE::ProjectManager hLayout->addWidget(m_gemInspector); } - void GemCatalogScreen::ReinitForProject(const QString& projectPath, bool isNewProject) + void GemCatalogScreen::ReinitForProject(const QString& projectPath) { m_gemModel->clear(); - FillModel(projectPath, isNewProject); + FillModel(projectPath); if (m_filterWidget) { @@ -88,18 +88,9 @@ namespace O3DE::ProjectManager }); } - void GemCatalogScreen::FillModel(const QString& projectPath, bool isNewProject) + void GemCatalogScreen::FillModel(const QString& projectPath) { - AZ::Outcome, AZStd::string> allGemInfosResult; - if (isNewProject) - { - allGemInfosResult = PythonBindingsInterface::Get()->GetEngineGemInfos(); - } - else - { - allGemInfosResult = PythonBindingsInterface::Get()->GetAllGemInfos(projectPath); - } - + AZ::Outcome, AZStd::string> allGemInfosResult = PythonBindingsInterface::Get()->GetAllGemInfos(projectPath); if (allGemInfosResult.IsSuccess()) { // Add all available gems to the model. diff --git a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h index 204ad0e5c5..5b48b2f90e 100644 --- a/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h +++ b/Code/Tools/ProjectManager/Source/GemCatalog/GemCatalogScreen.h @@ -28,13 +28,13 @@ namespace O3DE::ProjectManager ~GemCatalogScreen() = default; ProjectManagerScreen GetScreenEnum() override; - void ReinitForProject(const QString& projectPath, bool isNewProject); + void ReinitForProject(const QString& projectPath); bool EnableDisableGemsForProject(const QString& projectPath); GemModel* GetGemModel() const { return m_gemModel; } private: - void FillModel(const QString& projectPath, bool isNewProject); + void FillModel(const QString& projectPath); GemListView* m_gemListView = nullptr; GemInspector* m_gemInspector = nullptr; diff --git a/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp b/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp index e782f0b57f..0ff963e539 100644 --- a/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp +++ b/Code/Tools/ProjectManager/Source/ProjectBuilderController.cpp @@ -104,7 +104,7 @@ namespace O3DE::ProjectManager QMessageBox::critical(m_parent, tr("Project Failed to Build!"), result); m_projectInfo.m_buildFailed = true; - m_projectInfo.m_logUrl = QUrl(); + m_projectInfo.m_logUrl = QUrl("file:///" + m_worker->GetLogFilePath()); emit NotifyBuildProject(m_projectInfo); } diff --git a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp index 981a9352f7..6aba261cd2 100644 --- a/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp +++ b/Code/Tools/ProjectManager/Source/UpdateProjectCtrl.cpp @@ -94,7 +94,7 @@ namespace O3DE::ProjectManager Update(); // Gather the available gems that will be shown in the gem catalog. - m_gemCatalogScreen->ReinitForProject(m_projectInfo.m_path, /*isNewProject=*/false); + m_gemCatalogScreen->ReinitForProject(m_projectInfo.m_path); } void UpdateProjectCtrl::HandleGemsButton() diff --git a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp index 9a6f7c83ab..330b6571f3 100644 --- a/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp +++ b/Gems/Atom/Component/DebugCamera/Code/Source/CameraComponent.cpp @@ -235,7 +235,7 @@ namespace AZ UpdateViewToClipMatrix(); } - void CameraComponent::SetOrthographic(bool orthographic) + void CameraComponent::SetOrthographic([[maybe_unused]] bool orthographic) { AZ_Assert(!orthographic, "DebugCamera does not support orthographic projection"); } diff --git a/Gems/Atom/Feature/Common/Assets/Passes/UI.pass b/Gems/Atom/Feature/Common/Assets/Passes/UI.pass index ac43f17c11..fd59df5336 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/UI.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/UI.pass @@ -13,13 +13,7 @@ "ScopeAttachmentUsage": "DepthStencil", "LoadStoreAction": { "ClearValue": { - "Type": "DepthStencil", - "Value": [ - 0.0, - 0.0, - 0.0, - 0.0 - ] + "Type": "DepthStencil" }, "LoadActionStencil": "Clear" } diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignment.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignment.h index 907b1a1740..987e78ae0f 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignment.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignment.h @@ -66,6 +66,6 @@ namespace AZ //! Find an assignment id corresponding to the lod and label substring filters MaterialAssignmentId FindMaterialAssignmentIdInModel( - const Data::Instance model, const MaterialAssignmentLodIndex lodFilter, const AZStd::string& labelFilter); + const Data::Instance& model, const MaterialAssignmentLodIndex lodFilter, const AZStd::string& labelFilter); } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h index dd198a7179..e58a8397db 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Material/MaterialAssignmentId.h @@ -15,6 +15,7 @@ #include #include #include +#include namespace AZ { @@ -23,51 +24,50 @@ namespace AZ using MaterialAssignmentLodIndex = AZ::u64; //! MaterialAssignmentId is used to address available and overridable material slots on a model. - //! The LOD and one of the model's original material asset IDs are used as coordinates that identify + //! The LOD and one of the model's original material slot IDs are used as coordinates that identify //! a specific material slot or a set of slots matching either. struct MaterialAssignmentId final { AZ_RTTI(AZ::Render::MaterialAssignmentId, "{EB603581-4654-4C17-B6DE-AE61E79EDA97}"); AZ_CLASS_ALLOCATOR(AZ::Render::MaterialAssignmentId, SystemAllocator, 0); static void Reflect(ReflectContext* context); + static bool ConvertVersion(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement); MaterialAssignmentId() = default; - MaterialAssignmentId(MaterialAssignmentLodIndex lodIndex, const AZ::Data::AssetId& materialAssetId); + MaterialAssignmentId(MaterialAssignmentLodIndex lodIndex, RPI::ModelMaterialSlot::StableId materialSlotStableId); - //! Create an ID that maps to all material slots, regardless of asset ID or LOD, effectively applying to an entire model. + //! Create an ID that maps to all material slots, regardless of slot ID or LOD, effectively applying to an entire model. static MaterialAssignmentId CreateDefault(); - //! Create an ID that maps to all material slots with a corresponding asset ID, regardless of LOD. - static MaterialAssignmentId CreateFromAssetOnly(AZ::Data::AssetId materialAssetId); + //! Create an ID that maps to all material slots with a corresponding slot ID, regardless of LOD. + static MaterialAssignmentId CreateFromStableIdOnly(RPI::ModelMaterialSlot::StableId materialSlotStableId); - //! Create an ID that maps to a specific material slot with a corresponding asset ID and LOD. - static MaterialAssignmentId CreateFromLodAndAsset(MaterialAssignmentLodIndex lodIndex, AZ::Data::AssetId materialAssetId); + //! Create an ID that maps to a specific material slot with a corresponding stable ID and LOD. + static MaterialAssignmentId CreateFromLodAndStableId(MaterialAssignmentLodIndex lodIndex, RPI::ModelMaterialSlot::StableId materialSlotStableId); - //! Returns true if the asset ID and LOD are invalid + //! Returns true if the slot stable ID and LOD are invalid, meaning this assignment applies to the entire model. bool IsDefault() const; - //! Returns true if the asset ID is valid and LOD is invalid - bool IsAssetOnly() const; + //! Returns true if the slot stable ID is valid and LOD is invalid, meaning this assignment applies to every LOD. + bool IsSlotIdOnly() const; - //! Returns true if the asset ID and LOD are both valid - bool IsLodAndAsset() const; + //! Returns true if the slot stable ID and LOD are both valid, meaning this assignment applies to a single material slot on a specific LOD. + bool IsLodAndSlotId() const; - //! Creates a string composed of the asset path and LOD + //! Creates a string describing all the details of the assignment ID AZStd::string ToString() const; - //! Creates a hash composed of the asset ID sub ID and LOD + //! Creates a hash composed of all elements of the assignment ID size_t GetHash() const; - //! Returns true if both asset ID sub IDs and LODs match bool operator==(const MaterialAssignmentId& rhs) const; - - //! Returns true if both asset ID sub IDs and LODs do not match bool operator!=(const MaterialAssignmentId& rhs) const; static constexpr MaterialAssignmentLodIndex NonLodIndex = -1; + MaterialAssignmentLodIndex m_lodIndex = NonLodIndex; - AZ::Data::AssetId m_materialAssetId = AZ::Data::AssetId(); + RPI::ModelMaterialSlot::StableId m_materialSlotStableId = RPI::ModelMaterialSlot::InvalidStableId; }; } // namespace Render diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/SkinnedMesh/SkinnedMeshInputBuffers.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/SkinnedMesh/SkinnedMeshInputBuffers.h index 5d333e070e..c52bed8cf2 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/SkinnedMesh/SkinnedMeshInputBuffers.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/SkinnedMesh/SkinnedMeshInputBuffers.h @@ -45,7 +45,7 @@ namespace AZ uint32_t m_vertexOffset = 0; uint32_t m_vertexCount = 0; Aabb m_aabb = Aabb::CreateNull(); - Data::Asset m_material; + AZ::RPI::ModelMaterialSlot m_materialSlot; }; //! Buffer views for a specific sub-mesh that are not modified during skinning and thus are shared by all instances of the same skinned mesh diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexedDataVector.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexedDataVector.h new file mode 100644 index 0000000000..37835bd6a8 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexedDataVector.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +namespace AZ::Render +{ + // Growable vector that leverages indirection to support erasure of elements while maintaining + // resident data in a densely packed region of memory. Useful as a backing store for growable + // buffers intended to be uploaded to the GPU for example. + template + class IndexedDataVector + { + public: + IndexedDataVector(); + explicit IndexedDataVector(size_t initialReservedSize); + ~IndexedDataVector() = default; + + static constexpr IndexType NoFreeSlot = std::numeric_limits::max(); + IndexType m_firstFreeSlot = NoFreeSlot; + + void Clear(); + IndexType GetFreeSlotIndex(); + void RemoveIndex(IndexType index); + + DataType& GetData(IndexType index); + const DataType& GetData(IndexType index) const; + size_t GetDataCount() const; + + AZStd::vector& GetDataVector(); + const AZStd::vector& GetDataVector() const; + + AZStd::vector& GetIndexVector(); + const AZStd::vector& GetIndexVector() const; + + IndexType GetRawIndex(IndexType index) const; + + private: + constexpr static size_t InitialReservedSize = 128; + + // Stores data indices and an embedded free list + AZStd::vector m_indices; + // Stores the indirection index + AZStd::vector m_dataToIndices; + AZStd::vector m_data; + }; +} // namespace AZ::Render + +#include diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexedDataVector.inl b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexedDataVector.inl new file mode 100644 index 0000000000..076caad7f4 --- /dev/null +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Utils/IndexedDataVector.inl @@ -0,0 +1,134 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +namespace AZ::Render +{ + template + inline IndexedDataVector::IndexedDataVector() + : IndexedDataVector(InitialReservedSize) + { + } + + template + inline IndexedDataVector::IndexedDataVector(size_t initialReservedSize) + { + m_dataToIndices.reserve(initialReservedSize); + m_indices.reserve(initialReservedSize); + m_data.reserve(initialReservedSize); + } + + template + inline void IndexedDataVector::Clear() + { + m_dataToIndices.clear(); + m_indices.clear(); + m_data.clear(); + + m_firstFreeSlot = NoFreeSlot; + } + + template + inline IndexType IndexedDataVector::GetFreeSlotIndex() + { + IndexType freeSlotIndex = static_cast(m_indices.size()); + + if (freeSlotIndex == NoFreeSlot) + { + // the vector is full + return NoFreeSlot; + } + + if (m_firstFreeSlot == NoFreeSlot) + { + // If there's no free slot, add on to the end. + m_indices.push_back(freeSlotIndex); + } + else + { + // Fill the free slot. m_indices uses it's empty slots to store a linked list (via indices) to other empty slots. + freeSlotIndex = m_firstFreeSlot; + m_firstFreeSlot = m_indices.at(m_firstFreeSlot); + m_indices.at(freeSlotIndex) = static_cast(m_data.size()); + } + + // The data itself is always packed and m_indices points at it, so push a new entry to the back. + m_data.push_back(DataType()); + m_dataToIndices.push_back(freeSlotIndex); + + return freeSlotIndex; + } + + template + inline void IndexedDataVector::RemoveIndex(IndexType index) + { + IndexType dataIndex = m_indices.at(index); + + // Copy the back light on top of this one. + m_data.at(dataIndex) = m_data.back(); + m_dataToIndices.at(dataIndex) = m_dataToIndices.back(); + + // Update the index of the moved light + m_indices.at(m_dataToIndices.at(dataIndex)) = dataIndex; + + // Pop the back + m_data.pop_back(); + m_dataToIndices.pop_back(); + + // Use free slot to link to next free slot + m_indices.at(index) = m_firstFreeSlot; + m_firstFreeSlot = index; + } + + template + inline DataType& IndexedDataVector::GetData(IndexType index) + { + return m_data.at(m_indices.at(index)); + } + + template + inline const DataType& IndexedDataVector::GetData(IndexType index) const + { + return m_data.at(m_indices.at(index)); + } + + template + inline size_t IndexedDataVector::GetDataCount() const + { + return m_data.size(); + } + + template + inline AZStd::vector& IndexedDataVector::GetDataVector() + { + return m_data; + } + + template + inline const AZStd::vector& IndexedDataVector::GetDataVector() const + { + return m_data; + } + + template + inline AZStd::vector& IndexedDataVector::GetIndexVector() + { + return m_dataToIndices; + } + + template + inline const AZStd::vector& IndexedDataVector::GetIndexVector() const + { + return m_dataToIndices; + } + + template + IndexType IndexedDataVector::GetRawIndex(IndexType index) const + { + return m_indices.at(index); + } +} // namespace AZ::Render diff --git a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp index 6ad0099686..1500079b00 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CommonSystemComponent.cpp @@ -284,7 +284,7 @@ namespace AZ passSystem->AddPassCreator(Name("ReflectionScreenSpaceCompositePass"), &Render::ReflectionScreenSpaceCompositePass::Create); passSystem->AddPassCreator(Name("ReflectionCopyFrameBufferPass"), &Render::ReflectionCopyFrameBufferPass::Create); - // Add RayTracing pas + // Add RayTracing pass passSystem->AddPassCreator(Name("RayTracingPass"), &Render::RayTracingPass::Create); // setup handler for load pass template mappings diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.h index a85831e290..6749acfcf5 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/CapsuleLightFeatureProcessor.h @@ -10,7 +10,7 @@ #include #include -#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h index a312b31dda..4c486c4540 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h @@ -9,9 +9,9 @@ #pragma once #include -#include #include +#include #include #include #include diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h index 2e97ae1ded..36837a67fb 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/IndexedDataVector.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/IndexedDataVector.h deleted file mode 100644 index f2a372aca9..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/IndexedDataVector.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include - -namespace AZ -{ - namespace Render - { - template - class IndexedDataVector - { - public: - IndexedDataVector(); - ~IndexedDataVector() = default; - - static constexpr IndexType NoFreeSlot = std::numeric_limits::max(); - IndexType m_firstFreeSlot = NoFreeSlot; - - void Clear(); - IndexType GetFreeSlotIndex(); - void RemoveIndex(IndexType index); - - DataType& GetData(IndexType index); - const DataType& GetData(IndexType index) const; - size_t GetDataCount() const; - - AZStd::vector& GetDataVector(); - const AZStd::vector& GetDataVector() const; - - IndexType GetRawIndex(IndexType index) const; - - private: - - static constexpr size_t InitialReservedCount = 128; - - // stores the index of data vector for respective light, it also include a linked list to flag the free slots - AZStd::vector m_indices; - // stores the index of index vector for respective light - AZStd::vector m_dataToIndices; - // stores light data - AZStd::vector m_data; - }; - -#include "IndexedDataVector.inl" - } -} diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/IndexedDataVector.inl b/Gems/Atom/Feature/Common/Code/Source/CoreLights/IndexedDataVector.inl deleted file mode 100644 index da10e5a503..0000000000 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/IndexedDataVector.inl +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -template -inline IndexedDataVector::IndexedDataVector() -{ - m_dataToIndices.reserve(InitialReservedCount); - m_indices.reserve(InitialReservedCount); - m_data.reserve(InitialReservedCount); -} - -template -inline void IndexedDataVector::Clear() -{ - m_dataToIndices.clear(); - m_indices.clear(); - m_data.clear(); - - m_firstFreeSlot = NoFreeSlot; -} - -template -inline IndexType IndexedDataVector::GetFreeSlotIndex() -{ - IndexType freeSlotIndex = static_cast(m_indices.size()); - - if (freeSlotIndex == NoFreeSlot) - { - // the vector is full - return NoFreeSlot; - } - - if (m_firstFreeSlot == NoFreeSlot) - { - // If there's no free slot, add on to the end. - m_indices.push_back(freeSlotIndex); - } - else - { - // Fill the free slot. m_indices uses it's empty slots to store a linked list (via indices) to other empty slots. - freeSlotIndex = m_firstFreeSlot; - m_firstFreeSlot = m_indices.at(m_firstFreeSlot); - m_indices.at(freeSlotIndex) = static_cast(m_data.size()); - } - - // The data itself is always packed and m_indices points at it, so push a new entry to the back. - m_data.push_back(DataType()); - m_dataToIndices.push_back(freeSlotIndex); - - return freeSlotIndex; -} - -template -inline void IndexedDataVector::RemoveIndex(IndexType index) -{ - IndexType dataIndex = m_indices.at(index); - - // Copy the back light on top of this one. - m_data.at(dataIndex) = m_data.back(); - m_dataToIndices.at(dataIndex) = m_dataToIndices.back(); - - // Update the index of the moved light - m_indices.at(m_dataToIndices.at(dataIndex)) = dataIndex; - - // Pop the back - m_data.pop_back(); - m_dataToIndices.pop_back(); - - // Use free slot to link to next free slot - m_indices.at(index) = m_firstFreeSlot; - m_firstFreeSlot = index; -} - -template -inline DataType& IndexedDataVector::GetData(IndexType index) -{ - return m_data.at(m_indices.at(index)); -} - -template -inline const DataType& IndexedDataVector::GetData(IndexType index) const -{ - return m_data.at(m_indices.at(index)); -} - -template -inline size_t IndexedDataVector::GetDataCount() const -{ - return m_data.size(); -} - -template -inline AZStd::vector& IndexedDataVector::GetDataVector() -{ - return m_data; -} - -template -inline const AZStd::vector& IndexedDataVector::GetDataVector() const -{ - return m_data; -} - -template -IndexType IndexedDataVector::GetRawIndex(IndexType index) const -{ - return m_indices.at(index); -} diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h index b7b644da9e..3c231c1fb0 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/QuadLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/QuadLightFeatureProcessor.h index 567d309dff..17d6aab304 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/QuadLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/QuadLightFeatureProcessor.h @@ -10,7 +10,7 @@ #include #include -#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimplePointLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimplePointLightFeatureProcessor.h index 3d36bb1978..bd9160b171 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimplePointLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimplePointLightFeatureProcessor.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimpleSpotLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimpleSpotLightFeatureProcessor.h index 1d72c3e6cc..bc132be77c 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimpleSpotLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/SimpleSpotLightFeatureProcessor.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h index 649928d26d..57c5c69e0d 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Decals/DecalTextureArrayFeatureProcessor.h @@ -9,6 +9,7 @@ #pragma once #include +#include #include #include #include @@ -16,7 +17,6 @@ #include #include #include -#include namespace AZ { diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp index 074d5c39e8..4d437be244 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignment.cpp @@ -33,8 +33,7 @@ namespace AZ serializeContext->Class() ->Version(1) ->Field("MaterialAsset", &MaterialAssignment::m_materialAsset) - ->Field("PropertyOverrides", &MaterialAssignment::m_propertyOverrides) - ; + ->Field("PropertyOverrides", &MaterialAssignment::m_propertyOverrides); } if (auto behaviorContext = azrtti_cast(context)) @@ -50,8 +49,7 @@ namespace AZ ->Constructor&, const Data::Instance&>() ->Method("ToString", &MaterialAssignment::ToString) ->Property("materialAsset", BehaviorValueProperty(&MaterialAssignment::m_materialAsset)) - ->Property("propertyOverrides", BehaviorValueProperty(&MaterialAssignment::m_propertyOverrides)) - ; + ->Property("propertyOverrides", BehaviorValueProperty(&MaterialAssignment::m_propertyOverrides)); behaviorContext->ConstantProperty("DefaultMaterialAssignment", BehaviorConstant(DefaultMaterialAssignment)) ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) @@ -67,7 +65,6 @@ namespace AZ ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Category, "render") ->Attribute(AZ::Script::Attributes::Module, "render"); - } } @@ -123,7 +120,7 @@ namespace AZ } const MaterialAssignment& assetAssignment = - GetMaterialAssignmentFromMap(materials, MaterialAssignmentId::CreateFromAssetOnly(id.m_materialAssetId)); + GetMaterialAssignmentFromMap(materials, MaterialAssignmentId::CreateFromStableIdOnly(id.m_materialSlotStableId)); if (assetAssignment.m_materialInstance.get()) { return assetAssignment; @@ -152,11 +149,12 @@ namespace AZ { if (mesh.m_material) { - const MaterialAssignmentId generalId = MaterialAssignmentId::CreateFromAssetOnly(mesh.m_material->GetAssetId()); + const MaterialAssignmentId generalId = + MaterialAssignmentId::CreateFromStableIdOnly(mesh.m_materialSlotStableId); materials[generalId] = MaterialAssignment(mesh.m_material->GetAsset(), mesh.m_material); const MaterialAssignmentId specificId = - MaterialAssignmentId::CreateFromLodAndAsset(lodIndex, mesh.m_material->GetAssetId()); + MaterialAssignmentId::CreateFromLodAndStableId(lodIndex, mesh.m_materialSlotStableId); materials[specificId] = MaterialAssignment(mesh.m_material->GetAsset(), mesh.m_material); } } @@ -168,38 +166,36 @@ namespace AZ } MaterialAssignmentId FindMaterialAssignmentIdInLod( - const Data::Instance& lod, const MaterialAssignmentLodIndex lodIndex, const AZStd::string& labelFilter) + const Data::Instance& model, + const Data::Instance& lod, + const MaterialAssignmentLodIndex lodIndex, + const AZStd::string& labelFilter) { for (const AZ::RPI::ModelLod::Mesh& mesh : lod->GetMeshes()) { - if (mesh.m_material && mesh.m_material->GetAssetId().IsValid()) + const AZ::RPI::ModelMaterialSlot& slot = model->GetModelAsset()->FindMaterialSlot(mesh.m_materialSlotStableId); + if (AZ::StringFunc::Contains(slot.m_displayName.GetCStr(), labelFilter, true)) { - AZ::Data::AssetInfo assetInfo; - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - assetInfo, &AZ::Data::AssetCatalogRequests::GetAssetInfoById, mesh.m_material->GetAssetId()); - if (assetInfo.m_assetId.IsValid() && AZ::StringFunc::Contains(assetInfo.m_relativePath, labelFilter, true)) - { - return MaterialAssignmentId::CreateFromLodAndAsset(lodIndex, mesh.m_material->GetAssetId()); - } + return MaterialAssignmentId::CreateFromLodAndStableId(lodIndex, mesh.m_materialSlotStableId); } } return MaterialAssignmentId(); } MaterialAssignmentId FindMaterialAssignmentIdInModel( - const Data::Instance model, const MaterialAssignmentLodIndex lodFilter, const AZStd::string& labelFilter) + const Data::Instance& model, const MaterialAssignmentLodIndex lodFilter, const AZStd::string& labelFilter) { if (model && !labelFilter.empty()) { if (lodFilter < model->GetLodCount()) { - return FindMaterialAssignmentIdInLod(model->GetLods()[lodFilter], lodFilter, labelFilter); + return FindMaterialAssignmentIdInLod(model, model->GetLods()[lodFilter], lodFilter, labelFilter); } for (size_t lodIndex = 0; lodIndex < model->GetLodCount(); ++lodIndex) { const MaterialAssignmentId result = - FindMaterialAssignmentIdInLod(model->GetLods()[lodIndex], MaterialAssignmentId::NonLodIndex, labelFilter); + FindMaterialAssignmentIdInLod(model, model->GetLods()[lodIndex], MaterialAssignmentId::NonLodIndex, labelFilter); if (!result.IsDefault()) { return result; diff --git a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp index 71dea0596f..b8a03af6d1 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Material/MaterialAssignmentId.cpp @@ -14,14 +14,46 @@ namespace AZ { namespace Render { + bool MaterialAssignmentId::ConvertVersion(AZ::SerializeContext& context, AZ::SerializeContext::DataElementNode& classElement) + { + if (classElement.GetVersion() < 2) + { + constexpr AZ::u32 materialAssetIdCrc = AZ_CRC("materialAssetId"); + + AZ::Data::AssetId materialAssetId; + if (!classElement.GetChildData(materialAssetIdCrc, materialAssetId)) + { + AZ_Error("AZ::Render::MaterialAssignmentId::ConvertVersion", false, "Failed to get AssetId element"); + return false; + } + + if (!classElement.RemoveElementByName(materialAssetIdCrc)) + { + AZ_Error("AZ::Render::MaterialAssignmentId::ConvertVersion", false, "Failed to remove deprecated element materialAssetId"); + // No need to early-return, the object will still load successfully, it will just report more errors about the unrecognized element. + } + + if (materialAssetId.IsValid()) + { + classElement.AddElementWithData(context, "materialSlotStableId", materialAssetId.m_subId); + } + else + { + classElement.AddElementWithData(context, "materialSlotStableId", RPI::ModelMaterialSlot::InvalidStableId); + } + } + + return true; + } + void MaterialAssignmentId::Reflect(ReflectContext* context) { if (auto serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(1) + ->Version(2, &MaterialAssignmentId::ConvertVersion) ->Field("lodIndex", &MaterialAssignmentId::m_lodIndex) - ->Field("materialAssetId", &MaterialAssignmentId::m_materialAssetId) + ->Field("materialSlotStableId", &MaterialAssignmentId::m_materialSlotStableId) ; } @@ -33,75 +65,72 @@ namespace AZ ->Attribute(AZ::Script::Attributes::Module, "render") ->Constructor() ->Constructor() - ->Constructor() + ->Constructor() ->Method("IsDefault", &MaterialAssignmentId::IsDefault) - ->Method("IsAssetOnly", &MaterialAssignmentId::IsAssetOnly) - ->Method("IsLodAndAsset", &MaterialAssignmentId::IsLodAndAsset) + ->Method("IsAssetOnly", &MaterialAssignmentId::IsSlotIdOnly) // Included for compatibility. Use "IsSlotIdOnly" instead. + ->Method("IsLodAndAsset", &MaterialAssignmentId::IsLodAndSlotId) // Included for compatibility. Use "IsLodAndSlotId" instead. + ->Method("IsSlotIdOnly", &MaterialAssignmentId::IsSlotIdOnly) + ->Method("IsLodAndSlotId", &MaterialAssignmentId::IsLodAndSlotId) ->Method("ToString", &MaterialAssignmentId::ToString) ->Property("lodIndex", BehaviorValueProperty(&MaterialAssignmentId::m_lodIndex)) - ->Property("materialAssetId", BehaviorValueProperty(&MaterialAssignmentId::m_materialAssetId)) + ->Property("materialSlotStableId", BehaviorValueProperty(&MaterialAssignmentId::m_materialSlotStableId)) ; } } - MaterialAssignmentId::MaterialAssignmentId(MaterialAssignmentLodIndex lodIndex, const AZ::Data::AssetId& materialAssetId) + MaterialAssignmentId::MaterialAssignmentId(MaterialAssignmentLodIndex lodIndex, RPI::ModelMaterialSlot::StableId materialSlotStableId) : m_lodIndex(lodIndex) - , m_materialAssetId(materialAssetId) + , m_materialSlotStableId(materialSlotStableId) { } MaterialAssignmentId MaterialAssignmentId::CreateDefault() { - return MaterialAssignmentId(NonLodIndex, AZ::Data::AssetId()); + return MaterialAssignmentId(NonLodIndex, RPI::ModelMaterialSlot::InvalidStableId); } - MaterialAssignmentId MaterialAssignmentId::CreateFromAssetOnly(AZ::Data::AssetId materialAssetId) + MaterialAssignmentId MaterialAssignmentId::CreateFromStableIdOnly(RPI::ModelMaterialSlot::StableId materialSlotStableId) { - return MaterialAssignmentId(NonLodIndex, materialAssetId); + return MaterialAssignmentId(NonLodIndex, materialSlotStableId); } - MaterialAssignmentId MaterialAssignmentId::CreateFromLodAndAsset( - MaterialAssignmentLodIndex lodIndex, AZ::Data::AssetId materialAssetId) + MaterialAssignmentId MaterialAssignmentId::CreateFromLodAndStableId( + MaterialAssignmentLodIndex lodIndex, RPI::ModelMaterialSlot::StableId materialSlotStableId) { - return MaterialAssignmentId(lodIndex, materialAssetId); + return MaterialAssignmentId(lodIndex, materialSlotStableId); } bool MaterialAssignmentId::IsDefault() const { - return m_lodIndex == NonLodIndex && !m_materialAssetId.IsValid(); + return m_lodIndex == NonLodIndex && m_materialSlotStableId == RPI::ModelMaterialSlot::InvalidStableId; } - bool MaterialAssignmentId::IsAssetOnly() const + bool MaterialAssignmentId::IsSlotIdOnly() const { - return m_lodIndex == NonLodIndex && m_materialAssetId.IsValid(); + return m_lodIndex == NonLodIndex && m_materialSlotStableId != RPI::ModelMaterialSlot::InvalidStableId; } - bool MaterialAssignmentId::IsLodAndAsset() const + bool MaterialAssignmentId::IsLodAndSlotId() const { - return m_lodIndex != NonLodIndex && m_materialAssetId.IsValid(); + return m_lodIndex != NonLodIndex && m_materialSlotStableId != RPI::ModelMaterialSlot::InvalidStableId; } AZStd::string MaterialAssignmentId::ToString() const { - AZStd::string assetPathString; - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - assetPathString, &AZ::Data::AssetCatalogRequests::GetAssetPathById, m_materialAssetId); - AZ::StringFunc::Path::StripPath(assetPathString); - AZ::StringFunc::Path::StripExtension(assetPathString); - return AZStd::string::format("%s:%llu", assetPathString.c_str(), m_lodIndex); + return AZStd::string::format("%u:%llu", m_materialSlotStableId, m_lodIndex); } size_t MaterialAssignmentId::GetHash() const { size_t seed = 0; AZStd::hash_combine(seed, m_lodIndex); - AZStd::hash_combine(seed, m_materialAssetId.m_subId); + AZStd::hash_combine(seed, m_materialSlotStableId); return seed; } bool MaterialAssignmentId::operator==(const MaterialAssignmentId& rhs) const { - return m_lodIndex == rhs.m_lodIndex && m_materialAssetId.m_subId == rhs.m_materialAssetId.m_subId; + return m_lodIndex == rhs.m_lodIndex && m_materialSlotStableId == rhs.m_materialSlotStableId; } bool MaterialAssignmentId::operator!=(const MaterialAssignmentId& rhs) const diff --git a/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp index c6362f3a5d..8e2c6f2e9b 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Mesh/MeshFeatureProcessor.cpp @@ -485,20 +485,12 @@ namespace AZ AZ_Error("MeshDataInstance::MeshLoader", false, "Invalid model asset Id."); return; } - - // Check if the model is in the instance database and skip the loading process in this case. - // The model asset id is used as instance id to indicate that it is a static and shared. - Data::Instance model = Data::InstanceDatabase::Instance().Find(Data::InstanceId::CreateFromAssetId(m_modelAsset.GetId())); - if (model) + + if (!m_modelAsset.IsReady()) { - // In case the mesh asset requires instancing (e.g. when containing a cloth buffer), the model will always be cloned and there will not be a - // model instance with the asset id as instance id as searched above. - m_parent->Init(model); - m_modelChangedEvent.Signal(AZStd::move(model)); - return; + m_modelAsset.QueueLoad(); } - m_modelAsset.QueueLoad(); Data::AssetBus::Handler::BusConnect(modelAsset.GetId()); } @@ -589,18 +581,6 @@ namespace AZ { AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); - auto modelAsset = model->GetModelAsset(); - for (const auto& modelLodAsset : modelAsset->GetLodAssets()) - { - for (const auto& mesh : modelLodAsset->GetMeshes()) - { - if (mesh.GetMaterialAsset().GetStatus() != Data::AssetData::AssetStatus::Ready) - { - - } - } - } - m_model = model; const size_t modelLodCount = m_model->GetLodCount(); m_drawPacketListsByLod.resize(modelLodCount); @@ -644,10 +624,12 @@ namespace AZ for (size_t meshIndex = 0; meshIndex < meshCount; ++meshIndex) { - Data::Instance material = modelLod.GetMeshes()[meshIndex].m_material; + const RPI::ModelLod::Mesh& mesh = modelLod.GetMeshes()[meshIndex]; + + Data::Instance material = mesh.m_material; // Determine if there is a material override specified for this sub mesh - const MaterialAssignmentId materialAssignmentId(modelLodIndex, material ? material->GetAssetId() : AZ::Data::AssetId()); + const MaterialAssignmentId materialAssignmentId(modelLodIndex, mesh.m_materialSlotStableId); const MaterialAssignment& materialAssignment = GetMaterialAssignmentFromMapWithFallback(m_materialAssignments, materialAssignmentId); if (materialAssignment.m_materialInstance.get()) { @@ -790,7 +772,7 @@ namespace AZ // retrieve the material Data::Instance material = mesh.m_material; - const MaterialAssignmentId materialAssignmentId(rayTracingLod, material ? material->GetAssetId() : AZ::Data::AssetId()); + const MaterialAssignmentId materialAssignmentId(rayTracingLod, mesh.m_materialSlotStableId); const MaterialAssignment& materialAssignment = GetMaterialAssignmentFromMapWithFallback(m_materialAssignments, materialAssignmentId); if (materialAssignment.m_materialInstance.get()) { diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h index 3dbf88addb..8beed800b6 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h @@ -10,10 +10,10 @@ #include #include +#include #include #include #include -#include namespace AZ::Render { diff --git a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp index 155b751272..de2c52d1c8 100644 --- a/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/SkinnedMesh/SkinnedMeshInputBuffers.cpp @@ -640,7 +640,8 @@ namespace AZ Aabb localAabb = lod.m_subMeshProperties[i].m_aabb; modelLodCreator.SetMeshAabb(AZStd::move(localAabb)); - modelLodCreator.SetMeshMaterialAsset(lod.m_subMeshProperties[i].m_material); + modelCreator.AddMaterialSlot(lod.m_subMeshProperties[i].m_materialSlot); + modelLodCreator.SetMeshMaterialSlot(lod.m_subMeshProperties[i].m_materialSlot.m_stableId); modelLodCreator.EndMesh(); } diff --git a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake index 401fac8c0c..40188109ca 100644 --- a/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake +++ b/Gems/Atom/Feature/Common/Code/atom_feature_common_files.cmake @@ -37,6 +37,8 @@ set(FILES Include/Atom/Feature/TransformService/TransformServiceFeatureProcessor.h Include/Atom/Feature/Utils/FrameCaptureBus.h Include/Atom/Feature/Utils/GpuBufferHandler.h + Include/Atom/Feature/Utils/IndexedDataVector.h + Include/Atom/Feature/Utils/IndexedDataVector.inl Include/Atom/Feature/Utils/MultiIndexedDataVector.h Include/Atom/Feature/Utils/MultiSparseVector.h Include/Atom/Feature/Utils/ProfilingCaptureBus.h @@ -77,8 +79,6 @@ set(FILES Source/CoreLights/DiskLightFeatureProcessor.cpp Source/CoreLights/EsmShadowmapsPass.h Source/CoreLights/EsmShadowmapsPass.cpp - Source/CoreLights/IndexedDataVector.h - Source/CoreLights/IndexedDataVector.inl Source/CoreLights/LtcCommon.h Source/CoreLights/LtcCommon.cpp Source/CoreLights/PointLightFeatureProcessor.h diff --git a/Gems/Atom/RHI/Code/CMakeLists.txt b/Gems/Atom/RHI/Code/CMakeLists.txt index 8e1ae3bdf0..eeb8f73bac 100644 --- a/Gems/Atom/RHI/Code/CMakeLists.txt +++ b/Gems/Atom/RHI/Code/CMakeLists.txt @@ -7,9 +7,26 @@ # ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) +ly_get_list_relative_pal_filename(pal_source_dir ${CMAKE_CURRENT_LIST_DIR}/Source/Platform/${PAL_PLATFORM_NAME}) include(${pal_dir}/AtomRHITests_traits_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) +set(RENDERDOC_CMAKE ${CMAKE_CURRENT_SOURCE_DIR}/${pal_dir}/renderdoc_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) +if(EXISTS ${RENDERDOC_CMAKE}) + include(${RENDERDOC_CMAKE}) +endif() + +if(TARGET "3rdParty::renderdoc") + message(STATUS "Renderdoc found, adding as runtime dependency") + set(USE_RENDERDOC_DEFINE "USE_RENDERDOC") + set(RENDERDOC_BUILD_DEPENDENCY "3rdParty::renderdoc") + set(RENDERDOC_API_DEPENDENCY "3rdParty::renderdoc_api") +else() + set(USE_RENDERDOC_DEFINE "") + set(RENDERDOC_BUILD_DEPENDENCY "") + set(RENDERDOC_API_DEPENDENCY "") +endif() + ly_add_target( NAME Atom_RHI.Reflect STATIC NAMESPACE Gem @@ -33,9 +50,11 @@ ly_add_target( NAMESPACE Gem FILES_CMAKE atom_rhi_public_files.cmake + ${pal_source_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake INCLUDE_DIRECTORIES PRIVATE Source + ${pal_source_dir} PUBLIC Include BUILD_DEPENDENCIES @@ -43,6 +62,12 @@ ly_add_target( AZ::AzCore AZ::AzFramework Gem::Atom_RHI.Reflect + ${RENDERDOC_BUILD_DEPENDENCY} + PUBLIC + ${RENDERDOC_API_DEPENDENCY} + COMPILE_DEFINITIONS + PUBLIC + ${USE_RENDERDOC_DEFINE} ) ly_add_target( diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/Factory.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/Factory.h index a9f9120e8d..11f28e7a94 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/Factory.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/Factory.h @@ -11,6 +11,10 @@ #include #include +#if defined(USE_RENDERDOC) +#include +#endif + namespace AZ { namespace RHI @@ -66,7 +70,7 @@ namespace AZ public: AZ_TYPE_INFO(Factory, "{2C0231FD-DD11-4154-A4F5-177181E26D8E}"); - Factory() = default; + Factory(); virtual ~Factory() = default; // Note that you have to delete these for safety reasons, you will trip a static_assert if you do not @@ -93,6 +97,15 @@ namespace AZ /// Access the global factory instance. static Factory& Get(); +#if defined(USE_RENDERDOC) + /// Access the RenderDoc API pointer if available. + /// The availability of the render doc API at runtime depends on the following: + /// - You must not be building a packaged game/product (LY_MONOLITHIC_GAME not enabled in CMake) + /// - A valid renderdoc installation was found, either by auto-discovery, or by supplying ATOM_RENDERDOC_PATH as an environment variable + /// - The module loaded successfully at runtime, and the API function pointer was retrieved successfully + static RENDERDOC_API_1_1_2* GetRenderDocAPI(); +#endif + /// Returns the name of the Factory. virtual Name GetName() = 0; diff --git a/Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h b/Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h index 68d92a77bb..73e8e1ad56 100644 --- a/Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h +++ b/Gems/Atom/RHI/Code/Include/Atom/RHI/RHIUtils.h @@ -37,6 +37,9 @@ namespace AZ //! If multiple values exist it will return the last one AZStd::string GetCommandLineValue(const AZStd::string& commandLineOption); + //! Returns true if the command line option is set + bool QueryCommandLineOption(const AZStd::string& commandLineOption); + //! Returns if the current bakcend is a null renderer bool IsNullRenderer(); } diff --git a/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake b/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake new file mode 100644 index 0000000000..0faccf80ec --- /dev/null +++ b/Gems/Atom/RHI/Code/Platform/Linux/renderdoc_linux.cmake @@ -0,0 +1,36 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +# Prevent bundling the renderdoc dll with a packaged title +if(NOT LY_MONOLITHIC_GAME) + if(DEFINED ENV{"ATOM_RENDERDOC_PATH"}) + set(RENDERDOC_PATH ENV{"ATOM_RENDERDOC_PATH"}) + endif() + + if(RENDERDOC_PATH) + # Normalize file path + file(TO_CMAKE_PATH "${RENDERDOC_PATH}" RENDERDOC_PATH) + + if(EXISTS "${RENDERDOC_PATH}/librenderdoc.so") + ly_add_external_target( + NAME renderdoc + VERSION + 3RDPARTY_ROOT_DIRECTORY ${RENDERDOC_PATH} + INCLUDE_DIRECTORIES "." + RUNTIME_DEPENDENCIES "${RENDERDOC_PATH}/librenderdoc.so" + ) + + ly_add_external_target( + NAME renderdoc_api + VERSION + 3RDPARTY_ROOT_DIRECTORY ${RENDERDOC_PATH} + INCLUDE_DIRECTORIES "." + ) + endif() + endif() +endif() \ No newline at end of file diff --git a/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake b/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake new file mode 100644 index 0000000000..499321b2ab --- /dev/null +++ b/Gems/Atom/RHI/Code/Platform/Windows/renderdoc_windows.cmake @@ -0,0 +1,38 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +# Prevent bundling the renderdoc dll with a packaged title +if(NOT LY_MONOLITHIC_GAME) + # Common installation path for renderdoc path + set(RENDERDOC_PATH "C:/Program Files/RenderDoc") + if(DEFINED ENV{"ATOM_RENDERDOC_PATH"}) + set(RENDERDOC_PATH ENV{"ATOM_RENDERDOC_PATH"}) + endif() + + if(RENDERDOC_PATH) + # Normalize file path + file(TO_CMAKE_PATH "${RENDERDOC_PATH}" RENDERDOC_PATH) + + if(EXISTS "${RENDERDOC_PATH}/renderdoc.dll") + ly_add_external_target( + NAME renderdoc + VERSION + 3RDPARTY_ROOT_DIRECTORY ${RENDERDOC_PATH} + INCLUDE_DIRECTORIES "." + RUNTIME_DEPENDENCIES "${RENDERDOC_PATH}/renderdoc.dll" + ) + + ly_add_external_target( + NAME renderdoc_api + VERSION + 3RDPARTY_ROOT_DIRECTORY ${RENDERDOC_PATH} + INCLUDE_DIRECTORIES "." + ) + endif() + endif() +endif() \ No newline at end of file diff --git a/Gems/Atom/RHI/Code/Source/Platform/Android/Atom_RHI_Traits_Android.h b/Gems/Atom/RHI/Code/Source/Platform/Android/Atom_RHI_Traits_Android.h new file mode 100644 index 0000000000..2f9b2b7c00 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Android/Atom_RHI_Traits_Android.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#define AZ_TRAIT_RENDERDOC_MODULE "libVkLayer_GLES_RenderDoc.so" diff --git a/Gems/Atom/RHI/Code/Source/Platform/Android/Atom_RHI_Traits_Platform.h b/Gems/Atom/RHI/Code/Source/Platform/Android/Atom_RHI_Traits_Platform.h new file mode 100644 index 0000000000..6af80df81e --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Android/Atom_RHI_Traits_Platform.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include "Atom_RHI_Traits_Android.h" diff --git a/Code/Framework/AzAutoGen/CMakeLists.txt b/Gems/Atom/RHI/Code/Source/Platform/Android/platform_android_files.cmake similarity index 66% rename from Code/Framework/AzAutoGen/CMakeLists.txt rename to Gems/Atom/RHI/Code/Source/Platform/Android/platform_android_files.cmake index 9338520570..167afec34d 100644 --- a/Code/Framework/AzAutoGen/CMakeLists.txt +++ b/Gems/Atom/RHI/Code/Source/Platform/Android/platform_android_files.cmake @@ -6,9 +6,7 @@ # # -ly_add_target( - NAME AzAutoGen HEADERONLY - NAMESPACE AZ - FILES_CMAKE - azautogen_files.cmake +set(FILES + Atom_RHI_Traits_Platform.h + Atom_RHI_Traits_Android.h ) diff --git a/Gems/Atom/RHI/Code/Source/Platform/Linux/Atom_RHI_Traits_Linux.h b/Gems/Atom/RHI/Code/Source/Platform/Linux/Atom_RHI_Traits_Linux.h new file mode 100644 index 0000000000..35219a5d57 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Linux/Atom_RHI_Traits_Linux.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#define AZ_TRAIT_RENDERDOC_MODULE "librenderdoc.so" diff --git a/Gems/Atom/RHI/Code/Source/Platform/Linux/Atom_RHI_Traits_Platform.h b/Gems/Atom/RHI/Code/Source/Platform/Linux/Atom_RHI_Traits_Platform.h new file mode 100644 index 0000000000..2c2c28a96f --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Linux/Atom_RHI_Traits_Platform.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include "Atom_RHI_Traits_Linux.h" diff --git a/Gems/Atom/RHI/Code/Source/Platform/Linux/platform_linux_files.cmake b/Gems/Atom/RHI/Code/Source/Platform/Linux/platform_linux_files.cmake new file mode 100644 index 0000000000..c31e71cd20 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Linux/platform_linux_files.cmake @@ -0,0 +1,12 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + Atom_RHI_Traits_Platform.h + Atom_RHI_Traits_Linux.h +) diff --git a/Gems/Atom/RHI/Code/Source/Platform/Mac/Atom_RHI_Traits_Mac.h b/Gems/Atom/RHI/Code/Source/Platform/Mac/Atom_RHI_Traits_Mac.h new file mode 100644 index 0000000000..03320d1dd8 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Mac/Atom_RHI_Traits_Mac.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once diff --git a/Gems/Atom/RHI/Code/Source/Platform/Mac/Atom_RHI_Traits_Platform.h b/Gems/Atom/RHI/Code/Source/Platform/Mac/Atom_RHI_Traits_Platform.h new file mode 100644 index 0000000000..ae990ab471 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Mac/Atom_RHI_Traits_Platform.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include "Atom_RHI_Traits_Mac.h" diff --git a/Code/Framework/AzAutoGen/azautogen_files.cmake b/Gems/Atom/RHI/Code/Source/Platform/Mac/platform_mac_files.cmake similarity index 79% rename from Code/Framework/AzAutoGen/azautogen_files.cmake rename to Gems/Atom/RHI/Code/Source/Platform/Mac/platform_mac_files.cmake index 9eb4460b5c..2d4ecd8b4f 100644 --- a/Code/Framework/AzAutoGen/azautogen_files.cmake +++ b/Gems/Atom/RHI/Code/Source/Platform/Mac/platform_mac_files.cmake @@ -7,5 +7,6 @@ # set(FILES - AzAutoGen.py + Atom_RHI_Traits_Platform.h + Atom_RHI_Traits_Mac.h ) diff --git a/Gems/Atom/RHI/Code/Source/Platform/Windows/Atom_RHI_Traits_Platform.h b/Gems/Atom/RHI/Code/Source/Platform/Windows/Atom_RHI_Traits_Platform.h new file mode 100644 index 0000000000..6e19903677 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Windows/Atom_RHI_Traits_Platform.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include "Atom_RHI_Traits_Windows.h" diff --git a/Gems/Atom/RHI/Code/Source/Platform/Windows/Atom_RHI_Traits_Windows.h b/Gems/Atom/RHI/Code/Source/Platform/Windows/Atom_RHI_Traits_Windows.h new file mode 100644 index 0000000000..82358784a3 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Windows/Atom_RHI_Traits_Windows.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#define AZ_TRAIT_RENDERDOC_MODULE "renderdoc.dll" diff --git a/Gems/Atom/RHI/Code/Source/Platform/Windows/platform_windows_files.cmake b/Gems/Atom/RHI/Code/Source/Platform/Windows/platform_windows_files.cmake new file mode 100644 index 0000000000..fc282d0163 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/Windows/platform_windows_files.cmake @@ -0,0 +1,12 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + Atom_RHI_Traits_Platform.h + Atom_RHI_Traits_Windows.h +) diff --git a/Gems/Atom/RHI/Code/Source/Platform/iOS/Atom_RHI_Traits_Platform.h b/Gems/Atom/RHI/Code/Source/Platform/iOS/Atom_RHI_Traits_Platform.h new file mode 100644 index 0000000000..c39f94db8b --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/iOS/Atom_RHI_Traits_Platform.h @@ -0,0 +1,10 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include "Atom_RHI_Traits_iOS.h" diff --git a/Gems/Atom/RHI/Code/Source/Platform/iOS/Atom_RHI_Traits_iOS.h b/Gems/Atom/RHI/Code/Source/Platform/iOS/Atom_RHI_Traits_iOS.h new file mode 100644 index 0000000000..03320d1dd8 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/iOS/Atom_RHI_Traits_iOS.h @@ -0,0 +1,8 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once diff --git a/Gems/Atom/RHI/Code/Source/Platform/iOS/platform_ios_files.cmake b/Gems/Atom/RHI/Code/Source/Platform/iOS/platform_ios_files.cmake new file mode 100644 index 0000000000..d487385fa6 --- /dev/null +++ b/Gems/Atom/RHI/Code/Source/Platform/iOS/platform_ios_files.cmake @@ -0,0 +1,12 @@ +# +# Copyright (c) Contributors to the Open 3D Engine Project. +# For complete copyright and license terms please see the LICENSE at the root of this distribution. +# +# SPDX-License-Identifier: Apache-2.0 OR MIT +# +# + +set(FILES + Atom_RHI_Traits_Platform.h + Atom_RHI_Traits_iOS.h +) diff --git a/Gems/Atom/RHI/Code/Source/RHI/Factory.cpp b/Gems/Atom/RHI/Code/Source/RHI/Factory.cpp index 974d63f88b..3162a71e34 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/Factory.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/Factory.cpp @@ -11,6 +11,16 @@ #include #include +#if defined(USE_RENDERDOC) +#include +#include +#include + +static AZStd::unique_ptr s_renderDocModule; +static RENDERDOC_API_1_1_2* s_renderDocApi = nullptr; +#endif + + namespace AZ { namespace RHI @@ -30,6 +40,48 @@ namespace AZ return AZ_CRC("RHIPlatformService", 0xfff2cea4); } + Factory::Factory() + { +#if defined(USE_RENDERDOC) + // If RenderDoc is requested, we need to load the library as early as possible (before device queries/factories are made) + bool enableRenderDoc = RHI::QueryCommandLineOption("enableRenderDoc"); + + if (enableRenderDoc && AZ_TRAIT_RENDERDOC_MODULE && !s_renderDocModule) + { + s_renderDocModule = DynamicModuleHandle::Create(AZ_TRAIT_RENDERDOC_MODULE); + if (s_renderDocModule) + { + if (s_renderDocModule->Load(false)) + { + pRENDERDOC_GetAPI renderDocGetAPI = s_renderDocModule->GetFunction("RENDERDOC_GetAPI"); + if (renderDocGetAPI) + { + if (!renderDocGetAPI(eRENDERDOC_API_Version_1_1_2, reinterpret_cast(&s_renderDocApi))) + { + s_renderDocApi = nullptr; + } + } + + if (s_renderDocApi) + { + // Prevent RenderDoc from handling any exceptions that may interfere with the O3DE exception handler + s_renderDocApi->UnloadCrashHandler(); + } + else + { + AZ_Printf("RHISystem", "RenderDoc module loaded but failed to retrieve API function pointer.\n"); + } + } + else + { + AZ_Printf("RHISystem", "RenderDoc module requested but module failed to load.\n"); + } + } + } +#endif // defined(USE_RENDERDOC) + + } + void Factory::Register(Factory* instance) { Interface::Register(instance); @@ -58,6 +110,13 @@ namespace AZ ResourceInvalidateBus::ClearQueuedEvents(); Interface::Unregister(instance); + +#if defined(USE_RENDERDOC) + if (s_renderDocModule) + { + s_renderDocModule->Unload(); + } +#endif } bool Factory::IsReady() @@ -71,5 +130,12 @@ namespace AZ AZ_Assert(factory, "RHI::Factory is not connected to a platform. Call IsReady() to get the status of the platform. A null de-reference is imminent."); return *factory; } + +#if defined(USE_RENDERDOC) + RENDERDOC_API_1_1_2* Factory::GetRenderDocAPI() + { + return s_renderDocApi; + } +#endif } } diff --git a/Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp b/Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp index 8df5e5b5be..bc4cde9406 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/RHIUtils.cpp @@ -122,5 +122,17 @@ namespace AZ } return commandLineValue; } + + bool QueryCommandLineOption(const AZStd::string& commandLineOption) + { + const AzFramework::CommandLine* commandLine = nullptr; + AzFramework::ApplicationRequests::Bus::BroadcastResult(commandLine, &AzFramework::ApplicationRequests::GetApplicationCommandLine); + + if (commandLine) + { + return commandLine->HasSwitch(commandLineOption); + } + return false; + } } } diff --git a/Gems/Atom/RPI/Assets/Materials/Default.materialtype b/Gems/Atom/RPI/Assets/Materials/Default.materialtype deleted file mode 100644 index e8e6ff24eb..0000000000 --- a/Gems/Atom/RPI/Assets/Materials/Default.materialtype +++ /dev/null @@ -1,90 +0,0 @@ -{ - "description": "A simple default base material used primarily for imported model files like FBX.", - "propertyLayout": { - "version": 1, - "properties": { - "general": [ - { - "id": "DiffuseColor", - "type": "color", - "defaultValue": [ 1.0, 1.0, 1.0 ], - "connection": { - "type": "shaderInput", - "id": "m_diffuseColor" - } - }, - { - "id": "DiffuseMap", - "type": "image", - "defaultValue": "", - "connection": { - "type": "shaderInput", - "id": "m_diffuseMap" - } - }, - { - "id": "UseDiffuseMap", - "type": "bool", - "defaultValue": false, - "connection": { - "type": "shaderOption", - "id": "o_useDiffuseMap" - } - }, - { - "id": "SpecularColor", - "type": "color", - "defaultValue": [ 0.0, 0.0, 0.0 ], - "connection": { - "type": "shaderInput", - "id": "m_specularColor" - } - }, - { - "id": "SpecularMap", - "type": "image", - "defaultValue": "", - "connection": { - "type": "shaderInput", - "id": "m_specularMap" - } - }, - { - "id": "UseSpecularMap", - "type": "bool", - "defaultValue": false, - "connection": { - "type": "shaderOption", - "id": "o_useSpecularMap" - } - }, - { - "id": "NormalMap", - "type": "image", - "defaultValue": "", - "connection": { - "type": "shaderInput", - "id": "m_normalMap" - } - }, - { - "id": "UseNormalMap", - "type": "bool", - "defaultValue": false, - "connection": { - "type": "shaderOption", - "id": "o_useNormalMap" - } - } - ] - } - }, - "shaders": [ - { - "file": "DefaultMaterial.shader" - }, - { - "file": "DefaultMaterial_DepthPass.shader" - } - ] -} diff --git a/Gems/Atom/RPI/Assets/Materials/DefaultMaterial.azsl b/Gems/Atom/RPI/Assets/Materials/DefaultMaterial.azsl deleted file mode 100644 index 6640ed3fca..0000000000 --- a/Gems/Atom/RPI/Assets/Materials/DefaultMaterial.azsl +++ /dev/null @@ -1,127 +0,0 @@ - -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include - -#include -#include -#include - -ShaderResourceGroup MaterialSrg : SRG_PerMaterial -{ - float4 m_diffuseColor; - float3 m_specularColor; - - Texture2D m_diffuseMap; - Texture2D m_normalMap; - Texture2D m_specularMap; - - Sampler m_sampler - { - MaxAnisotropy = 16; - AddressU = Wrap; - AddressV = Wrap; - AddressW = Wrap; - }; -} - -option bool o_useDiffuseMap = false; -option bool o_useSpecularMap = false; -option bool o_useNormalMap = false; - -struct VertexInput -{ - float3 m_position : POSITION; - float3 m_normal : NORMAL; - float4 m_tangent : TANGENT; - float3 m_bitangent : BITANGENT; - float2 m_uv : UV0; -}; - -struct VertexOutput -{ - float4 m_position : SV_Position; - float3 m_normal : NORMAL; - float3 m_tangent : TANGENT; - float3 m_bitangent : BITANGENT; - float2 m_uv : UV0; - float3 m_positionToCamera : VIEW; -}; - -VertexOutput MainVS(VertexInput input) -{ - const float4x4 objectToWorldMatrix = ObjectSrg::GetWorldMatrix(); - - VertexOutput output; - float3 worldPosition = mul(objectToWorldMatrix, float4(input.m_position,1)).xyz; - output.m_position = mul(ViewSrg::m_viewProjectionMatrix, float4(worldPosition, 1.0)); - - output.m_uv = input.m_uv; - - output.m_positionToCamera = ViewSrg::m_worldPosition - worldPosition; - - float3x3 objectToWorldMatrixIT = ObjectSrg::GetWorldMatrixInverseTranspose(); - - ConstructTBN(input.m_normal, input.m_tangent, input.m_bitangent, objectToWorldMatrix, objectToWorldMatrixIT, output.m_normal, output.m_tangent, output.m_bitangent); - - return output; -} - -struct PixelOutput -{ - float4 m_color : SV_Target0; -}; - -PixelOutput MainPS(VertexOutput input) -{ - PixelOutput output; - - // Very rough placeholder lighting - static const float3 lightDir = normalize(float3(1,1,1)); - - float4 baseColor = MaterialSrg::m_diffuseColor; - if (o_useDiffuseMap) - { - baseColor *= MaterialSrg::m_diffuseMap.Sample(MaterialSrg::m_sampler, input.m_uv); - } - - float3 specular = MaterialSrg::m_specularColor; - if (o_useSpecularMap) - { - specular *= MaterialSrg::m_specularMap.Sample(MaterialSrg::m_sampler, input.m_uv).rgb; - } - - float3 normal; - if (o_useNormalMap) - { - float4 sampledValue = MaterialSrg::m_normalMap.Sample(MaterialSrg::m_sampler, input.m_uv); - normal = GetWorldSpaceNormal(sampledValue.xy, input.m_normal, input.m_tangent, input.m_bitangent); - } - else - { - normal = normalize(input.m_normal); - } - - float3 viewDir = normalize(input.m_positionToCamera); - float3 H = normalize(lightDir + viewDir); - float NdotH = max(0.001, dot(normal, H)); - float NdotL = saturate(dot(normal, lightDir)); - - float3 diffuse = NdotL * baseColor.xyz; - - specular = pow(NdotH, 5.0) * specular; - - // Combined - float3 result = diffuse + specular + float3(0.1, 0.1, 0.1) * baseColor.xyz; - - output.m_color = float4(result.xyz, baseColor.a); - - return output; -} diff --git a/Gems/Atom/RPI/Assets/Materials/DefaultMaterial.shader b/Gems/Atom/RPI/Assets/Materials/DefaultMaterial.shader deleted file mode 100644 index ceea480f43..0000000000 --- a/Gems/Atom/RPI/Assets/Materials/DefaultMaterial.shader +++ /dev/null @@ -1,26 +0,0 @@ -{ - "Source" : "DefaultMaterial.azsl", - - "DepthStencilState" : { - "Depth" : { "Enable" : true, "CompareFunc" : "Equal" } - }, - - "DrawList" : "forward", - - "ProgramSettings": - { - "EntryPoints": - [ - { - "name": "MainVS", - "type": "Vertex" - }, - { - "name": "MainPS", - "type": "Fragment" - } - ] - } -} - - diff --git a/Gems/Atom/RPI/Assets/Materials/DefaultMaterial_DepthPass.azsl b/Gems/Atom/RPI/Assets/Materials/DefaultMaterial_DepthPass.azsl deleted file mode 100644 index 961fde7568..0000000000 --- a/Gems/Atom/RPI/Assets/Materials/DefaultMaterial_DepthPass.azsl +++ /dev/null @@ -1,33 +0,0 @@ - -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include - -#include - -struct VertexInput -{ - float3 m_position : POSITION; -}; - -struct VertexOutput -{ - float4 m_position : SV_Position; -}; - -VertexOutput MainVS(VertexInput input) -{ - const float4x4 objectToWorldMatrix = ObjectSrg::GetWorldMatrix(); - - VertexOutput output; - float3 worldPosition = mul(objectToWorldMatrix, float4(input.m_position,1)).xyz; - output.m_position = mul(ViewSrg::m_viewProjectionMatrix, float4(worldPosition, 1.0)); - return output; -} diff --git a/Gems/Atom/RPI/Assets/Materials/DefaultMaterial_DepthPass.shader b/Gems/Atom/RPI/Assets/Materials/DefaultMaterial_DepthPass.shader deleted file mode 100644 index 19ba1d5d9d..0000000000 --- a/Gems/Atom/RPI/Assets/Materials/DefaultMaterial_DepthPass.shader +++ /dev/null @@ -1,20 +0,0 @@ -{ - "Source" : "DefaultMaterial_DepthPass.azsl", - - "DepthStencilState" : { - "Depth" : { "Enable" : true, "CompareFunc" : "GreaterEqual" } - }, - - "DrawList" : "depth", - - "ProgramSettings": - { - "EntryPoints": - [ - { - "name": "MainVS", - "type": "Vertex" - } - ] - } -} diff --git a/Gems/Atom/RPI/Assets/atom_rpi_asset_files.cmake b/Gems/Atom/RPI/Assets/atom_rpi_asset_files.cmake index 8f85259f7d..9e89427a70 100644 --- a/Gems/Atom/RPI/Assets/atom_rpi_asset_files.cmake +++ b/Gems/Atom/RPI/Assets/atom_rpi_asset_files.cmake @@ -7,11 +7,6 @@ # set(FILES - Materials/Default.materialtype - Materials/DefaultMaterial.azsl - Materials/DefaultMaterial.shader - Materials/DefaultMaterial_DepthPass.azsl - Materials/DefaultMaterial_DepthPass.shader Shader/DecomposeMsImage.azsl Shader/DecomposeMsImage.shader Shader/ImagePreview.azsl diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/Model.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/Model.h index 32880a221c..a19c985f2d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/Model.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/Model.h @@ -90,8 +90,8 @@ namespace AZ private: Model() = default; - static Data::Instance CreateInternal(ModelAsset& modelAsset); - RHI::ResultCode Init(ModelAsset& modelAsset); + static Data::Instance CreateInternal(const Data::Asset& modelAsset); + RHI::ResultCode Init(const Data::Asset& modelAsset); AZStd::fixed_vector, ModelLodAsset::LodCountMax> m_lods; Data::Asset m_modelAsset; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/ModelLod.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/ModelLod.h index dcc4813b3d..0d0304a04e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/ModelLod.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/Model/ModelLod.h @@ -18,6 +18,7 @@ #include #include +#include #include #include @@ -72,6 +73,8 @@ namespace AZ RHI::IndexBufferView m_indexBufferView; StreamInfoList m_streamInfo; + + ModelMaterialSlot::StableId m_materialSlotStableId = ModelMaterialSlot::InvalidStableId; //! The default material assigned to the mesh by the asset. Data::Instance m_material; @@ -82,7 +85,7 @@ namespace AZ AZ_INSTANCE_DATA(ModelLod, "{3C796FC9-2067-4E0F-A660-269F8254D1D5}"); AZ_CLASS_ALLOCATOR(ModelLod, AZ::SystemAllocator, 0); - static Data::Instance FindOrCreate(const Data::Asset& lodAsset); + static Data::Instance FindOrCreate(const Data::Asset& lodAsset, const Data::Asset& modelAsset); ~ModelLod() = default; @@ -122,8 +125,8 @@ namespace AZ private: ModelLod() = default; - static Data::Instance CreateInternal(ModelLodAsset& lodAsset); - RHI::ResultCode Init(ModelLodAsset& lodAsset); + static Data::Instance CreateInternal(const Data::Asset& lodAsset, const AZStd::any* modelAssetAny); + RHI::ResultCode Init(const Data::Asset& lodAsset, const Data::Asset& modelAsset); bool SetMeshInstanceData( const ModelLodAsset::Mesh::StreamBufferInfo& streamBufferInfo, diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAsset.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAsset.h index b7414f73a2..dbcfc69d56 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAsset.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAsset.h @@ -49,6 +49,12 @@ namespace AZ //! Returns the model-space axis aligned bounding box const AZ::Aabb& GetAabb() const; + + //! Returns the list of all ModelMaterialSlot's for the model, across all LODs. + const ModelMaterialSlotMap& GetMaterialSlots() const; + + //! Find a material slot with the given stableId, or returns an invalid slot if it isn't found. + const ModelMaterialSlot& FindMaterialSlot(uint32_t stableId) const; //! Returns the number of Lods in the model size_t GetLodCount() const; @@ -97,6 +103,13 @@ namespace AZ volatile mutable bool m_isKdTreeCalculationRunning = false; mutable AZStd::mutex m_kdTreeLock; mutable AZStd::optional m_modelTriangleCount; + + // Lists all of the material slots that are used by this LOD. + // Note the same slot can appear in multiple LODs in the model, so that LODs don't have to refer back to the model asset. + ModelMaterialSlotMap m_materialSlots; + + // A default ModelMaterialSlot to be returned upon error conditions. + ModelMaterialSlot m_fallbackSlot; AZStd::size_t CalculateTriangleCount() const; }; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAssetCreator.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAssetCreator.h index 0b8cb678dc..d87ae1c57e 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAssetCreator.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelAssetCreator.h @@ -29,6 +29,10 @@ namespace AZ //! Assigns a name to the model void SetName(AZStd::string_view name); + + //! Adds a new material slot to the asset. + //! If a slot with the same stable ID already exists, it will be replaced. + void AddMaterialSlot(const ModelMaterialSlot& materialSlot); //! Adds a Lod to the model. void AddLodAsset(Data::Asset&& lodAsset); diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelLodAsset.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelLodAsset.h index 4e86b0e367..8c8edddfe1 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelLodAsset.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelLodAsset.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -84,8 +85,9 @@ namespace AZ //! Returns the number of indices in this mesh uint32_t GetIndexCount() const; - //! Returns the reference to material asset used by this mesh - const Data::Asset & GetMaterialAsset() const; + //! Returns the ID of the material slot used by this mesh. + //! This maps into the ModelAsset's material slot list. + ModelMaterialSlot::StableId GetMaterialSlotId() const; //! Returns the name of this mesh const AZ::Name& GetName() const; @@ -124,7 +126,9 @@ namespace AZ AZ::Name m_name; AZ::Aabb m_aabb = AZ::Aabb::CreateNull(); - Data::Asset m_materialAsset{ Data::AssetLoadBehavior::PreLoad }; + // Identifies the material slot that is used by this mesh. + // References material slot in the ModelAsset that owns this mesh; see ModelAsset::FindMaterialSlot(). + ModelMaterialSlot::StableId m_materialSlotId = ModelMaterialSlot::InvalidStableId; // Both the buffer in m_indexBufferAssetView and the buffers in m_streamBufferInfo // may point to either unique buffers for the mesh or to consolidated @@ -147,7 +151,7 @@ namespace AZ private: AZStd::vector m_meshes; AZ::Aabb m_aabb = AZ::Aabb::CreateNull(); - + // These buffers owned by the lod are the consolidated super buffers. // Meshes may either have views into these buffers or they may own // their own buffers. diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelLodAssetCreator.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelLodAssetCreator.h index c3291e5c73..776347cb2b 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelLodAssetCreator.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelLodAssetCreator.h @@ -8,6 +8,7 @@ #pragma once +#include #include #include @@ -45,9 +46,9 @@ namespace AZ //! Begin and BeginMesh must be called first. void SetMeshAabb(AZ::Aabb&& aabb); - //! Sets the material asset for the current SubMesh. + //! Sets the ID of the model's material slot that this mesh uses. //! Begin and BeginMesh must be called first - void SetMeshMaterialAsset(const Data::Asset& materialAsset); + void SetMeshMaterialSlot(ModelMaterialSlot::StableId id); //! Sets the given BufferAssetView to the current SubMesh as the index buffer. //! Begin and BeginMesh must be called first diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelMaterialSlot.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelMaterialSlot.h new file mode 100644 index 0000000000..dd46aca6cd --- /dev/null +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Reflect/Model/ModelMaterialSlot.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace AZ +{ + class ReflectContext; + + namespace RPI + { + //! Use by model assets to identify a logical material slot. + //! Each slot has a unique ID, a name, and a default material. Each mesh in model will reference a single ModelMaterialSlot. + //! Other classes like MeshFeatureProcessor and MaterialComponent can override the material associated with individual slots + //! to alter the default appearance of the mesh. + struct ModelMaterialSlot + { + AZ_TYPE_INFO(ModelMaterialSlot, "{0E88A62A-D83D-4C1B-8DE7-CE972B8124B5}"); + + static void Reflect(AZ::ReflectContext* context); + + using StableId = uint32_t; + static const StableId InvalidStableId; + + //! This ID must have a consistent value when the asset is reprocessed by the asset pipeline, and must be unique within the ModelLodAsset. + //! In practice, this set using the MaterialUid from SceneAPI. See ModelAssetBuilderComponent::CreateMesh. + StableId m_stableId = InvalidStableId; + + Name m_displayName; //!< The name of the slot as displayed to the user in UI. (Using Name instead of string for fast copies) + + Data::Asset m_defaultMaterialAsset{ Data::AssetLoadBehavior::PreLoad }; //!< The material that will be applied to this slot by default. + }; + + using ModelMaterialSlotMap = AZStd::unordered_map; + + } //namespace RPI +} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.cpp index c55eb947a1..7187cb391a 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/MaterialAssetBuilderComponent.cpp @@ -91,7 +91,7 @@ namespace AZ if (auto* serialize = azrtti_cast(context)) { serialize->Class() - ->Version(14); // [ATOM-13410] + ->Version(16); // Optional material conversion } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp index aa2ad37647..76e427a708 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.cpp @@ -109,7 +109,7 @@ namespace AZ if (auto* serialize = azrtti_cast(context)) { serialize->Class() - ->Version(27); // [ATOM-15658] + ->Version(30); // (updated to separate material slot ID from default material asset) } } @@ -367,6 +367,9 @@ namespace AZ MorphTargetMetaAssetCreator morphTargetMetaCreator; morphTargetMetaCreator.Begin(MorphTargetMetaAsset::ConstructAssetId(modelAssetId, modelAssetName)); + + ModelAssetCreator modelAssetCreator; + modelAssetCreator.Begin(modelAssetId); uint32_t lodIndex = 0; for (const SourceMeshContentList& sourceMeshContentList : sourceMeshContentListsByLod) @@ -429,7 +432,7 @@ namespace AZ for (const ProductMeshView& meshView : lodMeshViews) { - if (!CreateMesh(meshView, indexBuffer, streamBuffers, lodAssetCreator, context.m_materialsByUid)) + if (!CreateMesh(meshView, indexBuffer, streamBuffers, modelAssetCreator, lodAssetCreator, context.m_materialsByUid)) { return AZ::SceneAPI::Events::ProcessingResult::Failure; } @@ -469,10 +472,6 @@ namespace AZ } sourceMeshContentListsByLod.clear(); - // Build the final asset structure - ModelAssetCreator modelAssetCreator; - modelAssetCreator.Begin(modelAssetId); - // Finalize all LOD assets for (auto& lodAsset : lodAssets) { @@ -1796,6 +1795,7 @@ namespace AZ const ProductMeshView& meshView, const BufferAssetView& lodIndexBuffer, const AZStd::vector& lodStreamBuffers, + ModelAssetCreator& modelAssetCreator, ModelLodAssetCreator& lodAssetCreator, const MaterialAssetsByUid& materialAssetsByUid) { @@ -1806,8 +1806,13 @@ namespace AZ auto iter = materialAssetsByUid.find(meshView.m_materialUid); if (iter != materialAssetsByUid.end()) { - const Data::Asset& materialAsset = iter->second.m_asset; - lodAssetCreator.SetMeshMaterialAsset(materialAsset); + ModelMaterialSlot materialSlot; + materialSlot.m_stableId = meshView.m_materialUid; + materialSlot.m_displayName = iter->second.m_name; + materialSlot.m_defaultMaterialAsset = iter->second.m_asset; + + modelAssetCreator.AddMaterialSlot(materialSlot); + lodAssetCreator.SetMeshMaterialSlot(materialSlot.m_stableId); } } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.h b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.h index 79dec962df..843f756df6 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.h +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Model/ModelAssetBuilderComponent.h @@ -42,6 +42,7 @@ namespace AZ using SkinData = AZ::SceneAPI::DataTypes::ISkinWeightData; class Stream; + class ModelAssetCreator; class ModelLodAssetCreator; class BufferAssetCreator; struct PackedCompressedMorphTargetDelta; @@ -294,6 +295,7 @@ namespace AZ const ProductMeshView& meshView, const BufferAssetView& lodIndexBuffer, const AZStd::vector& lodStreamBuffers, + ModelAssetCreator& modelAssetCreator, ModelLodAssetCreator& lodAssetCreator, const MaterialAssetsByUid& materialAssetsByUid); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp index e684c4832a..32fe297c57 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/Model.cpp @@ -40,7 +40,7 @@ namespace AZ return m_lods; } - Data::Instance Model::CreateInternal(ModelAsset& modelAsset) + Data::Instance Model::CreateInternal(const Data::Asset& modelAsset) { AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); Data::Instance model = aznew Model(); @@ -54,15 +54,15 @@ namespace AZ return nullptr; } - RHI::ResultCode Model::Init(ModelAsset& modelAsset) + RHI::ResultCode Model::Init(const Data::Asset& modelAsset) { AZ_PROFILE_FUNCTION(Debug::ProfileCategory::AzRender); - m_lods.resize(modelAsset.GetLodAssets().size()); + m_lods.resize(modelAsset->GetLodAssets().size()); for (size_t lodIndex = 0; lodIndex < m_lods.size(); ++lodIndex) { - const Data::Asset& lodAsset = modelAsset.GetLodAssets()[lodIndex]; + const Data::Asset& lodAsset = modelAsset->GetLodAssets()[lodIndex]; if (!lodAsset) { @@ -70,7 +70,7 @@ namespace AZ return RHI::ResultCode::Fail; } - Data::Instance lodInstance = ModelLod::FindOrCreate(lodAsset); + Data::Instance lodInstance = ModelLod::FindOrCreate(lodAsset, modelAsset); if (lodInstance == nullptr) { return RHI::ResultCode::Fail; @@ -98,7 +98,7 @@ namespace AZ m_lods[lodIndex] = AZStd::move(lodInstance); } - m_modelAsset = { &modelAsset, AZ::Data::AssetLoadBehavior::PreLoad }; + m_modelAsset = modelAsset; m_isUploadPending = true; return RHI::ResultCode::Success; } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLod.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLod.cpp index b68930e4a3..dc39200a65 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLod.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelLod.cpp @@ -19,11 +19,14 @@ namespace AZ { namespace RPI { - Data::Instance ModelLod::FindOrCreate(const Data::Asset& lodAsset) + Data::Instance ModelLod::FindOrCreate(const Data::Asset& lodAsset, const Data::Asset& modelAsset) { + AZStd::any modelAssetAny{&modelAsset}; + return Data::InstanceDatabase::Instance().FindOrCreate( Data::InstanceId::CreateFromAssetId(lodAsset.GetId()), - lodAsset); + lodAsset, + &modelAssetAny); } AZStd::array_view ModelLod::GetMeshes() const @@ -31,10 +34,13 @@ namespace AZ return m_meshes; } - Data::Instance ModelLod::CreateInternal(ModelLodAsset& lodAsset) + Data::Instance ModelLod::CreateInternal(const Data::Asset& lodAsset, const AZStd::any* modelAssetAny) { + AZ_Assert(modelAssetAny != nullptr, "Invalid model asset param"); + auto modelAsset = AZStd::any_cast*>(*modelAssetAny); + Data::Instance lod = aznew ModelLod(); - const RHI::ResultCode resultCode = lod->Init(lodAsset); + const RHI::ResultCode resultCode = lod->Init(lodAsset, *modelAsset); if (resultCode == RHI::ResultCode::Success) { @@ -44,11 +50,11 @@ namespace AZ return nullptr; } - RHI::ResultCode ModelLod::Init(ModelLodAsset& lodAsset) + RHI::ResultCode ModelLod::Init(const Data::Asset& lodAsset, const Data::Asset& modelAsset) { AZ_TRACE_METHOD(); - for (const ModelLodAsset::Mesh& mesh : lodAsset.GetMeshes()) + for (const ModelLodAsset::Mesh& mesh : lodAsset->GetMeshes()) { Mesh meshInstance; @@ -100,10 +106,13 @@ namespace AZ } } - auto& materialAsset = mesh.GetMaterialAsset(); - if (materialAsset.IsReady()) + const ModelMaterialSlot& materialSlot = modelAsset->FindMaterialSlot(mesh.GetMaterialSlotId()); + + meshInstance.m_materialSlotStableId = materialSlot.m_stableId; + + if (materialSlot.m_defaultMaterialAsset.IsReady()) { - meshInstance.m_material = Material::FindOrCreate(materialAsset); + meshInstance.m_material = Material::FindOrCreate(materialSlot.m_defaultMaterialAsset); } m_meshes.emplace_back(AZStd::move(meshInstance)); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelSystem.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelSystem.cpp index 610f183eb1..1ed81f8e16 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelSystem.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Model/ModelSystem.cpp @@ -24,6 +24,7 @@ namespace AZ { ModelLodAsset::Reflect(context); ModelAsset::Reflect(context); + ModelMaterialSlot::Reflect(context); MorphTargetMetaAsset::Reflect(context); SkinMetaAsset::Reflect(context); } @@ -40,9 +41,9 @@ namespace AZ { //Create Lod Database AZ::Data::InstanceHandler lodInstanceHandler; - lodInstanceHandler.m_createFunction = [](Data::AssetData* modelLodAsset) + lodInstanceHandler.m_createFunctionWithParam = [](Data::AssetData* modelLodAsset, const AZStd::any* modelAsset) { - return ModelLod::CreateInternal(*(azrtti_cast(modelLodAsset))); + return ModelLod::CreateInternal(Data::Asset{modelLodAsset, AZ::Data::AssetLoadBehavior::PreLoad}, modelAsset); }; Data::InstanceDatabase::Create(azrtti_typeid(), lodInstanceHandler); @@ -50,7 +51,7 @@ namespace AZ AZ::Data::InstanceHandler modelInstanceHandler; modelInstanceHandler.m_createFunction = [](Data::AssetData* modelAsset) { - return Model::CreateInternal(*(azrtti_cast(modelAsset))); + return Model::CreateInternal(Data::Asset{modelAsset, AZ::Data::AssetLoadBehavior::PreLoad}); }; Data::InstanceDatabase::Create(azrtti_typeid(), modelInstanceHandler); } diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/PipelineState.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/PipelineState.cpp index ba9e6b20ed..8e0aa62554 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/PipelineState.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/PipelineState.cpp @@ -172,7 +172,7 @@ namespace AZ } m_pipelineState = m_shader->AcquirePipelineState(descriptor); - } + } m_dirty = false; } return m_pipelineState; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp index 083de10d47..275b056514 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAsset.cpp @@ -29,9 +29,10 @@ namespace AZ if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) + ->Version(1) ->Field("Name", &ModelAsset::m_name) ->Field("Aabb", &ModelAsset::m_aabb) + ->Field("MaterialSlots", &ModelAsset::m_materialSlots) ->Field("LodAssets", &ModelAsset::m_lodAssets) ; } @@ -56,6 +57,25 @@ namespace AZ { return m_aabb; } + + const ModelMaterialSlotMap& ModelAsset::GetMaterialSlots() const + { + return m_materialSlots; + } + + const ModelMaterialSlot& ModelAsset::FindMaterialSlot(uint32_t stableId) const + { + auto iter = m_materialSlots.find(stableId); + + if (iter == m_materialSlots.end()) + { + return m_fallbackSlot; + } + else + { + return iter->second; + } + } size_t ModelAsset::GetLodCount() const { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAssetCreator.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAssetCreator.cpp index 0c7a12fa8b..b35c9e44fe 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAssetCreator.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelAssetCreator.cpp @@ -29,6 +29,33 @@ namespace AZ m_asset->m_name = name; } } + + void ModelAssetCreator::AddMaterialSlot(const ModelMaterialSlot& materialSlot) + { + if (ValidateIsReady()) + { + auto iter = m_asset->m_materialSlots.find(materialSlot.m_stableId); + + if (iter == m_asset->m_materialSlots.end()) + { + m_asset->m_materialSlots[materialSlot.m_stableId] = materialSlot; + } + else + { + if (materialSlot.m_displayName != iter->second.m_displayName) + { + ReportWarning("Material slot %u was already added with a different name.", materialSlot.m_stableId); + } + + if (materialSlot.m_defaultMaterialAsset != iter->second.m_defaultMaterialAsset) + { + ReportWarning("Material slot %u was already added with a different default MaterialAsset.", materialSlot.m_stableId); + } + + iter->second = materialSlot; + } + } + } void ModelAssetCreator::AddLodAsset(Data::Asset&& lodAsset) { diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelLodAsset.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelLodAsset.cpp index 190e4c5315..ccf0d49b46 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelLodAsset.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelLodAsset.cpp @@ -31,16 +31,16 @@ namespace AZ Mesh::Reflect(context); } - + void ModelLodAsset::Mesh::Reflect(AZ::ReflectContext* context) { if (auto* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(0) - ->Field("Material", &ModelLodAsset::Mesh::m_materialAsset) + ->Version(1) ->Field("Name", &ModelLodAsset::Mesh::m_name) ->Field("AABB", &ModelLodAsset::Mesh::m_aabb) + ->Field("MaterialSlotId", &ModelLodAsset::Mesh::m_materialSlotId) ->Field("IndexBufferAssetView", &ModelLodAsset::Mesh::m_indexBufferAssetView) ->Field("StreamBufferInfo", &ModelLodAsset::Mesh::m_streamBufferInfo) ; @@ -75,9 +75,9 @@ namespace AZ return m_indexBufferAssetView.GetBufferViewDescriptor().m_elementCount; } - const Data::Asset & ModelLodAsset::Mesh::GetMaterialAsset() const + ModelMaterialSlot::StableId ModelLodAsset::Mesh::GetMaterialSlotId() const { - return m_materialAsset; + return m_materialSlotId; } const AZ::Name& ModelLodAsset::Mesh::GetName() const @@ -118,7 +118,7 @@ namespace AZ { return m_aabb; } - + const BufferAssetView* ModelLodAsset::Mesh::GetSemanticBufferAssetView(const AZ::Name& semantic) const { const AZStd::array_view& streamBufferList = GetStreamBufferInfoList(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelLodAssetCreator.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelLodAssetCreator.cpp index 6f17a5c590..f94116db70 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelLodAssetCreator.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelLodAssetCreator.cpp @@ -60,13 +60,15 @@ namespace AZ m_currentMesh.m_aabb = AZStd::move(aabb); } } - - void ModelLodAssetCreator::SetMeshMaterialAsset(const Data::Asset& materialAsset) + + void ModelLodAssetCreator::SetMeshMaterialSlot(ModelMaterialSlot::StableId id) { - if (ValidateIsMeshReady()) + if (!ValidateIsMeshReady()) { - m_currentMesh.m_materialAsset = materialAsset; + return; } + + m_currentMesh.m_materialSlotId = id; } void ModelLodAssetCreator::SetMeshIndexBuffer(const BufferAssetView& bufferAssetView) @@ -288,7 +290,8 @@ namespace AZ creator.SetMeshName(sourceMesh.GetName()); AZ::Aabb aabb = sourceMesh.GetAabb(); creator.SetMeshAabb(AZStd::move(aabb)); - creator.SetMeshMaterialAsset(sourceMesh.GetMaterialAsset()); + + creator.SetMeshMaterialSlot(sourceMesh.GetMaterialSlotId()); // Mesh index buffer view const BufferAssetView& sourceIndexBufferView = sourceMesh.GetIndexBufferAssetView(); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelMaterialSlot.cpp b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelMaterialSlot.cpp new file mode 100644 index 0000000000..0900949625 --- /dev/null +++ b/Gems/Atom/RPI/Code/Source/RPI.Reflect/Model/ModelMaterialSlot.cpp @@ -0,0 +1,34 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include + +namespace AZ +{ + namespace RPI + { + // Normally this would be defined in the header file and substituted by the compiler, but for + // some reason clang doesn't accept it. + const ModelMaterialSlot::StableId ModelMaterialSlot::InvalidStableId = -1; + + void ModelMaterialSlot::Reflect(AZ::ReflectContext* context) + { + if (auto* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(0) + ->Field("StableId", &ModelMaterialSlot::m_stableId) + ->Field("DisplayName", &ModelMaterialSlot::m_displayName) + ->Field("DefaultMaterialAsset", &ModelMaterialSlot::m_defaultMaterialAsset) + ; + } + } + + } // namespace RPI +} // namespace AZ diff --git a/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp b/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp index cdf0d0166d..368fb2c3c6 100644 --- a/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp +++ b/Gems/Atom/RPI/Code/Tests/Model/ModelTests.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include @@ -91,7 +92,7 @@ namespace UnitTest AZ::Aabb m_aabb = AZ::Aabb::CreateNull(); uint32_t m_indexCount = 0; uint32_t m_vertexCount = 0; - AZ::Data::Asset m_material; + AZ::RPI::ModelMaterialSlot::StableId m_materialSlotId = AZ::RPI::ModelMaterialSlot::InvalidStableId; }; struct ExpectedLod @@ -106,6 +107,18 @@ namespace UnitTest AZStd::vector m_lods; }; + void SetUp() override + { + RPITestFixture::SetUp(); + + auto assetId = AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0); + auto typeId = AZ::AzTypeInfo::Uuid(); + m_materialAsset = AZ::Data::Asset(assetId, typeId, ""); + + // Some tests attempt to serialize-in the model asset, which should not attempt to actually load this dummy asset reference. + m_materialAsset.SetAutoLoadBehavior(AZ::Data::AssetLoadBehaviorNamespace::NoLoad); + } + AZ::RHI::ShaderSemantic GetPositionSemantic() const { return AZ::RHI::ShaderSemantic(AZ::Name("POSITION")); @@ -136,6 +149,7 @@ namespace UnitTest return true; } + //! This function assumes the model has "sharedMeshCount + separateMeshCount" unique material slots, with incremental IDs starting at 0. AZ::Data::Asset BuildTestLod(const uint32_t sharedMeshCount, const uint32_t separateMeshCount, ExpectedLod& expectedLod) { using namespace AZ; @@ -148,6 +162,8 @@ namespace UnitTest const uint32_t indexCount = 36; const uint32_t vertexCount = 36; + RPI::ModelMaterialSlot::StableId materialSlotId = 0; + if(sharedMeshCount > 0) { const uint32_t sharedIndexCount = indexCount * sharedMeshCount; @@ -164,7 +180,7 @@ namespace UnitTest ExpectedMesh expectedMesh; expectedMesh.m_indexCount = indexCount; expectedMesh.m_vertexCount = vertexCount; - expectedMesh.m_material = m_materialAsset; + expectedMesh.m_materialSlotId = i; RHI::BufferViewDescriptor indexBufferViewDescriptor = RHI::BufferViewDescriptor::CreateStructured(i * indexCount, indexCount, sizeof(uint32_t)); @@ -180,7 +196,7 @@ namespace UnitTest creator.BeginMesh(); Aabb aabb = expectedMesh.m_aabb; creator.SetMeshAabb(AZStd::move(aabb)); - creator.SetMeshMaterialAsset(m_materialAsset); + creator.SetMeshMaterialSlot(materialSlotId++); creator.SetMeshIndexBuffer({ sharedIndexBuffer, indexBufferViewDescriptor }); creator.AddMeshStreamBuffer(GetPositionSemantic(), AZ::Name(), { sharedPositionBuffer, vertexBufferViewDescriptor }); creator.EndMesh(); @@ -195,7 +211,7 @@ namespace UnitTest ExpectedMesh expectedMesh; expectedMesh.m_indexCount = indexCount; expectedMesh.m_vertexCount = vertexCount; - expectedMesh.m_material = m_materialAsset; + expectedMesh.m_materialSlotId = sharedMeshCount + i; RHI::BufferViewDescriptor indexBufferViewDescriptor = RHI::BufferViewDescriptor::CreateStructured(0, indexCount, sizeof(uint32_t)); @@ -213,7 +229,7 @@ namespace UnitTest creator.BeginMesh(); Aabb aabb = expectedMesh.m_aabb; creator.SetMeshAabb(AZStd::move(aabb)); - creator.SetMeshMaterialAsset(m_materialAsset); + creator.SetMeshMaterialSlot(materialSlotId++); creator.SetMeshIndexBuffer({ BuildTestBuffer(indexCount, sizeof(uint32_t)), indexBufferViewDescriptor }); creator.AddMeshStreamBuffer(GetPositionSemantic(), AZ::Name(), { positonBuffer, positionBufferViewDescriptor }); @@ -239,6 +255,15 @@ namespace UnitTest creator.Begin(Data::AssetId(AZ::Uuid::CreateRandom())); creator.SetName("TestModel"); + + for (RPI::ModelMaterialSlot::StableId materialSlotId = 0; materialSlotId < sharedMeshCount + separateMeshCount; ++materialSlotId) + { + RPI::ModelMaterialSlot slot; + slot.m_defaultMaterialAsset = m_materialAsset; + slot.m_displayName = AZStd::string::format("Slot%d", materialSlotId); + slot.m_stableId = materialSlotId; + creator.AddMaterialSlot(slot); + } for (uint32_t i = 0; i < lodCount; ++i) { @@ -263,7 +288,7 @@ namespace UnitTest EXPECT_TRUE(mesh.GetAabb() == expectedMesh.m_aabb); EXPECT_TRUE(mesh.GetIndexCount() == expectedMesh.m_indexCount); EXPECT_TRUE(mesh.GetVertexCount() == expectedMesh.m_vertexCount); - EXPECT_TRUE(mesh.GetMaterialAsset() == expectedMesh.m_material); + EXPECT_TRUE(mesh.GetMaterialSlotId() == expectedMesh.m_materialSlotId); } void ValidateLodAsset(const AZ::RPI::ModelLodAsset* lodAsset, const ExpectedLod& expectedLod) @@ -299,9 +324,7 @@ namespace UnitTest } const uint32_t m_manyMesh = 100; // Not too much to hold up the tests but enough to stress them - AZ::Data::Asset m_materialAsset = - AZ::Data::Asset(AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0), - AZ::AzTypeInfo::Uuid(), ""); + AZ::Data::Asset m_materialAsset; }; @@ -687,11 +710,11 @@ namespace UnitTest } } - // Tests that if we try to set the material id on a mesh + // Tests that if we try to set the material slot on a mesh // without calling Begin or BeginMesh that it fails // as expected. Also tests the case that Begin *is* // called but BeginMesh is not. - TEST_F(ModelTests, SetMaterialIdNoBeginNoBeginMesh) + TEST_F(ModelTests, SetMaterialSlotNoBeginNoBeginMesh) { using namespace AZ; @@ -699,7 +722,7 @@ namespace UnitTest { ErrorMessageFinder messageFinder("Begin() was not called"); - creator.SetMeshMaterialAsset(m_materialAsset); + creator.SetMeshMaterialSlot(0); } creator.Begin(Data::AssetId(AZ::Uuid::CreateRandom())); @@ -707,7 +730,7 @@ namespace UnitTest //This should still fail even if we call Begin but not BeginMesh { ErrorMessageFinder messageFinder("BeginMesh() was not called"); - creator.SetMeshMaterialAsset(m_materialAsset); + creator.SetMeshMaterialSlot(0); } } @@ -827,7 +850,7 @@ namespace UnitTest creator.BeginMesh(); creator.SetMeshAabb(AZStd::move(aabb)); - creator.SetMeshMaterialAsset(m_materialAsset); + creator.SetMeshMaterialSlot(0); creator.SetMeshIndexBuffer({ BuildTestBuffer(indexCount, sizeof(uint32_t)), indexBufferViewDescriptor }); creator.AddMeshStreamBuffer(GetPositionSemantic(), AZ::Name(), { BuildTestBuffer(vertexCount, sizeof(float) * 3), vertexBufferViewDescriptor }); @@ -842,7 +865,7 @@ namespace UnitTest ErrorMessageFinder messageFinder("BeginMesh() was not called", 5); creator.SetMeshAabb(AZStd::move(aabb)); - creator.SetMeshMaterialAsset(m_materialAsset); + creator.SetMeshMaterialSlot(0); creator.SetMeshIndexBuffer({ BuildTestBuffer(indexCount, sizeof(uint32_t)), indexBufferViewDescriptor }); creator.AddMeshStreamBuffer(GetPositionSemantic(), AZ::Name(), { BuildTestBuffer(vertexCount, sizeof(float) * 3), vertexBufferViewDescriptor }); @@ -885,7 +908,7 @@ namespace UnitTest creator.BeginMesh(); creator.SetMeshAabb(AZStd::move(aabb)); - creator.SetMeshMaterialAsset(m_materialAsset); + creator.SetMeshMaterialSlot(0); creator.SetMeshIndexBuffer({ BuildTestBuffer(indexCount, sizeof(uint32_t)), indexBufferViewDescriptor }); creator.AddMeshStreamBuffer(GetPositionSemantic(), AZ::Name(), { BuildTestBuffer(vertexCount, sizeof(float) * 3), vertexBufferViewDescriptor }); @@ -907,7 +930,7 @@ namespace UnitTest creator.BeginMesh(); creator.SetMeshAabb(AZStd::move(aabb)); - creator.SetMeshMaterialAsset(m_materialAsset); + creator.SetMeshMaterialSlot(0); creator.SetMeshIndexBuffer({ BuildTestBuffer(indexCount, sizeof(uint32_t)), indexBufferViewDescriptor }); creator.AddMeshStreamBuffer(GetPositionSemantic(), AZ::Name(), { BuildTestBuffer(vertexCount, sizeof(float) * 3), vertexBufferViewDescriptor }); @@ -1019,10 +1042,7 @@ namespace UnitTest lodCreator.BeginMesh(); lodCreator.SetMeshAabb(AZ::Aabb::CreateFromMinMax({-1.0f, -1.0f, -0.5f}, {1.0f, 1.0f, 0.5f})); - lodCreator.SetMeshMaterialAsset( - AZ::Data::Asset(AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0), - AZ::AzTypeInfo::Uuid(), "") - ); + lodCreator.SetMeshMaterialSlot(AZ::Sfmt::GetInstance().Rand32()); { AZ::Data::Asset indexBuffer = BuildTestBuffer(indicesCount, sizeof(uint32_t)); diff --git a/Gems/Atom/RPI/Code/atom_rpi_reflect_files.cmake b/Gems/Atom/RPI/Code/atom_rpi_reflect_files.cmake index c049837045..49c7231fed 100644 --- a/Gems/Atom/RPI/Code/atom_rpi_reflect_files.cmake +++ b/Gems/Atom/RPI/Code/atom_rpi_reflect_files.cmake @@ -22,6 +22,7 @@ set(FILES Include/Atom/RPI.Reflect/Model/ModelKdTree.h Include/Atom/RPI.Reflect/Model/ModelLodAsset.h Include/Atom/RPI.Reflect/Model/ModelLodIndex.h + Include/Atom/RPI.Reflect/Model/ModelMaterialSlot.h Include/Atom/RPI.Reflect/Model/ModelAssetCreator.h Include/Atom/RPI.Reflect/Model/ModelLodAssetCreator.h Include/Atom/RPI.Reflect/Model/MorphTargetDelta.h @@ -106,6 +107,7 @@ set(FILES Source/RPI.Reflect/Model/ModelLodAsset.cpp Source/RPI.Reflect/Model/ModelAssetCreator.cpp Source/RPI.Reflect/Model/ModelLodAssetCreator.cpp + Source/RPI.Reflect/Model/ModelMaterialSlot.cpp Source/RPI.Reflect/Model/MorphTargetDelta.cpp Source/RPI.Reflect/Model/MorphTargetMetaAsset.cpp Source/RPI.Reflect/Model/MorphTargetMetaAssetCreator.cpp diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h index 1d2ccc07e1..d8778a9b9d 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h @@ -16,18 +16,21 @@ namespace AtomToolsFramework { - class ModernViewportCameraControllerInstance; + class ModularViewportCameraControllerInstance; + + //! Builder class to create and configure a ModularViewportCameraControllerInstance. class ModularViewportCameraController : public AzFramework::MultiViewportController< - ModernViewportCameraControllerInstance, AzFramework::ViewportControllerPriority::DispatchToAllPriorities> + ModularViewportCameraControllerInstance, + AzFramework::ViewportControllerPriority::DispatchToAllPriorities> { public: using CameraListBuilder = AZStd::function; using CameraPropsBuilder = AZStd::function; - //! Sets the camera list builder callback used to populate new ModernViewportCameraControllerInstances + //! Sets the camera list builder callback used to populate new ModularViewportCameraControllerInstances void SetCameraListBuilderCallback(const CameraListBuilder& builder); - //! Sets the camera props builder callback used to populate new ModernViewportCameraControllerInstances + //! Sets the camera props builder callback used to populate new ModularViewportCameraControllerInstances void SetCameraPropsBuilderCallback(const CameraPropsBuilder& builder); //! Sets up a camera list based on this controller's CameraListBuilderCallback void SetupCameras(AzFramework::Cameras& cameras); @@ -35,18 +38,22 @@ namespace AtomToolsFramework void SetupCameraProperies(AzFramework::CameraProps& cameraProps); private: + //! Builder to generate a list of CameraInputs to run in the ModularViewportCameraControllerInstance. CameraListBuilder m_cameraListBuilder; - CameraPropsBuilder m_cameraPropsBuilder; + CameraPropsBuilder m_cameraPropsBuilder; //!< Builder to define custom camera properties to use for things such as rotate and + //!< translate interpolation. }; - class ModernViewportCameraControllerInstance final - : public AzFramework::MultiViewportControllerInstanceInterface, - public ModularViewportCameraControllerRequestBus::Handler, - private AzFramework::ViewportDebugDisplayEventBus::Handler + //! A customizable camera controller that can be configured to run a varying set of CameraInput instances. + //! The controller can also be animated from its current transform to a new translation and orientation. + class ModularViewportCameraControllerInstance final + : public AzFramework::MultiViewportControllerInstanceInterface + , public ModularViewportCameraControllerRequestBus::Handler + , private AzFramework::ViewportDebugDisplayEventBus::Handler { public: - explicit ModernViewportCameraControllerInstance(AzFramework::ViewportId viewportId, ModularViewportCameraController* controller); - ~ModernViewportCameraControllerInstance() override; + explicit ModularViewportCameraControllerInstance(AzFramework::ViewportId viewportId, ModularViewportCameraController* controller); + ~ModularViewportCameraControllerInstance() override; // MultiViewportControllerInstanceInterface overrides ... bool HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) override; @@ -60,25 +67,34 @@ namespace AtomToolsFramework // AzFramework::ViewportDebugDisplayEventBus overrides ... void DisplayViewport(const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) override; + //! The current mode the camera controller is in. enum class CameraMode { - Control, - Animation + Control, //!< The camera is being driven by user input. + Animation //!< The camera is being animated (interpolated) from one transform to another. }; - AzFramework::Camera m_camera; - AzFramework::Camera m_targetCamera; - AzFramework::CameraSystem m_cameraSystem; - AzFramework::CameraProps m_cameraProps; + //! Encapsulates an animation (interpolation) between two transforms. + struct CameraAnimation + { + //! The transform of the camera at the start of the animation. + AZ::Transform m_transformStart = AZ::Transform::CreateIdentity(); + AZ::Transform m_transformEnd = AZ::Transform::CreateIdentity(); //!< The transform of the camera at the end of the animation. + float m_time = 0.0f; //!< The interpolation amount between the start and end transforms (in the range 0.0 - 1.0). + }; - AZ::Transform m_transformStart = AZ::Transform::CreateIdentity(); - AZ::Transform m_transformEnd = AZ::Transform::CreateIdentity(); - float m_animationT = 0.0f; - CameraMode m_cameraMode = CameraMode::Control; + AzFramework::Camera m_camera; //!< The current camera state (pitch/yaw/position/look-distance). + AzFramework::Camera m_targetCamera; //!< The target (next) camera state that m_camera is catching up to. + AzFramework::CameraSystem m_cameraSystem; //!< The camera system responsible for managing all CameraInputs. + AzFramework::CameraProps m_cameraProps; //!< Camera properties to control rotate and translate smoothness. + + CameraAnimation m_cameraAnimation; //!< Camera animation state (used during CameraMode::Animation). + CameraMode m_cameraMode = CameraMode::Control; //!< The current mode the camera is operating in. AZStd::optional m_lookAtAfterInterpolation; //!< The look at point after an interpolation has finished. //!< Will be cleared when the view changes (camera looks away). - bool m_updatingTransform = false; - + //! Flag to prevent circular updates of the camera transform (while the viewport transform is being updated internally). + bool m_updatingTransformInternally = false; + //! Listen for camera view changes outside of the camera controller. AZ::RPI::ViewportContext::MatrixChangedEvent::Handler m_cameraViewMatrixChangeHandler; }; } // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp index 10cfa059aa..cc87ba1e46 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/ModularViewportCameraController.cpp @@ -84,7 +84,7 @@ namespace AtomToolsFramework } } - ModernViewportCameraControllerInstance::ModernViewportCameraControllerInstance( + ModularViewportCameraControllerInstance::ModularViewportCameraControllerInstance( const AzFramework::ViewportId viewportId, ModularViewportCameraController* controller) : MultiViewportControllerInstanceInterface(viewportId, controller) { @@ -95,7 +95,8 @@ namespace AtomToolsFramework { auto handleCameraChange = [this, viewportContext](const AZ::Matrix4x4&) { - if (!m_updatingTransform) + // ignore these updates if the camera is being updated internally + if (!m_updatingTransformInternally) { UpdateCameraFromTransform(m_targetCamera, viewportContext->GetCameraTransform()); m_camera = m_targetCamera; @@ -111,7 +112,7 @@ namespace AtomToolsFramework ModularViewportCameraControllerRequestBus::Handler::BusConnect(viewportId); } - ModernViewportCameraControllerInstance::~ModernViewportCameraControllerInstance() + ModularViewportCameraControllerInstance::~ModularViewportCameraControllerInstance() { ModularViewportCameraControllerRequestBus::Handler::BusDisconnect(); AzFramework::ViewportDebugDisplayEventBus::Handler::BusDisconnect(); @@ -132,7 +133,7 @@ namespace AtomToolsFramework return AzFramework::ViewportControllerPriority::Normal; } - bool ModernViewportCameraControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) + bool ModularViewportCameraControllerInstance::HandleInputChannelEvent(const AzFramework::ViewportControllerInputEvent& event) { if (event.m_priority == GetPriority(m_cameraSystem)) { @@ -142,7 +143,7 @@ namespace AtomToolsFramework return false; } - void ModernViewportCameraControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) + void ModularViewportCameraControllerInstance::UpdateViewport(const AzFramework::ViewportControllerUpdateEvent& event) { // only update for a single priority (normal is the default) if (event.m_priority != AzFramework::ViewportControllerPriority::Normal) @@ -152,7 +153,7 @@ namespace AtomToolsFramework if (auto viewportContext = RetrieveViewportContext(GetViewportId())) { - m_updatingTransform = true; + m_updatingTransformInternally = true; if (m_cameraMode == CameraMode::Control) { @@ -180,10 +181,12 @@ namespace AtomToolsFramework return t * t * t * (t * (t * 6.0f - 15.0f) + 10.0f); }; - const float transitionT = smootherStepFn(m_animationT); + const auto& [transformStart, transformEnd, animationTime] = m_cameraAnimation; + + const float transitionTime = smootherStepFn(animationTime); const AZ::Transform current = AZ::Transform::CreateFromQuaternionAndTranslation( - m_transformStart.GetRotation().Slerp(m_transformEnd.GetRotation(), transitionT), - m_transformStart.GetTranslation().Lerp(m_transformEnd.GetTranslation(), transitionT)); + transformStart.GetRotation().Slerp(transformEnd.GetRotation(), transitionTime), + transformStart.GetTranslation().Lerp(transformEnd.GetTranslation(), transitionTime)); const AZ::Vector3 eulerAngles = AzFramework::EulerAngles(AZ::Matrix3x3::CreateFromTransform(current)); m_camera.m_pitch = eulerAngles.GetX(); @@ -191,21 +194,21 @@ namespace AtomToolsFramework m_camera.m_lookAt = current.GetTranslation(); m_targetCamera = m_camera; - if (m_animationT >= 1.0f) + if (animationTime >= 1.0f) { m_cameraMode = CameraMode::Control; } - m_animationT = AZ::GetClamp(m_animationT + event.m_deltaTime.count(), 0.0f, 1.0f); + m_cameraAnimation.m_time = AZ::GetClamp(animationTime + event.m_deltaTime.count(), 0.0f, 1.0f); viewportContext->SetCameraTransform(current); } - m_updatingTransform = false; + m_updatingTransformInternally = false; } } - void ModernViewportCameraControllerInstance::DisplayViewport( + void ModularViewportCameraControllerInstance::DisplayViewport( [[maybe_unused]] const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { if (const float alpha = AZStd::min(-m_camera.m_lookDist / 5.0f, 1.0f); alpha > AZ::Constants::FloatEpsilon) @@ -216,16 +219,14 @@ namespace AtomToolsFramework } } - void ModernViewportCameraControllerInstance::InterpolateToTransform(const AZ::Transform& worldFromLocal, const float lookAtDistance) + void ModularViewportCameraControllerInstance::InterpolateToTransform(const AZ::Transform& worldFromLocal, const float lookAtDistance) { - m_animationT = 0.0f; m_cameraMode = CameraMode::Animation; - m_transformStart = m_camera.Transform(); - m_transformEnd = worldFromLocal; - m_lookAtAfterInterpolation = m_transformEnd.GetTranslation() + m_transformEnd.GetBasisY() * lookAtDistance; + m_cameraAnimation = CameraAnimation{ m_camera.Transform(), worldFromLocal, 0.0f }; + m_lookAtAfterInterpolation = worldFromLocal.GetTranslation() + worldFromLocal.GetBasisY() * lookAtDistance; } - AZStd::optional ModernViewportCameraControllerInstance::LookAtAfterInterpolation() const + AZStd::optional ModularViewportCameraControllerInstance::LookAtAfterInterpolation() const { return m_lookAtAfterInterpolation; } diff --git a/Gems/AtomLyIntegration/AtomBridge/Assets/Shaders/LyShineUI.azsl b/Gems/AtomLyIntegration/AtomBridge/Assets/Shaders/LyShineUI.azsl index 85b2dcc509..b5c0ffa068 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Assets/Shaders/LyShineUI.azsl +++ b/Gems/AtomLyIntegration/AtomBridge/Assets/Shaders/LyShineUI.azsl @@ -10,9 +10,6 @@ #include -// Indicates whether to use pre-multiplied alpha -option bool o_preMultiplyAlpha; - // If true pixels with an alpha value of less than 0.5 are clipped option bool o_alphaTest; @@ -86,9 +83,9 @@ struct PSOutput float4 m_color : SV_Target0; }; -float4 SampleTriangleTexture(int texIndex, float2 uv) +float4 SampleTriangleTexture(uint texIndex, float2 uv) { - if ((InstanceSrg::m_isClamp & (1 << texIndex)) != 0) + if ((InstanceSrg::m_isClamp & (1U << texIndex)) != 0) { return InstanceSrg::m_texture[texIndex].Sample(InstanceSrg::m_clampSampler, uv); } @@ -120,14 +117,6 @@ PSOutput MainPS(VSOutput IN) resColor.xyz = LinearToSRGB(resColor.xyz); } - // Check for flag to premultiply alpha - if (o_preMultiplyAlpha) - { - // premultiply the color by the alpha. This would not be required if we had full access to the separate alpha blend mode - float preMult = resColor.w; - resColor.xyz *= preMult; - } - // If the o_modulate option is not None it means that the verts have two texture indicies. The second texture is used to // mask the first. This is used for gradient masks. if (o_modulate == Modulate::Alpha) diff --git a/Gems/AtomLyIntegration/AtomBridge/Assets/Shaders/LyShineUI.shadervariantlist b/Gems/AtomLyIntegration/AtomBridge/Assets/Shaders/LyShineUI.shadervariantlist index c7eddb10f2..56f71e72f5 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Assets/Shaders/LyShineUI.shadervariantlist +++ b/Gems/AtomLyIntegration/AtomBridge/Assets/Shaders/LyShineUI.shadervariantlist @@ -4,7 +4,6 @@ { "StableId": 1, "Options": { - "o_preMultiplyAlpha": "false", "o_alphaTest": "false", "o_srgbWrite": "true", "o_modulate": "Modulate::None" @@ -13,11 +12,26 @@ { "StableId": 2, "Options": { - "o_preMultiplyAlpha": "false", - "o_alphaTest": "true", - "o_srgbWrite": "true", + "o_alphaTest": "false", + "o_srgbWrite": "false", "o_modulate": "Modulate::None" } + }, + { + "StableId": 3, + "Options": { + "o_alphaTest": "true", + "o_srgbWrite": "false", + "o_modulate": "Modulate::None" + } + }, + { + "StableId": 4, + "Options": { + "o_alphaTest": "false", + "o_srgbWrite": "false", + "o_modulate": "Modulate::Alpha" + } } ] } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h index 6b637a67c5..234ea99066 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/Material/MaterialComponentBus.h @@ -74,6 +74,10 @@ namespace AZ //! Get material assignment id matching lod and label substring virtual MaterialAssignmentId FindMaterialAssignmentId( const MaterialAssignmentLodIndex lod, const AZStd::string& label) const = 0; + + //! Returns the list of all ModelMaterialSlot's for the model, across all LODs. + virtual RPI::ModelMaterialSlotMap GetModelMaterialSlots() const = 0; + virtual MaterialAssignmentMap GetMaterialAssignments() const = 0; virtual AZStd::unordered_set GetModelUvNames() const = 0; }; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp index d7dc4335b3..a4e058561e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponent.cpp @@ -17,6 +17,7 @@ #include #include #include +#include AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include @@ -44,64 +45,15 @@ namespace AZ if (classElement.GetVersion() < 3) { - // The default material was changed from an asset to an EditorMaterialComponentSlot and old data must be converted - constexpr AZ::u32 defaultMaterialAssetDataCrc = AZ_CRC("defaultMaterialAsset", 0x736fc071); - - Data::Asset oldDefaultMaterialData; - if (!classElement.GetChildData(defaultMaterialAssetDataCrc, oldDefaultMaterialData)) - { - AZ_Error("AZ::Render::EditorMaterialComponent::ConvertVersion", false, "Failed to get defaultMaterialAsset element"); - return false; - } - - if (!classElement.RemoveElementByName(defaultMaterialAssetDataCrc)) - { - AZ_Error("AZ::Render::EditorMaterialComponent::ConvertVersion", false, "Failed to remove defaultMaterialAsset element"); - return false; - } - - EditorMaterialComponentSlot newDefaultMaterialData; - newDefaultMaterialData.m_id = DefaultMaterialAssignmentId; - newDefaultMaterialData.m_materialAsset = oldDefaultMaterialData; - classElement.AddElementWithData(context, "defaultMaterialSlot", newDefaultMaterialData); - - // Slots now support and display the default material asset when empty - // The old placeholder assignments are irrelevant and must be cleared - constexpr AZ::u32 materialSlotsByLodDataCrc = AZ_CRC("materialSlotsByLod", 0xb1498db6); - - EditorMaterialComponentSlotsByLodContainer lodSlotData; - if (!classElement.GetChildData(materialSlotsByLodDataCrc, lodSlotData)) - { - AZ_Error("AZ::Render::EditorMaterialComponent::ConvertVersion", false, "Failed to get materialSlotsByLod element"); - return false; - } - - if (!classElement.RemoveElementByName(materialSlotsByLodDataCrc)) - { - AZ_Error("AZ::Render::EditorMaterialComponent::ConvertVersion", false, "Failed to remove materialSlotsByLod element"); - return false; - } - - // Find and clear all slots that are assigned to the slot's default value - for (auto& lodSlots : lodSlotData) - { - for (auto& slot : lodSlots) - { - if (slot.m_materialAsset.GetId() == slot.m_id.m_materialAssetId) - { - slot.m_materialAsset = {}; - } - } - } - - classElement.AddElementWithData(context, "materialSlotsByLod", lodSlotData); + AZ_Error("EditorMaterialComponent", false, "Material Component version < 3 is no longer supported"); + return false; } if (classElement.GetVersion() < 4) { classElement.AddElementWithData(context, "materialSlotsByLodEnabled", true); } - + return true; } @@ -238,7 +190,7 @@ namespace AZ for (auto& materialSlotPair : GetMaterialSlots()) { EditorMaterialComponentSlot* materialSlot = materialSlotPair.second; - if (materialSlot->m_id.IsAssetOnly()) + if (materialSlot->m_id.IsSlotIdOnly()) { materialSlot->Clear(); } @@ -251,7 +203,7 @@ namespace AZ for (auto& materialSlotPair : GetMaterialSlots()) { EditorMaterialComponentSlot* materialSlot = materialSlotPair.second; - if (materialSlot->m_id.IsLodAndAsset()) + if (materialSlot->m_id.IsLodAndSlotId()) { materialSlot->Clear(); } @@ -318,7 +270,7 @@ namespace AZ // Build the controller configuration from the editor configuration MaterialComponentConfig config = m_controller.GetConfiguration(); config.m_materials.clear(); - + for (const auto& materialSlotPair : GetMaterialSlots()) { const EditorMaterialComponentSlot* materialSlot = materialSlotPair.second; @@ -341,7 +293,7 @@ namespace AZ else if (!materialSlot->m_propertyOverrides.empty() || !materialSlot->m_matModUvOverrides.empty()) { MaterialAssignment& materialAssignment = config.m_materials[materialSlot->m_id]; - materialAssignment.m_materialAsset.Create(materialSlot->m_id.m_materialAssetId); + materialAssignment.m_materialAsset = materialSlot->m_defaultMaterialAsset; materialAssignment.m_propertyOverrides = materialSlot->m_propertyOverrides; materialAssignment.m_matModUvOverrides = materialSlot->m_matModUvOverrides; } @@ -362,6 +314,9 @@ namespace AZ // Get the known material assignment slots from the associated model or other source MaterialAssignmentMap materialsFromSource; MaterialReceiverRequestBus::EventResult(materialsFromSource, GetEntityId(), &MaterialReceiverRequestBus::Events::GetMaterialAssignments); + + RPI::ModelMaterialSlotMap modelMaterialSlots; + MaterialReceiverRequestBus::EventResult(modelMaterialSlots, GetEntityId(), &MaterialReceiverRequestBus::Events::GetModelMaterialSlots); // Generate the table of editable materials using the source data to define number of groups, elements, and initial values for (const auto& materialPair : materialsFromSource) @@ -385,9 +340,33 @@ namespace AZ OnConfigurationChanged(); }; + const char* UnknownSlotName = ""; + + // If this is the default material assignment ID then it represents the default slot which is not contained in any other group + if (slot.m_id == DefaultMaterialAssignmentId) + { + slot.m_label = "Default Material"; + } + else + { + auto slotIter = modelMaterialSlots.find(slot.m_id.m_materialSlotStableId); + if (slotIter != modelMaterialSlots.end()) + { + const Name& displayName = slotIter->second.m_displayName; + slot.m_label = !displayName.IsEmpty() ? displayName.GetStringView() : UnknownSlotName; + + slot.m_defaultMaterialAsset = slotIter->second.m_defaultMaterialAsset; + } + else + { + slot.m_label = UnknownSlotName; + } + } + // if material is present in controller configuration, assign its data const MaterialAssignment& materialFromController = GetMaterialAssignmentFromMap(config.m_materials, slot.m_id); slot.m_materialAsset = materialFromController.m_materialAsset; + slot.m_propertyOverrides = materialFromController.m_propertyOverrides; slot.m_matModUvOverrides = materialFromController.m_matModUvOverrides; @@ -400,13 +379,13 @@ namespace AZ continue; } - if (slot.m_id.IsAssetOnly()) + if (slot.m_id.IsSlotIdOnly()) { m_materialSlots.push_back(slot); continue; } - if (slot.m_id.IsLodAndAsset()) + if (slot.m_id.IsLodAndSlotId()) { // Resize the containers to fit all elements m_materialSlotsByLod.resize(AZ::GetMax(m_materialSlotsByLod.size(), aznumeric_cast(slot.m_id.m_lodIndex + 1))); @@ -452,27 +431,26 @@ namespace AZ { AzToolsFramework::ScopedUndoBatch undoBatch("Generating materials."); SetDirty(); - + // First generating a unique set of all material asset IDs that will be used for source data generation - AZStd::unordered_set assetIds; + AZStd::unordered_map assetIdMap; auto materialSlots = GetMaterialSlots(); for (auto& materialSlotPair : materialSlots) { - EditorMaterialComponentSlot* materialSlot = materialSlotPair.second; - if (materialSlot->m_id.m_materialAssetId.IsValid()) + Data::AssetId defaultMaterialAssetId = materialSlotPair.second->m_defaultMaterialAsset.GetId(); + if (defaultMaterialAssetId.IsValid()) { - assetIds.insert(materialSlot->m_id.m_materialAssetId); + assetIdMap[defaultMaterialAssetId] = materialSlotPair.second->GetLabel(); } } // Convert the unique set of asset IDs into export items that can be configured in the dialog // The order should not matter because the table in the dialog can sort itself for a specific row EditorMaterialComponentExporter::ExportItemsContainer exportItems; - for (const AZ::Data::AssetId& assetId : assetIds) + for (auto assetIdInfo : assetIdMap) { - EditorMaterialComponentExporter::ExportItem exportItem; - exportItem.m_assetId = assetId; + EditorMaterialComponentExporter::ExportItem exportItem{assetIdInfo.first, assetIdInfo.second}; exportItems.push_back(exportItem); } @@ -486,15 +464,20 @@ namespace AZ continue; } - const auto& assetIdOutcome = AZ::RPI::AssetUtils::MakeAssetId(exportItem.m_exportPath, 0); + const auto& assetIdOutcome = AZ::RPI::AssetUtils::MakeAssetId(exportItem.GetExportPath(), 0); if (assetIdOutcome) { for (auto& materialSlotPair : materialSlots) { - EditorMaterialComponentSlot* materialSlot = materialSlotPair.second; - if (materialSlot && materialSlot->m_id.m_materialAssetId == exportItem.m_assetId) + EditorMaterialComponentSlot* editorMaterialSlot = materialSlotPair.second; + + if (editorMaterialSlot) { - materialSlot->m_materialAsset.Create(assetIdOutcome.GetValue()); + // We need to check whether replaced material corresponds to this slot's default material. + if (editorMaterialSlot->m_defaultMaterialAsset.GetId() == exportItem.GetOriginalAssetId()) + { + editorMaterialSlot->m_materialAsset.Create(assetIdOutcome.GetValue()); + } } } } @@ -582,3 +565,4 @@ namespace AZ } } // namespace Render } // namespace AZ + diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.cpp index bde500bdc5..32a36392a4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.cpp @@ -37,47 +37,7 @@ namespace AZ { namespace EditorMaterialComponentExporter { - AZStd::string GetLabelByAssetId(const AZ::Data::AssetId& assetId) - { - AZStd::string label; - if (assetId.IsValid()) - { - // Material assets that are exported through the scene pipeline have their filenames generated by adding - // the DCC material name as a prefix and a unique number to the end of the source file name. - // Rather than storing the DCC material name inside of the material asset we can reproduce it by removing - // the prefix and suffix from the product file name. - - // We need the material product path as the initial string that will be stripped down - const AZStd::string& productPath = AZ::RPI::AssetUtils::GetProductPathByAssetId(assetId); - if (!productPath.empty() && AzFramework::StringFunc::Path::GetFileName(productPath.c_str(), label)) - { - // If there is a source file, typically an FBX or other model file, we must get its filename to remove the prefix from the label - AZStd::string prefix; - const AZStd::string& sourcePath = AZ::RPI::AssetUtils::GetSourcePathByAssetId(assetId); - if (!sourcePath.empty() && AZ::StringFunc::Path::GetFileName(sourcePath.c_str(), prefix)) - { - if (!prefix.empty() && prefix.size() < label.size()) - { - if (AZ::StringFunc::StartsWith(label, prefix, false)) - { - // All of the product filename's tokens are separated by underscores so we must also remove the first underscore after the prefix - label = label.substr(prefix.size() + 1); - } - } - } - - // We can remove the numeric suffix by stripping the label of everything after the last underscore - const auto iter = label.find_last_of("_"); - if (iter != AZStd::string::npos) - { - label = label.substr(0, iter); - } - } - } - return label; - } - - AZStd::string GetExportPathByAssetId(const AZ::Data::AssetId& assetId) + AZStd::string GetExportPathByAssetId(const AZ::Data::AssetId& assetId, const AZStd::string& materialSlotName) { AZStd::string exportPath; if (assetId.IsValid()) @@ -85,7 +45,7 @@ namespace AZ exportPath = AZ::RPI::AssetUtils::GetSourcePathByAssetId(assetId); AZ::StringFunc::Path::StripExtension(exportPath); exportPath += "_"; - exportPath += GetLabelByAssetId(assetId); + exportPath += materialSlotName; exportPath += "."; exportPath += AZ::RPI::MaterialSourceData::Extension; AZ::StringFunc::Path::Normalize(exportPath); @@ -132,12 +92,12 @@ namespace AZ int row = 0; for (ExportItem& exportItem : exportItems) { - QFileInfo fileInfo(GetExportPathByAssetId(exportItem.m_assetId).c_str()); + QFileInfo fileInfo(GetExportPathByAssetId(exportItem.GetOriginalAssetId(), exportItem.GetMaterialSlotName()).c_str()); // Configuring initial settings based on whether or not the target file already exists - exportItem.m_exportPath = fileInfo.absoluteFilePath().toUtf8().constData(); - exportItem.m_exists = fileInfo.exists(); - exportItem.m_overwrite = false; + exportItem.SetExportPath(fileInfo.absoluteFilePath().toUtf8().constData()); + exportItem.SetExists(fileInfo.exists()); + exportItem.SetOverwrite(false); // Populate the table with data for every column tableWidget->setItem(row, MaterialSlotColumn, new QTableWidgetItem()); @@ -146,23 +106,23 @@ namespace AZ // Create a check box for toggling the enabled state of this item QCheckBox* materialSlotCheckBox = new QCheckBox(tableWidget); - materialSlotCheckBox->setChecked(exportItem.m_enabled); - materialSlotCheckBox->setText(GetLabelByAssetId(exportItem.m_assetId).c_str()); + materialSlotCheckBox->setChecked(exportItem.GetEnabled()); + materialSlotCheckBox->setText(exportItem.GetMaterialSlotName().c_str()); tableWidget->setCellWidget(row, MaterialSlotColumn, materialSlotCheckBox); // Create a file picker widget for selecting the save path for the exported material AzQtComponents::BrowseEdit* materialFileWidget = new AzQtComponents::BrowseEdit(tableWidget); materialFileWidget->setLineEditReadOnly(true); materialFileWidget->setClearButtonEnabled(false); - materialFileWidget->setEnabled(exportItem.m_enabled); + materialFileWidget->setEnabled(exportItem.GetEnabled()); materialFileWidget->setText(fileInfo.fileName()); tableWidget->setCellWidget(row, MaterialFileColumn, materialFileWidget); // Create a check box for toggling the overwrite state of this item QWidget* overwriteCheckBoxContainer = new QWidget(tableWidget); QCheckBox* overwriteCheckBox = new QCheckBox(overwriteCheckBoxContainer); - overwriteCheckBox->setChecked(exportItem.m_overwrite); - overwriteCheckBox->setEnabled(exportItem.m_enabled && exportItem.m_exists); + overwriteCheckBox->setChecked(exportItem.GetOverwrite()); + overwriteCheckBox->setEnabled(exportItem.GetEnabled() && exportItem.GetExists()); overwriteCheckBoxContainer->setLayout(new QHBoxLayout(overwriteCheckBoxContainer)); overwriteCheckBoxContainer->layout()->addWidget(overwriteCheckBox); @@ -173,21 +133,21 @@ namespace AZ // Whenever the selection is updated, automatically apply the change to the export item QObject::connect(materialSlotCheckBox, &QCheckBox::stateChanged, materialSlotCheckBox, [&exportItem, materialFileWidget, materialSlotCheckBox, overwriteCheckBox]([[maybe_unused]] int state) { - exportItem.m_enabled = materialSlotCheckBox->isChecked(); - materialFileWidget->setEnabled(exportItem.m_enabled); - overwriteCheckBox->setEnabled(exportItem.m_enabled && exportItem.m_exists); + exportItem.SetEnabled(materialSlotCheckBox->isChecked()); + materialFileWidget->setEnabled(exportItem.GetEnabled()); + overwriteCheckBox->setEnabled(exportItem.GetEnabled() && exportItem.GetExists()); }); // Whenever the overwrite check box is updated, automatically apply the change to the export item QObject::connect(overwriteCheckBox, &QCheckBox::stateChanged, overwriteCheckBox, [&exportItem, overwriteCheckBox]([[maybe_unused]] int state) { - exportItem.m_overwrite = overwriteCheckBox->isChecked(); + exportItem.SetOverwrite(overwriteCheckBox->isChecked()); }); // Whenever the browse button is clicked, open a save file dialog in the same location as the current export file setting QObject::connect(materialFileWidget, &AzQtComponents::BrowseEdit::attachedButtonTriggered, materialFileWidget, [&dialog, &exportItem, materialFileWidget, overwriteCheckBox]() { QFileInfo fileInfo = QFileDialog::getSaveFileName(&dialog, QString("Select Material Filename"), - exportItem.m_exportPath.c_str(), + exportItem.GetExportPath().c_str(), QString("Material (*.material)"), nullptr, QFileDialog::DontConfirmOverwrite); @@ -195,14 +155,14 @@ namespace AZ // Only update the export data if a valid path and filename was selected if (!fileInfo.absoluteFilePath().isEmpty()) { - exportItem.m_exportPath = fileInfo.absoluteFilePath().toUtf8().constData(); - exportItem.m_exists = fileInfo.exists(); - exportItem.m_overwrite = fileInfo.exists(); + exportItem.SetExportPath(fileInfo.absoluteFilePath().toUtf8().constData()); + exportItem.SetExists(fileInfo.exists()); + exportItem.SetOverwrite(fileInfo.exists()); // Update the controls to display the new state materialFileWidget->setText(fileInfo.fileName()); - overwriteCheckBox->setChecked(exportItem.m_overwrite); - overwriteCheckBox->setEnabled(exportItem.m_enabled && exportItem.m_exists); + overwriteCheckBox->setChecked(exportItem.GetOverwrite()); + overwriteCheckBox->setEnabled(exportItem.GetEnabled() && exportItem.GetExists()); } }); @@ -245,24 +205,24 @@ namespace AZ bool ExportMaterialSourceData(const ExportItem& exportItem) { - if (!exportItem.m_enabled || exportItem.m_exportPath.empty()) + if (!exportItem.GetEnabled() || exportItem.GetExportPath().empty()) { return false; } - if (exportItem.m_exists && !exportItem.m_overwrite) + if (exportItem.GetExists() && !exportItem.GetOverwrite()) { return true; } EditorMaterialComponentUtil::MaterialEditData editData; - if (!EditorMaterialComponentUtil::LoadMaterialEditDataFromAssetId(exportItem.m_assetId, editData)) + if (!EditorMaterialComponentUtil::LoadMaterialEditDataFromAssetId(exportItem.GetOriginalAssetId(), editData)) { AZ_Warning("AZ::Render::EditorMaterialComponentExporter", false, "Failed to load material data."); return false; } - if (!EditorMaterialComponentUtil::SaveSourceMaterialFromEditData(exportItem.m_exportPath, editData)) + if (!EditorMaterialComponentUtil::SaveSourceMaterialFromEditData(exportItem.GetExportPath(), editData)) { AZ_Warning("AZ::Render::EditorMaterialComponentExporter", false, "Failed to save material data."); return false; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.h index 00bef9ee66..4830db33c4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentExporter.h @@ -19,27 +19,48 @@ namespace AZ { namespace EditorMaterialComponentExporter { - // Attemts to generate a display label for a material slot by parsing its file name - AZStd::string GetLabelByAssetId(const AZ::Data::AssetId& assetId); + //! Generates a destination file path for exporting material source data + AZStd::string GetExportPathByAssetId(const AZ::Data::AssetId& assetId, const AZStd::string& materialSlotName); - // Generates a destination file path for exporting material source data - AZStd::string GetExportPathByAssetId(const AZ::Data::AssetId& assetId); - - struct ExportItem + class ExportItem { + public: + //! @param originalAssetId AssetId of the original built-in material, which will be exported. + //! @param materialSlotName The name of the material slot will be used as part of the exported file name. + ExportItem(AZ::Data::AssetId originalAssetId, const AZStd::string& materialSlotName) + : m_originalAssetId(originalAssetId) + , m_materialSlotName(materialSlotName) + {} + + void SetEnabled(bool enabled) { m_enabled = enabled; } + void SetExists(bool exists) { m_exists = exists; } + void SetOverwrite(bool overwrite) { m_overwrite = overwrite; } + void SetExportPath(const AZStd::string& exportPath) { m_exportPath = exportPath; } + + bool GetEnabled() const { return m_enabled; } + bool GetExists() const { return m_exists; } + bool GetOverwrite() const { return m_overwrite; } + const AZStd::string& GetExportPath() const { return m_exportPath; } + + AZ::Data::AssetId GetOriginalAssetId() const { return m_originalAssetId; } + const AZStd::string& GetMaterialSlotName() const { return m_materialSlotName; } + + private: bool m_enabled = true; bool m_exists = false; bool m_overwrite = false; - AZ::Data::AssetId m_assetId; AZStd::string m_exportPath; + AZ::Data::AssetId m_originalAssetId; //!< AssetId of the original built-in material, which will be exported. + AZStd::string m_materialSlotName; }; using ExportItemsContainer = AZStd::vector; - // Generates and opens a dialog for configuring material data export paths and actions + //! Generates and opens a dialog for configuring material data export paths and actions. + //! Note this will not modify the m_originalAssetId field in each ExportItem. bool OpenExportDialog(ExportItemsContainer& exportItems); - // Attemts to construct and save material source data from a product asset + //! Attemts to construct and save material source data from a product asset bool ExportMaterialSourceData(const ExportItem& exportItem); } // namespace EditorMaterialComponentExporter } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp index d341bbb290..39dde65a99 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.cpp @@ -20,7 +20,7 @@ AZ_PUSH_DISABLE_WARNING(4251 4800, "-Wunknown-warning-option") // disable warnings spawned by QT #include -#include +#include #include AZ_POP_DISABLE_WARNING @@ -48,7 +48,7 @@ namespace AZ return false; } - const MaterialAssignmentId newId(oldId.first, oldId.second); + const MaterialAssignmentId newId(oldId.first, oldId.second.m_subId); classElement.AddElementWithData(context, "id", newId); } @@ -80,9 +80,10 @@ namespace AZ if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) { serializeContext->Class() - ->Version(5, &EditorMaterialComponentSlot::ConvertVersion) + ->Version(6, &EditorMaterialComponentSlot::ConvertVersion) ->Field("id", &EditorMaterialComponentSlot::m_id) ->Field("materialAsset", &EditorMaterialComponentSlot::m_materialAsset) + ->Field("defaultMaterialAsset", &EditorMaterialComponentSlot::m_defaultMaterialAsset) ; if (AZ::EditContext* editContext = serializeContext->GetEditContext()) @@ -121,21 +122,12 @@ namespace AZ AZ::Data::AssetId EditorMaterialComponentSlot::GetDefaultAssetId() const { - return m_id.m_materialAssetId; + return m_defaultMaterialAsset.GetId(); } AZStd::string EditorMaterialComponentSlot::GetLabel() const { - // Generate the label for the material slot based on the assignment ID - // If this is the default material assignment ID then it represents the default slot which is not contained in any other group - if (m_id == DefaultMaterialAssignmentId) - { - return "Default Material"; - } - - // Otherwise the label can be generated by parsing the source file name associated with the asset ID - const AZStd::string& label = EditorMaterialComponentExporter::GetLabelByAssetId(m_id.m_materialAssetId); - return !label.empty() ? label : ""; + return m_label; } bool EditorMaterialComponentSlot::HasSourceData() const @@ -183,27 +175,21 @@ namespace AZ OnMaterialChanged(); } - void EditorMaterialComponentSlot::SetDefaultAsset() + void EditorMaterialComponentSlot::ResetToDefaultAsset() { - m_materialAsset = {}; + m_materialAsset = m_defaultMaterialAsset; m_propertyOverrides = {}; m_matModUvOverrides = {}; - if (m_id.m_materialAssetId.IsValid()) - { - // If no material is assigned to this slot, assign the default material from the slot id to edit its properties - m_materialAsset.Create(m_id.m_materialAssetId); - } OnMaterialChanged(); } void EditorMaterialComponentSlot::OpenMaterialExporter() { // Because we are generating a source material from this specific slot there is only one entry - // But we still need to allow the user to reconfigure it using the dialogue + // But we still need to allow the user to reconfigure it using the dialog EditorMaterialComponentExporter::ExportItemsContainer exportItems; { - EditorMaterialComponentExporter::ExportItem exportItem; - exportItem.m_assetId = m_id.m_materialAssetId; + EditorMaterialComponentExporter::ExportItem exportItem{m_defaultMaterialAsset.GetId(), m_label}; exportItems.push_back(exportItem); } @@ -218,7 +204,7 @@ namespace AZ } // Generate a new asset ID utilizing the export file path so that we can update this material slot to reference the new asset - const auto& assetIdOutcome = AZ::RPI::AssetUtils::MakeAssetId(exportItem.m_exportPath, 0); + const auto& assetIdOutcome = AZ::RPI::AssetUtils::MakeAssetId(exportItem.GetExportPath(), 0); if (assetIdOutcome) { m_materialAsset.Create(assetIdOutcome.GetValue()); @@ -258,7 +244,7 @@ namespace AZ // Treated as a special property. It will be updated together with properties. OnPropertyChanged(); }; - + if (m_materialAsset.GetId().IsValid()) { if (EditorMaterialComponentInspector::OpenInspectorDialog(m_materialAsset.GetId(), m_matModUvOverrides, m_modelUvNames, applyMatModUvOverrideChangedCallback)) @@ -275,7 +261,7 @@ namespace AZ QAction* action = nullptr; action = menu.addAction("Generate/Manage Source Material...", [this]() { OpenMaterialExporter(); }); - action->setEnabled(m_id.m_materialAssetId.IsValid()); + action->setEnabled(m_defaultMaterialAsset.GetId().IsValid()); menu.addSeparator(); diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h index e8b4f46854..79fddf2611 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/EditorMaterialComponentSlot.h @@ -34,7 +34,7 @@ namespace AZ AZStd::string GetLabel() const; bool HasSourceData() const; void OpenMaterialEditor() const; - void SetDefaultAsset(); + void ResetToDefaultAsset(); void Clear(); void ClearOverrides(); void OpenMaterialExporter(); @@ -42,7 +42,9 @@ namespace AZ void OpenUvNameMapInspector(); MaterialAssignmentId m_id; + AZStd::string m_label; Data::Asset m_materialAsset; + Data::Asset m_defaultMaterialAsset; MaterialPropertyOverrideMap m_propertyOverrides; AZStd::function m_materialChangedCallback; AZStd::function m_propertyChangedCallback; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentConfig.cpp index a0adcd3187..f7b7177e29 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentConfig.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Material/MaterialComponentConfig.cpp @@ -44,7 +44,7 @@ namespace AZ for (const auto& oldPair : oldMaterials) { const DeprecatedMaterialAssignmentId& oldId = oldPair.first; - const MaterialAssignmentId newId(oldId.first, oldId.second); + const MaterialAssignmentId newId(oldId.first, oldId.second.m_subId); newMaterials[newId] = oldPair.second; } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp index fa4586daba..cf548e965a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.cpp @@ -251,6 +251,19 @@ namespace AZ m_meshFeatureProcessor->SetTransform(m_meshHandle, m_transformInterface->GetWorldTM(), m_cachedNonUniformScale); } } + + RPI::ModelMaterialSlotMap MeshComponentController::GetModelMaterialSlots() const + { + Data::Asset modelAsset = GetModelAsset(); + if (modelAsset.IsReady()) + { + return modelAsset->GetMaterialSlots(); + } + else + { + return {}; + } + } MaterialAssignmentId MeshComponentController::FindMaterialAssignmentId( const MaterialAssignmentLodIndex lod, const AZStd::string& label) const diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.h index d99d5000eb..63dba83fef 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/Mesh/MeshComponentController.h @@ -113,6 +113,7 @@ namespace AZ // MaterialReceiverRequestBus::Handler overrides ... virtual MaterialAssignmentId FindMaterialAssignmentId( const MaterialAssignmentLodIndex lod, const AZStd::string& label) const override; + RPI::ModelMaterialSlotMap GetModelMaterialSlots() const override; MaterialAssignmentMap GetMaterialAssignments() const override; AZStd::unordered_set GetModelUvNames() const override; diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp index 3143191135..feabdb9510 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/ActorAsset.cpp @@ -96,12 +96,11 @@ namespace AZ skinnedSubMesh.m_vertexCount = aznumeric_cast(subMeshVertexCount); lodVertexCount += aznumeric_cast(subMeshVertexCount); - // The default material id used by a sub-mesh is the guid of the source scene file plus the subId which is a unique material ID from the scene API - AZ::u32 subId = modelMesh.GetMaterialAsset().GetId().m_subId; - AZ::Data::AssetId materialId{ actorAssetId.m_guid, subId }; + skinnedSubMesh.m_materialSlot = actor->GetMeshAsset()->FindMaterialSlot(modelMesh.GetMaterialSlotId()); // Queue the material asset - the ModelLod seems to handle delayed material loads - skinnedSubMesh.m_material = Data::AssetManager::Instance().GetAsset(materialId, azrtti_typeid(), skinnedSubMesh.m_material.GetAutoLoadBehavior()); + skinnedSubMesh.m_materialSlot.m_defaultMaterialAsset.QueueLoad(); + subMeshes.push_back(skinnedSubMesh); } else diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp index 706ed27a4d..2711ce2f76 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.cpp @@ -307,6 +307,19 @@ namespace AZ m_meshFeatureProcessor = nullptr; m_skinnedMeshFeatureProcessor = nullptr; } + + RPI::ModelMaterialSlotMap AtomActorInstance::GetModelMaterialSlots() const + { + Data::Asset modelAsset = GetModelAsset(); + if (modelAsset.IsReady()) + { + return modelAsset->GetMaterialSlots(); + } + else + { + return {}; + } + } MaterialAssignmentId AtomActorInstance::FindMaterialAssignmentId( const MaterialAssignmentLodIndex lod, const AZStd::string& label) const @@ -501,16 +514,18 @@ namespace AZ const AZStd::vector< SkinnedSubMeshProperties>& subMeshProperties = inputLod.GetSubMeshProperties(); for (const SkinnedSubMeshProperties& submesh : subMeshProperties) { - AZ_Error("AtomActorInstance", submesh.m_material, "Actor does not have a valid default material in lod %d", lodIndex); - if (submesh.m_material) + Data::Asset materialAsset = submesh.m_materialSlot.m_defaultMaterialAsset; + AZ_Error("AtomActorInstance", materialAsset, "Actor does not have a valid default material in lod %d", lodIndex); + + if (materialAsset) { - if (!submesh.m_material->IsReady()) + if (!materialAsset->IsReady()) { // Start listening for the material's OnAssetReady event. // AtomActorInstance::Create is called on the main thread, so there should be no need to synchronize with the OnAssetReady event handler // since those events will also come from the main thread - m_waitForMaterialLoadIds.insert(submesh.m_material->GetId()); - Data::AssetBus::MultiHandler::BusConnect(submesh.m_material->GetId()); + m_waitForMaterialLoadIds.insert(materialAsset->GetId()); + Data::AssetBus::MultiHandler::BusConnect(materialAsset->GetId()); } } } diff --git a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h index 1686b52d1a..b3e1a8a989 100644 --- a/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h +++ b/Gems/AtomLyIntegration/EMotionFXAtom/Code/Source/AtomActorInstance.h @@ -122,6 +122,7 @@ namespace AZ // MaterialReceiverRequestBus::Handler overrides... virtual MaterialAssignmentId FindMaterialAssignmentId( const MaterialAssignmentLodIndex lod, const AZStd::string& label) const override; + RPI::ModelMaterialSlotMap GetModelMaterialSlots() const override; MaterialAssignmentMap GetMaterialAssignments() const override; AZStd::unordered_set GetModelUvNames() const override; diff --git a/Gems/Blast/Code/Source/Asset/BlastChunksAsset.cpp b/Gems/Blast/Code/Source/Asset/BlastChunksAsset.cpp new file mode 100644 index 0000000000..1d0ce15241 --- /dev/null +++ b/Gems/Blast/Code/Source/Asset/BlastChunksAsset.cpp @@ -0,0 +1,33 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +namespace Blast +{ + void BlastChunksAsset::SetModelAssetIds(const AZStd::vector& modelAssetIds) + { + m_modelAssetIds = modelAssetIds; + } + + const AZStd::vector& BlastChunksAsset::GetModelAssetIds() const + { + return m_modelAssetIds; + } + + void BlastChunksAsset::Reflect(AZ::ReflectContext* context) + { + if (auto serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1) + ->Field("modelAssetIds", &BlastChunksAsset::m_modelAssetIds); + } + } + +} // namespace Blast diff --git a/Gems/Blast/Code/Source/Asset/BlastChunksAsset.h b/Gems/Blast/Code/Source/Asset/BlastChunksAsset.h new file mode 100644 index 0000000000..1f6442d8fd --- /dev/null +++ b/Gems/Blast/Code/Source/Asset/BlastChunksAsset.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include + +namespace Blast +{ + //! The product asset file from a .blast_chunks file product asset file + class BlastChunksAsset final + : public AZ::Data::AssetData + { + public: + AZ_RTTI(BlastChunksAsset, "{993F0B0F-37D9-48C6-9CC2-E27D3F3E343E}", AZ::Data::AssetData); + AZ_CLASS_ALLOCATOR(BlastChunksAsset, AZ::SystemAllocator, 0); + + BlastChunksAsset() = default; + ~BlastChunksAsset() override = default; + + void SetModelAssetIds(const AZStd::vector& modelAssetIds); + const AZStd::vector& GetModelAssetIds() const; + + static void Reflect(AZ::ReflectContext* context); + + private: + AZStd::vector m_modelAssetIds; + }; +} // namespace Blast diff --git a/Gems/Blast/Code/Source/Asset/BlastSliceAsset.cpp b/Gems/Blast/Code/Source/Asset/BlastSliceAsset.cpp deleted file mode 100644 index acb3043c19..0000000000 --- a/Gems/Blast/Code/Source/Asset/BlastSliceAsset.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include - -namespace Blast -{ - void BlastSliceAsset::SetMeshIdList(const AZStd::vector& meshAssetIdList) - { - m_meshAssetIdList = meshAssetIdList; - } - - const AZStd::vector& BlastSliceAsset::GetMeshIdList() const - { - return m_meshAssetIdList; - } - - void BlastSliceAsset::SetMaterialId(const AZ::Data::AssetId& materialAssetId) - { - m_materialAssetId = materialAssetId; - } - - const AZ::Data::AssetId& BlastSliceAsset::GetMaterialId() const - { - return m_materialAssetId; - } - - void BlastSliceAsset::Reflect(AZ::ReflectContext* context) - { - if (auto serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1) - ->Field("meshAssetIdList", &BlastSliceAsset::m_meshAssetIdList) - ->Field("materialAssetId", &BlastSliceAsset::m_materialAssetId); - } - - if (AZ::BehaviorContext* behavior = azrtti_cast(context)) - { - behavior->Class("BlastSliceAsset") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) - ->Attribute(AZ::Script::Attributes::Module, "blast") - ->Method("SetMeshIdList", &BlastSliceAsset::SetMeshIdList) - ->Method("GetMeshIdList", &BlastSliceAsset::GetMeshIdList) - ->Method("SetMaterialId", &BlastSliceAsset::SetMaterialId) - ->Method("GetMaterialId", &BlastSliceAsset::GetMaterialId) - ->Method( - "GetAssetTypeId", - [](BlastSliceAsset*) - { - return azrtti_typeid(); - }); - } - } - -} // namespace Blast diff --git a/Gems/Blast/Code/Source/Asset/BlastSliceAsset.h b/Gems/Blast/Code/Source/Asset/BlastSliceAsset.h deleted file mode 100644 index cab51791cd..0000000000 --- a/Gems/Blast/Code/Source/Asset/BlastSliceAsset.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include - -namespace Blast -{ - //! The product asset file from a .blast_slice file product asset file - class BlastSliceAsset final : public AZ::Data::AssetData - { - public: - AZ_RTTI(BlastSliceAsset, "{D04AAF07-EB12-4E50-8964-114A9B9C1FD1}", AZ::Data::AssetData); - AZ_CLASS_ALLOCATOR(BlastSliceAsset, AZ::SystemAllocator, 0); - - BlastSliceAsset() = default; - ~BlastSliceAsset() override = default; - - void SetMeshIdList(const AZStd::vector& meshAssetIdList); - const AZStd::vector& GetMeshIdList() const; - - void SetMaterialId(const AZ::Data::AssetId& materialAssetId); - const AZ::Data::AssetId& GetMaterialId() const; - - static void Reflect(AZ::ReflectContext* context); - - private: - AZStd::vector m_meshAssetIdList; - AZ::Data::AssetId m_materialAssetId; - }; -} // namespace Blast diff --git a/Gems/Blast/Code/Source/BlastModule.cpp b/Gems/Blast/Code/Source/BlastModule.cpp index cbb93a86f7..70b3285d1d 100644 --- a/Gems/Blast/Code/Source/BlastModule.cpp +++ b/Gems/Blast/Code/Source/BlastModule.cpp @@ -16,7 +16,6 @@ #ifdef BLAST_EDITOR #include #include -#include #include #endif @@ -40,8 +39,7 @@ namespace Blast #ifdef BLAST_EDITOR EditorSystemComponent::CreateDescriptor(), EditorBlastFamilyComponent::CreateDescriptor(), - EditorBlastMeshDataComponent::CreateDescriptor(), - BlastSliceAssetStorageComponent::CreateDescriptor(), + EditorBlastMeshDataComponent::CreateDescriptor() #endif }); } diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastChunksAssetHandler.cpp b/Gems/Blast/Code/Source/Editor/EditorBlastChunksAssetHandler.cpp new file mode 100644 index 0000000000..d3ae8222b1 --- /dev/null +++ b/Gems/Blast/Code/Source/Editor/EditorBlastChunksAssetHandler.cpp @@ -0,0 +1,144 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Blast +{ + // + // EditorBlastChunksAssetHandler + // + + EditorBlastChunksAssetHandler::~EditorBlastChunksAssetHandler() + { + Unregister(); + } + + AZ::Data::AssetPtr EditorBlastChunksAssetHandler::CreateAsset(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) + { + if (type != GetAssetType()) + { + AZ_Error("Blast", type == GetAssetType(), "Invalid asset type! We only handle 'BlastChunksAsset'"); + return {}; + } + + if (!CanHandleAsset(id)) + { + return nullptr; + } + + return aznew BlastChunksAsset; + } + + AZ::Data::AssetHandler::LoadResult EditorBlastChunksAssetHandler::LoadAssetData( + const AZ::Data::Asset& asset, + AZStd::shared_ptr stream, + [[maybe_unused]] const AZ::Data::AssetFilterCB& assetLoadFilterCB) + { + BlastChunksAsset* blastChunksAsset = asset.GetAs(); + AZ_Error("blast", blastChunksAsset, + "This should be a BlastChunksAsset type, as this is the only type we process!"); + if (!blastChunksAsset) + { + return LoadResult::Error; + } + + // get all products from the source scene asset + bool found = false; + AZStd::vector productsAssetInfo; + AzToolsFramework::AssetSystemRequestBus::BroadcastResult( + found, + &AzToolsFramework::AssetSystemRequestBus::Events::GetAssetsProducedBySourceUUID, + asset.Get()->GetId().m_guid, + productsAssetInfo); + + if (!found) + { + AZ_Error("blast", + found, + "Could not find asset models produced by source asset ID %s, verify the output product model assets.", + asset.Get()->GetId().m_guid.ToString().c_str()); + return LoadResult::Error; + } + + // find all model assets + AZStd::vector modelAssetIdList; + for (const AZ::Data::AssetInfo& assetInfo : productsAssetInfo) + { + if (azrtti_typeid() == assetInfo.m_assetType) + { + modelAssetIdList.push_back(assetInfo.m_assetId); + } + } + blastChunksAsset->SetModelAssetIds(modelAssetIdList); + + return LoadResult::LoadComplete; + } + + void EditorBlastChunksAssetHandler::DestroyAsset(AZ::Data::AssetPtr ptr) + { + delete ptr; + } + + void EditorBlastChunksAssetHandler::GetHandledAssetTypes(AZStd::vector& assetTypes) + { + assetTypes.push_back(azrtti_typeid()); + } + + void EditorBlastChunksAssetHandler::Register() + { + AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!"); + AZ::Data::AssetManager::Instance().RegisterHandler(this, azrtti_typeid()); + AZ::AssetTypeInfoBus::Handler::BusConnect(azrtti_typeid()); + } + + void EditorBlastChunksAssetHandler::Unregister() + { + AZ::AssetTypeInfoBus::Handler::BusDisconnect(azrtti_typeid()); + if (AZ::Data::AssetManager::IsReady()) + { + AZ::Data::AssetManager::Instance().UnregisterHandler(this); + } + } + + AZ::Data::AssetType EditorBlastChunksAssetHandler::GetAssetType() const + { + return azrtti_typeid(); + } + + const char* EditorBlastChunksAssetHandler::GetAssetTypeDisplayName() const + { + return "Blast Chunks Asset"; + } + + const char* EditorBlastChunksAssetHandler::GetGroup() const + { + return "Blast"; + } + + const char* EditorBlastChunksAssetHandler::GetBrowserIcon() const + { + return "Icons/Components/Box.png"; + } + + void EditorBlastChunksAssetHandler::GetAssetTypeExtensions(AZStd::vector& extensions) + { + extensions.push_back("blast_chunks"); + } + +} // namespace Blast diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastChunksAssetHandler.h b/Gems/Blast/Code/Source/Editor/EditorBlastChunksAssetHandler.h new file mode 100644 index 0000000000..baeb26a1ff --- /dev/null +++ b/Gems/Blast/Code/Source/Editor/EditorBlastChunksAssetHandler.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Blast +{ + class EditorBlastChunksAssetHandler final + : public AZ::Data::AssetHandler + , public AZ::AssetTypeInfoBus::Handler + { + public: + AZ_CLASS_ALLOCATOR(EditorBlastChunksAssetHandler, AZ::SystemAllocator, 0); + + ~EditorBlastChunksAssetHandler() override; + + // AZ::Data::AssetHandler + AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override; + LoadResult LoadAssetData( + const AZ::Data::Asset& asset, + AZStd::shared_ptr stream, + const AZ::Data::AssetFilterCB& assetLoadFilterCB) override; + void DestroyAsset(AZ::Data::AssetPtr ptr) override; + void GetHandledAssetTypes(AZStd::vector& assetTypes) override; + + // AZ::AssetTypeInfoBus::Handler + AZ::Data::AssetType GetAssetType() const override; + const char* GetAssetTypeDisplayName() const override; + const char* GetGroup() const override; + const char* GetBrowserIcon() const override; + void GetAssetTypeExtensions(AZStd::vector& extensions) override; + + void Register(); + void Unregister(); + }; +} // namespace Blast diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.cpp b/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.cpp index 3c29d1498e..27e57a569e 100644 --- a/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.cpp +++ b/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.cpp @@ -45,10 +45,10 @@ namespace Blast if (AZ::SerializeContext* serialize = azrtti_cast(context)) { serialize->Class() - ->Version(4) + ->Version(5) ->Field("Show Mesh Assets", &EditorBlastMeshDataComponent::m_showMeshAssets) ->Field("Mesh Assets", &EditorBlastMeshDataComponent::m_meshAssets) - ->Field("Blast Slice", &EditorBlastMeshDataComponent::m_blastSliceAsset); + ->Field("Blast Chunks", &EditorBlastMeshDataComponent::m_blastChunksAsset); if (AZ::EditContext* ec = serialize->GetEditContext()) { @@ -77,9 +77,9 @@ namespace Blast ->Attribute(AZ::Edit::Attributes::AutoExpand, false) ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorBlastMeshDataComponent::OnMeshAssetsChanged) ->DataElement( - AZ::Edit::UIHandlers::Default, &EditorBlastMeshDataComponent::m_blastSliceAsset, "Blast Slice", - "Slice override to fill out meshes and material") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorBlastMeshDataComponent::OnSliceAssetChanged); + AZ::Edit::UIHandlers::Default, &EditorBlastMeshDataComponent::m_blastChunksAsset, "Blast Chunks", + "Manifest override to fill out meshes and material") + ->Attribute(AZ::Edit::Attributes::ChangeNotify, &EditorBlastMeshDataComponent::OnBlastChunksAssetChanged); } } } @@ -107,23 +107,27 @@ namespace Blast UnregisterModel(); } - void EditorBlastMeshDataComponent::OnSliceAssetChanged() + void EditorBlastMeshDataComponent::OnBlastChunksAssetChanged() { - if (!m_blastSliceAsset.GetId().IsValid()) + if (!m_blastChunksAsset.GetId().IsValid()) { return; } using namespace AZ::Data; + const AssetId blastAssetId = m_blastChunksAsset.GetId(); + m_blastChunksAsset = AssetManager::Instance().GetAsset(blastAssetId, AssetLoadBehavior::QueueLoad); + m_blastChunksAsset.BlockUntilLoadComplete(); - const AssetId blastAssetId = m_blastSliceAsset.GetId(); - m_blastSliceAsset = - AssetManager::Instance().GetAsset(blastAssetId, AssetLoadBehavior::QueueLoad); - m_blastSliceAsset.BlockUntilLoadComplete(); + if (!m_blastChunksAsset.Get() || m_blastChunksAsset.Get()->GetModelAssetIds().empty()) + { + AZ_Warning("blast", false, "Blast Chunk Asset does not contain any models.") + return; + } // load up the new mesh list m_meshAssets.clear(); - for (const auto& meshId : m_blastSliceAsset.Get()->GetMeshIdList()) + for (const auto& meshId : m_blastChunksAsset.Get()->GetModelAssetIds()) { auto meshAsset = AssetManager::Instance().GetAsset(meshId, AssetLoadBehavior::QueueLoad); if (meshAsset) @@ -135,8 +139,8 @@ namespace Blast UnregisterModel(); RegisterModel(); - AzToolsFramework::ToolsApplicationEvents::Bus::Broadcast( - &AzToolsFramework::ToolsApplicationEvents::InvalidatePropertyDisplay, AzToolsFramework::Refresh_EntireTree); + using namespace AzToolsFramework; + ToolsApplicationEvents::Bus::Broadcast(&ToolsApplicationEvents::InvalidatePropertyDisplay, Refresh_EntireTree); } void EditorBlastMeshDataComponent::OnMeshAssetsChanged() @@ -205,9 +209,9 @@ namespace Blast gameEntity->CreateComponent(m_meshAssets); } - const AZ::Data::Asset& EditorBlastMeshDataComponent::GetBlastSliceAsset() const + const AZ::Data::Asset& EditorBlastMeshDataComponent::GetBlastChunksAsset() const { - return m_blastSliceAsset; + return m_blastChunksAsset; } const AZStd::vector>& EditorBlastMeshDataComponent::GetMeshAssets() const diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.h b/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.h index 81818d3bf7..aed5155be7 100644 --- a/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.h +++ b/Gems/Blast/Code/Source/Editor/EditorBlastMeshDataComponent.h @@ -7,7 +7,7 @@ */ #pragma once -#include +#include #include #include #include @@ -43,14 +43,14 @@ namespace Blast // EditorComponentBase void BuildGameEntity(AZ::Entity* gameEntity) override; - const AZ::Data::Asset& GetBlastSliceAsset() const; + const AZ::Data::Asset& GetBlastChunksAsset() const; const AZStd::vector>& GetMeshAssets() const; void OnMaterialsUpdated(const AZ::Render::MaterialAssignmentMap& materials) override; void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; private: - void OnSliceAssetChanged(); + void OnBlastChunksAssetChanged(); void OnMeshAssetsChanged(); AZ::Crc32 GetMeshAssetsVisibility() const; void OnMeshAssetsVisibilityChanged(); @@ -62,7 +62,7 @@ namespace Blast ////////////////////////////////////////////////////////////////////////// // Reflected data bool m_showMeshAssets = false; - AZ::Data::Asset m_blastSliceAsset; + AZ::Data::Asset m_blastChunksAsset; AZStd::vector> m_meshAssets; ////////////////////////////////////////////////////////////////////////// diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastSliceAssetHandler.cpp b/Gems/Blast/Code/Source/Editor/EditorBlastSliceAssetHandler.cpp deleted file mode 100644 index 52df273254..0000000000 --- a/Gems/Blast/Code/Source/Editor/EditorBlastSliceAssetHandler.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -namespace Blast -{ - // BlastSliceAssetStorageComponent - - void BlastSliceAssetStorageComponent::Reflect(AZ::ReflectContext* context) - { - using namespace AZ::Edit; - - if (AZ::SerializeContext* serialize = azrtti_cast(context)) - { - serialize->Class() - ->Version(2) - ->Field("Mesh Data", &BlastSliceAssetStorageComponent::m_meshAssetIdList) - ->Field("Mesh Path List", &BlastSliceAssetStorageComponent::m_meshAssetPathList); - - if (AZ::EditContext* ec = serialize->GetEditContext()) - { - ec->Class( - "Blast Slice Storage Component", "Used process blast slice data") - ->ClassElement(AZ::Edit::ClassElements::EditorData, "") - ->Attribute(AZ::Edit::Attributes::Category, "Physics") - ->Attribute(AZ::Edit::Attributes::Icon, "Icons/Components/Box.png") - ->Attribute(AZ::Edit::Attributes::ViewportIcon, "Icons/Components/Viewport/Box.png") - ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game")) - ->Attribute(AZ::Edit::Attributes::AutoExpand, true) - ->Attribute(AZ::Edit::Attributes::AddableByUser, false) - ->DataElement( - AZ::Edit::UIHandlers::Default, &BlastSliceAssetStorageComponent::m_meshAssetIdList, "Mesh Data", - "Slice data to fill out the mesh list") - ->DataElement( - AZ::Edit::UIHandlers::Default, &BlastSliceAssetStorageComponent::m_meshAssetPathList, - "Mesh Paths", "The mesh path list"); - } - } - - if (AZ::BehaviorContext* behavior = azrtti_cast(context)) - { - behavior->Class("BlastSliceAssetStorageComponent") - ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Automation) - ->Attribute(AZ::Script::Attributes::Module, "blast") - ->Method("GenerateAssetInfo", &BlastSliceAssetStorageComponent::GenerateAssetInfo) - ->Method("WriteMaterialFile", &BlastSliceAssetStorageComponent::WriteMaterialFile); - } - } - - bool BlastSliceAssetStorageComponent::GenerateAssetInfo( - const AZStd::vector& chunkNames, AZStd::string_view blastFilename, - AZStd::string_view assetinfoFilename) - { - AZ::SerializeContext* serializeContext = nullptr; - AZ::ComponentApplicationBus::BroadcastResult( - serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); - if (serializeContext == nullptr) - { - return false; - } - using namespace AZ::SceneAPI::Containers; - using namespace AZ::SceneAPI::SceneData; - - AZStd::string filename; - AZ::StringFunc::Path::Split(blastFilename.data(), nullptr, nullptr, &filename, nullptr); - - AZStd::any sceneManifestPointer(serializeContext->CreateAny(azrtti_typeid())); - SceneManifest* sceneManifest = AZStd::any_cast(&sceneManifestPointer); - - AZStd::vector meshGroupData; - meshGroupData.reserve(chunkNames.size()); - - AZStd::vector materialRuleData; - materialRuleData.reserve(chunkNames.size()); - - for (const AZStd::string& chunkName : chunkNames) - { - meshGroupData.emplace_back(serializeContext->CreateAny(azrtti_typeid())); - AZStd::any& meshGroupPointer = meshGroupData.back(); - MeshGroup* meshGroup = AZStd::any_cast(&meshGroupPointer); - - // make selection list - meshGroup->GetSceneNodeSelectionList().RemoveSelectedNode("RootNode"); - for (const AZStd::string& node : chunkNames) - { - meshGroup->GetSceneNodeSelectionList().RemoveSelectedNode( - AZStd::string::format("RootNode.%s", node.c_str())); - } - meshGroup->GetSceneNodeSelectionList().AddSelectedNode( - AZStd::string::format("RootNode.%s", chunkName.c_str())); - - // create a default material for the mesh group - materialRuleData.emplace_back(serializeContext->CreateAny(azrtti_typeid())); - AZStd::any& materialRulePointer = materialRuleData.back(); - MaterialRule* materialRule = AZStd::any_cast(&materialRulePointer); - - // override the deleter since the AZStd::any will clean up later on - AZStd::shared_ptr materialRuleEntry = AZStd::shared_ptr( - materialRule, - [](auto) - { - }); - meshGroup->GetRuleContainer().AddRule(materialRuleEntry); - - // construct the asset name for the chunk's mesh group - AZStd::string meshGroupName(filename); - meshGroupName.append("-"); - meshGroupName.append(chunkName); - // TODO: Uncomment lines below as part of SPEC-3542 - // meshGroup->OverrideId(AZ::Uuid::CreateName(meshGroupName.c_str())); - // meshGroup->SetName(AZStd::move(meshGroupName)); - - // override the deleter since the AZStd::any will clean up later on - AZStd::shared_ptr meshGroupEntry = AZStd::shared_ptr( - meshGroup, - [](auto) - { - }); - sceneManifest->AddEntry(AZStd::move(meshGroupEntry)); - } - - return sceneManifest->SaveToFile(assetinfoFilename.data()); - } - - bool BlastSliceAssetStorageComponent::WriteMaterialFile( - AZStd::string_view materialGroupName, const AZStd::vector& materialNames, - AZStd::string_view materialFilename) - { - AZ::GFxFramework::MaterialGroup group; - for (const auto& texture : materialNames) - { - auto mat = AZStd::make_shared(); - mat->SetName(texture); - mat->SetTexture(AZ::GFxFramework::TextureMapType::Diffuse, "EngineAssets/Textures/white.dds"); - group.AddMaterial(mat); - } - group.SetMtlName(materialGroupName); - return group.WriteMtlFile(materialFilename.data()); - } - - // - // EditorBlastSliceAssetHandler - // - - EditorBlastSliceAssetHandler::~EditorBlastSliceAssetHandler() - { - Unregister(); - } - - AZ::Data::AssetPtr EditorBlastSliceAssetHandler::CreateAsset( - const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) - { - if (type != GetAssetType()) - { - AZ_Error("Blast", type == GetAssetType(), "Invalid asset type! We only handle 'BlastAsset'"); - return {}; - } - - if (!CanHandleAsset(id)) - { - return nullptr; - } - - return aznew BlastSliceAsset; - } - - AZ::Data::AssetHandler::LoadResult EditorBlastSliceAssetHandler::LoadAssetData( - const AZ::Data::Asset& asset, AZStd::shared_ptr stream, - const AZ::Data::AssetFilterCB& assetLoadFilterCB) - { - BlastSliceAsset* blastSliceAssetData = asset.GetAs(); - AZ_Error( - "blast", blastSliceAssetData, - "This should be a BlastSliceAsset type, as this is the only type we process!"); - AZ::SerializeContext* serializeContext = nullptr; - AZ::ComponentApplicationBus::BroadcastResult( - serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext); - if (blastSliceAssetData && serializeContext) - { - AZ::ObjectStream::FilterDescriptor filter(assetLoadFilterCB); - AZStd::unique_ptr baseEntity( - AZ::Utils::LoadObjectFromStream(*stream, serializeContext, filter)); - AZ_Error("Blast", baseEntity, "Could not load slice root entity {asset id}"); - if (!baseEntity) - { - return LoadResult::Error; - } - - auto&& sliceComponent = baseEntity->FindComponent(); - AZ_Error("Blast", sliceComponent, "blast_slice entity missing SliceComponent!"); - if (sliceComponent == nullptr) - { - return LoadResult::Error; - } - - AZStd::vector enityList; - sliceComponent->GetEntities(enityList); - for (auto&& entity : enityList) - { - // the base element type to store Blast mesh data is the BlastSliceAssetStorageComponent - auto&& blastSliceAssetStorage = entity->FindComponent(); - if (blastSliceAssetStorage) - { - if (blastSliceAssetStorage->GetMeshData().empty() == false) - { - blastSliceAssetData->SetMeshIdList(blastSliceAssetStorage->GetMeshData()); - return LoadResult::LoadComplete; - } - else if (blastSliceAssetStorage->GetMeshPathList().empty() == false) - { - AZStd::vector meshAssetIdList; - meshAssetIdList.reserve(blastSliceAssetStorage->GetMeshPathList().size()); - - for (auto&& assetPath : blastSliceAssetStorage->GetMeshPathList()) - { - AZ::Data::AssetId meshAssetId; - AZ::Data::AssetCatalogRequestBus::BroadcastResult( - meshAssetId, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, - assetPath.c_str(), AZ::Data::s_invalidAssetType, false); - - if (meshAssetId.IsValid()) - { - meshAssetIdList.emplace_back(meshAssetId); - } - } - blastSliceAssetData->SetMeshIdList(meshAssetIdList); - return LoadResult::LoadComplete; - } - } - - // back up logic to load blast data for the EditorBlastMeshDataComponent - auto&& meshDataComponent = entity->FindComponent(); - if (meshDataComponent) - { - auto&& innerBlastSliceAsset = meshDataComponent->GetBlastSliceAsset(); - if (innerBlastSliceAsset.IsReady()) - { - blastSliceAssetData->SetMeshIdList(innerBlastSliceAsset.Get()->GetMeshIdList()); - blastSliceAssetData->SetMaterialId(innerBlastSliceAsset.Get()->GetMaterialId()); - return LoadResult::LoadComplete; - } - else - { - auto&& meshDataList = meshDataComponent->GetMeshAssets(); - AZStd::vector meshAssetIdList; - meshAssetIdList.reserve(meshDataList.size()); - for (auto&& meshData : meshDataList) - { - AZ::RPI::ModelAsset* meshAsset = meshData.Get(); - if (meshAsset) - { - meshAssetIdList.push_back(meshAsset->GetId()); - } - } - blastSliceAssetData->SetMeshIdList(meshAssetIdList); - return LoadResult::LoadComplete; - } - } - } - AZ_Error( - "Blast", false, "blast_slice assetId:%s missing EditorBlastMeshDataComponent!", - asset->GetId().ToString().c_str()); - } - return LoadResult::Error; - } - - void EditorBlastSliceAssetHandler::DestroyAsset(AZ::Data::AssetPtr ptr) - { - delete ptr; - } - - void EditorBlastSliceAssetHandler::GetHandledAssetTypes(AZStd::vector& assetTypes) - { - assetTypes.push_back(azrtti_typeid()); - } - - void EditorBlastSliceAssetHandler::Register() - { - AZ_Assert(AZ::Data::AssetManager::IsReady(), "Asset manager isn't ready!"); - AZ::Data::AssetManager::Instance().RegisterHandler(this, azrtti_typeid()); - AZ::AssetTypeInfoBus::Handler::BusConnect(azrtti_typeid()); - } - - void EditorBlastSliceAssetHandler::Unregister() - { - AZ::AssetTypeInfoBus::Handler::BusDisconnect(azrtti_typeid()); - if (AZ::Data::AssetManager::IsReady()) - { - AZ::Data::AssetManager::Instance().UnregisterHandler(this); - } - } - - AZ::Data::AssetType EditorBlastSliceAssetHandler::GetAssetType() const - { - return azrtti_typeid(); - } - - const char* EditorBlastSliceAssetHandler::GetAssetTypeDisplayName() const - { - return "Blast Slice Asset"; - } - - const char* EditorBlastSliceAssetHandler::GetGroup() const - { - return "Blast"; - } - - const char* EditorBlastSliceAssetHandler::GetBrowserIcon() const - { - return "Icons/Components/Box.png"; - } - - void EditorBlastSliceAssetHandler::GetAssetTypeExtensions(AZStd::vector& extensions) - { - extensions.push_back("blast_slice"); - } - -} // namespace Blast diff --git a/Gems/Blast/Code/Source/Editor/EditorBlastSliceAssetHandler.h b/Gems/Blast/Code/Source/Editor/EditorBlastSliceAssetHandler.h deleted file mode 100644 index f33290f7f8..0000000000 --- a/Gems/Blast/Code/Source/Editor/EditorBlastSliceAssetHandler.h +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace Blast -{ - //! Used to create store asset references (i.e. ids) to fill out the EditorBlastMeshDataComponent - class BlastSliceAssetStorageComponent final : public AzToolsFramework::Components::EditorComponentBase - { - public: - AZ_COMPONENT( - BlastSliceAssetStorageComponent, "{696C7E62-1EA4-41E2-B4F6-7BD0D30888DC}", - AzToolsFramework::Components::EditorComponentBase); - - ~BlastSliceAssetStorageComponent() override = default; - - static void Reflect(AZ::ReflectContext* context); - - const AZStd::vector& GetMeshData() const - { - return m_meshAssetIdList; - } - - void SetMeshData(const AZStd::vector& meshAssetIdList) - { - m_meshAssetIdList = meshAssetIdList; - } - - const AZStd::vector& GetMeshPathList() const - { - return m_meshAssetPathList; - } - - void SetMeshPathList(const AZStd::vector& meshAssetPathList) - { - m_meshAssetPathList = meshAssetPathList; - } - - private: - // AZ::Component interface implementation - void Activate() override {} - void Deactivate() override {} - - // EditorComponentBase - void BuildGameEntity([[maybe_unused]] AZ::Entity* gameEntity) override {} - - // Script API - bool GenerateAssetInfo( - const AZStd::vector& chunkNames, - AZStd::string_view blastFilename, - AZStd::string_view assetinfoFilename); - - bool WriteMaterialFile( - AZStd::string_view materialGroupName, - const AZStd::vector& materialNames, - AZStd::string_view materialFilename); - - AZStd::vector m_meshAssetIdList; - AZStd::vector m_meshAssetPathList; - }; - - class EditorBlastSliceAssetHandler final - : public AZ::Data::AssetHandler - , public AZ::AssetTypeInfoBus::Handler - { - public: - AZ_CLASS_ALLOCATOR(EditorBlastSliceAssetHandler, AZ::SystemAllocator, 0); - - ~EditorBlastSliceAssetHandler() override; - - // AZ::Data::AssetHandler - AZ::Data::AssetPtr CreateAsset(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override; - LoadResult LoadAssetData( - const AZ::Data::Asset& asset, AZStd::shared_ptr stream, - const AZ::Data::AssetFilterCB& assetLoadFilterCB) override; - void DestroyAsset(AZ::Data::AssetPtr ptr) override; - void GetHandledAssetTypes(AZStd::vector& assetTypes) override; - - // AZ::AssetTypeInfoBus::Handler - AZ::Data::AssetType GetAssetType() const override; - const char* GetAssetTypeDisplayName() const override; - const char* GetGroup() const override; - const char* GetBrowserIcon() const override; - void GetAssetTypeExtensions(AZStd::vector& extensions) override; - - void Register(); - void Unregister(); - }; -} // namespace Blast diff --git a/Gems/Blast/Code/Source/Editor/EditorSystemComponent.cpp b/Gems/Blast/Code/Source/Editor/EditorSystemComponent.cpp index d8d703e51f..dc1cb0fc98 100644 --- a/Gems/Blast/Code/Source/Editor/EditorSystemComponent.cpp +++ b/Gems/Blast/Code/Source/Editor/EditorSystemComponent.cpp @@ -6,7 +6,7 @@ * */ -#include +#include #include #include #include @@ -16,7 +16,7 @@ namespace Blast { void EditorSystemComponent::Reflect(AZ::ReflectContext* context) { - BlastSliceAsset::Reflect(context); + BlastChunksAsset::Reflect(context); if (auto serializeContext = azrtti_cast(context)) { @@ -26,14 +26,14 @@ namespace Blast void EditorSystemComponent::Activate() { - m_editorBlastSliceAssetHandler = AZStd::make_unique(); - m_editorBlastSliceAssetHandler->Register(); + m_editorBlastChunksAssetHandler = AZStd::make_unique(); + m_editorBlastChunksAssetHandler->Register(); auto assetCatalog = AZ::Data::AssetCatalogRequestBus::FindFirstHandler(); if (assetCatalog) { - assetCatalog->EnableCatalogForAsset(azrtti_typeid()); - assetCatalog->AddExtension("blast_slice"); + assetCatalog->EnableCatalogForAsset(azrtti_typeid()); + assetCatalog->AddExtension("blast_chunks"); } AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); @@ -46,7 +46,7 @@ namespace Blast void EditorSystemComponent::Deactivate() { AzToolsFramework::EditorEvents::Bus::Handler::BusDisconnect(); - m_editorBlastSliceAssetHandler.reset(); + m_editorBlastChunksAssetHandler.reset(); } // This will be called when the IEditor instance is ready diff --git a/Gems/Blast/Code/Source/Editor/EditorSystemComponent.h b/Gems/Blast/Code/Source/Editor/EditorSystemComponent.h index 737a7d968d..31daae1a18 100644 --- a/Gems/Blast/Code/Source/Editor/EditorSystemComponent.h +++ b/Gems/Blast/Code/Source/Editor/EditorSystemComponent.h @@ -11,7 +11,7 @@ #include #include #include -#include +#include namespace Blast { @@ -39,7 +39,7 @@ namespace Blast required.push_back(AZ_CRC("BlastService", 0x75beae2d)); } - AZStd::unique_ptr m_editorBlastSliceAssetHandler; + AZStd::unique_ptr m_editorBlastChunksAssetHandler; // AZ::Component void Activate() override; diff --git a/Gems/Blast/Code/Tests/Editor/EditorBlastChunksAssetHandlerTest.cpp b/Gems/Blast/Code/Tests/Editor/EditorBlastChunksAssetHandlerTest.cpp new file mode 100644 index 0000000000..9f48cae4da --- /dev/null +++ b/Gems/Blast/Code/Tests/Editor/EditorBlastChunksAssetHandlerTest.cpp @@ -0,0 +1,207 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#include +#include +#include + +#include +#include +#include + +#include + +namespace UnitTest +{ + MockComponentApplication::MockComponentApplication() + { + AZ::ComponentApplicationBus::Handler::BusConnect(); + AZ::Interface::Register(this); + } + + MockComponentApplication::~MockComponentApplication() + { + AZ::Interface::Unregister(this); + AZ::ComponentApplicationBus::Handler::BusDisconnect(); + } + + class MockAssetCatalogRequestBusHandler final + : public AZ::Data::AssetCatalogRequestBus::Handler + { + public: + MockAssetCatalogRequestBusHandler() + { + AZ::Data::AssetCatalogRequestBus::Handler::BusConnect(); + } + + virtual ~MockAssetCatalogRequestBusHandler() + { + AZ::Data::AssetCatalogRequestBus::Handler::BusDisconnect(); + } + + MOCK_METHOD3(GetAssetIdByPath, AZ::Data::AssetId(const char*, const AZ::Data::AssetType&, bool)); + MOCK_METHOD1(GetAssetInfoById, AZ::Data::AssetInfo(const AZ::Data::AssetId&)); + MOCK_METHOD1(AddAssetType, void(const AZ::Data::AssetType&)); + MOCK_METHOD1(AddDeltaCatalog, bool(AZStd::shared_ptr)); + MOCK_METHOD1(AddExtension, void(const char*)); + MOCK_METHOD0(ClearCatalog, void()); + MOCK_METHOD5(CreateBundleManifest, bool(const AZStd::string&, const AZStd::vector&, const AZStd::string&, int, const AZStd::vector&)); + MOCK_METHOD2(CreateDeltaCatalog, bool(const AZStd::vector&, const AZStd::string&)); + MOCK_METHOD0(DisableCatalog, void()); + MOCK_METHOD1(EnableCatalogForAsset, void(const AZ::Data::AssetType&)); + MOCK_METHOD3(EnumerateAssets, void(BeginAssetEnumerationCB, AssetEnumerationCB, EndAssetEnumerationCB)); + MOCK_METHOD1(GenerateAssetIdTEMP, AZ::Data::AssetId(const char*)); + MOCK_METHOD1(GetAllProductDependencies, AZ::Outcome, AZStd::string>(const AZ::Data::AssetId&)); + MOCK_METHOD3(GetAllProductDependenciesFilter, AZ::Outcome, AZStd::string>(const AZ::Data::AssetId&, const AZStd::unordered_set&, const AZStd::vector&)); + MOCK_METHOD1(GetAssetPathById, AZStd::string(const AZ::Data::AssetId&)); + MOCK_METHOD1(GetDirectProductDependencies, AZ::Outcome, AZStd::string>(const AZ::Data::AssetId&)); + MOCK_METHOD1(GetHandledAssetTypes, void(AZStd::vector&)); + MOCK_METHOD0(GetRegisteredAssetPaths, AZStd::vector()); + MOCK_METHOD2(InsertDeltaCatalog, bool(AZStd::shared_ptr, size_t)); + MOCK_METHOD2(InsertDeltaCatalogBefore, bool(AZStd::shared_ptr, AZStd::shared_ptr)); + MOCK_METHOD1(LoadCatalog, bool(const char*)); + MOCK_METHOD2(RegisterAsset, void(const AZ::Data::AssetId&, AZ::Data::AssetInfo&)); + MOCK_METHOD1(RemoveDeltaCatalog, bool(AZStd::shared_ptr)); + MOCK_METHOD1(SaveCatalog, bool(const char*)); + MOCK_METHOD0(StartMonitoringAssets, void()); + MOCK_METHOD0(StopMonitoringAssets, void()); + MOCK_METHOD1(UnregisterAsset, void(const AZ::Data::AssetId&)); + }; + + class MockAssetManager + : public AZ::Data::AssetManager + { + public: + MockAssetManager(const AZ::Data::AssetManager::Descriptor& desc) : + AssetManager(desc) + { + } + }; + + class EditorBlastChunkAssetHandlerTestFixture + : public AllocatorsTestFixture + { + public: + AZStd::unique_ptr m_mockComponentApplicationBusHandler; + AZStd::unique_ptr m_mockAssetCatalogRequestBusHandler; + AZStd::unique_ptr m_mockAssetManager; + AZStd::unique_ptr m_serializeContext; + + void SetUpChunkComponents() + { + m_serializeContext = AZStd::make_unique(); + + AZ::Entity::Reflect(m_serializeContext.get()); + AzToolsFramework::Components::EditorComponentBase::Reflect(m_serializeContext.get()); + } + + void TearDownChunkComponents() + { + m_serializeContext.reset(); + } + + void SetUp() override final + { + AllocatorsTestFixture::SetUp(); + AZ::AllocatorInstance::Create(); + AZ::AllocatorInstance::Create(); + + m_mockComponentApplicationBusHandler = AZStd::make_unique(); + m_mockAssetCatalogRequestBusHandler = AZStd::make_unique(); + m_mockAssetManager = AZStd::make_unique(AZ::Data::AssetManager::Descriptor{}); + + AZ::Data::AssetManager::SetInstance(m_mockAssetManager.get()); + } + + void TearDown() override final + { + m_mockAssetManager.release(); + AZ::Data::AssetManager::Destroy(); + + m_mockAssetCatalogRequestBusHandler.reset(); + m_mockComponentApplicationBusHandler.reset(); + + AZ::AllocatorInstance::Destroy(); + AZ::AllocatorInstance::Destroy(); + AllocatorsTestFixture::TearDown(); + } + + void SaveChunkAssetToStream(AZ::Entity* chunkAssetEntity, AZStd::vector& buffer) + { + buffer.clear(); + AZ::IO::ByteContainerStream> stream(&buffer); + AZ::ObjectStream* objStream = AZ::ObjectStream::Create(&stream, *m_serializeContext.get(), AZ::ObjectStream::ST_XML); + objStream->WriteClass(chunkAssetEntity); + EXPECT_TRUE(objStream->Finalize()); + } + }; + + TEST_F(EditorBlastChunkAssetHandlerTestFixture, EditorBlastChunkAssetHandler_AssetManager_Registered) + { + Blast::EditorBlastChunksAssetHandler handler; + handler.Register(); + EXPECT_NE(nullptr, AZ::Data::AssetManager::Instance().GetHandler(azrtti_typeid())); + handler.Unregister(); + } + + TEST_F(EditorBlastChunkAssetHandlerTestFixture, EditorBlastChunkAssetHandler_AssetTypeInfoBus_Responds) + { + auto assetId = azrtti_typeid(); + + Blast::EditorBlastChunksAssetHandler handler; + handler.Register(); + + AZ::Data::AssetType assetType = AZ::Uuid::CreateNull(); + AZ::AssetTypeInfoBus::EventResult(assetType, assetId, &AZ::AssetTypeInfoBus::Events::GetAssetType); + EXPECT_NE(AZ::Uuid::CreateNull(), assetType); + + const char* displayName = nullptr; + AZ::AssetTypeInfoBus::EventResult(displayName, assetId, &AZ::AssetTypeInfoBus::Events::GetAssetTypeDisplayName); + EXPECT_STREQ("Blast Chunks Asset", displayName); + + const char* group = nullptr; + AZ::AssetTypeInfoBus::EventResult(group, assetId, &AZ::AssetTypeInfoBus::Events::GetGroup); + EXPECT_STREQ("Blast", group); + + const char* icon = nullptr; + AZ::AssetTypeInfoBus::EventResult(icon, assetId, &AZ::AssetTypeInfoBus::Events::GetBrowserIcon); + EXPECT_STREQ("Icons/Components/Box.png", icon); + + AZStd::vector extensions; + AZ::AssetTypeInfoBus::Event(assetId, &AZ::AssetTypeInfoBus::Events::GetAssetTypeExtensions, extensions); + ASSERT_EQ(1, extensions.size()); + ASSERT_EQ("blast_chunks", extensions[0]); + + handler.Unregister(); + } + + TEST_F(EditorBlastChunkAssetHandlerTestFixture, EditorBlastChunkAssetHandler_AssetHandler_Ready) + { + auto assetType = azrtti_typeid(); + auto&& assetManager = AZ::Data::AssetManager::Instance(); + + Blast::EditorBlastChunksAssetHandler handler; + handler.Register(); + EXPECT_EQ(&handler, assetManager.GetHandler(assetType)); + + // create and release an instance of the BlastChunkAsset asset type + { + using ::testing::Return; + using ::testing::_; + + EXPECT_CALL(*m_mockAssetCatalogRequestBusHandler, GetAssetInfoById(_)) + .Times(2) + .WillRepeatedly(Return(AZ::Data::AssetInfo{})); + + auto assetPtr = assetManager.CreateAsset(AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0)); + EXPECT_NE(nullptr, assetPtr.Get()); + EXPECT_EQ(azrtti_typeid(), assetPtr.GetType()); + } + + handler.Unregister(); + } + +} diff --git a/Gems/Blast/Code/Tests/Editor/EditorBlastSliceAssetHandlerTest.cpp b/Gems/Blast/Code/Tests/Editor/EditorBlastSliceAssetHandlerTest.cpp deleted file mode 100644 index 3df22d081f..0000000000 --- a/Gems/Blast/Code/Tests/Editor/EditorBlastSliceAssetHandlerTest.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include -#include -#include - -#include - -#include -#include -#include - -namespace UnitTest -{ - class MockComponentApplicationBusHandler final - //: public MockComponentApplication - : public AZ::ComponentApplicationBus::Handler - { - public: - MockComponentApplicationBusHandler() - { - AZ::ComponentApplicationBus::Handler::BusConnect(); - } - - virtual ~MockComponentApplicationBusHandler() - { - AZ::ComponentApplicationBus::Handler::BusDisconnect(); - } - - MOCK_METHOD0(Destroy, void()); - MOCK_METHOD1(RegisterComponentDescriptor, void(const AZ::ComponentDescriptor*)); - MOCK_METHOD1(UnregisterComponentDescriptor, void(const AZ::ComponentDescriptor*)); - MOCK_METHOD1(RemoveEntity, bool(AZ::Entity*)); - MOCK_METHOD1(DeleteEntity, bool(const AZ::EntityId&)); - MOCK_METHOD1(GetEntityName, AZStd::string(const AZ::EntityId&)); - MOCK_METHOD1(AddEntity, bool(AZ::Entity*)); - MOCK_METHOD1(FindEntity, AZ::Entity*(const AZ::EntityId&)); - MOCK_METHOD1(EnumerateEntities, void(const ComponentApplicationRequests::EntityCallback&)); - MOCK_METHOD0(GetApplication, AZ::ComponentApplication* ()); - MOCK_METHOD0(GetSerializeContext, AZ::SerializeContext* ()); - MOCK_METHOD0(GetBehaviorContext, AZ::BehaviorContext* ()); - MOCK_METHOD0(GetJsonRegistrationContext, AZ::JsonRegistrationContext* ()); - MOCK_METHOD0(GetAppRoot, const char* ()); - MOCK_CONST_METHOD0(GetExecutableFolder, const char* ()); - MOCK_METHOD0(GetDrillerManager, AZ::Debug::DrillerManager* ()); - MOCK_METHOD0(GetTickDeltaTime, float()); - MOCK_METHOD1(Tick, void(float)); - MOCK_METHOD0(TickSystem, void()); - MOCK_CONST_METHOD0(GetRequiredSystemComponents, AZ::ComponentTypeList()); - MOCK_METHOD1(ResolveModulePath, void(AZ::OSString&)); - MOCK_METHOD0(CreateSerializeContext, void()); - MOCK_METHOD0(DestroySerializeContext, void()); - MOCK_METHOD0(CreateBehaviorContext, void()); - MOCK_METHOD0(DestroyBehaviorContext, void()); - MOCK_METHOD0(RegisterCoreComponents, void()); - MOCK_METHOD1(AddSystemComponents, void(AZ::Entity*)); - MOCK_METHOD0(ReflectSerialize, void()); - MOCK_METHOD1(Reflect, void(AZ::ReflectContext*)); - MOCK_CONST_METHOD0(GetBinFolder, const char* ()); - }; - - class MockAssetCatalogRequestBusHandler final - : public AZ::Data::AssetCatalogRequestBus::Handler - { - public: - MockAssetCatalogRequestBusHandler() - { - AZ::Data::AssetCatalogRequestBus::Handler::BusConnect(); - } - - virtual ~MockAssetCatalogRequestBusHandler() - { - AZ::Data::AssetCatalogRequestBus::Handler::BusDisconnect(); - } - - MOCK_METHOD3(GetAssetIdByPath, AZ::Data::AssetId(const char*, const AZ::Data::AssetType&, bool)); - MOCK_METHOD1(GetAssetInfoById, AZ::Data::AssetInfo(const AZ::Data::AssetId&)); - MOCK_METHOD1(AddAssetType, void(const AZ::Data::AssetType&)); - MOCK_METHOD1(AddDeltaCatalog, bool(AZStd::shared_ptr)); - MOCK_METHOD1(AddExtension, void(const char*)); - MOCK_METHOD0(ClearCatalog, void()); - MOCK_METHOD5(CreateBundleManifest, bool(const AZStd::string&, const AZStd::vector&, const AZStd::string&, int, const AZStd::vector&)); - MOCK_METHOD2(CreateDeltaCatalog, bool(const AZStd::vector&, const AZStd::string&)); - MOCK_METHOD0(DisableCatalog, void()); - MOCK_METHOD1(EnableCatalogForAsset, void(const AZ::Data::AssetType&)); - MOCK_METHOD3(EnumerateAssets, void(BeginAssetEnumerationCB, AssetEnumerationCB, EndAssetEnumerationCB)); - MOCK_METHOD1(GenerateAssetIdTEMP, AZ::Data::AssetId(const char*)); - MOCK_METHOD1(GetAllProductDependencies, AZ::Outcome, AZStd::string>(const AZ::Data::AssetId&)); - MOCK_METHOD3(GetAllProductDependenciesFilter, AZ::Outcome, AZStd::string>(const AZ::Data::AssetId&, const AZStd::unordered_set&, const AZStd::vector&)); - MOCK_METHOD1(GetAssetPathById, AZStd::string(const AZ::Data::AssetId&)); - MOCK_METHOD1(GetDirectProductDependencies, AZ::Outcome, AZStd::string>(const AZ::Data::AssetId&)); - MOCK_METHOD1(GetHandledAssetTypes, void(AZStd::vector&)); - MOCK_METHOD0(GetRegisteredAssetPaths, AZStd::vector()); - MOCK_METHOD2(InsertDeltaCatalog, bool(AZStd::shared_ptr, size_t)); - MOCK_METHOD2(InsertDeltaCatalogBefore, bool(AZStd::shared_ptr, AZStd::shared_ptr)); - MOCK_METHOD1(LoadCatalog, bool(const char*)); - MOCK_METHOD2(RegisterAsset, void(const AZ::Data::AssetId&, AZ::Data::AssetInfo&)); - MOCK_METHOD1(RemoveDeltaCatalog, bool(AZStd::shared_ptr)); - MOCK_METHOD1(SaveCatalog, bool(const char*)); - MOCK_METHOD0(StartMonitoringAssets, void()); - MOCK_METHOD0(StopMonitoringAssets, void()); - MOCK_METHOD1(UnregisterAsset, void(const AZ::Data::AssetId&)); - }; - - class MockAssetManager - : public AZ::Data::AssetManager - { - public: - MockAssetManager(const AZ::Data::AssetManager::Descriptor& desc) : - AssetManager(desc) - { - } - }; - - class EditorBlastSliceAssetHandlerTestFixture - : public AllocatorsTestFixture - { - public: - AZStd::unique_ptr m_mockComponentApplicationBusHandler; - //AZStd::unique_ptr m_mockComponentApplicationBusHandler; - AZStd::unique_ptr m_mockAssetCatalogRequestBusHandler; - AZStd::unique_ptr m_mockAssetManager; - AZStd::unique_ptr m_serializeContext; - const AZ::ComponentDescriptor* m_sliceComponentDescriptor = nullptr; - - void SetUpSliceComponents() - { - m_serializeContext = AZStd::make_unique(); - - AZ::Entity::Reflect(m_serializeContext.get()); - Blast::BlastSliceAssetStorageComponent::Reflect(m_serializeContext.get()); - AzToolsFramework::Components::EditorComponentBase::Reflect(m_serializeContext.get()); - - m_sliceComponentDescriptor = AZ::SliceComponent::CreateDescriptor(); - m_sliceComponentDescriptor->Reflect(m_serializeContext.get()); - } - - void TearDownSliceComponents() - { - delete m_sliceComponentDescriptor; - m_serializeContext.reset(); - } - - void SetUp() override final - { - AllocatorsTestFixture::SetUp(); - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - - m_mockComponentApplicationBusHandler = AZStd::make_unique(); - m_mockAssetCatalogRequestBusHandler = AZStd::make_unique(); - m_mockAssetManager = AZStd::make_unique(AZ::Data::AssetManager::Descriptor{}); - - AZ::Data::AssetManager::SetInstance(m_mockAssetManager.get()); - } - - void TearDown() override final - { - AZ::Data::AssetManager::SetInstance(nullptr); - - m_mockAssetManager.reset(); - m_mockAssetCatalogRequestBusHandler.reset(); - m_mockComponentApplicationBusHandler.reset(); - - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - AllocatorsTestFixture::TearDown(); - } - - void SaveSliceAssetToStream(AZ::Entity* sliceAssetEntity, AZStd::vector& buffer) - { - buffer.clear(); - AZ::IO::ByteContainerStream> stream(&buffer); - AZ::ObjectStream* objStream = AZ::ObjectStream::Create(&stream, *m_serializeContext.get(), AZ::ObjectStream::ST_XML); - objStream->WriteClass(sliceAssetEntity); - EXPECT_TRUE(objStream->Finalize()); - } - }; - - TEST_F(EditorBlastSliceAssetHandlerTestFixture, EditorBlastSliceAssetHandler_AssetManager_Registered) - { - Blast::EditorBlastSliceAssetHandler handler; - handler.Register(); - EXPECT_NE(nullptr, AZ::Data::AssetManager::Instance().GetHandler(azrtti_typeid())); - handler.Unregister(); - } - - TEST_F(EditorBlastSliceAssetHandlerTestFixture, BlastSliceAssetStorageComponent_Behavior_Registered) - { - AZ::BehaviorContext behaviorContext; - Blast::BlastSliceAssetStorageComponent::Reflect(&behaviorContext); - - auto classEntry = behaviorContext.m_classes.find("BlastSliceAssetStorageComponent"); - EXPECT_NE(behaviorContext.m_classes.end(), classEntry); - AZ::BehaviorClass* behaviorClass = classEntry->second; - auto methodEntry = behaviorClass->m_methods.find("GenerateAssetInfo"); - EXPECT_NE(behaviorClass->m_methods.end(), methodEntry); - AZ::BehaviorMethod* behaviorMethod = methodEntry->second; - EXPECT_EQ(4, behaviorMethod->GetNumArguments()); - EXPECT_EQ(behaviorMethod->GetArgument(0)->m_typeId, azrtti_typeid()); - EXPECT_EQ(behaviorMethod->GetArgument(1)->m_typeId, azrtti_typeid>()); - EXPECT_EQ(behaviorMethod->GetArgument(2)->m_typeId, azrtti_typeid()); - EXPECT_EQ(behaviorMethod->GetArgument(3)->m_typeId, azrtti_typeid()); - } - - TEST_F(EditorBlastSliceAssetHandlerTestFixture, BlastSliceAsset_Behavior_Registered) - { - AZ::BehaviorContext behaviorContext; - Blast::BlastSliceAsset::Reflect(&behaviorContext); - - auto classEntry = behaviorContext.m_classes.find("BlastSliceAsset"); - EXPECT_NE(behaviorContext.m_classes.end(), classEntry); - AZ::BehaviorClass* behaviorClass = classEntry->second; - - auto setMeshIdListEntry = behaviorClass->m_methods.find("SetMeshIdList"); - EXPECT_NE(behaviorClass->m_methods.end(), setMeshIdListEntry); - { - AZ::BehaviorMethod* behaviorMethod = setMeshIdListEntry->second; - EXPECT_EQ(2, behaviorMethod->GetNumArguments()); - EXPECT_EQ(behaviorMethod->GetArgument(0)->m_typeId, azrtti_typeid()); - EXPECT_EQ(behaviorMethod->GetArgument(1)->m_typeId, azrtti_typeid>()); - } - - auto getMeshIdListEntry = behaviorClass->m_methods.find("GetMeshIdList"); - EXPECT_NE(behaviorClass->m_methods.end(), getMeshIdListEntry); - { - AZ::BehaviorMethod* behaviorMethod = getMeshIdListEntry->second; - EXPECT_EQ(1, behaviorMethod->GetNumArguments()); - EXPECT_EQ(behaviorMethod->GetArgument(0)->m_typeId, azrtti_typeid()); - EXPECT_EQ(behaviorMethod->GetResult()->m_typeId, azrtti_typeid>()); - } - - auto setMaterialIdEntry = behaviorClass->m_methods.find("SetMaterialId"); - EXPECT_NE(behaviorClass->m_methods.end(), setMaterialIdEntry); - { - AZ::BehaviorMethod* behaviorMethod = setMaterialIdEntry->second; - EXPECT_EQ(2, behaviorMethod->GetNumArguments()); - EXPECT_EQ(behaviorMethod->GetArgument(0)->m_typeId, azrtti_typeid()); - EXPECT_EQ(behaviorMethod->GetArgument(1)->m_typeId, azrtti_typeid()); - } - - auto getMaterialIdEntry = behaviorClass->m_methods.find("GetMaterialId"); - EXPECT_NE(behaviorClass->m_methods.end(), getMaterialIdEntry); - { - AZ::BehaviorMethod* behaviorMethod = getMaterialIdEntry->second; - EXPECT_EQ(1, behaviorMethod->GetNumArguments()); - EXPECT_EQ(behaviorMethod->GetArgument(0)->m_typeId, azrtti_typeid()); - EXPECT_EQ(behaviorMethod->GetResult()->m_typeId, azrtti_typeid()); - } - - auto getAssetTypeIdEntry = behaviorClass->m_methods.find("GetAssetTypeId"); - EXPECT_NE(behaviorClass->m_methods.end(), getAssetTypeIdEntry); - { - AZ::BehaviorMethod* behaviorMethod = getAssetTypeIdEntry->second; - EXPECT_EQ(1, behaviorMethod->GetNumArguments()); - EXPECT_EQ(behaviorMethod->GetArgument(0)->m_typeId, azrtti_typeid()); - EXPECT_EQ(behaviorMethod->GetResult()->m_typeId, azrtti_typeid()); - } - } - - TEST_F(EditorBlastSliceAssetHandlerTestFixture, EditorBlastSliceAssetHandler_AssetTypeInfoBus_Responds) - { - auto assetId = azrtti_typeid(); - - Blast::EditorBlastSliceAssetHandler handler; - handler.Register(); - - AZ::Data::AssetType assetType = AZ::Uuid::CreateNull(); - AZ::AssetTypeInfoBus::EventResult(assetType, assetId, &AZ::AssetTypeInfoBus::Events::GetAssetType); - EXPECT_NE(AZ::Uuid::CreateNull(), assetType); - - const char* displayName = nullptr; - AZ::AssetTypeInfoBus::EventResult(displayName, assetId, &AZ::AssetTypeInfoBus::Events::GetAssetTypeDisplayName); - EXPECT_STREQ("Blast Slice Asset", displayName); - - const char* group = nullptr; - AZ::AssetTypeInfoBus::EventResult(group, assetId, &AZ::AssetTypeInfoBus::Events::GetGroup); - EXPECT_STREQ("Blast", group); - - const char* icon = nullptr; - AZ::AssetTypeInfoBus::EventResult(icon, assetId, &AZ::AssetTypeInfoBus::Events::GetBrowserIcon); - EXPECT_STREQ("Editor/Icons/Components/Box.png", icon); - - AZStd::vector extensions; - AZ::AssetTypeInfoBus::Event(assetId, &AZ::AssetTypeInfoBus::Events::GetAssetTypeExtensions, extensions); - ASSERT_EQ(1, extensions.size()); - ASSERT_EQ("blast_slice", extensions[0]); - - handler.Unregister(); - } - - TEST_F(EditorBlastSliceAssetHandlerTestFixture, EditorBlastSliceAssetHandler_AssetHandler_Ready) - { - auto assetType = azrtti_typeid(); - auto&& assetManager = AZ::Data::AssetManager::Instance(); - - Blast::EditorBlastSliceAssetHandler handler; - handler.Register(); - EXPECT_EQ(&handler, assetManager.GetHandler(assetType)); - - // create and release an instance of the BlastSliceAsset asset type - { - using ::testing::Return; - using ::testing::_; - - EXPECT_CALL(*m_mockAssetCatalogRequestBusHandler, GetAssetInfoById(_)) - .Times(1) - .WillRepeatedly(Return(AZ::Data::AssetInfo{})); - - auto assetPtr = assetManager.CreateAsset(AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0)); - EXPECT_NE(nullptr, assetPtr.Get()); - EXPECT_EQ(azrtti_typeid(), assetPtr.GetType()); - } - - handler.Unregister(); - } - - TEST_F(EditorBlastSliceAssetHandlerTestFixture, EditorBlastSliceAssetHandler_AssetHandler_LoadsAssetData) - { - SetUpSliceComponents(); - - AZStd::vector meshAssetPathList = { "/foo/path/thing.cgf", "/foo/path/that.cgf" }; - AZ::Entity* storageEntity = aznew AZ::Entity(); - auto* blastStorage = storageEntity->CreateComponent(); - blastStorage->SetMeshPathList(meshAssetPathList); - - AZ::Entity sliceEntity; - AZ::SliceComponent* slice = sliceEntity.CreateComponent(); - slice->AddEntity(storageEntity); - - AZStd::vector buffer; - SaveSliceAssetToStream(&sliceEntity, buffer); - - // Load a slice with the BlastSliceAssetStorageComponent - Blast::EditorBlastSliceAssetHandler handler; - handler.Register(); - { - using ::testing::Return; - using ::testing::_; - - EXPECT_CALL(*m_mockComponentApplicationBusHandler, GetSerializeContext) - .Times(1) - .WillOnce(Return(m_serializeContext.get())); - - EXPECT_CALL(*m_mockComponentApplicationBusHandler, FindEntity(_)) - .Times(1) - .WillOnce(Return(&sliceEntity)); - - EXPECT_CALL(*m_mockAssetCatalogRequestBusHandler, GetAssetIdByPath(_,_,_)) - .Times(2) - .WillRepeatedly(Return(AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0))); - - EXPECT_CALL(*m_mockAssetCatalogRequestBusHandler, GetAssetInfoById(_)) - .Times(2) - .WillRepeatedly(Return(AZ::Data::AssetInfo{})); - - auto&& assetManager = AZ::Data::AssetManager::Instance(); - auto assetPtr = assetManager.CreateAsset(AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0)); - - AZ::IO::ByteContainerStream> stream(&buffer); - stream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN); - - const AZ::Data::AssetFilterCB assetLoadFilterCB{}; - bool loaded = handler.LoadAssetData(assetPtr, &stream, assetLoadFilterCB); - EXPECT_TRUE(loaded); - } - handler.Unregister(); - - TearDownSliceComponents(); - } -} diff --git a/Gems/Blast/Code/blast_editor_files.cmake b/Gems/Blast/Code/blast_editor_files.cmake index 7d417176a2..dc991fb8a9 100644 --- a/Gems/Blast/Code/blast_editor_files.cmake +++ b/Gems/Blast/Code/blast_editor_files.cmake @@ -11,8 +11,8 @@ set(FILES Source/Editor/EditorBlastFamilyComponent.cpp Source/Editor/EditorBlastMeshDataComponent.cpp Source/Editor/EditorBlastMeshDataComponent.h - Source/Editor/EditorBlastSliceAssetHandler.h - Source/Editor/EditorBlastSliceAssetHandler.cpp + Source/Editor/EditorBlastChunksAssetHandler.h + Source/Editor/EditorBlastChunksAssetHandler.cpp Source/Editor/EditorSystemComponent.h Source/Editor/EditorSystemComponent.cpp Editor/ConfigurationWidget.h diff --git a/Gems/Blast/Code/blast_editor_tests_files.cmake b/Gems/Blast/Code/blast_editor_tests_files.cmake index 4e2a63d75c..7076530312 100644 --- a/Gems/Blast/Code/blast_editor_tests_files.cmake +++ b/Gems/Blast/Code/blast_editor_tests_files.cmake @@ -7,6 +7,6 @@ # set(FILES - # Tests/Editor/EditorBlastSliceAssetHandlerTest.cpp + Tests/Editor/EditorBlastChunksAssetHandlerTest.cpp Tests/Editor/EditorTestMain.cpp ) diff --git a/Gems/Blast/Code/blast_files.cmake b/Gems/Blast/Code/blast_files.cmake index 1707ec46a0..530d9cf7ca 100644 --- a/Gems/Blast/Code/blast_files.cmake +++ b/Gems/Blast/Code/blast_files.cmake @@ -26,8 +26,8 @@ set(FILES Source/Asset/BlastAsset.cpp Source/Asset/BlastAssetHandler.h Source/Asset/BlastAssetHandler.cpp - Source/Asset/BlastSliceAsset.h - Source/Asset/BlastSliceAsset.cpp + Source/Asset/BlastChunksAsset.h + Source/Asset/BlastChunksAsset.cpp Source/Components/BlastFamilyComponent.h Source/Components/BlastFamilyComponent.cpp Source/Components/BlastFamilyComponentNotificationBusHandler.h diff --git a/Gems/Blast/Editor/Scripts/asset_builder_blast.py b/Gems/Blast/Editor/Scripts/asset_builder_blast.py deleted file mode 100755 index beb455e335..0000000000 --- a/Gems/Blast/Editor/Scripts/asset_builder_blast.py +++ /dev/null @@ -1,323 +0,0 @@ -""" -Copyright (c) Contributors to the Open 3D Engine Project. -For complete copyright and license terms please see the LICENSE at the root of this distribution. - -SPDX-License-Identifier: Apache-2.0 OR MIT -""" -def install_user_site(): - import os - import sys - import azlmbr.paths - executableBinFolder = azlmbr.paths.executableFolder - - # the PyAssImp module checks the Windows PATH for the assimp DLL file - if os.name == "nt": - os.environ['PATH'] = os.environ['PATH'] + os.pathsep + executableBinFolder - - # PyAssImp module needs to find the shared library for assimp to load; "posix" handles Mac and Linux - if os.name == "posix": - if 'LD_LIBRARY_PATH' in os.environ: - os.environ['LD_LIBRARY_PATH'] = os.environ['LD_LIBRARY_PATH'] + os.pathsep + executableBinFolder - else: - os.environ['LD_LIBRARY_PATH'] = executableBinFolder - - # add the user site packages folder to find the pyassimp egg link - import site - for item in sys.path: - if (item.find('site-packages') != -1): - site.addsitedir(item) - -install_user_site() -import pyassimp - -import azlmbr.asset -import azlmbr.asset.builder -import azlmbr.asset.entity -import azlmbr.blast -import azlmbr.bus as bus -import azlmbr.editor as editor -import azlmbr.entity -import azlmbr.math -import os -import traceback -import binascii -import sys - -# the UUID must be unique amongst all the asset builders in Python or otherwise -# a collision of builders will happen preventing one from running -busIdString = '{CF5C74D1-9ED4-4851-85B1-9B15090DBEC7}' -busId = azlmbr.math.Uuid_CreateString(busIdString, 0) -handler = None -jobKeyName = 'Blast Chunk Assets' -sceneManifestType = azlmbr.math.Uuid_CreateString('{9274AD17-3212-4651-9F3B-7DCCB080E467}', 0) -dccMaterialType = azlmbr.math.Uuid_CreateString('{C88469CF-21E7-41EB-96FD-BF14FBB05EDC}', 0) - - -def log_exception_traceback(): - exc_type, exc_value, exc_tb = sys.exc_info() - data = traceback.format_exception(exc_type, exc_value, exc_tb) - print(str(data)) - - -def get_source_fbx_filename(request): - fullPath = os.path.join(request.watchFolder, request.sourceFile) - basePath, filePart = os.path.split(fullPath) - filename = os.path.splitext(filePart)[0] + '.fbx' - filename = os.path.join(basePath, filename) - return filename - - -def raise_error(message): - raise RuntimeError(f'[ERROR]: {message}') - - -def generate_asset_info(chunkNames, request): - import azlmbr.blast - - # write out an object stream with the extension of .fbx.assetinfo.generated - basePath, sceneFile = os.path.split(request.sourceFile) - assetinfoFilename = os.path.splitext(sceneFile)[0] + '.fbx.assetinfo.generated' - assetinfoFilename = os.path.join(basePath, assetinfoFilename) - assetinfoFilename = assetinfoFilename.replace('\\', '/').lower() - outputFilename = os.path.join(request.tempDirPath, assetinfoFilename) - - storage = azlmbr.blast.BlastSliceAssetStorageComponent() - if (storage.GenerateAssetInfo(chunkNames, request.sourceFile, outputFilename)): - product = azlmbr.asset.builder.JobProduct(assetinfoFilename, sceneManifestType, 1) - product.dependenciesHandled = True - return product - raise_error('Failed to generate assetinfo.generated') - - -def export_fbx_manifest(request): - output = [] - fbxFilename = get_source_fbx_filename(request) - sceneAsset = pyassimp.load(fbxFilename) - with sceneAsset as scene: - rootNode = scene.mRootNode.contents - for index in range(0, rootNode.mNumChildren): - child = rootNode.mChildren[index] - childNode = child.contents - childNodeName = bytes.decode(childNode.mName.data) - output.append(str(childNodeName)) - return output - - -def convert_to_asset_paths(fbxFilename, gameRoot, chunkNameList): - realtivePath = fbxFilename[len(gameRoot) + 1:] - realtivePath = os.path.splitext(realtivePath)[0] - output = [] - for chunk in chunkNameList: - assetPath = realtivePath + '-' + chunk + '.cgf' - assetPath = assetPath.replace('\\', '/') - assetPath = assetPath.lower() - output.append(assetPath) - return output - - -# creates a single job to compile for each platform -def create_jobs(request): - fbxSidecarFilename = get_source_fbx_filename(request) - if (os.path.exists(fbxSidecarFilename) is False): - print('[WARN] Sidecar FBX file {} is missing for blast file {}'.format(fbxSidecarFilename, request.sourceFile)) - return azlmbr.asset.builder.CreateJobsResponse() - - # see if the FBX file already has a .assetinfo source asset, if so then do not create a job - if (os.path.exists(f'{fbxSidecarFilename}.assetinfo')): - response = azlmbr.asset.builder.CreateJobsResponse() - response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess - return response - - # create job descriptor for each platform - jobDescriptorList = [] - for platformInfo in request.enabledPlatforms: - jobDesc = azlmbr.asset.builder.JobDescriptor() - jobDesc.jobKey = jobKeyName - jobDesc.priority = 12 # higher than the 'Scene compilation' or 'fbx' - jobDesc.set_platform_identifier(platformInfo.identifier) - jobDescriptorList.append(jobDesc) - - response = azlmbr.asset.builder.CreateJobsResponse() - response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess - response.createJobOutputs = jobDescriptorList - return response - -# handler to create jobs for a source asset - - -def on_create_jobs(args): - try: - request = args[0] - return create_jobs(request) - except: - log_exception_traceback() - return azlmbr.asset.builder.CreateJobsResponse() - - -def generate_blast_slice_asset(chunkNameList, request): - # get list of relative chunk paths - fbxFilename = get_source_fbx_filename(request) - assetPaths = convert_to_asset_paths(fbxFilename, request.watchFolder, chunkNameList) - - outcome = azlmbr.asset.entity.PythonBuilderRequestBus(bus.Broadcast, 'CreateEditorEntity', 'BlastData') - if (outcome.IsSuccess() is False): - raise_error('could not create an editor entity') - blastDataEntityId = outcome.GetValue() - - # create a component for the editor entity - gameType = azlmbr.entity.EntityType().Game - blastMeshDataTypeIdList = editor.EditorComponentAPIBus(bus.Broadcast, 'FindComponentTypeIdsByEntityType', ["Blast Slice Storage Component"], gameType) - componentOutcome = editor.EditorComponentAPIBus(bus.Broadcast, 'AddComponentOfType', blastDataEntityId, blastMeshDataTypeIdList[0]) - if (componentOutcome.IsSuccess() is False): - raise_error('failed to add component (Blast Slice Storage Component) to the blast_slice') - - # build the blast slice using the chunk asset paths - blastMeshComponentId = componentOutcome.GetValue()[0] - outcome = editor.EditorComponentAPIBus(bus.Broadcast, 'BuildComponentPropertyTreeEditor', blastMeshComponentId) - if(outcome.IsSuccess() is False): - raise_error(f'failed to create Property Tree Editor for component ({blastMeshComponentId})') - pte = outcome.GetValue() - pte.set_visible_enforcement(True) - pte.set_value('Mesh Paths', assetPaths) - - # write out an object stream with the extension of .blast_slice - basePath, sceneFile = os.path.split(request.sourceFile) - blastFilename = os.path.splitext(sceneFile)[0] + '.blast_slice' - blastFilename = os.path.join(basePath, blastFilename) - blastFilename = blastFilename.replace('\\', '/').lower() - tempFilename = os.path.join(request.tempDirPath, blastFilename) - entityList = [blastDataEntityId] - makeDynamic = False - outcome = azlmbr.asset.entity.PythonBuilderRequestBus(bus.Broadcast, 'WriteSliceFile', tempFilename, entityList, makeDynamic) - if (outcome.IsSuccess() is False): - raise_error(f'WriteSliceFile failed for blast_slice file ({blastFilename})') - - # return a job product - blastSliceAsset = azlmbr.blast.BlastSliceAsset() - subId = binascii.crc32(blastFilename.encode('utf8')) - product = azlmbr.asset.builder.JobProduct(blastFilename, blastSliceAsset.GetAssetTypeId(), subId) - product.dependenciesHandled = True - return product - - -def read_in_string(data, dataLength): - stringData = '' - for idx in range(4, dataLength - 1): - char = bytes.decode(data[idx]) - if (str.isascii(char)): - stringData += char - return stringData - - -def import_material_info(fbxFilename): - _, group_name = os.path.split(fbxFilename) - group_name = os.path.splitext(group_name)[0] - output = {} - output['group_name'] = group_name - output['material_name_list'] = [] - sceneAsset = pyassimp.load(fbxFilename) - with sceneAsset as scene: - for materialIndex in range(0, scene.mNumMaterials): - material = scene.mMaterials[materialIndex].contents - for materialPropertyIdx in range(0, material.mNumProperties): - materialProperty = material.mProperties[materialPropertyIdx].contents - materialPropertyName = bytes.decode(materialProperty.mKey.data) - if (materialPropertyName.endswith('mat.name') and materialProperty.mType is 3): - stringData = read_in_string(materialProperty.mData, materialProperty.mDataLength) - output['material_name_list'].append(stringData) - return output - - -def write_material_file(sourceFile, destFolder): - # preserve source MTL files - rootPath, materialSourceFile = os.path.split(sourceFile) - materialSourceFile = os.path.splitext(materialSourceFile)[0] + '.mtl' - materialSourceFile = os.path.join(rootPath, materialSourceFile) - if (os.path.exists(materialSourceFile)): - print(f'{materialSourceFile} source already exists') - return None - - # auto-generate a DCC material file - info = import_material_info(sourceFile) - materialGroupName = info['group_name'] - materialNames = info['material_name_list'] - materialFilename = materialGroupName + '.dccmtl.generated' - subId = binascii.crc32(materialFilename.encode('utf8')) - materialFilename = os.path.join(destFolder, materialFilename) - storage = azlmbr.blast.BlastSliceAssetStorageComponent() - storage.WriteMaterialFile(materialGroupName, materialNames, materialFilename) - product = azlmbr.asset.builder.JobProduct(materialFilename, dccMaterialType, subId) - product.dependenciesHandled = True - return product - - -def process_fbx_file(request): - # fill out response object - response = azlmbr.asset.builder.ProcessJobResponse() - productOutputs = [] - - # write out DCCMTL file as a product (if needed) - materialProduct = write_material_file(get_source_fbx_filename(request), request.tempDirPath) - if (materialProduct is not None): - productOutputs.append(materialProduct) - - # prepare output folder - basePath, _ = os.path.split(request.sourceFile) - outputPath = os.path.join(request.tempDirPath, basePath) - os.makedirs(outputPath) - - # parse FBX for chunk names - chunkNameList = export_fbx_manifest(request) - - # create assetinfo generated (is product) - productOutputs.append(generate_asset_info(chunkNameList, request)) - - # write out the blast_slice object stream - productOutputs.append(generate_blast_slice_asset(chunkNameList, request)) - - response.outputProducts = productOutputs - response.resultCode = azlmbr.asset.builder.ProcessJobResponse_Success - response.dependenciesHandled = True - return response - - -# using the incoming 'request' find the type of job via 'jobKey' to determine what to do -def on_process_job(args): - try: - request = args[0] - if (request.jobDescription.jobKey.startswith(jobKeyName)): - return process_fbx_file(request) - - return azlmbr.asset.builder.ProcessJobResponse() - except: - log_exception_traceback() - return azlmbr.asset.builder.ProcessJobResponse() - -# register asset builder -def register_asset_builder(): - assetPattern = azlmbr.asset.builder.AssetBuilderPattern() - assetPattern.pattern = '*.blast' - assetPattern.type = azlmbr.asset.builder.AssetBuilderPattern_Wildcard - - builderDescriptor = azlmbr.asset.builder.AssetBuilderDesc() - builderDescriptor.name = "Blast Gem" - builderDescriptor.patterns = [assetPattern] - builderDescriptor.busId = busId - builderDescriptor.version = 5 - - outcome = azlmbr.asset.builder.PythonAssetBuilderRequestBus(azlmbr.bus.Broadcast, 'RegisterAssetBuilder', builderDescriptor) - if outcome.IsSuccess(): - # created the asset builder to hook into the notification bus - handler = azlmbr.asset.builder.PythonBuilderNotificationBusHandler() - handler.connect(busId) - handler.add_callback('OnCreateJobsRequest', on_create_jobs) - handler.add_callback('OnProcessJobRequest', on_process_job) - return handler - - -# create the asset builder handler -try: - handler = register_asset_builder() -except: - handler = None - log_exception_traceback() diff --git a/Gems/Blast/Editor/Scripts/blast_asset_builder.py b/Gems/Blast/Editor/Scripts/blast_asset_builder.py new file mode 100644 index 0000000000..06dc15f5c1 --- /dev/null +++ b/Gems/Blast/Editor/Scripts/blast_asset_builder.py @@ -0,0 +1,290 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT +""" + +""" +This a Python Asset Builder script examines each .blast file to see if an +associated .fbx file needs to be processed by exporting all of its chunks +into a scene manifest + +This is also a SceneAPI script that executes from a foo.fbx.assetinfo scene +manifest that writes out asset chunk data for .blast files +""" +import os, traceback, binascii, sys, json, pathlib +import azlmbr.math +import azlmbr.asset +import azlmbr.asset.entity +import azlmbr.asset.builder +import azlmbr.bus + +# +# Python Asset Builder +# +busId = azlmbr.math.Uuid_CreateString('{D4FA20E3-8EF4-44A3-A045-AAE6C1CCAAAB}', 0) +jobKeyName = 'Blast Chunk Assets' + +def log_exception_traceback(): + exc_type, exc_value, exc_tb = sys.exc_info() + data = traceback.format_exception(exc_type, exc_value, exc_tb) + print(str(data)) + +def raise_error(message): + print (f'ERROR - {message}'); + raise RuntimeError(f'[ERROR]: {message}'); + +# creates a single job to compile for each platform +def get_source_fbx_filename(request): + fullPath = os.path.join(request.watchFolder, request.sourceFile) + basePath, filePart = os.path.split(fullPath) + filename = os.path.splitext(filePart)[0] + '.fbx' + filename = os.path.join(basePath, filename) + return filename + +def create_jobs(request): + fbxSidecarFilename = get_source_fbx_filename(request) + if (os.path.exists(fbxSidecarFilename) is False): + print('[WARN] Sidecar FBX file {} is missing for blast file {}'.format(fbxSidecarFilename, request.sourceFile)) + return azlmbr.asset.builder.CreateJobsResponse() + + # see if the FBX file already has a .assetinfo source asset, if so then do not create a job + establishedAssetInfo = f'{fbxSidecarFilename}.assetinfo'; + if (os.path.exists(establishedAssetInfo)): + response = azlmbr.asset.builder.CreateJobsResponse() + response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess + return response + + # create job descriptor for each platform + jobDescriptorList = [] + for platformInfo in request.enabledPlatforms: + sourceFileDependency = azlmbr.asset.builder.SourceFileDependency() + sourceFileDependency.sourceFileDependencyPath = fbxSidecarFilename + + jobDependency = azlmbr.asset.builder.JobDependency() + jobDependency.sourceFile = sourceFileDependency + jobDependency.jobKey = jobKeyName + jobDependency.platformIdentifier = platformInfo.identifier + + jobDesc = azlmbr.asset.builder.JobDescriptor() + jobDesc.jobKey = jobKeyName + jobDesc.set_platform_identifier(platformInfo.identifier) + jobDesc.jobDependencyList = [jobDependency] + jobDescriptorList.append(jobDesc) + + response = azlmbr.asset.builder.CreateJobsResponse() + response.result = azlmbr.asset.builder.CreateJobsResponse_ResultSuccess + response.createJobOutputs = jobDescriptorList + return response + +# to create jobs for a source asset +def on_create_jobs(args): + try: + request = args[0] + return create_jobs(request) + except: + log_exception_traceback() + return azlmbr.asset.builder.CreateJobsResponse() + +def generate_assetinfo_product(request): + # write out a product asset file with the extension of .fbx.assetinfo.generated + basePath, sceneFile = os.path.split(request.sourceFile) + assetinfoFilename = os.path.splitext(sceneFile)[0] + '.fbx.assetinfo.generated' + assetinfoFilename = os.path.join(basePath, assetinfoFilename) + assetinfoFilename = assetinfoFilename.replace('\\', '/').lower() + outputFilename = os.path.join(request.tempDirPath, assetinfoFilename) + + # the only rule in it is to run this file again as a scene processor + currentScript = pathlib.Path(__file__).resolve() + aDict = {"values": [{"$type": "ScriptProcessorRule", "scriptFilename": f"{currentScript}"}]} + jsonString = json.dumps(aDict) + jsonFile = open(outputFilename, "w") + jsonFile.write(jsonString) + jsonFile.close() + + # return a job product for the generated assetinfo file + sceneManifestType = azlmbr.math.Uuid_CreateString('{9274AD17-3212-4651-9F3B-7DCCB080E467}', 0) + subId = 1 + product = azlmbr.asset.builder.JobProduct(outputFilename, sceneManifestType, subId) + product.dependenciesHandled = True + return product + +def process_fbx_file(request): + # fill out response object + response = azlmbr.asset.builder.ProcessJobResponse() + productOutputs = [] + + # prepare output folder + basePath, _ = os.path.split(request.sourceFile) + outputPath = os.path.join(request.tempDirPath, basePath) + os.makedirs(outputPath) + + # create assetinfo generated file + productOutputs.append(generate_assetinfo_product(request)) + + response.outputProducts = productOutputs + response.resultCode = azlmbr.asset.builder.ProcessJobResponse_Success + response.dependenciesHandled = True + return response + +# using the incoming 'request' find the type of job via 'jobKey' to determine what to do +def on_process_job(args): + try: + request = args[0] + if (request.jobDescription.jobKey.startswith(jobKeyName)): + return process_fbx_file(request) + + return azlmbr.asset.builder.ProcessJobResponse() + except: + log_exception_traceback() + return azlmbr.asset.builder.ProcessJobResponse() + +# register asset builder +def register_asset_builder(): + assetPattern = azlmbr.asset.builder.AssetBuilderPattern() + assetPattern.pattern = '*.blast' + assetPattern.type = azlmbr.asset.builder.AssetBuilderPattern_Wildcard + + builderDescriptor = azlmbr.asset.builder.AssetBuilderDesc() + builderDescriptor.name = "Blast Scene Builder" + builderDescriptor.patterns = [assetPattern] + builderDescriptor.busId = busId + builderDescriptor.version = 1 + + outcome = azlmbr.asset.builder.PythonAssetBuilderRequestBus(azlmbr.bus.Broadcast, 'RegisterAssetBuilder', builderDescriptor) + if outcome.IsSuccess(): + # created the asset builder to hook into the notification bus + handler = azlmbr.asset.builder.PythonBuilderNotificationBusHandler() + handler.connect(busId) + handler.add_callback('OnCreateJobsRequest', on_create_jobs) + handler.add_callback('OnProcessJobRequest', on_process_job) + return handler + +# create the asset builder handler +pythonAssetBuilderHandler = None +try: + if (pythonAssetBuilderHandler == None): + pythonAssetBuilderHandler = register_asset_builder() +except: + pythonAssetBuilderHandler = None + +# +# SceneAPI Processor +# +blastChunksAssetType = azlmbr.math.Uuid_CreateString('{993F0B0F-37D9-48C6-9CC2-E27D3F3E343E}', 0) + +def export_chunk_asset(scene, outputDirectory, platformIdentifier, productList): + import azlmbr.scene + import azlmbr.object + import azlmbr.paths + import json, os + + jsonFilename = os.path.basename(scene.sourceFilename) + jsonFilename = os.path.join(outputDirectory, jsonFilename + '.blast_chunks') + + # prepare output folder + basePath, _ = os.path.split(jsonFilename) + outputPath = os.path.join(outputDirectory, basePath) + if not os.path.exists(outputPath): + os.makedirs(outputPath, False) + + # write out a JSON file with the chunk file info + with open(jsonFilename, "w") as jsonFile: + jsonFile.write(scene.manifest.ExportToJson()) + + exportProduct = azlmbr.scene.ExportProduct() + exportProduct.filename = jsonFilename + exportProduct.sourceId = scene.sourceGuid + exportProduct.assetType = blastChunksAssetType + exportProduct.subId = 101 + + exportProductList = azlmbr.scene.ExportProductList() + exportProductList.AddProduct(exportProduct) + return exportProductList + +def on_prepare_for_export(args): + try: + scene = args[0] # azlmbr.scene.Scene + outputDirectory = args[1] # string + platformIdentifier = args[2] # string + productList = args[3] # azlmbr.scene.ExportProductList + return export_chunk_asset(scene, outputDirectory, platformIdentifier, productList) + except: + log_exception_traceback() + +def get_mesh_node_names(sceneGraph): + import azlmbr.scene as sceneApi + import azlmbr.scene.graph + from scene_api import scene_data as sceneData + + meshDataList = [] + node = sceneGraph.get_root() + children = [] + + while node.IsValid(): + # store children to process after siblings + if sceneGraph.has_node_child(node): + children.append(sceneGraph.get_node_child(node)) + + # store any node that has mesh data content + nodeContent = sceneGraph.get_node_content(node) + if nodeContent is not None and nodeContent.CastWithTypeName('MeshData'): + if sceneGraph.is_node_end_point(node) is False: + nodeName = sceneData.SceneGraphName(sceneGraph.get_node_name(node)) + nodePath = nodeName.get_path() + if (len(nodeName.get_path())): + meshDataList.append(sceneData.SceneGraphName(sceneGraph.get_node_name(node))) + + # advance to next node + if sceneGraph.has_node_sibling(node): + node = sceneGraph.get_node_sibling(node) + elif children: + node = children.pop() + else: + node = azlmbr.scene.graph.NodeIndex() + + return meshDataList + +def update_manifest(scene): + import uuid, os + import azlmbr.scene as sceneApi + import azlmbr.scene.graph + from scene_api import scene_data as sceneData + + graph = sceneData.SceneGraph(scene.graph) + meshNameList = get_mesh_node_names(graph) + sceneManifest = sceneData.SceneManifest() + sourceFilenameOnly = os.path.basename(scene.sourceFilename) + sourceFilenameOnly = sourceFilenameOnly.replace('.','_') + + for activeMeshIndex in range(len(meshNameList)): + chunkName = meshNameList[activeMeshIndex] + chunkPath = chunkName.get_path() + meshGroupName = '{}_{}'.format(sourceFilenameOnly, chunkName.get_name()) + meshGroup = sceneManifest.add_mesh_group(meshGroupName) + meshGroup['id'] = '{' + str(uuid.uuid5(uuid.NAMESPACE_DNS, sourceFilenameOnly + chunkPath)) + '}' + sceneManifest.mesh_group_select_node(meshGroup, chunkPath) + + return sceneManifest.export() + +sceneJobHandler = None + +def on_update_manifest(args): + try: + scene = args[0] + return update_manifest(scene) + except: + global sceneJobHandler + sceneJobHandler = None + log_exception_traceback() + +# try to create SceneAPI handler for processing +try: + import azlmbr.scene as sceneApi + if (sceneJobHandler == None): + sceneJobHandler = sceneApi.ScriptBuildingNotificationBusHandler() + sceneJobHandler.connect() + sceneJobHandler.add_callback('OnUpdateManifest', on_update_manifest) + sceneJobHandler.add_callback('OnPrepareForExport', on_prepare_for_export) +except: + sceneJobHandler = None diff --git a/Gems/Blast/Editor/Scripts/bootstrap.py b/Gems/Blast/Editor/Scripts/bootstrap.py index d9687bb85b..93004d474f 100755 --- a/Gems/Blast/Editor/Scripts/bootstrap.py +++ b/Gems/Blast/Editor/Scripts/bootstrap.py @@ -4,6 +4,13 @@ For complete copyright and license terms please see the LICENSE at the root of t SPDX-License-Identifier: Apache-2.0 OR MIT """ - -# LYN-652 to re-enable once the Blast gem tests are stable -# import asset_builder_blast +try: + import azlmbr.asset + import azlmbr.asset.entity + import azlmbr.asset.builder + import blast_asset_builder +except: + # this script only runs in an asset processing environment + # like the AssetProcessor or an AssetBuilder + # plus the Blast gem needs to be enabled for the project + pass diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp index f72833df56..fe41312701 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeCommands.cpp @@ -11,6 +11,7 @@ #include "CommandManager.h" #include +#include #include #include #include @@ -858,8 +859,16 @@ namespace CommandSystem // add it to the old node group if it was assigned to one before if (!mNodeGroupName.empty()) { - commandString = AZStd::string::format("AnimGraphAdjustNodeGroup -animGraphID %i -name \"%s\" -nodeNames \"%s\" -nodeAction \"add\"", animGraph->GetID(), mNodeGroupName.c_str(), mName.c_str()); - if (GetCommandManager()->ExecuteCommandInsideCommand(commandString.c_str(), outResult) == false) + auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), + /*animGraphId = */ animGraph->GetID(), + /*name = */ mNodeGroupName, + /*visible = */ AZStd::nullopt, + /*newName = */ AZStd::nullopt, + /*nodeNames = */ {{mName}}, + /*nodeAction = */ CommandSystem::CommandAnimGraphAdjustNodeGroup::NodeAction::Add + ); + if (GetCommandManager()->ExecuteCommandInsideCommand(command, outResult) == false) { if (outResult.size() > 0) { @@ -1363,11 +1372,16 @@ namespace CommandSystem EMotionFX::AnimGraphNodeGroup* nodeGroup = node->GetAnimGraph()->FindNodeGroupForNode(node); if (nodeGroup && !cutMode) { - commandString = AZStd::string::format("AnimGraphAdjustNodeGroup -animGraphID %d -name \"%s\" -nodeNames \"%s\" -nodeAction \"add\"", - targetAnimGraph->GetID(), - nodeGroup->GetName(), - nodeName.c_str()); - commandGroup->AddCommandString(commandString); + auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), + /*animGraphId = */ targetAnimGraph->GetID(), + /*name = */ nodeGroup->GetNameString(), + /*visible = */ AZStd::nullopt, + /*newName = */ AZStd::nullopt, + /*nodeNames = */ {{nodeName}}, + /*nodeAction = */ CommandSystem::CommandAnimGraphAdjustNodeGroup::NodeAction::Add + ); + commandGroup->AddCommand(command); } // Recurse through the child nodes. diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp index 29ee45312b..f5f913f0ca 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.cpp @@ -6,6 +6,7 @@ * */ +#include #include #include "AnimGraphNodeGroupCommands.h" #include "AnimGraphConnectionCommands.h" @@ -22,45 +23,46 @@ namespace CommandSystem { + AZ_CLASS_ALLOCATOR_IMPL(CommandAnimGraphAdjustNodeGroup, EMotionFX::CommandAllocator, 0) + //-------------------------------------------------------------------------------- // CommandAnimGraphAdjustNodeGroup //-------------------------------------------------------------------------------- - CommandAnimGraphAdjustNodeGroup::CommandAnimGraphAdjustNodeGroup(MCore::Command* orgCommand) - : MCore::Command("AnimGraphAdjustNodeGroup", orgCommand) + CommandAnimGraphAdjustNodeGroup::CommandAnimGraphAdjustNodeGroup( + MCore::Command* orgCommand, + AZ::u32 animGraphId, + AZStd::string name, + AZStd::optional visible, + AZStd::optional newName, + AZStd::optional> nodeNames, + AZStd::optional nodeAction, + AZStd::optional color, + AZStd::optional updateUI + ) + : MCore::Command(s_commandName, orgCommand) + , ParameterMixinAnimGraphId(animGraphId) + , m_name(AZStd::move(name)) + , m_isVisible(visible) + , m_newName(AZStd::move(newName)) + , m_nodeNames(AZStd::move(nodeNames)) + , m_nodeAction(nodeAction) + , m_color(color) + , m_updateUI(updateUI) { } - - CommandAnimGraphAdjustNodeGroup::~CommandAnimGraphAdjustNodeGroup() + AZStd::vector CommandAnimGraphAdjustNodeGroup::GenerateNodeNameVector(EMotionFX::AnimGraph* animGraph, const AZStd::vector& nodeIDs) { - } - - - AZStd::string CommandAnimGraphAdjustNodeGroup::GenerateNodeNameString(EMotionFX::AnimGraph* animGraph, const AZStd::vector& nodeIDs) - { - if (nodeIDs.empty()) + AZStd::vector result; + for (const auto& nodeID : nodeIDs) { - return ""; - } - - AZStd::string result; - - const size_t numNodes = nodeIDs.size(); - for (size_t i = 0; i < numNodes; ++i) - { - EMotionFX::AnimGraphNode* animGraphNode = animGraph->RecursiveFindNodeById(nodeIDs[i]); + const EMotionFX::AnimGraphNode* animGraphNode = animGraph->RecursiveFindNodeById(nodeID); if (!animGraphNode) { continue; } - - result += animGraphNode->GetName(); - if (i < numNodes - 1) - { - result += ';'; - } + result.emplace_back(animGraphNode->GetName()); } - return result; } @@ -80,78 +82,51 @@ namespace CommandSystem } - bool CommandAnimGraphAdjustNodeGroup::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) + bool CommandAnimGraphAdjustNodeGroup::Execute(const MCore::CommandLine&, AZStd::string& outResult) { - EMotionFX::AnimGraph* animGraph = CommandsGetAnimGraph(parameters, this, outResult); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); if (!animGraph) { return false; } - // get the node group name - AZStd::string groupName; - parameters.GetValue("name", this, groupName); - // find the node group index - const uint32 groupIndex = animGraph->FindNodeGroupIndexByName(groupName.c_str()); + const uint32 groupIndex = animGraph->FindNodeGroupIndexByName(m_name.c_str()); if (groupIndex == MCORE_INVALIDINDEX32) { - outResult = AZStd::string::format("Node group \"%s\" can not be found.", groupName.c_str()); + outResult = AZStd::string::format("Node group \"%s\" can not be found.", m_name.c_str()); return false; } - // get a pointer to the node group and keep the old name EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(groupIndex); - mOldName = nodeGroup->GetName(); - // is visible? - if (parameters.CheckIfHasParameter("isVisible")) + if (m_isVisible.has_value()) { - const bool isVisible = parameters.GetValueAsBool("isVisible", this); - mOldIsVisible = nodeGroup->GetIsVisible(); - nodeGroup->SetIsVisible(isVisible); + m_oldIsVisible = nodeGroup->GetIsVisible(); + nodeGroup->SetIsVisible(*m_isVisible); } - // background color - if (parameters.CheckIfHasParameter("color")) + if (m_color.has_value()) { - const AZ::Vector4 colorVector4 = parameters.GetValueAsVector4("color", this); - const AZ::u32 color = AZ::Color(static_cast(colorVector4.GetX()), static_cast(colorVector4.GetY()), static_cast(colorVector4.GetZ()), static_cast(colorVector4.GetW())).ToU32(); - mOldColor = nodeGroup->GetColor(); - nodeGroup->SetColor(color); + m_oldColor = nodeGroup->GetColor(); + nodeGroup->SetColor(*m_color); } - // set the new name - // if the new name is empty, the name is not changed - AZStd::string newGroupName; - parameters.GetValue("newName", this, newGroupName); - if (!newGroupName.empty()) + if (m_newName.has_value()) { - nodeGroup->SetName(newGroupName.c_str()); + nodeGroup->SetName(m_newName->c_str()); } // check if parametes nodeNames is set - if (parameters.CheckIfHasParameter("nodeNames")) + if (m_nodeNames.has_value()) { // keep the old nodes IDs - mOldNodeIds = CollectNodeIdsFromGroup(nodeGroup); - - // get the node action - AZStd::string nodeAction; - parameters.GetValue("nodeAction", this, nodeAction); - - // get the node names and split the string - AZStd::string nodeNamesString; - parameters.GetValue("nodeNames", this, nodeNamesString); - - - AZStd::vector nodeNames; - AzFramework::StringFunc::Tokenize(nodeNamesString.c_str(), nodeNames, ";", false, true); + m_oldNodeIds = CollectNodeIdsFromGroup(nodeGroup); // remove the selected nodes from the given node group - if (AzFramework::StringFunc::Equal(nodeAction.c_str(), "remove")) + if (*m_nodeAction == NodeAction::Remove) { - for (const AZStd::string& nodeName : nodeNames) + for (const AZStd::string& nodeName : *m_nodeNames) { EMotionFX::AnimGraphNode* animGraphNode = animGraph->RecursiveFindNodeByName(nodeName.c_str()); if (!animGraphNode) @@ -163,9 +138,9 @@ namespace CommandSystem nodeGroup->RemoveNodeById(animGraphNode->GetId()); } } - else if (AzFramework::StringFunc::Equal(nodeAction.c_str(), "add")) // add the selected nodes to the given node group + else if (*m_nodeAction == NodeAction::Add) { - for (const AZStd::string& nodeName : nodeNames) + for (const AZStd::string& nodeName : *m_nodeNames) { EMotionFX::AnimGraphNode* animGraphNode = animGraph->RecursiveFindNodeByName(nodeName.c_str()); if (!animGraphNode) @@ -184,12 +159,12 @@ namespace CommandSystem nodeGroup->AddNode(animGraphNode->GetId()); } } - else if (AzFramework::StringFunc::Equal(nodeAction.c_str(), "replace")) // clear the node group and then add the selected nodes to the given node group + else if (*m_nodeAction == NodeAction::Replace) { // clear the node group upfront nodeGroup->RemoveAllNodes(); - for (const AZStd::string& nodeName : nodeNames) + for (const AZStd::string& nodeName : *m_nodeNames) { EMotionFX::AnimGraphNode* animGraphNode = animGraph->RecursiveFindNodeByName(nodeName.c_str()); if (!animGraphNode) @@ -211,68 +186,40 @@ namespace CommandSystem } // save the current dirty flag and tell the anim graph that something got changed - mOldDirtyFlag = animGraph->GetDirtyFlag(); + m_oldDirtyFlag = animGraph->GetDirtyFlag(); animGraph->SetDirtyFlag(true); return true; } // undo the command - bool CommandAnimGraphAdjustNodeGroup::Undo(const MCore::CommandLine& parameters, AZStd::string& outResult) + bool CommandAnimGraphAdjustNodeGroup::Undo(const MCore::CommandLine&, AZStd::string& outResult) { - EMotionFX::AnimGraph* animGraph = CommandsGetAnimGraph(parameters, this, outResult); + EMotionFX::AnimGraph* animGraph = EMotionFX::GetAnimGraphManager().FindAnimGraphByID(m_animGraphId); if (!animGraph) { return false; } - AZStd::string commandString = AZStd::string::format("AnimGraphAdjustNodeGroup -animGraphID %i", animGraph->GetID()); - - // set the old name or simply set the name if the name is not changed - if (parameters.CheckIfHasParameter("newName")) - { - AZStd::string newName; - parameters.GetValue("newName", this, newName); - - commandString += AZStd::string::format(" -name \"%s\"", newName.c_str()); - commandString += AZStd::string::format(" -newName \"%s\"", mOldName.c_str()); - } - else - { - commandString += AZStd::string::format(" -name \"%s\"", mOldName.c_str()); - } - - // set the old visible flag - if (parameters.CheckIfHasParameter("isVisible")) - { - commandString += AZStd::string::format(" -isVisible %i", mOldIsVisible); - } - - // set the old color - if (parameters.CheckIfHasParameter("color")) - { - AZ::Color oldColor; - oldColor.FromU32(mOldColor); - const AZStd::string oldColorString = AZStd::string::format("%.8f,%.8f,%.8f,%.8f", static_cast(oldColor.GetR()), static_cast(oldColor.GetG()), static_cast(oldColor.GetB()), static_cast(oldColor.GetA())); - - commandString += AZStd::string::format(" -color \"%s\"", oldColorString.c_str()); - } - - // set the old nodes - if (parameters.CheckIfHasParameter("nodeNames")) - { - const AZStd::string nodeNamesString = CommandAnimGraphAdjustNodeGroup::GenerateNodeNameString(animGraph, mOldNodeIds); - commandString += AZStd::string::format(" -nodeNames \"%s\" -nodeAction \"replace\"", nodeNamesString.c_str()); - } + CommandAnimGraphAdjustNodeGroup* command = aznew CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandAnimGraphAdjustNodeGroup::s_commandName), + /*animGraphId = */ m_animGraphId, + /*name = */ m_newName.has_value() ? *m_newName : m_name, + /*visible = */ m_isVisible.has_value() ? AZStd::optional(m_oldIsVisible) : AZStd::nullopt, + /*newName = */ m_newName.has_value() ? AZStd::optional(m_name) : AZStd::nullopt, + /*nodeNames = */ m_nodeNames.has_value() ? AZStd::optional>(GenerateNodeNameVector(animGraph, m_oldNodeIds)) : AZStd::nullopt, + /*nodeAction = */ m_nodeNames.has_value() ? AZStd::optional(NodeAction::Replace) : AZStd::nullopt, + /*color = */ m_color.has_value() ? AZStd::optional(m_oldColor) : AZStd::nullopt + ); // execute the command - if (!GetCommandManager()->ExecuteCommandInsideCommand(commandString, outResult)) + if (!GetCommandManager()->ExecuteCommandInsideCommand(command, outResult)) { AZ_Error("EMotionFX", false, outResult.c_str()); } // set the dirty flag back to the old value - animGraph->SetDirtyFlag(mOldDirtyFlag); + animGraph->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -282,7 +229,7 @@ namespace CommandSystem { GetSyntax().ReserveParameters(8); GetSyntax().AddRequiredParameter("name", "The name of the node group to adjust.", MCore::CommandSyntax::PARAMTYPE_STRING); - GetSyntax().AddParameter("animGraphID", "The id of the blend set the node group belongs to.", MCore::CommandSyntax::PARAMTYPE_INT, "-1"); + EMotionFX::ParameterMixinAnimGraphId::InitSyntax(GetSyntax(), /*isParameterRequired=*/ false); GetSyntax().AddParameter("isVisible", "The visibility flag of the node group.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "true"); GetSyntax().AddParameter("newName", "The new name of the node group.", MCore::CommandSyntax::PARAMTYPE_STRING, ""); GetSyntax().AddParameter("nodeNames", "A list of node names that should be added/removed to/from the node group.", MCore::CommandSyntax::PARAMTYPE_STRING, ""); @@ -291,6 +238,51 @@ namespace CommandSystem GetSyntax().AddParameter("updateUI", "Setting this to true will trigger a refresh of the node groups UI.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "true"); } + bool CommandAnimGraphAdjustNodeGroup::SetCommandParameters(const MCore::CommandLine& parameters) + { + EMotionFX::ParameterMixinAnimGraphId::SetCommandParameters(parameters); + m_name = parameters.GetValue("name", this); + + if (parameters.CheckIfHasParameter("isVisible")) + { + m_isVisible = parameters.GetValueAsBool("isVisible", this); + } + if (parameters.CheckIfHasParameter("newName")) + { + m_newName = parameters.GetValue("newName", this); + } + if (parameters.CheckIfHasParameter("nodeNames")) + { + m_nodeNames.emplace(); + AzFramework::StringFunc::Tokenize(parameters.GetValue("nodeNames", this), m_nodeNames.value(), ";", false, true); + } + if (parameters.CheckIfHasValue("nodeAction")) + { + const AZStd::string& nodeActionStr = parameters.GetValue("nodeAction", this); + if (nodeActionStr == "add") + { + m_nodeAction = NodeAction::Add; + } + else if (nodeActionStr == "remove") + { + m_nodeAction = NodeAction::Remove; + } + else if (nodeActionStr == "replace") + { + m_nodeAction = NodeAction::Replace; + } + } + if (parameters.CheckIfHasParameter("color")) + { + m_color = AZ::Color(parameters.GetValueAsVector4("color", this)).ToU32(); + } + if (parameters.CheckIfHasParameter("updateUI")) + { + m_updateUI = parameters.GetValueAsBool("updateUI", this); + } + + return true; + } const char* CommandAnimGraphAdjustNodeGroup::GetDescription() const { @@ -447,21 +439,20 @@ namespace CommandSystem MCore::CommandGroup commandGroup; - AZStd::string commandString = AZStd::string::format("AnimGraphAddNodeGroup -animGraphID %i -name \"%s\" -updateUI %s",animGraph->GetID(), mOldName.c_str(), updateWindow.c_str()); - commandGroup.AddCommandString(commandString); + commandGroup.AddCommandString(AZStd::string::format("AnimGraphAddNodeGroup -animGraphID %i -name \"%s\" -updateUI %s",animGraph->GetID(), mOldName.c_str(), updateWindow.c_str())); - const AZStd::string nodeNamesString = CommandAnimGraphAdjustNodeGroup::GenerateNodeNameString(animGraph, mOldNodeIds); + auto* command = aznew CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandAnimGraphAdjustNodeGroup::s_commandName), + /*animGraphId = */ animGraph->GetID(), + /*name = */ mOldName, + /*visible = */ mOldIsVisible, + /*newName = */ AZStd::nullopt, + /*nodeNames = */ CommandAnimGraphAdjustNodeGroup::GenerateNodeNameVector(animGraph, mOldNodeIds), + /*nodeAction = */ CommandAnimGraphAdjustNodeGroup::NodeAction::Add, + /*color = */ mOldColor + ); - AZ::Color oldColor; - oldColor.FromU32(mOldColor); - const AZStd::string oldColorString = AZStd::string::format("%.8f,%.8f,%.8f,%.8f", - static_cast(oldColor.GetR()), static_cast(oldColor.GetG()), static_cast(oldColor.GetB()), static_cast(oldColor.GetA())); - - commandString = AZStd::string::format( - "AnimGraphAdjustNodeGroup -animGraphID %i -name \"%s\" -isVisible %s -color \"%s\" -nodeNames \"%s\" -nodeAction \"add\" -updateUI %s", - animGraph->GetID(), mOldName.c_str(), AZStd::to_string(mOldIsVisible).c_str(), oldColorString.c_str(), nodeNamesString.c_str(), updateWindow.c_str()); - - commandGroup.AddCommandString(commandString); + commandGroup.AddCommand(command); AZStd::string result; if (!GetCommandManager()->ExecuteCommandGroupInsideCommand(commandGroup, result)) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h index 85bd92f970..0fc497d2f1 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/AnimGraphNodeGroupCommands.h @@ -13,22 +13,73 @@ #include #include #include +#include namespace CommandSystem { // adjust a node group - MCORE_DEFINECOMMAND_START(CommandAnimGraphAdjustNodeGroup, "Adjust anim graph node group", true) -public: - static AZStd::string GenerateNodeNameString(EMotionFX::AnimGraph* animGraph, const AZStd::vector& nodeIDs); - static AZStd::vector CollectNodeIdsFromGroup(EMotionFX::AnimGraphNodeGroup* nodeGroup); + class CommandAnimGraphAdjustNodeGroup + : public MCore::Command + , public EMotionFX::ParameterMixinAnimGraphId + { + public: + AZ_CLASS_ALLOCATOR_DECL - AZStd::string mOldName; - bool mOldIsVisible; - AZ::u32 mOldColor; - AZStd::vector mOldNodeIds; - bool mOldDirtyFlag; - MCORE_DEFINECOMMAND_END + static constexpr inline AZStd::string_view s_commandName = "AnimGraphAdjustNodeGroup"; + enum class NodeAction + { + Add, + Remove, + Replace + }; + + explicit CommandAnimGraphAdjustNodeGroup( + MCore::Command* orgCommand = nullptr, + AZ::u32 animGraphId = MCORE_INVALIDINDEX32, + AZStd::string name = AZStd::string{}, + AZStd::optional visible = AZStd::nullopt, + AZStd::optional newName = AZStd::nullopt, + AZStd::optional> nodeNames = AZStd::nullopt, + AZStd::optional nodeAction = AZStd::nullopt, + AZStd::optional color = AZStd::nullopt, + AZStd::optional updateUI = AZStd::nullopt + ); + bool Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) override; + bool Undo(const MCore::CommandLine& parameters, AZStd::string& outResult) override; + void InitSyntax() override; + bool SetCommandParameters(const MCore::CommandLine& parameters) override; + bool GetIsUndoable() const override + { + return true; + } + const char* GetHistoryName() const override + { + return "Adjust anim graph node group"; + } + const char* GetDescription() const override; + MCore::Command* Create() override + { + return new CommandAnimGraphAdjustNodeGroup(this); + } + + static AZStd::vector GenerateNodeNameVector(EMotionFX::AnimGraph* animGraph, const AZStd::vector& nodeIDs); + static AZStd::vector CollectNodeIdsFromGroup(EMotionFX::AnimGraphNodeGroup* nodeGroup); + + private: + AZStd::string m_name; + AZStd::optional m_isVisible; + AZStd::optional m_newName; + AZStd::optional> m_nodeNames; + AZStd::optional m_nodeAction; + AZStd::optional m_color; + AZStd::optional m_updateUI; + + bool m_oldIsVisible; + AZ::u32 m_oldColor; + AZStd::vector m_oldNodeIds; + bool m_oldDirtyFlag; + }; // add node group MCORE_DEFINECOMMAND_START(CommandAnimGraphAddNodeGroup, "Add anim graph node group", true) diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp index fe4a3e1ca9..ea83d90d4b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.cpp @@ -9,7 +9,7 @@ // include the required headers #include "NodeGroupCommands.h" #include "CommandManager.h" -#include +#include #include #include #include @@ -20,230 +20,147 @@ namespace CommandSystem //-------------------------------------------------------------------------------- // CommandAdjustNodeGroup //-------------------------------------------------------------------------------- + AZ_CLASS_ALLOCATOR_IMPL(CommandAdjustNodeGroup, EMotionFX::CommandAllocator, 0) - // constructor - CommandAdjustNodeGroup::CommandAdjustNodeGroup(MCore::Command* orgCommand) - : MCore::Command("AdjustNodeGroup", orgCommand) - , mOldNodeGroup(nullptr) + CommandAdjustNodeGroup::CommandAdjustNodeGroup( + MCore::Command* orgCommand, + uint32 actorId, + const AZStd::string& name, + AZStd::optional newName, + AZStd::optional enabledOnDefault, + AZStd::optional> nodeNames, + AZStd::optional nodeAction + ) + : MCore::Command(s_commandName.data(), orgCommand) + , EMotionFX::ParameterMixinActorId(actorId) + , m_name(name) + , m_newName(AZStd::move(newName)) + , m_enabledOnDefault(enabledOnDefault) + , m_nodeNames(AZStd::move(nodeNames)) + , m_nodeAction(nodeAction) { } - // destructor - CommandAdjustNodeGroup::~CommandAdjustNodeGroup() - { - if (mOldNodeGroup) - { - mOldNodeGroup->Destroy(); - } - } - - // execute - bool CommandAdjustNodeGroup::Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) + bool CommandAdjustNodeGroup::Execute(const MCore::CommandLine&, AZStd::string& outResult) { - AZStd::string valueString; - - // get the motion id and the corresponding motion pointer - const int32 actorID = parameters.GetValueAsInt("actorID", this); - parameters.GetValue("name", this, &valueString); - // get the actor - EMotionFX::Actor* actor = EMotionFX::GetActorManager().FindActorByID(actorID); + EMotionFX::Actor* actor = EMotionFX::GetActorManager().FindActorByID(m_actorId); if (actor == nullptr) { - outResult = AZStd::string::format("Cannot adjust node group. Actor with id='%i' does not exist.", actorID); + outResult = AZStd::string::format("Cannot adjust node group. Actor with id='%i' does not exist.", m_actorId); return false; } // get the node group - EMotionFX::NodeGroup* nodeGroup = actor->FindNodeGroupByNameNoCase(valueString.c_str()); + EMotionFX::NodeGroup* nodeGroup = actor->FindNodeGroupByNameNoCase(m_name.c_str()); if (nodeGroup == nullptr) { - outResult = AZStd::string::format("Cannot adjust node group. Node group with name='%s' does not exist.", valueString.c_str()); + outResult = AZStd::string::format("Cannot adjust node group. Node group with name='%s' does not exist.", m_name.c_str()); return false; } - // copy the old node group for undo - if (mOldNodeGroup) - { - mOldNodeGroup->Destroy(); - } - - mOldNodeGroup = aznew EMotionFX::NodeGroup(*nodeGroup); + m_oldNodeGroup = AZStd::make_unique(*nodeGroup); // check if newName is set and apply new name - if (parameters.CheckIfHasParameter("newName")) + if (m_newName.has_value()) { - parameters.GetValue("newName", this, &valueString); - nodeGroup->SetName(valueString.c_str()); + nodeGroup->SetName(*m_newName); } // check if parameter disabledOnDefault is set and adjust it - if (parameters.CheckIfHasParameter("enabledOnDefault")) + if (m_enabledOnDefault.has_value()) { - const bool enabledOnDefault = parameters.GetValueAsBool("enabledOnDefault", this); - nodeGroup->SetIsEnabledOnDefault(enabledOnDefault); + nodeGroup->SetIsEnabledOnDefault(*m_enabledOnDefault); } // check if parametes nodeNames is set - if (parameters.CheckIfHasParameter("nodeNames")) + if (m_nodeNames.has_value()) { - // get the node action - AZStd::string nodeAction; - parameters.GetValue("nodeAction", this, &valueString); - - // get the node names and split the string - AZStd::string nodeNameString; - parameters.GetValue("nodeNames", this, &nodeNameString); - - // get the individual node names - AZStd::vector nodeNames; - AzFramework::StringFunc::Tokenize(nodeNameString.c_str(), nodeNames, MCore::CharacterConstants::semiColon, true /* keep empty strings */, true /* keep space strings */); - - // get the number of nodes - const size_t numNodes = nodeNames.size(); - - // remove the selected nodes from the node group - if (AzFramework::StringFunc::Equal(valueString.c_str(), "remove", false /* no case */)) + if (*m_nodeAction == NodeAction::Replace) { - for (size_t i = 0; i < numNodes; ++i) - { - // get the node - EMotionFX::Node* node = actor->GetSkeleton()->FindNodeByName(nodeNames[i].c_str()); - if (node == nullptr) - { - continue; - } - - // remove the node - nodeGroup->RemoveNodeByNodeIndex((uint16)node->GetNodeIndex()); - } - } - else if (AzFramework::StringFunc::Equal(valueString.c_str(), "add", false /* no case */)) // add the selected nodes to the node group - { - for (size_t i = 0; i < numNodes; ++i) - { - // get the node - EMotionFX::Node* node = actor->GetSkeleton()->FindNodeByName(nodeNames[i].c_str()); - if (node == nullptr) - { - continue; - } - - // add the node - uint16 nodeIndex = (uint16)node->GetNodeIndex(); - nodeGroup->RemoveNodeByNodeIndex(nodeIndex); - nodeGroup->AddNode(nodeIndex); - } - } - else // selected nodes form the new node group - { - // clear previous nodes nodeGroup->GetNodeArray().Clear(); - - // add all nodes to the group - for (size_t i = 0; i < numNodes; ++i) + } + for (const AZStd::string& nodeName : *m_nodeNames) + { + EMotionFX::Node* node = actor->GetSkeleton()->FindNodeByName(nodeName); + if (!node) { - // get the node - EMotionFX::Node* node = actor->GetSkeleton()->FindNodeByName(nodeNames[i].c_str()); + continue; + } - // check if node exists - if (node == nullptr) - { - continue; - } - - // add the node - nodeGroup->AddNode((uint16)node->GetNodeIndex()); + uint16 nodeIndex = (uint16)node->GetNodeIndex(); + nodeGroup->RemoveNodeByNodeIndex(nodeIndex); + if (*m_nodeAction == NodeAction::Add || *m_nodeAction == NodeAction::Replace) + { + nodeGroup->AddNode(nodeIndex); } } } // save the current dirty flag and tell the actor that something got changed - mOldDirtyFlag = actor->GetDirtyFlag(); + m_oldDirtyFlag = actor->GetDirtyFlag(); actor->SetDirtyFlag(true); return true; } // undo the command - bool CommandAdjustNodeGroup::Undo(const MCore::CommandLine& parameters, AZStd::string& outResult) + bool CommandAdjustNodeGroup::Undo(const MCore::CommandLine&, AZStd::string& outResult) { // return if no information about the previous node group was stored - if (!mOldNodeGroup) + if (!m_oldNodeGroup) { return false; } - // get the motion id and the corresponding motion pointer - int32 actorID = parameters.GetValueAsInt("actorID", this); - - // get the name - AZStd::string name; - if (parameters.CheckIfHasParameter("newName")) - { - parameters.GetValue("newName", this, &name); - } - else - { - parameters.GetValue("name", this, &name); - } - - // get the actor - EMotionFX::Actor* actor = EMotionFX::GetActorManager().FindActorByID(actorID); + EMotionFX::Actor* actor = EMotionFX::GetActorManager().FindActorByID(m_actorId); // return error if actor was not found if (actor == nullptr) { - outResult = AZStd::string::format("Cannot adjust node group. Actor with id='%i' does not exist.", actorID); + outResult = AZStd::string::format("Cannot adjust node group. Actor with id='%i' does not exist.", m_actorId); return false; } - // get the node group - EMotionFX::NodeGroup* nodeGroup = actor->FindNodeGroupByNameNoCase(name.c_str()); + EMotionFX::NodeGroup* nodeGroup = actor->FindNodeGroupByNameNoCase(m_newName.has_value() ? m_newName->c_str() : m_name.c_str()); - // return error if node group name is not set - if (nodeGroup == nullptr) + if (!nodeGroup) { - outResult = AZStd::string::format("Cannot adjust node group. Node group with name='%s' does not exist.", name.c_str()); + outResult = AZStd::string::format("Cannot adjust node group. Node group with name='%s' does not exist.", m_newName.has_value() ? m_newName->c_str() : m_name.c_str()); return false; } // reset the old values - if (parameters.CheckIfHasParameter("enabledOnDefault")) + if (m_enabledOnDefault.has_value()) { - nodeGroup->SetIsEnabledOnDefault(mOldNodeGroup->GetIsEnabledOnDefault()); + nodeGroup->SetIsEnabledOnDefault(m_oldNodeGroup->GetIsEnabledOnDefault()); } - if (parameters.CheckIfHasParameter("newName")) + if (m_newName.has_value()) { - nodeGroup->SetName(mOldNodeGroup->GetName()); + nodeGroup->SetName(m_oldNodeGroup->GetName()); } - if (parameters.CheckIfHasParameter("nodeNames")) + if (m_nodeNames.has_value()) { // clear previous nodes nodeGroup->GetNodeArray().Clear(); - const uint32 numNodes = mOldNodeGroup->GetNumNodes(); - nodeGroup->SetNumNodes(static_cast(numNodes)); + const uint16 numNodes = m_oldNodeGroup->GetNumNodes(); + nodeGroup->SetNumNodes(numNodes); // add all nodes to the group - for (uint32 i = 0; i < numNodes; ++i) + for (uint16 i = 0; i < numNodes; ++i) { - nodeGroup->SetNode(static_cast(i), mOldNodeGroup->GetNode(static_cast(i))); + nodeGroup->SetNode(i, m_oldNodeGroup->GetNode(i)); } } - // delete the old node group - if (mOldNodeGroup) - { - mOldNodeGroup->Destroy(); - } - mOldNodeGroup = nullptr; + m_oldNodeGroup = nullptr; // set the dirty flag back to the old value - actor->SetDirtyFlag(mOldDirtyFlag); + actor->SetDirtyFlag(m_oldDirtyFlag); return true; } @@ -252,7 +169,7 @@ namespace CommandSystem void CommandAdjustNodeGroup::InitSyntax() { GetSyntax().ReserveParameters(6); - GetSyntax().AddRequiredParameter("actorID", "The id of the actor the node group belongs to.", MCore::CommandSyntax::PARAMTYPE_INT); + EMotionFX::ParameterMixinActorId::InitSyntax(GetSyntax(), /*isParameterRequired=*/ true); GetSyntax().AddRequiredParameter("name", "The name of the node group to adjust.", MCore::CommandSyntax::PARAMTYPE_STRING); GetSyntax().AddParameter("newName", "The new name of the node group.", MCore::CommandSyntax::PARAMTYPE_STRING, ""); GetSyntax().AddParameter("enabledOnDefault", "The enabled on default flag.", MCore::CommandSyntax::PARAMTYPE_BOOLEAN, "false"); @@ -261,6 +178,45 @@ namespace CommandSystem } + bool CommandAdjustNodeGroup::SetCommandParameters(const MCore::CommandLine& parameters) + { + EMotionFX::ParameterMixinActorId::SetCommandParameters(parameters); + + m_name = parameters.GetValue("name", this); + if (parameters.CheckIfHasParameter("newName")) + { + m_newName = parameters.GetValue("newName", this); + } + if (parameters.CheckIfHasParameter("enabledOnDefault")) + { + m_enabledOnDefault = parameters.GetValueAsBool("enabledOnDefault", this); + } + if (parameters.CheckIfHasParameter("nodeNames")) + { + m_nodeNames.emplace(); + AzFramework::StringFunc::Tokenize(parameters.GetValue("nodeNames", this), m_nodeNames.value(), ";", false, true); + } + if (parameters.CheckIfHasParameter("nodeAction")) + { + const AZStd::string& nodeActionStr = parameters.GetValue("nodeAction", this); + if (nodeActionStr == "add") + { + m_nodeAction = NodeAction::Add; + } + else if (nodeActionStr == "remove") + { + m_nodeAction = NodeAction::Remove; + } + else if (nodeActionStr == "replace") + { + m_nodeAction = NodeAction::Replace; + } + } + + return true; + } + + // get the description const char* CommandAdjustNodeGroup::GetDescription() const { @@ -304,7 +260,7 @@ namespace CommandSystem } // add new node group to the actor - EMotionFX::NodeGroup* nodeGroup = EMotionFX::NodeGroup::Create(name.c_str()); + EMotionFX::NodeGroup* nodeGroup = aznew EMotionFX::NodeGroup(name); actor->AddNodeGroup(nodeGroup); // save the current dirty flag and tell the actor that something got changed @@ -374,10 +330,7 @@ namespace CommandSystem // destructor CommandRemoveNodeGroup::~CommandRemoveNodeGroup() { - if (mOldNodeGroup) - { - mOldNodeGroup->Destroy(); - } + delete mOldNodeGroup; } @@ -407,11 +360,7 @@ namespace CommandSystem } // copy the old node group for undo - if (mOldNodeGroup) - { - mOldNodeGroup->Destroy(); - } - + delete mOldNodeGroup; mOldNodeGroup = aznew EMotionFX::NodeGroup(*nodeGroup); // remove the node group diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.h index e87ce2d62d..d29918822d 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/NodeGroupCommands.h @@ -9,10 +9,13 @@ #pragma once // include the required headers +#include #include "CommandSystemConfig.h" #include #include #include +#include +#include EMFX_FORWARD_DECLARE(Actor); EMFX_FORWARD_DECLARE(NodeGroup); @@ -20,20 +23,68 @@ EMFX_FORWARD_DECLARE(NodeGroup); namespace CommandSystem { // adjust a node group - MCORE_DEFINECOMMAND_START(CommandAdjustNodeGroup, "Adjust node group", true) - bool mOldDirtyFlag; - EMotionFX::NodeGroup* mOldNodeGroup; - MCORE_DEFINECOMMAND_END + class CommandAdjustNodeGroup + : public MCore::Command + , public EMotionFX::ParameterMixinActorId + { + public: + AZ_CLASS_ALLOCATOR_DECL + enum class NodeAction + { + Add, + Remove, + Replace + }; + + static constexpr inline AZStd::string_view s_commandName = "AdjustNodeGroup"; + + CommandAdjustNodeGroup( + MCore::Command* orgCommand = nullptr, + uint32 actorId = MCORE_INVALIDINDEX32, + const AZStd::string& name = {}, + AZStd::optional newName = AZStd::nullopt, + AZStd::optional enabledOnDefault = AZStd::nullopt, + AZStd::optional> nodeNames = AZStd::nullopt, + AZStd::optional nodeAction = AZStd::nullopt + ); + bool Execute(const MCore::CommandLine& parameters, AZStd::string& outResult) override; + bool Undo(const MCore::CommandLine& parameters, AZStd::string& outResult) override; + void InitSyntax() override; + bool SetCommandParameters(const MCore::CommandLine& parameters) override; + bool GetIsUndoable() const override + { + return true; + } + const char* GetHistoryName() const override + { + return "Adjust node group"; + } + const char* GetDescription() const override; + MCore::Command* Create() override + { + return new CommandAdjustNodeGroup(this); + } + + private: + AZStd::string m_name; + AZStd::optional m_newName; + AZStd::optional m_enabledOnDefault; + AZStd::optional> m_nodeNames; + AZStd::optional m_nodeAction; + + bool m_oldDirtyFlag = false; + AZStd::unique_ptr m_oldNodeGroup = nullptr; + }; // add node group - MCORE_DEFINECOMMAND_START(CommandAddNodeGroup, "Add node group", true) + MCORE_DEFINECOMMAND_START(CommandAddNodeGroup, "Add node group", true) bool mOldDirtyFlag; MCORE_DEFINECOMMAND_END // remove a node group - MCORE_DEFINECOMMAND_START(CommandRemoveNodeGroup, "Remove node group", true) + MCORE_DEFINECOMMAND_START(CommandRemoveNodeGroup, "Remove node group", true) EMotionFX::NodeGroup * mOldNodeGroup; bool mOldDirtyFlag; MCORE_DEFINECOMMAND_END diff --git a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ParameterMixins.h b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ParameterMixins.h index eb5de65f13..6461921160 100644 --- a/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ParameterMixins.h +++ b/Gems/EMotionFX/Code/EMotionFX/CommandSystem/Source/ParameterMixins.h @@ -80,6 +80,8 @@ namespace EMotionFX AZ_RTTI(ParameterMixinAnimGraphId, "{3F48199E-6566-471F-A7EA-ADF67CAC4DCD}") AZ_CLASS_ALLOCATOR_DECL + ParameterMixinAnimGraphId() = default; + ParameterMixinAnimGraphId(AZ::u32 id) : m_animGraphId(id) {} virtual ~ParameterMixinAnimGraphId() = default; static void Reflect(AZ::ReflectContext* context); diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp index 973d8eb460..c6b210da58 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Actor.cpp @@ -1015,7 +1015,7 @@ namespace EMotionFX const uint32 numGroups = mNodeGroups.GetLength(); for (uint32 i = 0; i < numGroups; ++i) { - mNodeGroups[i]->Destroy(); + delete mNodeGroups[i]; } mNodeGroups.Clear(); } @@ -2085,7 +2085,7 @@ namespace EMotionFX { if (delFromMem) { - mNodeGroups[index]->Destroy(); + delete mNodeGroups[index]; } mNodeGroups.Remove(index); @@ -2097,7 +2097,7 @@ namespace EMotionFX mNodeGroups.RemoveByValue(group); if (delFromMem) { - group->Destroy(); + delete group; } } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp index 7e7a9ae1c2..3cec3b599c 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/Importer/ChunkProcessors.cpp @@ -1469,7 +1469,7 @@ namespace EMotionFX } // create the new group inside the actor - NodeGroup* newGroup = NodeGroup::Create(groupName, fileGroup.mNumNodes, fileGroup.mDisabledOnDefault ? false : true); + NodeGroup* newGroup = aznew NodeGroup(groupName, fileGroup.mNumNodes, fileGroup.mDisabledOnDefault ? false : true); // read the node numbers uint16 nodeIndex; diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp index d73926a166..e22ad5f064 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.cpp @@ -17,63 +17,16 @@ namespace EMotionFX AZ_CLASS_ALLOCATOR_IMPL(NodeGroup, NodeAllocator, 0) - // default constructor - NodeGroup::NodeGroup() - : BaseObject() + NodeGroup::NodeGroup(const AZStd::string& groupName, uint16 numNodes, bool enabledOnDefault) + : mName(groupName) + , mNodes(numNodes) + , mEnabledOnDefault(enabledOnDefault) { - SetIsEnabledOnDefault(true); - } - - - // extended constructor - NodeGroup::NodeGroup(const char* groupName, bool enabledOnDefault) - : BaseObject() - { - SetName(groupName); - SetIsEnabledOnDefault(enabledOnDefault); - } - - - // another extended constructor - NodeGroup::NodeGroup(const char* groupName, uint16 numNodes, bool enabledOnDefault) - : BaseObject() - { - SetName(groupName); - SetNumNodes(numNodes); - SetIsEnabledOnDefault(enabledOnDefault); - } - - - // destructor - NodeGroup::~NodeGroup() - { - mNodes.Clear(); - } - - - // create - NodeGroup* NodeGroup::Create() - { - return aznew NodeGroup(); - } - - - // create - NodeGroup* NodeGroup::Create(const char* groupName, bool enabledOnDefault) - { - return aznew NodeGroup(groupName, enabledOnDefault); - } - - - // create - NodeGroup* NodeGroup::Create(const char* groupName, uint16 numNodes, bool enabledOnDefault) - { - return aznew NodeGroup(groupName, numNodes, enabledOnDefault); } // set the name of the group - void NodeGroup::SetName(const char* groupName) + void NodeGroup::SetName(const AZStd::string& groupName) { mName = groupName; } diff --git a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h index c6dc86273b..dfe876c86a 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h +++ b/Gems/EMotionFX/Code/EMotionFX/Source/NodeGroup.h @@ -30,38 +30,19 @@ namespace EMotionFX * might contain incorrect or even uninitialized data. */ class EMFX_API NodeGroup - : public BaseObject { public: AZ_CLASS_ALLOCATOR_DECL - /** - * The default creation method. - * This does not assign a name and there will be nodes inside this group on default. - * Also the default enabled state is set to true. - */ - static NodeGroup* Create(); - /** - * Extended creation. - * @param groupName The name of the group. Please keep in mind that it is not allowed to have two groups with the same name inside an Actor. - * @param enabledOnDefault Set to true (default) when the nodes inside this group should be enabled on default. - */ - static NodeGroup* Create(const char* groupName, bool enabledOnDefault = true); - - /** - * Another extended constructor. - * @param groupName The name of the group. Please keep in mind that it is not allowed to have two groups with the same name inside an Actor. - * @param numNodes The number of nodes to create inside the group. This will have all uninitialized values for the node indices in the group, so be sure that you - * set them all to some valid node index using the NodeGroup::SetNode(...) method. This method automatically calls the SetNumNodes(...) method. - * @param enabledOnDefault Set to true (default) when the nodes inside this group should be enabled on default. - */ - static NodeGroup* Create(const char* groupName, uint16 numNodes, bool enabledOnDefault = true); + NodeGroup(const AZStd::string& groupName = {}, uint16 numNodes = 0, bool enabledOnDefault = true); + NodeGroup(const NodeGroup& aOther); + NodeGroup& operator=(const NodeGroup& aOther); /** * Set the name of the group. Please keep in mind that group names must be unique inside the Actor objects. So you should not have two or more groups with the same name. * @param groupName The name of the group. */ - void SetName(const char* groupName); + void SetName(const AZStd::string& groupName); /** * Get the name of the group as null terminated character buffer. @@ -172,37 +153,6 @@ namespace EMotionFX */ void SetIsEnabledOnDefault(bool enabledOnDefault); - /** - * The default constructor. - * This does not assign a name and there will be nodes inside this group on default. - * Also the default enabled state is set to true. - */ - NodeGroup(); - - /** - * Extended constructor. - * @param groupName The name of the group. Please keep in mind that it is not allowed to have two groups with the same name inside an Actor. - * @param enabledOnDefault Set to true (default) when the nodes inside this group should be enabled on default. - */ - NodeGroup(const char* groupName, bool enabledOnDefault = true); - - /** - * Another extended constructor. - * @param groupName The name of the group. Please keep in mind that it is not allowed to have two groups with the same name inside an Actor. - * @param numNodes The number of nodes to create inside the group. This will have all uninitialized values for the node indices in the group, so be sure that you - * set them all to some valid node index using the NodeGroup::SetNode(...) method. This method automatically calls the SetNumNodes(...) method. - * @param enabledOnDefault Set to true (default) when the nodes inside this group should be enabled on default. - */ - NodeGroup(const char* groupName, uint16 numNodes, bool enabledOnDefault = true); - - /** - * The destructor. - */ - ~NodeGroup(); - - NodeGroup(const NodeGroup& aOther); - NodeGroup& operator=(const NodeGroup& aOther); - private: AZStd::string mName; /**< The name of the group. */ MCore::SmallArray mNodes; /**< The node index numbers that are inside this group. */ diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp index 9ec28d2e21..8a4a338b6e 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/BlendGraphWidget.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -1208,7 +1209,7 @@ namespace EMStudio MCore::CommandGroup commandGroup("Adjust anim graph node group"); - AZStd::string nodeNames; + AZStd::vector nodeNames; for (const QModelIndex& selectedIndex : selectionList) { // Skip transitions and blend tree connections. @@ -1221,12 +1222,19 @@ namespace EMStudio EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->FindNodeGroupForNode(selectedNode); if (nodeGroup) { - const AZStd::string command = AZStd::string::format("AnimGraphAdjustNodeGroup -animGraphID %i -name \"%s\" -nodeNames \"%s\" -nodeAction \"remove\"", animGraph->GetID(), nodeGroup->GetName(), selectedNode->GetName()); - commandGroup.AddCommandString(command); + auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), + /*animGraphId = */ animGraph->GetID(), + /*name = */ nodeGroup->GetNameString(), + /*visible = */ AZStd::nullopt, + /*newName = */ AZStd::nullopt, + /*nodeNames = */ {{selectedNode->GetNameString()}}, + /*nodeAction = */ CommandSystem::CommandAnimGraphAdjustNodeGroup::NodeAction::Remove + ); + commandGroup.AddCommand(command); } - nodeNames += selectedNode->GetName(); - nodeNames += ";"; + nodeNames.emplace_back(selectedNode->GetName()); } if (!nodeNames.empty()) { @@ -1235,8 +1243,16 @@ namespace EMStudio if (newNodeGroup) { - const AZStd::string command = AZStd::string::format("AnimGraphAdjustNodeGroup -animGraphID %i -name \"%s\" -nodeNames \"%s\" -nodeAction \"add\"", animGraph->GetID(), newNodeGroup->GetName(), nodeNames.c_str()); - commandGroup.AddCommandString(command); + auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), + /*animGraphId = */ animGraph->GetID(), + /*name = */ newNodeGroup->GetNameString(), + /*visible = */ AZStd::nullopt, + /*newName = */ AZStd::nullopt, + /*nodeNames = */ nodeNames, + /*nodeAction = */ CommandSystem::CommandAnimGraphAdjustNodeGroup::NodeAction::Add + ); + commandGroup.AddCommand(command); } AZStd::string outResult; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.cpp index ecb9a227af..8ab7aa8d72 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/NodeGroupWindow.cpp @@ -74,11 +74,6 @@ namespace EMStudio mLineEdit->setText(nodeGroup.c_str()); mLineEdit->selectAll(); - // create add the error message - /*mErrorMsg = new QLabel("Error: Duplicate name found"); - mErrorMsg->setAlignment(Qt::AlignVCenter | Qt::AlignLeft); - mErrorMsg->setVisible(false);*/ - // create the button layout QHBoxLayout* buttonLayout = new QHBoxLayout(); mOKButton = new QPushButton("OK"); @@ -139,10 +134,16 @@ namespace EMStudio void NodeGroupRenameWindow::Accepted() { // Execute the command - AZStd::string commandString, outResult; + AZStd::string outResult; const AZStd::string convertedNewName = FromQtString(mLineEdit->text()); - commandString = AZStd::string::format("AnimGraphAdjustNodeGroup -animGraphID %i -name \"%s\" -newName \"%s\"", mAnimGraph->GetID(), mNodeGroup.c_str(), convertedNewName.c_str()); - if (GetCommandManager()->ExecuteCommand(commandString.c_str(), outResult) == false) + auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), + mAnimGraph->GetID(), + /*name = */ mNodeGroup, + /*visible = */ AZStd::nullopt, + /*newName = */ convertedNewName + ); + if (!GetCommandManager()->ExecuteCommand(command, outResult)) { MCore::LogError(outResult.c_str()); } @@ -167,7 +168,7 @@ namespace EMStudio mAdjustCallback = new CommandAnimGraphAdjustNodeGroupCallback(false); GetCommandManager()->RegisterCommandCallback("AnimGraphAddNodeGroup", mCreateCallback); GetCommandManager()->RegisterCommandCallback("AnimGraphRemoveNodeGroup", mRemoveCallback); - GetCommandManager()->RegisterCommandCallback("AnimGraphAdjustNodeGroup", mAdjustCallback); + GetCommandManager()->RegisterCommandCallback(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName.data(), mAdjustCallback); // add the add button mAddAction = new QAction(MysticQt::GetMysticQt()->FindIcon("Images/Icons/Plus.svg"), tr("Add new node group"), this); @@ -486,13 +487,16 @@ namespace EMStudio bool isVisible = state == Qt::Checked; - // construct the command - AZStd::string commandString; - commandString = AZStd::string::format("AnimGraphAdjustNodeGroup -animGraphID %i -name \"%s\" -isVisible %s", animGraph->GetID(), nodeGroup->GetName(), AZStd::to_string(isVisible).c_str()); + auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), + /*animGraphId = */ animGraph->GetID(), + /*name = */ nodeGroup->GetNameString(), + /*visible = */ isVisible + ); // execute the command AZStd::string resultString; - if (GetCommandManager()->ExecuteCommand(commandString.c_str(), resultString) == false) + if (GetCommandManager()->ExecuteCommand(command, resultString) == false) { if (resultString.size() > 0) { @@ -519,16 +523,21 @@ namespace EMStudio // get a pointer to the node group EMotionFX::AnimGraphNodeGroup* nodeGroup = animGraph->GetNodeGroup(groupIndex); - // get the color - AZ::Vector4 finalColor = color.GetAsVector4(); - // construct the command - AZStd::string commandString; - commandString = AZStd::string::format("AnimGraphAdjustNodeGroup -animGraphID %i -name \"%s\" -color \"%s\"", animGraph->GetID(), nodeGroup->GetName(), AZStd::to_string(finalColor).c_str()); + auto* command = aznew CommandSystem::CommandAnimGraphAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAnimGraphAdjustNodeGroup::s_commandName), + /*animGraphId = */ animGraph->GetID(), + /*name = */ nodeGroup->GetName(), + /*visible = */ AZStd::nullopt, + /*newName = */ AZStd::nullopt, + /*nodeNames = */ AZStd::nullopt, + /*nodeAction = */ AZStd::nullopt, + /*color = */ color.ToU32() + ); // execute the command AZStd::string resultString; - if (GetCommandManager()->ExecuteCommand(commandString.c_str(), resultString) == false) + if (GetCommandManager()->ExecuteCommand(command, resultString) == false) { if (resultString.size() > 0) { diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp index 1624b9d9ea..84c281a18f 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupManagementWidget.cpp @@ -112,8 +112,13 @@ namespace EMStudio // execute the command AZStd::string outResult; - AZStd::string command = AZStd::string::format("AdjustNodeGroup -actorID %i -name \"%s\" -newName \"%s\"", mActor->GetID(), mNodeGroupName.c_str(), convertedNewName.c_str()); - if (GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false) + auto* command = aznew CommandSystem::CommandAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAdjustNodeGroup::s_commandName), + /*actorId=*/ mActor->GetID(), + /*name=*/ mNodeGroupName, + /*newName=*/ convertedNewName + ); + if (GetCommandManager()->ExecuteCommand(command, outResult) == false) { AZ_Error("EMotionFX", false, outResult.c_str()); } @@ -362,98 +367,6 @@ namespace EMStudio mSelectedRow = MCORE_INVALIDINDEX32; } } - /*void NodeGroupManagementWidget::UpdateNodeGroupWidget(QTableWidgetItem* current, QTableWidgetItem* previous) - { - MCORE_UNUSED(previous); - - // return if no node group widget is set - if (mNodeGroupWidget == nullptr) - return; - - // set the node group widget to the actual selection - mNodeGroupWidget->SetActor( mActor ); - - if (current) - { - // set the current row - mSelectedRow = current->row(); - - // set the node group - NodeGroup* nodeGroup = mActor->FindNodeGroupByName( FromQtString(mNodeGroupsTable->item(current->row(), 1)->text()).c_str() ); - mNodeGroupWidget->SetNodeGroup( nodeGroup ); - } - else - { - mNodeGroupWidget->SetNodeGroup( nullptr ); - mSelectedRow = MCORE_INVALIDINDEX32; - } - }*/ - - - // called whenever a cell is changed - /*void NodeGroupManagementWidget::NodeGroupNamesChanged(const QString& text) - { - // get the sender widget - QWidget* senderWidget = (QWidget*)sender(); - - // check for duplicates - const int duplicateFound = SearchTableForString( mNodeGroupsTable, text ); - - // mark edit field in red, if entry already exists - if (duplicateFound >= 0) - GetManager()->SetWidgetAsInvalidInput( senderWidget ); - else - senderWidget->setStyleSheet(""); - }*/ - - - // starts editing - /*void NodeGroupManagementWidget::NodeGroupeNameDoubleClicked(QTableWidgetItem* item) - { - // add new line edit for the selected widget - QLineEdit* lineEdit = new QLineEdit( mNodeGroupsTable->item(item->row(), 0)->text() ); - mNodeGroupsTable->setCellWidget( item->row(), 0, lineEdit ); - - // jump into the edit field - lineEdit->selectAll(); - lineEdit->setFocus(); - mNodeGroupsTable->setCurrentCell( item->row(), 0 ); - - // connect slots for edit finishing and text change - connect( lineEdit, SIGNAL(editingFinished()), this, SLOT(NodeGroupNameEditingFinished()) ); - connect( lineEdit, SIGNAL(textChanged(QString)), this, SLOT(NodeGroupNamesChanged(QString)) ); - }*/ - - - // called when editing is finished - /*void NodeGroupManagementWidget::NodeGroupNameEditingFinished() - { - // get the current item - QTableWidgetItem* item = mNodeGroupsTable->currentItem(); - - // get the sender widget - QLineEdit* senderWidget = (QLineEdit*)sender(); - - // return if one of the widgets does not exist - if (item == nullptr || senderWidget == nullptr) - return; - - // call commands for name change if name does not exist yet - if (senderWidget->styleSheet() == "") - { - // call command for adding a new node group - String outResult; - String command; - command.Format( "AdjustNodeGroup -actorID %i -name \"%s\" -newName \"%s\"", mActor->GetID(), FromQtString(item->text()).c_str(), FromQtString(senderWidget->text()).c_str() ); - if (EMStudio::GetCommandManager()->ExecuteCommand( command.c_str(), outResult ) == false) - LogError( outResult.c_str() ); - } - else - { - // delete the line edit - mNodeGroupsTable->setCellWidget(item->row(), item->column(), nullptr); - } - }*/ // function to add a new node group with the specified name @@ -562,16 +475,20 @@ namespace EMStudio if (rowChechbox == senderCheckbox) { nodeGroupName = mNodeGroupsTable->item(i, 1)->text().toUtf8().data(); + break; } } // execute the command AZStd::string outResult; - const AZStd::string command = AZStd::string::format("AdjustNodeGroup -actorID %i -name \"%s\" -enabledOnDefault \"%s\"", - mActor->GetID(), - nodeGroupName.c_str(), - AZStd::to_string(checked).c_str()); - if (EMStudio::GetCommandManager()->ExecuteCommand(command.c_str(), outResult) == false) + auto* command = aznew CommandSystem::CommandAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAdjustNodeGroup::s_commandName), + /*actorId=*/ mActor->GetID(), + /*name=*/ nodeGroupName, + /*newName=*/ AZStd::nullopt, + /*enabledOnDefault=*/ checked + ); + if (EMStudio::GetCommandManager()->ExecuteCommand(command, outResult) == false) { AZ_Error("EMotionFX", false, outResult.c_str()); } diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.cpp index 31d704a1d5..39ee1c4f5b 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.cpp @@ -35,7 +35,6 @@ namespace EMStudio mNodeTable = nullptr; mSelectNodesButton = nullptr; mNodeGroup = nullptr; - mNodeAction = ""; // init the widget Init(); @@ -254,11 +253,11 @@ namespace EMStudio QWidget* senderWidget = (QWidget*)sender(); if (senderWidget == mAddNodesButton) { - mNodeAction = "add"; + mNodeAction = CommandSystem::CommandAdjustNodeGroup::NodeAction::Add; } else { - mNodeAction = "select"; + mNodeAction = CommandSystem::CommandAdjustNodeGroup::NodeAction::Replace; } // get the selected actorinstance @@ -293,46 +292,37 @@ namespace EMStudio // remove nodes void NodeGroupWidget::RemoveNodesButtonPressed() { - // generate node list string - AZStd::string nodeList; - uint32 lowestSelectedRow = MCORE_INVALIDINDEX32; - const uint32 numTableRows = mNodeTable->rowCount(); - for (uint32 i = 0; i < numTableRows; ++i) - { - // get the current table item - QTableWidgetItem* item = mNodeTable->item(i, 0); - if (item == nullptr) - { - continue; - } - - // add the item to remove list, if it's selected - if (item->isSelected()) - { - nodeList += AZStd::string::format("%s;", item->text().toUtf8().data()); - if ((uint32)item->row() < lowestSelectedRow) - { - lowestSelectedRow = (uint32)item->row(); - } - } - } - - // stop here if nothing selected - if (nodeList.empty()) + if (mNodeTable->selectedItems().empty()) { return; } - // call command for adjusting disable on default flag + // generate node list string + AZStd::vector nodeList; + int lowestSelectedRow = AZStd::numeric_limits::max(); + for (const QTableWidgetItem* item : mNodeTable->selectedItems()) + { + nodeList.emplace_back(FromQtString(item->text())); + lowestSelectedRow = AZStd::min(lowestSelectedRow, item->row()); + } + AZStd::string outResult; - AZStd::string command = AZStd::string::format("AdjustNodeGroup -actorID %i -name \"%s\" -nodeAction \"remove\" -nodeNames \"%s\"", mActor->GetID(), mNodeGroup->GetName(), nodeList.c_str()); + auto* command = aznew CommandSystem::CommandAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAdjustNodeGroup::s_commandName), + /*actorId=*/ mActor->GetID(), + /*name=*/ mNodeGroup->GetName(), + /*newName=*/ AZStd::nullopt, + /*enabledOnDefault=*/ AZStd::nullopt, + /*nodeNames=*/ AZStd::move(nodeList), + /*nodeAction=*/ CommandSystem::CommandAdjustNodeGroup::NodeAction::Remove + ); if (EMStudio::GetCommandManager()->ExecuteCommand(command, outResult) == false) { AZ_Error("EMotionFX", false, outResult.c_str()); } // selected the next row - if (lowestSelectedRow > ((uint32)mNodeTable->rowCount() - 1)) + if (lowestSelectedRow > (mNodeTable->rowCount() - 1)) { mNodeTable->selectRow(lowestSelectedRow - 1); } @@ -353,19 +343,23 @@ namespace EMStudio } // generate node list string - AZStd::string nodeList; - nodeList.reserve(16448); - const uint32 numSelectedNodes = selectionList.GetLength(); - for (uint32 i = 0; i < numSelectedNodes; ++i) + AZStd::vector nodeList; + const uint32 selectionListSize = selectionList.GetLength(); + for (uint32 i = 0; i < selectionListSize; ++i) { - nodeList += selectionList[i].GetNodeName(); - nodeList += ";"; + nodeList.emplace_back(selectionList[i].GetNodeName()); } - AzFramework::StringFunc::Strip(nodeList, MCore::CharacterConstants::semiColon, true /* case sensitive */, false /* beginning */, true /* ending */); - // call command for adjusting disable on default flag AZStd::string outResult; - AZStd::string command = AZStd::string::format("AdjustNodeGroup -actorID %i -name \"%s\" -nodeAction \"%s\" -nodeNames \"%s\"", mActor->GetID(), mNodeGroup->GetName(), mNodeAction.c_str(), nodeList.c_str()); + auto* command = aznew CommandSystem::CommandAdjustNodeGroup( + GetCommandManager()->FindCommand(CommandSystem::CommandAdjustNodeGroup::s_commandName), + /*actorId=*/ mActor->GetID(), + /*name=*/ mNodeGroup->GetName(), + /*newName=*/ AZStd::nullopt, + /*enabledOnDefault=*/ AZStd::nullopt, + /*nodeNames=*/ AZStd::move(nodeList), + /*nodeAction=*/ mNodeAction + ); if (EMStudio::GetCommandManager()->ExecuteCommand(command, outResult) == false) { AZ_Error("EMotionFX", false, outResult.c_str()); diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.h b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.h index ebef94b05c..2b4cad06de 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.h +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupWidget.h @@ -13,6 +13,7 @@ #include #include "../../../../EMStudioSDK/Source/DockWidgetPlugin.h" #include "../../../../EMStudioSDK/Source/NodeSelectionWindow.h" +#include #endif QT_FORWARD_DECLARE_CLASS(QLineEdit) @@ -58,7 +59,7 @@ namespace EMStudio CommandSystem::SelectionList mNodeSelectionList; EMotionFX::NodeGroup* mNodeGroup; uint16 mNodeGroupIndex; - AZStd::string mNodeAction; + CommandSystem::CommandAdjustNodeGroup::NodeAction mNodeAction; // widgets QTableWidget* mNodeTable; diff --git a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.cpp b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.cpp index 91a96ef39d..218035dc30 100644 --- a/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.cpp +++ b/Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/NodeGroups/NodeGroupsPlugin.cpp @@ -11,6 +11,7 @@ #include "../../../../EMStudioSDK/Source/EMStudioCore.h" #include #include +#include #include "../../../../EMStudioSDK/Source/EMStudioManager.h" // include qt headers @@ -99,7 +100,7 @@ namespace EMStudio GetCommandManager()->RegisterCommandCallback("Select", mSelectCallback); GetCommandManager()->RegisterCommandCallback("Unselect", mUnselectCallback); GetCommandManager()->RegisterCommandCallback("ClearSelection", mClearSelectionCallback); - GetCommandManager()->RegisterCommandCallback("AdjustNodeGroup", mAdjustNodeGroupCallback); + GetCommandManager()->RegisterCommandCallback(CommandSystem::CommandAdjustNodeGroup::s_commandName.data(), mAdjustNodeGroupCallback); GetCommandManager()->RegisterCommandCallback("AddNodeGroup", mAddNodeGroupCallback); GetCommandManager()->RegisterCommandCallback("RemoveNodeGroup", mRemoveNodeGroupCallback); diff --git a/Gems/EMotionFX/Code/MCore/Source/Command.cpp b/Gems/EMotionFX/Code/MCore/Source/Command.cpp index b358a28546..39e9fde965 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Command.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/Command.cpp @@ -28,10 +28,10 @@ namespace MCore // constructor - Command::Command(const char* commandName, Command* originalCommand) + Command::Command(AZStd::string commandName, Command* originalCommand) + : mOrgCommand(originalCommand) + , mCommandName(AZStd::move(commandName)) { - mCommandName = commandName; - mOrgCommand = originalCommand; } diff --git a/Gems/EMotionFX/Code/MCore/Source/Command.h b/Gems/EMotionFX/Code/MCore/Source/Command.h index 6ad10ff559..7309c5dc91 100644 --- a/Gems/EMotionFX/Code/MCore/Source/Command.h +++ b/Gems/EMotionFX/Code/MCore/Source/Command.h @@ -185,7 +185,7 @@ namespace MCore * @param commandName The unique identifier for the command. * @param originalCommand The original command, or nullptr when this is the original command. */ - Command(const char* commandName, Command* originalCommand); + Command(AZStd::string commandName, Command* originalCommand); /** * Destructor. diff --git a/Gems/GradientSignal/Code/Source/GradientSampler.cpp b/Gems/GradientSignal/Code/Source/GradientSampler.cpp index bb17ef3557..d224a93e6b 100644 --- a/Gems/GradientSignal/Code/Source/GradientSampler.cpp +++ b/Gems/GradientSignal/Code/Source/GradientSampler.cpp @@ -61,45 +61,38 @@ namespace GradientSignal ->DataElement(0, &GradientSampler::m_invertInput, "Invert Input", "") ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) - ->DataElement(0, &GradientSampler::m_enableTransform, "Enable Transform", "") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) + + ->GroupElementToggle("Enable Transform", &GradientSampler::m_enableTransform) + ->Attribute(AZ::Edit::Attributes::AutoExpand, false) ->DataElement(0, &GradientSampler::m_translate, "Translate", "") ->Attribute(AZ::Edit::Attributes::ReadOnly, &GradientSampler::AreTransformSettingsDisabled) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) ->DataElement(0, &GradientSampler::m_scale, "Scale", "") ->Attribute(AZ::Edit::Attributes::ReadOnly, &GradientSampler::AreTransformSettingsDisabled) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) ->DataElement(0, &GradientSampler::m_rotate, "Rotate", "Rotation in degrees.") ->Attribute(AZ::Edit::Attributes::ReadOnly, &GradientSampler::AreTransformSettingsDisabled) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) - ->DataElement(0, &GradientSampler::m_enableLevels, "Enable Levels", "") - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) + ->GroupElementToggle("Enable Levels", &GradientSampler::m_enableLevels) + ->Attribute(AZ::Edit::Attributes::AutoExpand, false) ->DataElement(AZ::Edit::UIHandlers::Slider, &GradientSampler::m_inputMid, "Input Mid", "") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Max, 10.0f) ->Attribute(AZ::Edit::Attributes::ReadOnly, &GradientSampler::AreLevelSettingsDisabled) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) ->DataElement(AZ::Edit::UIHandlers::Slider, &GradientSampler::m_inputMin, "Input Min", "") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Max, 1.0f) ->Attribute(AZ::Edit::Attributes::ReadOnly, &GradientSampler::AreLevelSettingsDisabled) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) ->DataElement(AZ::Edit::UIHandlers::Slider, &GradientSampler::m_inputMax, "Input Max", "") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Max, 1.0f) ->Attribute(AZ::Edit::Attributes::ReadOnly, &GradientSampler::AreLevelSettingsDisabled) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) ->DataElement(AZ::Edit::UIHandlers::Slider, &GradientSampler::m_outputMin, "Output Min", "") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Max, 1.0f) ->Attribute(AZ::Edit::Attributes::ReadOnly, &GradientSampler::AreLevelSettingsDisabled) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) ->DataElement(AZ::Edit::UIHandlers::Slider, &GradientSampler::m_outputMax, "Output Max", "") ->Attribute(AZ::Edit::Attributes::Min, 0.0f) ->Attribute(AZ::Edit::Attributes::Max, 1.0f) ->Attribute(AZ::Edit::Attributes::ReadOnly, &GradientSampler::AreLevelSettingsDisabled) - ->Attribute(AZ::Edit::Attributes::ChangeNotify, &GradientSampler::ChangeNotify) ->ClassElement(AZ::Edit::ClassElements::Group, "Preview (Inbound)") ->Attribute(AZ::Edit::Attributes::AutoExpand, false) diff --git a/Gems/LyShine/Assets/Passes/LyShineParent.pass b/Gems/LyShine/Assets/Passes/LyShineParent.pass new file mode 100644 index 0000000000..7bbd4748a7 --- /dev/null +++ b/Gems/LyShine/Assets/Passes/LyShineParent.pass @@ -0,0 +1,22 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "PassAsset", + "ClassData": { + "PassTemplate": { + "Name": "LyShineParentTemplate", + "PassClass": "LyShinePass", + "Slots": [ + { + "Name": "ColorInputOutput", + "SlotType": "InputOutput" + }, + { + "Name": "DepthInputOutput", + "SlotType": "InputOutput", + "ScopeAttachmentUsage": "DepthStencil" + } + ] + } + } +} diff --git a/Gems/LyShine/Assets/Passes/LyShinePassTemplates.azasset b/Gems/LyShine/Assets/Passes/LyShinePassTemplates.azasset new file mode 100644 index 0000000000..c9ee5186e0 --- /dev/null +++ b/Gems/LyShine/Assets/Passes/LyShinePassTemplates.azasset @@ -0,0 +1,13 @@ +{ + "Type": "JsonSerialization", + "Version": 1, + "ClassName": "AssetAliasesSourceData", + "ClassData": { + "AssetPaths": [ + { + "Name": "LyShineParentTemplate", + "Path": "Passes/LyShineParent.pass" + } + ] + } +} diff --git a/Gems/LyShine/Code/CMakeLists.txt b/Gems/LyShine/Code/CMakeLists.txt index 171927c4a3..93bf84c66e 100644 --- a/Gems/LyShine/Code/CMakeLists.txt +++ b/Gems/LyShine/Code/CMakeLists.txt @@ -193,6 +193,9 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) FILES_CMAKE lyshine_common_module_files.cmake lyshine_tests_files.cmake + COMPILE_DEFINITIONS + PRIVATE + LYSHINE_TESTS INCLUDE_DIRECTORIES PRIVATE Tests diff --git a/Gems/LyShine/Code/Editor/EditorWindow.cpp b/Gems/LyShine/Code/Editor/EditorWindow.cpp index 81360ed793..8d7e20492d 100644 --- a/Gems/LyShine/Code/Editor/EditorWindow.cpp +++ b/Gems/LyShine/Code/Editor/EditorWindow.cpp @@ -1547,6 +1547,20 @@ AssetTreeEntry* EditorWindow::GetSliceLibraryTree() return m_sliceLibraryTree; } +AZ::EntityId EditorWindow::GetCanvasForCurrentEditorMode() +{ + AZ::EntityId canvasEntityId; + if (GetEditorMode() == UiEditorMode::Edit) + { + canvasEntityId = GetCanvas(); + } + else + { + canvasEntityId = GetPreviewModeCanvas(); + } + return canvasEntityId; +} + void EditorWindow::ToggleEditorMode() { m_editorMode = (m_editorMode == UiEditorMode::Edit) ? UiEditorMode::Preview : UiEditorMode::Edit; diff --git a/Gems/LyShine/Code/Editor/EditorWindow.h b/Gems/LyShine/Code/Editor/EditorWindow.h index c2fa6808f1..d9b3e60c32 100644 --- a/Gems/LyShine/Code/Editor/EditorWindow.h +++ b/Gems/LyShine/Code/Editor/EditorWindow.h @@ -143,6 +143,9 @@ public: // member functions //! Returns the current mode of the editor (Edit or Preview) UiEditorMode GetEditorMode() { return m_editorMode; } + //! Returns the UI canvas for the current mode (Edit or Preview) + AZ::EntityId GetCanvasForCurrentEditorMode(); + //! Toggle the editor mode between Edit and Preview void ToggleEditorMode(); diff --git a/Gems/LyShine/Code/Editor/ViewportWidget.cpp b/Gems/LyShine/Code/Editor/ViewportWidget.cpp index 46f4f4f8fa..1ce8f5b64d 100644 --- a/Gems/LyShine/Code/Editor/ViewportWidget.cpp +++ b/Gems/LyShine/Code/Editor/ViewportWidget.cpp @@ -7,6 +7,8 @@ */ #include "EditorCommon.h" +#include "UiCanvasComponent.h" + #include "EditorDefs.h" #include "Settings.h" #include @@ -245,6 +247,7 @@ ViewportWidget::ViewportWidget(EditorWindow* parent) FontNotificationBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); + AZ::RPI::ViewportContextNotificationBus::Handler::BusConnect(GetCurrentContextName()); } ViewportWidget::~ViewportWidget() @@ -252,6 +255,8 @@ ViewportWidget::~ViewportWidget() AzToolsFramework::EditorPickModeNotificationBus::Handler::BusDisconnect(); FontNotificationBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); + LyShinePassDataRequestBus::Handler::BusDisconnect(); + AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(); m_uiRenderer.reset(); @@ -272,6 +277,8 @@ void ViewportWidget::InitUiRenderer() lyShine->SetUiRendererForEditor(m_uiRenderer); m_draw2d = AZStd::make_shared(GetViewportContext()); + + LyShinePassDataRequestBus::Handler::BusConnect(GetViewportContext()->GetRenderScene()->GetId()); } ViewportInteraction* ViewportWidget::GetViewportInteraction() @@ -487,30 +494,44 @@ void ViewportWidget::EnableCanvasRender() } void ViewportWidget::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) +{ + // Update + UiEditorMode editorMode = m_editorWindow->GetEditorMode(); + if (editorMode == UiEditorMode::Edit) + { + UpdateEditMode(deltaTime); + } + else // if (editorMode == UiEditorMode::Preview) + { + UpdatePreviewMode(deltaTime); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +int ViewportWidget::GetTickOrder() +{ + return AZ::TICK_PRE_RENDER; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +void ViewportWidget::OnRenderTick() { if (!m_uiRenderer->IsReady() || !m_canvasRenderIsEnabled) { return; } -#ifdef LYSHINE_ATOM_TODO - gEnv->pRenderer->SetSrgbWrite(true); -#endif - const float dpiScale = QtHelpers::GetHighDpiScaleFactor(*this); ViewportIcon::SetDpiScaleFactor(dpiScale); - // Set up to render a frame to this viewport's window - GetViewportContext()->RenderTick(); - UiEditorMode editorMode = m_editorWindow->GetEditorMode(); if (editorMode == UiEditorMode::Edit) { - RenderEditMode(deltaTime); + RenderEditMode(); } else // if (editorMode == UiEditorMode::Preview) { - RenderPreviewMode(deltaTime); + RenderPreviewMode(); } } @@ -884,17 +905,37 @@ void ViewportWidget::OnFontTextureUpdated([[maybe_unused]] IFFont* font) m_fontTextureHasChanged = true; } +LyShine::AttachmentImagesAndDependencies ViewportWidget::GetRenderTargets() +{ + LyShine::AttachmentImagesAndDependencies canvasTargets; + + AZ::EntityId canvasEntityId = m_editorWindow->GetCanvasForCurrentEditorMode(); + if (canvasEntityId.IsValid()) + { + AZ::Entity* canvasEntity = nullptr; + EBUS_EVENT_RESULT(canvasEntity, AZ::ComponentApplicationBus, FindEntity, canvasEntityId); + AZ_Assert(canvasEntity, "Canvas entity not found by ID"); + if (canvasEntity) + { + UiCanvasComponent* canvasComponent = canvasEntity->FindComponent(); + AZ_Assert(canvasComponent, "Canvas entity has no canvas component"); + if (canvasComponent) + { + canvasComponent->GetRenderTargets(canvasTargets); + } + } + } + + return canvasTargets; +} + QPointF ViewportWidget::WidgetToViewport(const QPointF & point) const { return point * WidgetToViewportFactor(); } -void ViewportWidget::RenderEditMode(float deltaTime) +void ViewportWidget::UpdateEditMode(float deltaTime) { - // sort keys for different layers - static const int64_t backgroundKey = -0x1000; - static const int64_t topLayerKey = 0x1000000; - if (m_fontTextureHasChanged) { // A font texture has changed since we last rendered. Force a render graph update for each loaded canvas @@ -908,6 +949,28 @@ void ViewportWidget::RenderEditMode(float deltaTime) return; // this can happen if a render happens during a restart } + AZ::Vector2 canvasSize; + EBUS_EVENT_ID_RESULT(canvasSize, canvasEntityId, UiCanvasBus, GetCanvasSize); + + // Set the target size of the canvas + EBUS_EVENT_ID(canvasEntityId, UiCanvasBus, SetTargetCanvasSize, false, canvasSize); + + // Update this canvas (must be done after SetTargetCanvasSize) + EBUS_EVENT_ID(canvasEntityId, UiEditorCanvasBus, UpdateCanvasInEditorViewport, deltaTime, false); +} + +void ViewportWidget::RenderEditMode() +{ + // sort keys for different layers + static const int64_t backgroundKey = -0x1000; + static const int64_t topLayerKey = 0x1000000; + + AZ::EntityId canvasEntityId = m_editorWindow->GetCanvas(); + if (!canvasEntityId.IsValid()) + { + return; // this can happen if a render happens during a restart + } + Draw2dHelper draw2d(m_draw2d.get()); // sets and resets 2D draw mode in constructor/destructor QTreeWidgetItemRawPtrQList selection = m_editorWindow->GetHierarchy()->selectedItems(); @@ -936,9 +999,6 @@ void ViewportWidget::RenderEditMode(float deltaTime) // Set the target size of the canvas EBUS_EVENT_ID(canvasEntityId, UiCanvasBus, SetTargetCanvasSize, false, canvasSize); - // Update this canvas (must be done after SetTargetCanvasSize) - EBUS_EVENT_ID(canvasEntityId, UiEditorCanvasBus, UpdateCanvasInEditorViewport, deltaTime, false); - // Render this canvas QSize scaledViewportSize = QtHelpers::GetDpiScaledViewportSize(*this); AZ::Vector2 viewportSize(scaledViewportSize.width(), scaledViewportSize.height()); @@ -1037,11 +1097,8 @@ void ViewportWidget::RenderEditMode(float deltaTime) } } -void ViewportWidget::RenderPreviewMode(float deltaTime) +void ViewportWidget::UpdatePreviewMode(float deltaTime) { - // sort keys for different layers - static const int64_t backgroundKey = -0x1000; - AZ::EntityId canvasEntityId = m_editorWindow->GetPreviewModeCanvas(); if (m_fontTextureHasChanged) @@ -1051,6 +1108,37 @@ void ViewportWidget::RenderPreviewMode(float deltaTime) m_fontTextureHasChanged = false; } + if (canvasEntityId.IsValid()) + { + QSize scaledViewportSize = QtHelpers::GetDpiScaledViewportSize(*this); + AZ::Vector2 viewportSize(scaledViewportSize.width(), scaledViewportSize.height()); + + // Get the canvas size + AZ::Vector2 canvasSize = m_editorWindow->GetPreviewCanvasSize(); + if (canvasSize.GetX() == 0.0f && canvasSize.GetY() == 0.0f) + { + // special value of (0,0) means use the viewport size + canvasSize = viewportSize; + } + + // Set the target size of the canvas + EBUS_EVENT_ID(canvasEntityId, UiCanvasBus, SetTargetCanvasSize, true, canvasSize); + + // Update this canvas (must be done after SetTargetCanvasSize) + EBUS_EVENT_ID(canvasEntityId, UiEditorCanvasBus, UpdateCanvasInEditorViewport, deltaTime, true); + + // Execute events that have been queued during the canvas update + gEnv->pLyShine->ExecuteQueuedEvents(); + } +} + +void ViewportWidget::RenderPreviewMode() +{ + // sort keys for different layers + static const int64_t backgroundKey = -0x1000; + + AZ::EntityId canvasEntityId = m_editorWindow->GetPreviewModeCanvas(); + // Rather than scaling to exactly fit we try to draw at one of these preset scale factors // to make it it bit more obvious that the canvas size is changing float zoomScales[] = { @@ -1096,15 +1184,6 @@ void ViewportWidget::RenderPreviewMode(float deltaTime) } } - // Set the target size of the canvas - EBUS_EVENT_ID(canvasEntityId, UiCanvasBus, SetTargetCanvasSize, true, canvasSize); - - // Update this canvas (must be done after SetTargetCanvasSize) - EBUS_EVENT_ID(canvasEntityId, UiEditorCanvasBus, UpdateCanvasInEditorViewport, deltaTime, true); - - // Execute events that have been queued during the canvas update - gEnv->pLyShine->ExecuteQueuedEvents(); - // match scale to one of the predefined scales. If the scale is so small // that it is less than the smallest scale then leave it as it is for (int i = 0; i < AZ_ARRAY_SIZE(zoomScales); ++i) @@ -1131,14 +1210,6 @@ void ViewportWidget::RenderPreviewMode(float deltaTime) canvasToViewportMatrix.SetTranslation(translation); EBUS_EVENT_ID(canvasEntityId, UiCanvasBus, SetCanvasToViewportMatrix, canvasToViewportMatrix); -#ifdef LYSHINE_ATOM_TODO // mask support with Atom - // clear the stencil buffer before rendering each canvas - required for masking - // NOTE: the FRT_CLEAR_IMMEDIATE is required since we will not be setting the render target - // We also clear the color to a mid grey so that we can see the bounds of the canvas - ColorF viewportBackgroundColor(0.5f, 0.5f, 0.5f, 0); // if clearing color we want to set alpha to zero also - gEnv->pRenderer->ClearTargetsImmediately(FRT_CLEAR, viewportBackgroundColor); -#endif - m_draw2d->SetSortKey(backgroundKey); RenderViewportBackground(); diff --git a/Gems/LyShine/Code/Editor/ViewportWidget.h b/Gems/LyShine/Code/Editor/ViewportWidget.h index 0473b219dc..620cb8fb35 100644 --- a/Gems/LyShine/Code/Editor/ViewportWidget.h +++ b/Gems/LyShine/Code/Editor/ViewportWidget.h @@ -9,9 +9,11 @@ #if !defined(Q_MOC_RUN) #include "EditorCommon.h" +#include "LyShinePassDataBus.h" #include #include +#include #include @@ -27,6 +29,8 @@ class ViewportWidget : public AtomToolsFramework::RenderViewportWidget , private AzToolsFramework::EditorPickModeNotificationBus::Handler , private FontNotificationBus::Handler + , private LyShinePassDataRequestBus::Handler + , public AZ::RPI::ViewportContextNotificationBus::Handler { Q_OBJECT @@ -138,15 +142,29 @@ private: // member functions void OnFontTextureUpdated(IFFont* font) override; // ~FontNotifications + // LyShinePassDataRequestBus + LyShine::AttachmentImagesAndDependencies GetRenderTargets() override; + // ~LyShinePassDataRequestBus + // AZ::TickBus::Handler void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + int GetTickOrder() override; // ~AZ::TickBus::Handler + // AZ::RPI::ViewportContextNotificationBus::Handler overrides... + void OnRenderTick() override; + + //! Update UI canvases when in edit mode + void UpdateEditMode(float deltaTime); + //! Render the viewport when in edit mode - void RenderEditMode(float deltaTime); + void RenderEditMode(); + + //! Update UI canvases when in preview mode + void UpdatePreviewMode(float deltaTime); //! Render the viewport when in preview mode - void RenderPreviewMode(float deltaTime); + void RenderPreviewMode(); //! Fill the entire viewport area with a background color void RenderViewportBackground(); diff --git a/Gems/LyShine/Code/Source/Draw2d.cpp b/Gems/LyShine/Code/Source/Draw2d.cpp index 34ffb38fa3..2d3612fc07 100644 --- a/Gems/LyShine/Code/Source/Draw2d.cpp +++ b/Gems/LyShine/Code/Source/Draw2d.cpp @@ -9,6 +9,7 @@ #include // for SVF_P3F_C4B_T2F which will be removed in a coming PR #include +#include "LyShinePassDataBus.h" #include #include @@ -95,6 +96,12 @@ void CDraw2d::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstrapSc AZ_Assert(scene != nullptr, "Attempting to create a DynamicDrawContext for a viewport context that has not been associated with a scene yet."); // Create and initialize a DynamicDrawContext for 2d drawing + + // Get the pass for the dynamic draw context to render to + AZ::RPI::RasterPass* uiCanvasPass = nullptr; + AZ::RPI::SceneId sceneId = scene->GetId(); + LyShinePassRequestBus::EventResult(uiCanvasPass, sceneId, &LyShinePassRequestBus::Events::GetUiCanvasPass); + m_dynamicDraw = AZ::RPI::DynamicDrawInterface::Get()->CreateDynamicDrawContext(); AZ::RPI::ShaderOptionList shaderOptions; shaderOptions.push_back(AZ::RPI::ShaderOption(AZ::Name("o_useColorChannels"), AZ::Name("true"))); @@ -106,7 +113,15 @@ void CDraw2d::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstrapSc {"TEXCOORD0", AZ::RHI::Format::R32G32_FLOAT} }); m_dynamicDraw->AddDrawStateOptions(AZ::RPI::DynamicDrawContext::DrawStateOptions::PrimitiveType | AZ::RPI::DynamicDrawContext::DrawStateOptions::BlendMode); - m_dynamicDraw->SetOutputScope(scene.get()); + if (uiCanvasPass) + { + m_dynamicDraw->SetOutputScope(uiCanvasPass); + } + else + { + // Render target support is disabled + m_dynamicDraw->SetOutputScope(scene.get()); + } m_dynamicDraw->EndInit(); AZ::RHI::TargetBlendState targetBlendState; @@ -491,6 +506,7 @@ bool CDraw2d::GetDeferPrimitives() return m_deferCalls; } +//////////////////////////////////////////////////////////////////////////////////////////////////// void CDraw2d::SetSortKey(int64_t key) { m_dynamicDraw->SetSortKey(key); diff --git a/Gems/LyShine/Code/Source/LyShine.cpp b/Gems/LyShine/Code/Source/LyShine.cpp index f5edc4d7f1..c776dc11e9 100644 --- a/Gems/LyShine/Code/Source/LyShine.cpp +++ b/Gems/LyShine/Code/Source/LyShine.cpp @@ -163,6 +163,8 @@ CLyShine::CLyShine(ISystem* system) AzFramework::InputTextEventListener::Connect(); UiCursorBus::Handler::BusConnect(); AZ::TickBus::Handler::BusConnect(); + AZ::RPI::ViewportContextNotificationBus::Handler::BusConnect( + AZ::RPI::ViewportContextRequests::Get()->GetDefaultViewportContextName()); AZ::Render::Bootstrap::NotificationBus::Handler::BusConnect(); // These are internal Amazon components, so register them so that we can send back their names to our metrics collection @@ -240,9 +242,11 @@ CLyShine::~CLyShine() { UiCursorBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); + AZ::RPI::ViewportContextNotificationBus::Handler::BusDisconnect(); AzFramework::InputTextEventListener::Disconnect(); AzFramework::InputChannelEventListener::Disconnect(); AZ::Render::Bootstrap::NotificationBus::Handler::BusDisconnect(); + LyShinePassDataRequestBus::Handler::BusDisconnect(); UiCanvasComponent::Shutdown(); @@ -642,15 +646,19 @@ void CLyShine::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time { // Update the loaded UI canvases Update(deltaTime); - - // Recreate dirty render graphs and send primitive data to the dynamic draw context - Render(); } //////////////////////////////////////////////////////////////////////////////////////////////////// int CLyShine::GetTickOrder() { - return AZ::TICK_UI; + return AZ::TICK_PRE_RENDER; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +void CLyShine::OnRenderTick() +{ + // Recreate dirty render graphs and send primitive data to the dynamic draw context + Render(); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -658,6 +666,16 @@ void CLyShine::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstrapS { // Load cursor if its path was set before RPI was initialized LoadUiCursor(); + + LyShinePassDataRequestBus::Handler::BusConnect(AZ::RPI::RPISystemInterface::Get()->GetDefaultScene()->GetId()); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +LyShine::AttachmentImagesAndDependencies CLyShine::GetRenderTargets() +{ + LyShine::AttachmentImagesAndDependencies attachmentImagesAndDependencies; + m_uiCanvasManager->GetRenderTargets(attachmentImagesAndDependencies); + return attachmentImagesAndDependencies; } //////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/LyShine/Code/Source/LyShine.h b/Gems/LyShine/Code/Source/LyShine.h index a7a8cab700..488131389a 100644 --- a/Gems/LyShine/Code/Source/LyShine.h +++ b/Gems/LyShine/Code/Source/LyShine.h @@ -16,8 +16,11 @@ #include #include +#include #include +#include "LyShinePassDataBus.h" + #if !defined(_RELEASE) #define LYSHINE_INTERNAL_UNIT_TEST #endif @@ -40,7 +43,9 @@ class CLyShine , public AzFramework::InputChannelEventListener , public AzFramework::InputTextEventListener , public AZ::TickBus::Handler + , public AZ::RPI::ViewportContextNotificationBus::Handler , protected AZ::Render::Bootstrap::NotificationBus::Handler + , protected LyShinePassDataRequestBus::Handler { public: @@ -111,10 +116,17 @@ public: int GetTickOrder() override; // ~TickEvents + // AZ::RPI::ViewportContextNotificationBus::Handler overrides... + void OnRenderTick() override; + // AZ::Render::Bootstrap::NotificationBus void OnBootstrapSceneReady(AZ::RPI::Scene* bootstrapScene) override; // ~AZ::Render::Bootstrap::NotificationBus + // LyShinePassDataRequestBus + LyShine::AttachmentImagesAndDependencies GetRenderTargets() override; + // ~LyShinePassDataRequestBus + // Get the UIRenderer for the game (which is owned by CLyShine). This is not exposed outside the gem. UiRenderer* GetUiRenderer(); diff --git a/Gems/LyShine/Code/Source/LyShinePass.cpp b/Gems/LyShine/Code/Source/LyShinePass.cpp new file mode 100644 index 0000000000..fbf7f34e14 --- /dev/null +++ b/Gems/LyShine/Code/Source/LyShinePass.cpp @@ -0,0 +1,274 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "LyShinePass.h" + +namespace LyShine +{ + AZ::RPI::Ptr LyShinePass::Create(const AZ::RPI::PassDescriptor& descriptor) + { + return aznew LyShinePass(descriptor); + } + + LyShinePass::LyShinePass(const AZ::RPI::PassDescriptor& descriptor) + : Base(descriptor) + { + } + + LyShinePass::~LyShinePass() + { + LyShinePassRequestBus::Handler::BusDisconnect(); + } + + void LyShinePass::ResetInternal() + { + LyShinePassRequestBus::Handler::BusDisconnect(); + + Base::ResetInternal(); + } + + void LyShinePass::BuildInternal() + { + AZ::RPI::Scene* scene = GetScene(); + if (scene) + { + // Listen for rebuild requests + LyShinePassRequestBus::Handler::BusConnect(scene->GetId()); + + RemoveChildren(); + + // Get the current list of render targets being used across all loaded UI Canvases + LyShine::AttachmentImagesAndDependencies attachmentImagesAndDependencies; + LyShinePassDataRequestBus::EventResult( + attachmentImagesAndDependencies, + scene->GetId(), + &LyShinePassDataRequestBus::Events::GetRenderTargets + ); + + AddRttChildPasses(attachmentImagesAndDependencies); + AddUiCanvasChildPass(attachmentImagesAndDependencies); + } + + Base::BuildInternal(); + } + + void LyShinePass::RebuildRttChildren() + { + QueueForBuildAndInitialization(); + } + + AZ::RPI::RasterPass* LyShinePass::GetRttPass(const AZStd::string& name) + { + for (auto child:m_children) + { + if (child->GetName() == AZ::Name(name)) + { + return azrtti_cast(child.get()); + } + } + return nullptr; + } + + AZ::RPI::RasterPass* LyShinePass::GetUiCanvasPass() + { + return m_uiCanvasChildPass.get(); + } + + void LyShinePass::AddRttChildPasses(LyShine::AttachmentImagesAndDependencies attachmentImagesAndDependencies) + { + for (const auto& attachmentImageAndDependencies : attachmentImagesAndDependencies) + { + AddRttChildPass(attachmentImageAndDependencies.first, attachmentImageAndDependencies.second); + } + } + + void LyShinePass::AddRttChildPass(AZ::Data::Instance attachmentImage, AttachmentImages attachmentImageDependencies) + { + // Add a pass that renders to the specified texture + + // Create a pass template + auto passTemplate = AZStd::make_shared(); + passTemplate->m_name = "RttChildPass"; + passTemplate->m_passClass = AZ::Name("RttChildPass"); + + // Slots + passTemplate->m_slots.resize(2); + + AZ::RPI::PassSlot& depthInOutSlot = passTemplate->m_slots[0]; + depthInOutSlot.m_name = "DepthInputOutput"; + depthInOutSlot.m_slotType = AZ::RPI::PassSlotType::InputOutput; + depthInOutSlot.m_scopeAttachmentUsage = AZ::RHI::ScopeAttachmentUsage::DepthStencil; + depthInOutSlot.m_loadStoreAction.m_clearValue = AZ::RHI::ClearValue::CreateDepthStencil(0.0f, 0); + depthInOutSlot.m_loadStoreAction.m_loadActionStencil = AZ::RHI::AttachmentLoadAction::Clear; + + AZ::RPI::PassSlot& outSlot = passTemplate->m_slots[1]; + outSlot.m_name = AZ::Name("RenderTargetOutput"); + outSlot.m_slotType = AZ::RPI::PassSlotType::Output; + outSlot.m_scopeAttachmentUsage = AZ::RHI::ScopeAttachmentUsage::RenderTarget; + outSlot.m_loadStoreAction.m_clearValue = AZ::RHI::ClearValue::CreateVector4Float(0.0f, 0.0f, 0.0f, 0.0f); + outSlot.m_loadStoreAction.m_loadAction = AZ::RHI::AttachmentLoadAction::Clear; + + // Connections + passTemplate->m_connections.resize(1); + + AZ::RPI::PassConnection& depthInOutConnection = passTemplate->m_connections[0]; + depthInOutConnection.m_localSlot = "DepthInputOutput"; + depthInOutConnection.m_attachmentRef.m_pass = "Parent"; + depthInOutConnection.m_attachmentRef.m_attachment = "DepthInputOutput"; + + // Pass data + AZStd::shared_ptr passData = AZStd::make_shared(); + passData->m_drawListTag = AZ::Name("uicanvas"); + passData->m_pipelineViewTag = AZ::Name("MainCamera"); + auto size = attachmentImage->GetRHIImage()->GetDescriptor().m_size; + passData->m_overrideScissor = AZ::RHI::Scissor(0, 0, size.m_width, size.m_height); + passData->m_overrideViewport = AZ::RHI::Viewport(0, size.m_width, 0, size.m_height); + passTemplate->m_passData = AZStd::move(passData); + // Create a pass descriptor for the new child pass + AZ::RPI::PassDescriptor childDesc; + childDesc.m_passTemplate = passTemplate; + childDesc.m_passName = attachmentImage->GetAttachmentId(); + + AZ::RPI::PassSystemInterface* passSystem = AZ::RPI::PassSystemInterface::Get(); + AZ::RPI::Ptr rttChildPass = passSystem->CreatePass(childDesc); + AZ_Assert(rttChildPass, "[LyShinePass] Unable to create %s.", passTemplate->m_name.GetCStr()); + + // Store the info needed to attach to slots and set up frame graph dependencies + rttChildPass->m_attachmentImage = attachmentImage; + rttChildPass->m_attachmentImageDependencies = attachmentImageDependencies; + + AddChild(rttChildPass); + } + + void LyShinePass::AddUiCanvasChildPass(LyShine::AttachmentImagesAndDependencies AttachmentImagesAndDependencies) + { + if (!m_uiCanvasChildPass) + { + // Create a pass template + auto passTemplate = AZStd::make_shared(); + passTemplate->m_name = AZ::Name("LyShineChildPass"); + passTemplate->m_passClass = AZ::Name("LyShineChildPass"); + + // Slots + passTemplate->m_slots.resize(2); + + AZ::RPI::PassSlot& depthInOutSlot = passTemplate->m_slots[0]; + depthInOutSlot.m_name = "DepthInputOutput"; + depthInOutSlot.m_slotType = AZ::RPI::PassSlotType::InputOutput; + depthInOutSlot.m_scopeAttachmentUsage = AZ::RHI::ScopeAttachmentUsage::DepthStencil; + depthInOutSlot.m_loadStoreAction.m_clearValue = AZ::RHI::ClearValue::CreateDepthStencil(0.0f, 0); + depthInOutSlot.m_loadStoreAction.m_loadActionStencil = AZ::RHI::AttachmentLoadAction::Clear; + + AZ::RPI::PassSlot& inOutSlot = passTemplate->m_slots[1]; + inOutSlot.m_name = "ColorInputOutput"; + inOutSlot.m_slotType = AZ::RPI::PassSlotType::InputOutput; + inOutSlot.m_scopeAttachmentUsage = AZ::RHI::ScopeAttachmentUsage::RenderTarget; + + // Connections + passTemplate->m_connections.resize(2); + + AZ::RPI::PassConnection& depthInOutConnection = passTemplate->m_connections[0]; + depthInOutConnection.m_localSlot = "DepthInputOutput"; + depthInOutConnection.m_attachmentRef.m_pass = "Parent"; + depthInOutConnection.m_attachmentRef.m_attachment = "DepthInputOutput"; + + AZ::RPI::PassConnection& inOutConnection = passTemplate->m_connections[1]; + inOutConnection.m_localSlot = "ColorInputOutput"; + inOutConnection.m_attachmentRef.m_pass = "Parent"; + inOutConnection.m_attachmentRef.m_attachment = "ColorInputOutput"; + + // Pass data + AZStd::shared_ptr passData = AZStd::make_shared(); + passData->m_drawListTag = AZ::Name("uicanvas"); + passData->m_pipelineViewTag = AZ::Name("MainCamera"); + passTemplate->m_passData = AZStd::move(passData); + + // Create a pass descriptor for the new child pass + AZ::RPI::PassDescriptor childDesc; + childDesc.m_passTemplate = passTemplate; + childDesc.m_passName = AZ::Name("LyShineChildPass"); + + AZ::RPI::PassSystemInterface* passSystem = AZ::RPI::PassSystemInterface::Get(); + m_uiCanvasChildPass = passSystem->CreatePass(childDesc); + AZ_Assert(m_uiCanvasChildPass, "[LyShinePass] Unable to create %s.", passTemplate->m_name.GetCStr()); + } + + // Store the info needed to set up frame graph dependencies + m_uiCanvasChildPass->m_attachmentImageDependencies.clear(); + for (const auto& attachmentImageAndDescendents : AttachmentImagesAndDependencies) + { + m_uiCanvasChildPass->m_attachmentImageDependencies.emplace_back(attachmentImageAndDescendents.first); + } + + AddChild(m_uiCanvasChildPass); + } + + AZ::RPI::Ptr LyShineChildPass::Create(const AZ::RPI::PassDescriptor& descriptor) + { + return aznew LyShineChildPass(descriptor); + } + + LyShineChildPass::LyShineChildPass(const AZ::RPI::PassDescriptor& descriptor) + : RasterPass(descriptor) + { + } + + LyShineChildPass::~LyShineChildPass() + { + } + + void LyShineChildPass::SetupFrameGraphDependencies(AZ::RHI::FrameGraphInterface frameGraph) + { + AZ::RPI::RasterPass::SetupFrameGraphDependencies(frameGraph); + + for (auto attachmentImage : m_attachmentImageDependencies) + { + // Ensure that the image is imported into the attachment database. + // The image may not be imported if the owning pass has been disabled. + auto attachmentImageId = attachmentImage->GetAttachmentId(); + if (!frameGraph.GetAttachmentDatabase().IsAttachmentValid(attachmentImageId)) + { + frameGraph.GetAttachmentDatabase().ImportImage(attachmentImageId, attachmentImage->GetRHIImage()); + } + + AZ::RHI::ImageScopeAttachmentDescriptor desc; + desc.m_attachmentId = attachmentImageId; + desc.m_imageViewDescriptor = attachmentImage->GetImageView()->GetDescriptor(); + desc.m_loadStoreAction.m_loadAction = AZ::RHI::AttachmentLoadAction::Load; + + frameGraph.UseShaderAttachment(desc, AZ::RHI::ScopeAttachmentAccess::Read); + } + } + + AZ::RPI::Ptr RttChildPass::Create(const AZ::RPI::PassDescriptor& descriptor) + { + return aznew RttChildPass(descriptor); + } + + RttChildPass::RttChildPass(const AZ::RPI::PassDescriptor& descriptor) + : LyShineChildPass(descriptor) + { + } + + RttChildPass::~RttChildPass() + { + } + + void RttChildPass::BuildInternal() + { + AttachImageToSlot(AZ::Name("RenderTargetOutput"), m_attachmentImage); + } +} // namespace LyShine diff --git a/Gems/LyShine/Code/Source/LyShinePass.h b/Gems/LyShine/Code/Source/LyShinePass.h new file mode 100644 index 0000000000..6275353641 --- /dev/null +++ b/Gems/LyShine/Code/Source/LyShinePass.h @@ -0,0 +1,110 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include +#include +#include +#include +#include "LyShinePassDataBus.h" + +namespace LyShine +{ + class LyShineChildPass; + + //! Manages child passes at runtime that render to render targets + class LyShinePass final + : public AZ::RPI::ParentPass + , protected LyShinePassRequestBus::Handler + { + AZ_RPI_PASS(LyShinePass); + using Base = AZ::RPI::ParentPass; + + public: + AZ_CLASS_ALLOCATOR(LyShinePass, AZ::SystemAllocator, 0); + AZ_RTTI(LyShinePass, "C3B812ED-3771-42F4-A96F-EBD94B4D54CA", Base); + + virtual ~LyShinePass(); + static AZ::RPI::Ptr Create(const AZ::RPI::PassDescriptor& descriptor); + + protected: + // Pass behavior overrides + void ResetInternal() override; + void BuildInternal() override; + + // LyShinePassRequestBus overrides + void RebuildRttChildren() override; + AZ::RPI::RasterPass* GetRttPass(const AZStd::string& name) override; + AZ::RPI::RasterPass* GetUiCanvasPass() override; + + private: + LyShinePass() = delete; + explicit LyShinePass(const AZ::RPI::PassDescriptor& descriptor); + + // Build the render to texture child passes + void AddRttChildPasses(LyShine::AttachmentImagesAndDependencies AttachmentImagesAndDependencies); + + // Add a render to texture child pass + void AddRttChildPass(AZ::Data::Instance attachmentImage, AttachmentImages dependentAttachmentImages); + + // Append the final pass to render UI Canvas elements to the screen + void AddUiCanvasChildPass(LyShine::AttachmentImagesAndDependencies AttachmentImagesAndDependencies); + + // Pass that renders the UI Canvas elements to the screen + AZ::RPI::Ptr m_uiCanvasChildPass; + }; + + // Child pass with potential attachment dependencies + class LyShineChildPass + : public AZ::RPI::RasterPass + { + AZ_RPI_PASS(LyShineChildPass); + + friend class LyShinePass; + public: + AZ_RTTI(LyShineChildPass, "{41D525F9-09EB-4004-97DC-082078FF8DD2}", RasterPass); + AZ_CLASS_ALLOCATOR(LyShineChildPass, AZ::SystemAllocator, 0); + virtual ~LyShineChildPass(); + + //! Creates a LyShineChildPass + static AZ::RPI::Ptr Create(const AZ::RPI::PassDescriptor& descriptor); + + protected: + LyShineChildPass(const AZ::RPI::PassDescriptor& descriptor); + + // Scope producer Overrides... + void SetupFrameGraphDependencies(AZ::RHI::FrameGraphInterface frameGraph) override; + + AttachmentImages m_attachmentImageDependencies; + }; + + // Child pass that renders UI elements to a render target + class RttChildPass + : public LyShineChildPass + { + AZ_RPI_PASS(RttChildPass); + + friend class LyShinePass; + + public: + AZ_RTTI(RttChildPass, "{54B0574D-2EB3-4054-9E1D-0E0D9C8CB09A}", LyShineChildPass); + AZ_CLASS_ALLOCATOR(RttChildPass, AZ::SystemAllocator, 0); + virtual ~RttChildPass(); + + //! Creates a RttChildPass + static AZ::RPI::Ptr Create(const AZ::RPI::PassDescriptor& descriptor); + + protected: + RttChildPass(const AZ::RPI::PassDescriptor& descriptor); + + // Pass behavior overrides + void BuildInternal() override; + + AZ::Data::Instance m_attachmentImage; + }; +} // namespace LyShine diff --git a/Gems/LyShine/Code/Source/LyShinePassDataBus.h b/Gems/LyShine/Code/Source/LyShinePassDataBus.h new file mode 100644 index 0000000000..a07e43bc44 --- /dev/null +++ b/Gems/LyShine/Code/Source/LyShinePassDataBus.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include +#include +#include + +namespace AZ +{ + namespace RPI + { + class AttachmentImage; + class RasterPass; + } +} + +namespace LyShine +{ + using AttachmentImages = AZStd::vector>; + using AttachmentImageAndDependentsPair = AZStd::pair, AttachmentImages>; + using AttachmentImagesAndDependencies = AZStd::vector; +} + +class LyShinePassRequests + : public AZ::EBusTraits +{ +public: + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + using BusIdType = AZ::RPI::SceneId; + + //! Called when the number of render targets has changed and the LyShine pass needs to rebuild + virtual void RebuildRttChildren() = 0; + + //! Returns a render to texture pass based on render target name + virtual AZ::RPI::RasterPass* GetRttPass(const AZStd::string& name) = 0; + + //! Returns the final pass that renders the UI canvas contents + virtual AZ::RPI::RasterPass* GetUiCanvasPass() = 0; +}; +using LyShinePassRequestBus = AZ::EBus; + +class LyShinePassDataRequests + : public AZ::EBusTraits +{ +public: + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Single; + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById; + using BusIdType = AZ::RPI::SceneId; + + //! Get a list of render targets that require a render to texture pass, and any + //! other render targets that are drawn on them + virtual LyShine::AttachmentImagesAndDependencies GetRenderTargets() = 0; +}; +using LyShinePassDataRequestBus = AZ::EBus; diff --git a/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp b/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp index 337fe27bc5..f05cbc04d4 100644 --- a/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp +++ b/Gems/LyShine/Code/Source/LyShineSystemComponent.cpp @@ -49,6 +49,7 @@ #include "UiDynamicLayoutComponent.h" #include "UiDynamicScrollBoxComponent.h" #include "UiNavigationSettings.h" +#include "LyShinePass.h" namespace LyShine { @@ -113,9 +114,11 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void LyShineSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required) + void LyShineSystemComponent::GetRequiredServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& required) { - (void)required; +#if !defined(LYSHINE_BUILDER) && !defined(LYSHINE_TESTS) + required.push_back(AZ_CRC("RPISystem", 0xf2add773)); +#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -186,6 +189,17 @@ namespace LyShine RegisterComponentTypeForMenuOrdering(UiDynamicScrollBoxComponent::RTTI_Type()); RegisterComponentTypeForMenuOrdering(UiParticleEmitterComponent::RTTI_Type()); RegisterComponentTypeForMenuOrdering(UiFlipbookAnimationComponent::RTTI_Type()); + +#if !defined(LYSHINE_BUILDER) && !defined(LYSHINE_TESTS) + // Add LyShine pass + auto* passSystem = AZ::RPI::PassSystemInterface::Get(); + AZ_Assert(passSystem, "Cannot get the pass system."); + passSystem->AddPassCreator(AZ::Name("LyShinePass"), &LyShine::LyShinePass::Create); + + // Setup handler for load pass template mappings + m_loadTemplatesHandler = AZ::RPI::PassSystemInterface::OnReadyLoadTemplatesEvent::Handler([this]() { this->LoadPassTemplateMappings(); }); + AZ::RPI::PassSystemInterface::Get()->ConnectEvent(m_loadTemplatesHandler); +#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -386,4 +400,13 @@ namespace LyShine { UiCursorBus::Broadcast(&UiCursorInterface::SetUiCursor, m_cursorImagePathname.GetAssetPath().c_str()); } + +#if !defined(LYSHINE_BUILDER) && !defined(LYSHINE_TESTS) + //////////////////////////////////////////////////////////////////////////////////////////////////// + void LyShineSystemComponent::LoadPassTemplateMappings() + { + const char* passTemplatesFile = "Passes/LyShinePassTemplates.azasset"; + AZ::RPI::PassSystemInterface::Get()->LoadPassTemplateMappings(passTemplatesFile); + } +#endif } diff --git a/Gems/LyShine/Code/Source/LyShineSystemComponent.h b/Gems/LyShine/Code/Source/LyShineSystemComponent.h index 9b5f32aa57..2e0d40e8b0 100644 --- a/Gems/LyShine/Code/Source/LyShineSystemComponent.h +++ b/Gems/LyShine/Code/Source/LyShineSystemComponent.h @@ -20,6 +20,10 @@ #include #include "LyShine.h" +#if !defined(LYSHINE_BUILDER) && !defined(LYSHINE_TESTS) +#include +#endif + namespace LyShine { // LyShine depends on the LegacyAllocator and CryStringAllocator. This will be managed @@ -90,6 +94,11 @@ namespace LyShine void BroadcastCursorImagePathname(); +#if !defined(LYSHINE_BUILDER) && !defined(LYSHINE_TESTS) + // Load pass template mappings for this gem + void LoadPassTemplateMappings(); +#endif + protected: // data CLyShine* m_pLyShine = nullptr; @@ -102,5 +111,9 @@ namespace LyShine // We only store this in order to generate metrics on LyShine specific components static const AZStd::list* m_componentDescriptors; + +#if !defined(LYSHINE_BUILDER) && !defined(LYSHINE_TESTS) + AZ::RPI::PassSystemInterface::OnReadyLoadTemplatesEvent::Handler m_loadTemplatesHandler; +#endif }; } diff --git a/Gems/LyShine/Code/Source/RenderGraph.cpp b/Gems/LyShine/Code/Source/RenderGraph.cpp index 9ee26cdf8e..ee26d1dd61 100644 --- a/Gems/LyShine/Code/Source/RenderGraph.cpp +++ b/Gems/LyShine/Code/Source/RenderGraph.cpp @@ -10,6 +10,9 @@ #include "UiRenderer.h" #include +#include + +#include #ifndef _RELEASE #include @@ -78,57 +81,28 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void PrimitiveListRenderNode::Render(UiRenderer* uiRenderer) + void PrimitiveListRenderNode::Render(UiRenderer* uiRenderer + , const AZ::Matrix4x4& modelViewProjMat + , AZ::RHI::Ptr dynamicDraw) { -#ifdef LYSHINE_ATOM_TODO // keeping this code for reference for future phase (masks/render targets) - for (int i = 0; i < m_numTextures; ++i) - { - uiRenderer->SetTexture(m_textures[i].m_texture, i, m_textures[i].m_isClampTextureMode); - } - - int blendModeState = m_blendModeState; - - IRenderer* renderer = gEnv->pRenderer; - renderer->SetState(blendModeState | uiRenderer->GetBaseState()); - - if (m_isTextureSRGB) - { - renderer->SetSrgbWrite(false); - } - - // We are using SetColorOp as a way to set flags for the ui.cfx shader by reusing flags - // that the FixedPipelineEmu.cfx shader uses. So the names colorOp and alphaOp are used - // just because this are the inputs to SetColorOp. - uint8 colorOp = m_preMultiplyAlpha ? ColorOp_PreMultiplyAlpha : ColorOp_Normal; - uint8 alphaOp = AlphaOp_Normal; - switch (m_alphaMaskType) - { - case AlphaMaskType::None: - alphaOp = AlphaOp_Normal; - break; - case AlphaMaskType::ModulateAlpha: - alphaOp = AlphaOp_ModulateAlpha; - break; - case AlphaMaskType::ModulateAlphaAndColor: - alphaOp = AlphaOp_ModulateAlphaAndColor; - break; - } - - renderer->SetColorOp(colorOp, alphaOp, DEF_TEXARG0, DEF_TEXARG0); - - renderer->DrawDynUiPrimitiveList(m_primitives, m_totalNumVertices, m_totalNumIndices); - - if (m_isTextureSRGB) - { - renderer->SetSrgbWrite(true); - } -#endif if (!uiRenderer->IsReady()) { return; } - AZ::RHI::Ptr dynamicDraw = uiRenderer->GetDynamicDrawContext(); + UiRenderer::BaseState curBaseState = uiRenderer->GetBaseState(); + UiRenderer::BaseState prevBaseState = curBaseState; + if (m_isTextureSRGB) + { + curBaseState.m_srgbWrite = false; + } + + if (m_alphaMaskType == AlphaMaskType::ModulateAlpha) + { + curBaseState.m_modulateAlpha = true; + } + uiRenderer->SetBaseState(curBaseState); + const UiRenderer::UiShaderData& uiShaderData = uiRenderer->GetUiShaderData(); // Set render state @@ -167,7 +141,7 @@ namespace LyShine drawSrg->SetConstant(uiShaderData.m_isClampInputIndex, isClampTextureMode); // Set projection matrix - drawSrg->SetConstant(uiShaderData.m_viewProjInputIndex, uiRenderer->GetModelViewProjectionMatrix()); + drawSrg->SetConstant(uiShaderData.m_viewProjInputIndex, modelViewProjMat); drawSrg->Compile(); @@ -180,6 +154,8 @@ namespace LyShine { dynamicDraw->DrawIndexed(primitive.m_vertices, primitive.m_numVertices, primitive.m_indices, primitive.m_numIndices, AZ::RHI::IndexFormat::Uint16, drawSrg); } + + uiRenderer->SetBaseState(prevBaseState); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -303,33 +279,35 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void MaskRenderNode::Render(UiRenderer* uiRenderer) + void MaskRenderNode::Render(UiRenderer* uiRenderer + , const AZ::Matrix4x4& modelViewProjMat + , AZ::RHI::Ptr dynamicDraw) { UiRenderer::BaseState priorBaseState = uiRenderer->GetBaseState(); if (m_isMaskingEnabled || m_drawBehind) { - SetupBeforeRenderingMask(uiRenderer, true, priorBaseState); + SetupBeforeRenderingMask(uiRenderer, dynamicDraw, true, priorBaseState); for (RenderNode* renderNode : m_maskRenderNodes) { - renderNode->Render(uiRenderer); + renderNode->Render(uiRenderer, modelViewProjMat, dynamicDraw); } - SetupAfterRenderingMask(uiRenderer, true, priorBaseState); + SetupAfterRenderingMask(uiRenderer, dynamicDraw, true, priorBaseState); } for (RenderNode* renderNode : m_contentRenderNodes) { - renderNode->Render(uiRenderer); + renderNode->Render(uiRenderer, modelViewProjMat, dynamicDraw); } if (m_isMaskingEnabled || m_drawInFront) { - SetupBeforeRenderingMask(uiRenderer, false, priorBaseState); + SetupBeforeRenderingMask(uiRenderer, dynamicDraw, false, priorBaseState); for (RenderNode* renderNode : m_maskRenderNodes) { - renderNode->Render(uiRenderer); + renderNode->Render(uiRenderer, modelViewProjMat, dynamicDraw); } - SetupAfterRenderingMask(uiRenderer, false, priorBaseState); + SetupAfterRenderingMask(uiRenderer, dynamicDraw, false, priorBaseState); } } @@ -367,7 +345,9 @@ namespace LyShine #endif //////////////////////////////////////////////////////////////////////////////////////////////////// - void MaskRenderNode::SetupBeforeRenderingMask(UiRenderer* uiRenderer, bool firstPass, UiRenderer::BaseState priorBaseState) + void MaskRenderNode::SetupBeforeRenderingMask(UiRenderer* uiRenderer, + AZ::RHI::Ptr dynamicDraw, + bool firstPass, UiRenderer::BaseState priorBaseState) { UiRenderer::BaseState curBaseState = priorBaseState; @@ -406,7 +386,6 @@ namespace LyShine curBaseState.m_stencilState.m_backFace = stencilOpState; // set up for stencil write - AZ::RHI::Ptr dynamicDraw = uiRenderer->GetDynamicDrawContext(); dynamicDraw->SetStencilReference(uiRenderer->GetStencilRef()); curBaseState.m_stencilState.m_enable = true; curBaseState.m_stencilState.m_writeMask = 0xFF; @@ -421,7 +400,9 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void MaskRenderNode::SetupAfterRenderingMask(UiRenderer* uiRenderer, bool firstPass, UiRenderer::BaseState priorBaseState) + void MaskRenderNode::SetupAfterRenderingMask(UiRenderer* uiRenderer, + AZ::RHI::Ptr dynamicDraw, + bool firstPass, UiRenderer::BaseState priorBaseState) { if (m_isMaskingEnabled) { @@ -439,7 +420,6 @@ namespace LyShine uiRenderer->DecrementStencilRef(); } - AZ::RHI::Ptr dynamicDraw = uiRenderer->GetDynamicDrawContext(); dynamicDraw->SetStencilReference(uiRenderer->GetStencilRef()); if (firstPass) @@ -474,16 +454,14 @@ namespace LyShine //////////////////////////////////////////////////////////////////////////////////////////////////// RenderTargetRenderNode::RenderTargetRenderNode( RenderTargetRenderNode* parentRenderTarget, - int renderTargetHandle, - SDepthTexture* renderTargetDepthSurface, + AZ::Data::Instance attachmentImage, const AZ::Vector2& viewportTopLeft, const AZ::Vector2& viewportSize, const AZ::Color& clearColor, int nestLevel) : RenderNode(RenderNodeType::RenderTarget) , m_parentRenderTarget(parentRenderTarget) - , m_renderTargetHandle(renderTargetHandle) - , m_renderTargetDepthSurface(renderTargetDepthSurface) + , m_attachmentImage(attachmentImage) , m_viewportX(viewportTopLeft.GetX()) , m_viewportY(viewportTopLeft.GetY()) , m_viewportWidth(viewportSize.GetX()) @@ -491,6 +469,13 @@ namespace LyShine , m_clearColor(clearColor) , m_nestLevel(nestLevel) { + AZ::MakeOrthographicMatrixRH(m_modelViewProjMat, + m_viewportX, + m_viewportX + m_viewportWidth, + m_viewportY + m_viewportHeight, + m_viewportY, + 0.0f, + 1.0f); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -505,9 +490,11 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void RenderTargetRenderNode::Render(UiRenderer* uiRenderer) + void RenderTargetRenderNode::Render(UiRenderer* uiRenderer + , [[maybe_unused]] const AZ::Matrix4x4& modelViewProjMat + , [[maybe_unused]] AZ::RHI::Ptr dynamicDraw) { - if (m_renderTargetHandle <= 0) + if (!m_attachmentImage) { return; } @@ -515,39 +502,52 @@ namespace LyShine ISystem* system = gEnv->pSystem; if (system && !gEnv->IsDedicated()) { - TransformationMatrices backupMatrices; - gEnv->pRenderer->Set2DModeNonZeroTopLeft(m_viewportX, m_viewportY, m_viewportWidth, m_viewportHeight, backupMatrices); - - // this will change the viewport - gEnv->pRenderer->SetRenderTarget(m_renderTargetHandle, m_renderTargetDepthSurface); - - // clear the render target before rendering to it - // NOTE: the FRT_CLEAR_IMMEDIATE is required since we will have already set the render target - // In theory we could call this before setting the render target without the immediate flag - // but that doesn't work. Perhaps because FX_Commit is not called. - ColorF viewportBackgroundColor(m_clearColor.GetR(), m_clearColor.GetG(), m_clearColor.GetB(), m_clearColor.GetA()); - gEnv->pRenderer->ClearTargetsImmediately(FRT_CLEAR, viewportBackgroundColor); - - // we could use SetSrgbWrite to write to a linear texture here. But that gets complicated with - // having to affect all decsendant element renders. So we just let it write srgb to the render target and - // allow for that when we render using the render target as a source texture. - - for (RenderNode* renderNode : m_childRenderNodes) + // Use a dedicated dynamic draw context for rendering to the texture since it can only have one draw list tag + if (!m_dynamicDraw) { - renderNode->Render(uiRenderer); + m_dynamicDraw = uiRenderer->CreateDynamicDrawContextForRTT(GetRenderTargetName()); } - gEnv->pRenderer->SetRenderTarget(0); // restore render target + if (m_dynamicDraw) + { + UiRenderer::BaseState priorBaseState = uiRenderer->GetBaseState(); - gEnv->pRenderer->Unset2DMode(backupMatrices); + UiRenderer::BaseState curBaseState = priorBaseState; + curBaseState.m_blendState.m_blendAlphaSource = AZ::RHI::BlendFactor::One; + curBaseState.m_blendState.m_blendAlphaDest = AZ::RHI::BlendFactor::AlphaSource1Inverse; + uiRenderer->SetBaseState(curBaseState); + + for (RenderNode* renderNode : m_childRenderNodes) + { + renderNode->Render(uiRenderer, m_modelViewProjMat, m_dynamicDraw); + } + + uiRenderer->SetBaseState(priorBaseState); + } + else + { + AZ_WarningOnce("UI", false, "Failed to create a Dynamic Draw Context for UI Element's render target. "\ + "Please ensure that the custom LyShinePass has been added to the project's main render pipeline."); + } } } //////////////////////////////////////////////////////////////////////////////////////////////////// const char* RenderTargetRenderNode::GetRenderTargetName() const { - ITexture* texture = gEnv->pRenderer->EF_GetTextureByID(m_renderTargetHandle); - return texture->GetName(); + return m_attachmentImage->GetRHIImage()->GetName().GetCStr(); + } + + //////////////////////////////////////////////////////////////////////////////////////////////////// + int RenderTargetRenderNode::GetNestLevel() const + { + return m_nestLevel; + } + + //////////////////////////////////////////////////////////////////////////////////////////////////// + const AZ::Data::Instance RenderTargetRenderNode::GetRenderTarget() const + { + return m_attachmentImage; } #ifndef _RELEASE @@ -671,31 +671,29 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void RenderGraph::BeginRenderToTexture(int renderTargetHandle, SDepthTexture* renderTargetDepthSurface, + void RenderGraph::BeginRenderToTexture([[maybe_unused]] int renderTargetHandle, [[maybe_unused]] SDepthTexture* renderTargetDepthSurface, + [[maybe_unused]] const AZ::Vector2& viewportTopLeft, [[maybe_unused]] const AZ::Vector2& viewportSize, [[maybe_unused]] const AZ::Color& clearColor) + { + // LYSHINE_ATOM_TODO - this function will be removed when all IRenderer references are gone from UI components + } + + //////////////////////////////////////////////////////////////////////////////////////////////////// + void RenderGraph::BeginRenderToTexture(AZ::Data::Instance attachmentImage, const AZ::Vector2& viewportTopLeft, const AZ::Vector2& viewportSize, const AZ::Color& clearColor) { -#ifdef LYSHINE_ATOM_TODO // keeping this code for future phase (masks and render targets) // this uses pool allocator RenderTargetRenderNode* renderTargetRenderNode = new RenderTargetRenderNode( - m_currentRenderTarget, renderTargetHandle, renderTargetDepthSurface, + m_currentRenderTarget, attachmentImage, viewportTopLeft, viewportSize, clearColor, m_renderTargetNestLevel); m_currentRenderTarget = renderTargetRenderNode; m_renderNodeListStack.push(&m_currentRenderTarget->GetChildRenderNodeList()); m_renderTargetNestLevel++; -#else - AZ_UNUSED(clearColor); - AZ_UNUSED(viewportSize); - AZ_UNUSED(viewportTopLeft); - AZ_UNUSED(renderTargetDepthSurface); - AZ_UNUSED(renderTargetHandle); -#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// void RenderGraph::EndRenderToTexture() { -#ifdef LYSHINE_ATOM_TODO // keeping this code for future phase (masks and render targets) AZ_Assert(m_currentRenderTarget, "Calling EndRenderToTexture while not defining a render target node"); if (m_currentRenderTarget) { @@ -709,7 +707,6 @@ namespace LyShine m_renderNodeListStack.pop(); m_renderTargetNestLevel--; } -#endif } void RenderGraph::AddPrimitive( @@ -803,11 +800,22 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void RenderGraph::AddAlphaMaskPrimitive(IRenderer::DynUiPrimitive* primitive, - ITexture* texture, ITexture* maskTexture, - bool isClampTextureMode, bool isTextureSRGB, bool isTexturePremultipliedAlpha, BlendMode blendMode) + void RenderGraph::AddAlphaMaskPrimitive([[maybe_unused]] IRenderer::DynUiPrimitive* primitive, + [[maybe_unused]] ITexture* texture, [[maybe_unused]] ITexture* maskTexture, + [[maybe_unused]] bool isClampTextureMode, [[maybe_unused]] bool isTextureSRGB, [[maybe_unused]] bool isTexturePremultipliedAlpha, [[maybe_unused]] BlendMode blendMode) + { + // LYSHINE_ATOM_TODO - this function will be removed when all IRenderer references are gone from UI components + } + + //////////////////////////////////////////////////////////////////////////////////////////////////// + void RenderGraph::AddAlphaMaskPrimitiveAtom(IRenderer::DynUiPrimitive* primitive, + AZ::Data::Instance contentAttachmentImage, + AZ::Data::Instance maskAttachmentImage, + bool isClampTextureMode, + bool isTextureSRGB, + bool isTexturePremultipliedAlpha, + BlendMode blendMode) { -#ifdef LYSHINE_ATOM_TODO // keeping this code for future phase (masks and render targets) AZStd::vector* renderNodeList = m_renderNodeListStack.top(); int texUnit0 = -1; @@ -842,8 +850,8 @@ namespace LyShine { // render state is the same - we can add the primitive to this list if the texture is in // the list or there is space for another texture - texUnit0 = primListRenderNode->GetOrAddTexture(texture, true); - texUnit1 = primListRenderNode->GetOrAddTexture(maskTexture, true); + texUnit0 = primListRenderNode->GetOrAddTexture(contentAttachmentImage, true); + texUnit1 = primListRenderNode->GetOrAddTexture(maskAttachmentImage, true); if (texUnit0 != -1 && texUnit1 != -1) { @@ -857,7 +865,7 @@ namespace LyShine { // We can't add this primitive to the existing render node, we need to create a new render node // this uses a pool allocator for fast allocation - renderNodeToAddTo = new PrimitiveListRenderNode(texture, maskTexture, + renderNodeToAddTo = new PrimitiveListRenderNode(contentAttachmentImage, maskAttachmentImage, isClampTextureMode, isTextureSRGB, isPreMultiplyAlpha, alphaMaskType, blendModeState); renderNodeList->push_back(renderNodeToAddTo); @@ -881,15 +889,6 @@ namespace LyShine // add this primitive to the render node renderNodeToAddTo->AddPrimitive(primitive); } -#else - AZ_UNUSED(primitive); - AZ_UNUSED(texture); - AZ_UNUSED(maskTexture); - AZ_UNUSED(isClampTextureMode); - AZ_UNUSED(isTextureSRGB); - AZ_UNUSED(isTexturePremultipliedAlpha); - AZ_UNUSED(blendMode); -#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -972,11 +971,8 @@ namespace LyShine } //////////////////////////////////////////////////////////////////////////////////////////////////// - void RenderGraph::Render(UiRenderer* uiRenderer, const AZ::Vector2& viewportSize) + void RenderGraph::Render(UiRenderer* uiRenderer, [[maybe_unused]] const AZ::Vector2& viewportSize) { - // LYSHINE_ATOM_TODO - will probably need to support this when converting UI Editor to use Atom - AZ_UNUSED(viewportSize); - AZ::RHI::Ptr dynamicDraw = uiRenderer->GetDynamicDrawContext(); // Disable stencil and enable blend/color write @@ -984,57 +980,35 @@ namespace LyShine dynamicDraw->SetTarget0BlendState(uiRenderer->GetBaseState().m_blendState); // First render the render targets, they are sorted so that more deeply nested ones are rendered first. - -#ifdef LYSHINE_ATOM_TODO // keeping this code for reference for future phase (render targets) // They only need to be rendered the first time that a render graph is rendered after it has been built. - // Though there is a special case, if this is the first time a shader variant has been used it can miss - // the first render. So to be safe we only stop rendering to render targets after we have rendered to - // them twice with no shader compiles initiated. - if (m_renderToRenderTargetCount < 2) + if (m_renderToRenderTargetCount == 0) + { + // Enable the Rtt passes to draw onto the render targets + SetRttPassesEnabled(uiRenderer, true); + } + + // LYSHINE_ATOM_TODO - It is currently necessary to render to the targets twice. Needs investigation + constexpr int timesToRenderToRenderTargets = 2; + if (m_renderToRenderTargetCount < timesToRenderToRenderTargets) { for (RenderNode* renderNode : m_renderTargetRenderNodes) { - renderNode->Render(uiRenderer); - } - - // if the render targets render OK we don't need to render them every frame. But if a new shader - // variant needed to be compiled then they will not have rendered OK. So we check is there are - // any shaders still in the process of compiling. Because they are compiled on the render - // thread, we may not know until the next frame that a shader needed to be compiled. So we need - // the counter. - SShaderCacheStatistics stats; - gEnv->pRenderer->EF_Query(EFQ_GetShaderCacheInfo, stats); - bool waitingOnShadersToCompile = stats.m_nNumShaderAsyncCompiles > 0 ? true : false; - if (!waitingOnShadersToCompile) - { - m_renderToRenderTargetCount++; - } - else - { - m_renderToRenderTargetCount = 0; + renderNode->Render(uiRenderer, uiRenderer->GetModelViewProjectionMatrix(), dynamicDraw); } + m_renderToRenderTargetCount++; } -#else - for (RenderNode* renderNode : m_renderTargetRenderNodes) + else if (m_renderToRenderTargetCount < timesToRenderToRenderTargets + 1) { - renderNode->Render(uiRenderer); + // Disable the rtt render passes since they don't need to be rendered to until the graph becomes invalidated again. + // This is also necessary to prevent the render targets' contents getting cleared on load by the pass. + SetRttPassesEnabled(uiRenderer, false); + m_renderToRenderTargetCount++; } -#endif -#ifdef LYSHINE_ATOM_TODO // keeping this code for reference for future phase (UI Editor) - // Set2DMode defines the viewport so we set it to canvas viewport here (the render target render nodes - // above will have set the viewport as they needed). - TransformationMatrices backupMatrices; - gEnv->pRenderer->Set2DMode(static_cast(viewportSize.GetX()), static_cast(viewportSize.GetY()), backupMatrices); -#endif for (RenderNode* renderNode : m_renderNodes) { - renderNode->Render(uiRenderer); + renderNode->Render(uiRenderer, uiRenderer->GetModelViewProjectionMatrix(), dynamicDraw); } -#ifdef LYSHINE_ATOM_TODO // keeping this code for reference for future phase (UI Editor) - // end the 2D mode - gEnv->pRenderer->Unset2DMode(backupMatrices); -#endif } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1072,6 +1046,31 @@ namespace LyShine return m_renderNodes.empty(); } + //////////////////////////////////////////////////////////////////////////////////////////////////// + void RenderGraph::GetRenderTargetsAndDependencies(LyShine::AttachmentImagesAndDependencies& attachmentImagesAndDependencies) + { + for (RenderNode* renderNode : m_renderTargetRenderNodes) + { + const RenderTargetRenderNode* renderTargetRenderNode = static_cast(renderNode); + + if (renderTargetRenderNode->GetNestLevel() == 0) + { + LyShine::AttachmentImages attachmentImages; + const AZStd::vector& childNodeList = renderTargetRenderNode->GetChildRenderNodeList(); + for (auto& childNode : childNodeList) + { + if (childNode->GetType() == RenderNodeType::RenderTarget) + { + const RenderTargetRenderNode* childRenderTargetRenderNode = static_cast(childNode); + attachmentImages.emplace_back(childRenderTargetRenderNode->GetRenderTarget()); + } + } + + attachmentImagesAndDependencies.emplace_back(AttachmentImageAndDependentsPair(renderTargetRenderNode->GetRenderTarget(), attachmentImages)); + } + } + } + #ifndef _RELEASE //////////////////////////////////////////////////////////////////////////////////////////////////// void RenderGraph::ValidateGraph() @@ -1540,4 +1539,19 @@ namespace LyShine return flags; } + void RenderGraph::SetRttPassesEnabled(UiRenderer* uiRenderer, bool enabled) + { + // Enable or disable the rtt render passes + AZ::RPI::SceneId sceneId = uiRenderer->GetViewportContext()->GetRenderScene()->GetId(); + for (RenderTargetRenderNode* renderTargetRenderNode : m_renderTargetRenderNodes) + { + // Find the rtt pass to disable + AZ::RPI::RasterPass* rttPass = nullptr; + LyShinePassRequestBus::EventResult(rttPass, sceneId, &LyShinePassRequestBus::Events::GetRttPass, renderTargetRenderNode->GetRenderTargetName()); + if (rttPass) + { + rttPass->SetEnabled(enabled); + } + } + } } diff --git a/Gems/LyShine/Code/Source/RenderGraph.h b/Gems/LyShine/Code/Source/RenderGraph.h index 2529c0f47e..bc5bd094c8 100644 --- a/Gems/LyShine/Code/Source/RenderGraph.h +++ b/Gems/LyShine/Code/Source/RenderGraph.h @@ -15,10 +15,13 @@ #include #include +#include #include +#include #include #include "UiRenderer.h" +#include "LyShinePass.h" #ifndef _RELEASE #include "LyShineDebug.h" #endif @@ -46,7 +49,9 @@ namespace LyShine RenderNode(RenderNodeType type) : m_type(type) {} virtual ~RenderNode() {}; - virtual void Render(UiRenderer* uiRenderer) = 0; + virtual void Render(UiRenderer* uiRenderer + , const AZ::Matrix4x4& modelViewProjMat + , AZ::RHI::Ptr dynamicDraw) = 0; RenderNodeType GetType() const { return m_type; } @@ -70,7 +75,9 @@ namespace LyShine PrimitiveListRenderNode(const AZ::Data::Instance& texture, const AZ::Data::Instance& maskTexture, bool isClampTextureMode, bool isTextureSRGB, bool preMultiplyAlpha, AlphaMaskType alphaMaskType, int blendModeState); ~PrimitiveListRenderNode() override; - void Render(UiRenderer* uiRenderer) override; + void Render(UiRenderer* uiRenderer + , const AZ::Matrix4x4& modelViewProjMat + , AZ::RHI::Ptr dynamicDraw) override; void AddPrimitive(IRenderer::DynUiPrimitive* primitive); IRenderer::DynUiPrimitiveList& GetPrimitives() const; @@ -128,7 +135,9 @@ namespace LyShine MaskRenderNode(MaskRenderNode* parentMask, bool isMaskingEnabled, bool useAlphaTest, bool drawBehind, bool drawInFront); ~MaskRenderNode() override; - void Render(UiRenderer* uiRenderer) override; + void Render(UiRenderer* uiRenderer + , const AZ::Matrix4x4& modelViewProjMat + , AZ::RHI::Ptr dynamicDraw) override; AZStd::vector& GetMaskRenderNodeList() { return m_maskRenderNodes; } const AZStd::vector& GetMaskRenderNodeList() const { return m_maskRenderNodes; } @@ -152,8 +161,12 @@ namespace LyShine #endif private: // functions - void SetupBeforeRenderingMask(UiRenderer* uiRenderer, bool firstPass, UiRenderer::BaseState priorBaseState); - void SetupAfterRenderingMask(UiRenderer* uiRenderer, bool firstPass, UiRenderer::BaseState priorBaseState); + void SetupBeforeRenderingMask(UiRenderer* uiRenderer, + AZ::RHI::Ptr dynamicDraw, + bool firstPass, UiRenderer::BaseState priorBaseState); + void SetupAfterRenderingMask(UiRenderer* uiRenderer, + AZ::RHI::Ptr dynamicDraw, + bool firstPass, UiRenderer::BaseState priorBaseState); private: // data AZStd::vector m_maskRenderNodes; //!< The render nodes used to render the mask shape @@ -175,15 +188,17 @@ namespace LyShine // We use a pool allocator to keep these allocations fast. AZ_CLASS_ALLOCATOR(RenderTargetRenderNode, AZ::PoolAllocator, 0); - RenderTargetRenderNode(RenderTargetRenderNode* parentRenderTarget, int renderTargetHandle, - SDepthTexture* renderTargetDepthSurface, + RenderTargetRenderNode(RenderTargetRenderNode* parentRenderTarget, + AZ::Data::Instance attachmentImage, const AZ::Vector2& viewportTopLeft, const AZ::Vector2& viewportSize, const AZ::Color& clearColor, int nestLevel); ~RenderTargetRenderNode() override; - void Render(UiRenderer* uiRenderer) override; + void Render(UiRenderer* uiRenderer + , const AZ::Matrix4x4& modelViewProjMat + , AZ::RHI::Ptr dynamicDraw) override; AZStd::vector& GetChildRenderNodeList() { return m_childRenderNodes; } const AZStd::vector& GetChildRenderNodeList() const { return m_childRenderNodes; } @@ -197,6 +212,9 @@ namespace LyShine AZ::Color GetClearColor() const { return m_clearColor; } const char* GetRenderTargetName() const; + int GetNestLevel() const; + + const AZ::Data::Instance GetRenderTarget() const; #ifndef _RELEASE // A debug-only function useful for debugging @@ -213,13 +231,16 @@ namespace LyShine RenderTargetRenderNode* m_parentRenderTarget = nullptr; //! Used while building the render graph. - int m_renderTargetHandle = -1; - SDepthTexture* m_renderTargetDepthSurface = nullptr; + AZ::Data::Instance m_attachmentImage; + + // Each render target requires a unique dynamic draw context to draw to the raster pass associated with the target + AZ::RHI::Ptr m_dynamicDraw; float m_viewportX = 0; float m_viewportY = 0; float m_viewportWidth = 0; float m_viewportHeight = 0; + AZ::Matrix4x4 m_modelViewProjMat; AZ::Color m_clearColor; int m_nestLevel = 0; }; @@ -241,9 +262,10 @@ namespace LyShine void StartChildrenForMask() override; void EndMask() override; + //! Begin rendering to a texture void BeginRenderToTexture(int renderTargetHandle, SDepthTexture* renderTargetDepthSurface, - const AZ::Vector2& viewportTopLeft, const AZ::Vector2& viewportSize, - const AZ::Color& clearColor) override; + const AZ::Vector2& viewportTopLeft, const AZ::Vector2& viewportSize, const AZ::Color& clearColor) override; + void EndRenderToTexture() override; void AddPrimitive(IRenderer::DynUiPrimitive* primitive, ITexture* texture, @@ -268,6 +290,20 @@ namespace LyShine void AddPrimitiveAtom(IRenderer::DynUiPrimitive* primitive, const AZ::Data::Instance& texture, bool isClampTextureMode, bool isTextureSRGB, bool isTexturePremultipliedAlpha, BlendMode blendMode); + //! Add an indexed triangle list primitive to the render graph which will use maskTexture as an alpha (gradient) mask + void AddAlphaMaskPrimitiveAtom(IRenderer::DynUiPrimitive* primitive, + AZ::Data::Instance contentAttachmentImage, + AZ::Data::Instance maskAttachmentImage, + bool isClampTextureMode, + bool isTextureSRGB, + bool isTexturePremultipliedAlpha, + BlendMode blendMode); + + void BeginRenderToTexture(AZ::Data::Instance attachmentImage, + const AZ::Vector2& viewportTopLeft, + const AZ::Vector2& viewportSize, + const AZ::Color& clearColor); + //! Render the display graph void Render(UiRenderer* uiRenderer, const AZ::Vector2& viewportSize); @@ -283,6 +319,8 @@ namespace LyShine //! Test whether the render graph contains any render nodes bool IsEmpty(); + void GetRenderTargetsAndDependencies(LyShine::AttachmentImagesAndDependencies& attachmentImagesAndDependencies); + #ifndef _RELEASE // A debug-only function useful for debugging, not called but calls can be added during debugging void ValidateGraph(); @@ -311,6 +349,8 @@ namespace LyShine //! Given a blend mode and whether the shader will be outputing premultiplied alpha, return state flags int GetBlendModeState(LyShine::BlendMode blendMode, bool isShaderOutputPremultAlpha) const; + void SetRttPassesEnabled(UiRenderer* uiRenderer, bool enabled); + protected: // data AZStd::vector m_renderNodes; diff --git a/Gems/LyShine/Code/Source/RenderToTextureBus.h b/Gems/LyShine/Code/Source/RenderToTextureBus.h new file mode 100644 index 0000000000..310f1f93cf --- /dev/null +++ b/Gems/LyShine/Code/Source/RenderToTextureBus.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +namespace LyShine +{ + //! Ebus to handle render target requests + class RenderToTextureRequests + : public AZ::ComponentBus + { + public: + virtual AZ::RHI::AttachmentId UseRenderTarget(const AZ::Name& renderTargetName, AZ::RHI::Size size) = 0; + virtual void ReleaseRenderTarget(const AZ::RHI::AttachmentId& attachmentId) = 0; + virtual AZ::Data::Instance GetRenderTarget(const AZ::RHI::AttachmentId& attachmentId) = 0; + }; + + using RenderToTextureRequestBus = AZ::EBus; +} diff --git a/Gems/LyShine/Code/Source/UiCanvasComponent.cpp b/Gems/LyShine/Code/Source/UiCanvasComponent.cpp index 72d9f92d1f..824b0d5698 100644 --- a/Gems/LyShine/Code/Source/UiCanvasComponent.cpp +++ b/Gems/LyShine/Code/Source/UiCanvasComponent.cpp @@ -49,6 +49,8 @@ #include #include +#include +#include #include "Animation/UiAnimationSystem.h" @@ -64,6 +66,8 @@ #include #endif +#include "LyShinePassDataBus.h" + //////////////////////////////////////////////////////////////////////////////////////////////////// //! UiCanvasNotificationBus Behavior context handler class class UiCanvasNotificationBusBehaviorHandler @@ -251,14 +255,22 @@ namespace UiRenderer* GetUiRendererForGame() { - CLyShine* lyShine = static_cast(gEnv->pLyShine); - return lyShine ? lyShine->GetUiRenderer() : nullptr; + if (gEnv && gEnv->pLyShine) + { + CLyShine* lyShine = static_cast(gEnv->pLyShine); + return lyShine->GetUiRenderer(); + } + return nullptr; } UiRenderer* GetUiRendererForEditor() { - CLyShine* lyShine = static_cast(gEnv->pLyShine); - return lyShine ? lyShine->GetUiRendererForEditor() : nullptr; + if (gEnv && gEnv->pLyShine) + { + CLyShine* lyShine = static_cast(gEnv->pLyShine); + return lyShine->GetUiRendererForEditor(); + } + return nullptr; } bool IsValidInteractable(const AZ::EntityId& entityId) @@ -1829,6 +1841,46 @@ void UiCanvasComponent::MarkRenderGraphDirty() } } +//////////////////////////////////////////////////////////////////////////////////////////////////// +AZ::RHI::AttachmentId UiCanvasComponent::UseRenderTarget(const AZ::Name& renderTargetName, AZ::RHI::Size size) +{ + // Create a render target that UI elements will render to + AZ::RHI::ImageDescriptor imageDesc; + imageDesc.m_bindFlags = AZ::RHI::ImageBindFlags::Color | AZ::RHI::ImageBindFlags::ShaderReadWrite; + imageDesc.m_size = size; + imageDesc.m_format = AZ::RHI::Format::R8G8B8A8_UNORM; + + AZ::Data::Instance pool = AZ::RPI::ImageSystemInterface::Get()->GetSystemAttachmentPool(); + auto attachmentImage = AZ::RPI::AttachmentImage::Create(*pool.get(), imageDesc, renderTargetName); + if (!attachmentImage) + { + AZ_Warning("UI", false, "Failed to create render target"); + return AZ::RHI::AttachmentId(); + } + + m_attachmentImageMap[attachmentImage->GetAttachmentId()] = attachmentImage; + + // Notify LyShine render pass that it needs to rebuild + QueueRttPassRebuild(); + + return attachmentImage->GetAttachmentId(); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +void UiCanvasComponent::ReleaseRenderTarget(const AZ::RHI::AttachmentId& attachmentId) +{ + m_attachmentImageMap.erase(attachmentId); + + // Notify LyShine render pass that it needs to rebuild + QueueRttPassRebuild(); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +AZ::Data::Instance UiCanvasComponent::GetRenderTarget(const AZ::RHI::AttachmentId& attachmentId) +{ + return m_attachmentImageMap[attachmentId]; +} + //////////////////////////////////////////////////////////////////////////////////////////////////// void UiCanvasComponent::UpdateCanvas(float deltaTime, bool isInGame) { @@ -1864,6 +1916,8 @@ void UiCanvasComponent::RenderCanvas(bool isInGame, AZ::Vector2 viewportSize, Ui return; } + m_renderInEditor = uiRenderer ? true : false; + if (!uiRenderer) { uiRenderer = GetUiRendererForGame(); @@ -1948,6 +2002,12 @@ void UiCanvasComponent::ScheduleElementDestroy(AZ::EntityId entityId) m_elementsScheduledForDestroy.push_back(entityId); } +//////////////////////////////////////////////////////////////////////////////////////////////////// +void UiCanvasComponent::GetRenderTargets(LyShine::AttachmentImagesAndDependencies& attachmentImagesAndDependencies) +{ + m_renderGraph.GetRenderTargetsAndDependencies(attachmentImagesAndDependencies); +} + //////////////////////////////////////////////////////////////////////////////////////////////////// void UiCanvasComponent::DestroyScheduledElements() { @@ -1959,6 +2019,17 @@ void UiCanvasComponent::DestroyScheduledElements() m_elementsScheduledForDestroy.clear(); } +//////////////////////////////////////////////////////////////////////////////////////////////////// +void UiCanvasComponent::QueueRttPassRebuild() +{ + UiRenderer* uiRenderer = m_renderInEditor ? GetUiRendererForEditor() : GetUiRendererForGame(); + if (uiRenderer && uiRenderer->GetViewportContext()) // can be null in automated testing + { + AZ::RPI::SceneId sceneId = uiRenderer->GetViewportContext()->GetRenderScene()->GetId(); + EBUS_EVENT_ID(sceneId, LyShinePassRequestBus, RebuildRttChildren); + } +} + //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef _RELEASE void UiCanvasComponent::GetDebugInfoInteractables(AZ::EntityId& activeInteractable, AZ::EntityId& hoverInteractable) const @@ -2350,6 +2421,7 @@ void UiCanvasComponent::Activate() UiCanvasComponentImplementationBus::Handler::BusConnect(m_entity->GetId()); UiEditorCanvasBus::Handler::BusConnect(m_entity->GetId()); UiAnimationBus::Handler::BusConnect(m_entity->GetId()); + LyShine::RenderToTextureRequestBus::Handler::BusConnect(m_entity->GetId()); // Reconnect to buses that we connect to intermittently // This will only happen if we have been deactivated and reactivated at runtime @@ -2382,6 +2454,7 @@ void UiCanvasComponent::Deactivate() UiCanvasComponentImplementationBus::Handler::BusDisconnect(); UiEditorCanvasBus::Handler::BusDisconnect(); UiAnimationBus::Handler::BusDisconnect(); + LyShine::RenderToTextureRequestBus::Handler::BusDisconnect(); // disconnect from any other buses we could be connected to if (m_hoverInteractable.IsValid() && AZ::EntityBus::Handler::BusIsConnectedId(m_hoverInteractable)) @@ -2400,6 +2473,12 @@ void UiCanvasComponent::Deactivate() DestroyRenderTarget(); } + // Destroy owned render targets + m_attachmentImageMap.clear(); + + //! Notify LyShine pass that it needs to rebuild + QueueRttPassRebuild(); + delete m_layoutManager; m_layoutManager = nullptr; diff --git a/Gems/LyShine/Code/Source/UiCanvasComponent.h b/Gems/LyShine/Code/Source/UiCanvasComponent.h index 852bb482d0..0848e368fa 100644 --- a/Gems/LyShine/Code/Source/UiCanvasComponent.h +++ b/Gems/LyShine/Code/Source/UiCanvasComponent.h @@ -32,6 +32,8 @@ #include "TextureAtlas/TextureAtlasBus.h" #include "TextureAtlas/TextureAtlasNotificationBus.h" +#include "RenderToTextureBus.h" + namespace AZ { class SerializeContext; @@ -51,6 +53,7 @@ class UiCanvasComponent , public IUiAnimationListener , public UiEditorCanvasBus::Handler , public UiCanvasComponentImplementationBus::Handler + , public LyShine::RenderToTextureRequestBus::Handler { public: // constants static const AZ::Vector2 s_defaultCanvasSize; @@ -232,6 +235,12 @@ public: // member functions void MarkRenderGraphDirty() override; // ~UiCanvasComponentImplementationInterface + // RenderToTextureRequests + AZ::RHI::AttachmentId UseRenderTarget(const AZ::Name& renderTargetName, AZ::RHI::Size size) override; + void ReleaseRenderTarget(const AZ::RHI::AttachmentId& attachmentId) override; + AZ::Data::Instance GetRenderTarget(const AZ::RHI::AttachmentId& attachmentId) override; + // ~RenderToTextureRequests + void UpdateCanvas(float deltaTime, bool isInGame); void RenderCanvas(bool isInGame, AZ::Vector2 viewportSize, UiRenderer* uiRenderer = nullptr); @@ -257,6 +266,10 @@ public: // member functions //! Queue an element to be destroyed at end of frame void ScheduleElementDestroy(AZ::EntityId entityId); + bool IsRenderGraphDirty() { return m_renderGraph.GetDirtyFlag(); } + + void GetRenderTargets(LyShine::AttachmentImagesAndDependencies& attachmentImagesAndDependencies); + #ifndef _RELEASE struct DebugInfoNumElements { @@ -427,6 +440,9 @@ private: // member functions void DestroyScheduledElements(); + //! Notify LyShine pass that it needs to rebuild its Rtt child passes + void QueueRttPassRebuild(); + private: // static member functions static AZ::u64 CreateUniqueId(); @@ -597,4 +613,8 @@ private: // static data LyShine::RenderGraph m_renderGraph; //!< the render graph for rendering the canvas, can be cached between frames bool m_isRendering = false; + bool m_renderInEditor = false; //!< indicates whether this canvas will render in the Editor viewport or the Game viewport + + //! Map of attachments used by this canvas's elements + AZStd::unordered_map> m_attachmentImageMap; }; diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.cpp b/Gems/LyShine/Code/Source/UiCanvasManager.cpp index cb27f09672..0672d7b5f6 100644 --- a/Gems/LyShine/Code/Source/UiCanvasManager.cpp +++ b/Gems/LyShine/Code/Source/UiCanvasManager.cpp @@ -301,6 +301,17 @@ void UiCanvasManager::OnFontTextureUpdated([[maybe_unused]] IFFont* font) m_fontTextureHasChanged = true; } +//////////////////////////////////////////////////////////////////////////////////////////////////// +void UiCanvasManager::GetRenderTargets(LyShine::AttachmentImagesAndDependencies& attachmentImagesAndDependencies) +{ + for (auto canvas : m_loadedCanvases) + { + LyShine::AttachmentImagesAndDependencies canvasTargets; + canvas->GetRenderTargets(canvasTargets); + attachmentImagesAndDependencies.insert(attachmentImagesAndDependencies.end(), canvasTargets.begin(), canvasTargets.end()); + } +} + //////////////////////////////////////////////////////////////////////////////////////////////////// void UiCanvasManager::OnCatalogAssetChanged(const AZ::Data::AssetId& assetId) { @@ -606,13 +617,6 @@ void UiCanvasManager::RenderLoadedCanvases() m_fontTextureHasChanged = false; } -#ifdef LYSHINE_ATOM_TODO // render target conversion to Atom - // clear the stencil buffer before rendering the loaded canvases - required for masking - // NOTE: We want to use ClearTargetsImmediately instead of ClearTargetsLater since we will not be setting the render target - ColorF viewportBackgroundColor(0, 0, 0, 0); // if clearing color we want to set alpha to zero also - gEnv->pRenderer->ClearTargetsImmediately(FRT_CLEAR_STENCIL, viewportBackgroundColor); -#endif - for (auto canvas : m_loadedCanvases) { if (!canvas->GetIsRenderToTexture()) diff --git a/Gems/LyShine/Code/Source/UiCanvasManager.h b/Gems/LyShine/Code/Source/UiCanvasManager.h index 85783fab84..a2bf2dde97 100644 --- a/Gems/LyShine/Code/Source/UiCanvasManager.h +++ b/Gems/LyShine/Code/Source/UiCanvasManager.h @@ -11,6 +11,7 @@ #include #include #include +#include "LyShinePassDataBus.h" #include class UiCanvasComponent; @@ -92,6 +93,9 @@ public: // member functions bool HandleInputEventForLoadedCanvases(const AzFramework::InputChannel& inputChannel); bool HandleTextEventForLoadedCanvases(const AZStd::string& textUTF8); + // Get the render targets used by all currently loaded UI Canvases + void GetRenderTargets(LyShine::AttachmentImagesAndDependencies& attachmentImagesAndDependencies); + #ifndef _RELEASE void DebugDisplayCanvasData(int setting) const; void DebugDisplayDrawCallData() const; diff --git a/Gems/LyShine/Code/Source/UiFaderComponent.cpp b/Gems/LyShine/Code/Source/UiFaderComponent.cpp index dbc3981056..f195689a43 100644 --- a/Gems/LyShine/Code/Source/UiFaderComponent.cpp +++ b/Gems/LyShine/Code/Source/UiFaderComponent.cpp @@ -6,6 +6,7 @@ * */ #include "UiFaderComponent.h" +#include "RenderGraph.h" #include #include @@ -14,6 +15,9 @@ #include #include +#include +#include + #include #include #include @@ -22,6 +26,7 @@ #include #include "UiSerialize.h" +#include "RenderToTextureBus.h" // BehaviorContext UiFaderNotificationBus forwarder class BehaviorUiFaderNotificationBusHandler @@ -120,7 +125,7 @@ void UiFaderComponent::Render(LyShine::IRenderGraph* renderGraph, UiElementInter AZ::Vector2 renderTargetSize = pixelAlignedBottomRight - pixelAlignedTopLeft; bool needsResize = static_cast(renderTargetSize.GetX()) != m_renderTargetWidth || static_cast(renderTargetSize.GetY()) != m_renderTargetHeight; - if (m_renderTargetHandle == -1 || needsResize) + if (m_attachmentImageId.IsEmpty() || needsResize) { // We delay first creation of the render target until render time since size is not known in Activate // We also call this if the size has changed @@ -128,7 +133,7 @@ void UiFaderComponent::Render(LyShine::IRenderGraph* renderGraph, UiElementInter } // if the render target failed to be created (zero size for example) we don't render the element at all - if (m_renderTargetHandle == -1) + if (m_attachmentImageId.IsEmpty()) { return; } @@ -139,7 +144,7 @@ void UiFaderComponent::Render(LyShine::IRenderGraph* renderGraph, UiElementInter else { // destroy previous render target, if exists - if (m_renderTargetHandle != -1) + if (!m_attachmentImageId.IsEmpty()) { DestroyRenderTarget(); } @@ -452,54 +457,22 @@ void UiFaderComponent::CreateOrResizeRenderTarget(const AZ::Vector2& pixelAligne m_viewportTopLeft = pixelAlignedTopLeft; m_viewportSize = renderTargetSize; -#ifdef LYSHINE_ATOM_TODO // [LYN-3359] Support RTT using Atom - // Check if the render target already exists - if (m_renderTargetHandle != -1) - { - // Render target exists, resize it to the given size - if (!gEnv->pRenderer->ResizeRenderTarget(m_renderTargetHandle, static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY()))) - { - AZ_Warning("UI", false, "Failed to resize render target for UiFaderComponent"); - DestroyRenderTarget(); - } - } - else - { - // Create a render target that this element and its children will be rendered to. - m_renderTargetHandle = gEnv->pRenderer->CreateRenderTarget(m_renderTargetName.c_str(), - static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY()), Clr_Transparent, eTF_R8G8B8A8); + // LYSHINE_ATOM_TODO: optimize by reusing/resizing targets + DestroyRenderTarget(); - if (m_renderTargetHandle == -1) - { - AZ_Warning("UI", false, "Failed to create render target for UiFaderComponent"); - } - } - - // if depth surface already exists then destroy it - if (m_renderTargetDepthSurface) + // Create a render target that this element and its children will be rendered to + AZ::EntityId canvasEntityId; + EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); + AZ::RHI::Size imageSize(renderTargetSize.GetX(), renderTargetSize.GetY(), 1); + EBUS_EVENT_ID_RESULT(m_attachmentImageId, canvasEntityId, LyShine::RenderToTextureRequestBus, UseRenderTarget, AZ::Name(m_renderTargetName.c_str()), imageSize); + if (m_attachmentImageId.IsEmpty()) { - gEnv->pRenderer->DestroyDepthSurface(m_renderTargetDepthSurface); - m_renderTargetDepthSurface = nullptr; + AZ_Warning("UI", false, "Failed to create render target for UiFaderComponent"); } - if (m_renderTargetHandle != -1) - { - // Also create a depth surface to render the canvas to, we need depth for masking - // since that uses the stencil buffer. We support any combination of nesting faders and masks - m_renderTargetDepthSurface = gEnv->pRenderer->CreateDepthSurface( - static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY())); - - if (!m_renderTargetDepthSurface) - { - AZ_Warning("UI", false, "Failed to create depth surface for UiFaderComponent"); - DestroyRenderTarget(); - } - } -#endif - // at this point either all render targets and depth surfaces are created or none are. // If all succeeded then update the render target size - if (m_renderTargetHandle != -1) + if (!m_attachmentImageId.IsEmpty()) { m_renderTargetWidth = static_cast(renderTargetSize.GetX()); m_renderTargetHeight = static_cast(renderTargetSize.GetY()); @@ -511,16 +484,12 @@ void UiFaderComponent::CreateOrResizeRenderTarget(const AZ::Vector2& pixelAligne //////////////////////////////////////////////////////////////////////////////////////////////////// void UiFaderComponent::DestroyRenderTarget() { - if (m_renderTargetHandle != -1) + if (!m_attachmentImageId.IsEmpty()) { - gEnv->pRenderer->DestroyRenderTarget(m_renderTargetHandle); - m_renderTargetHandle = -1; - } - - if (m_renderTargetDepthSurface) - { - gEnv->pRenderer->DestroyDepthSurface(m_renderTargetDepthSurface); - m_renderTargetDepthSurface = nullptr; + AZ::EntityId canvasEntityId; + EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); + EBUS_EVENT_ID(canvasEntityId, LyShine::RenderToTextureRequestBus, ReleaseRenderTarget, m_attachmentImageId); + m_attachmentImageId = AZ::RHI::AttachmentId{}; } } @@ -594,14 +563,20 @@ void UiFaderComponent::RenderStandardFader(LyShine::IRenderGraph* renderGraph, U void UiFaderComponent::RenderRttFader(LyShine::IRenderGraph* renderGraph, UiElementInterface* elementInterface, UiRenderInterface* renderInterface, int numChildren, bool isInGame) { + // Get the render target + AZ::Data::Instance attachmentImage; + AZ::EntityId canvasEntityId; + EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); + EBUS_EVENT_ID_RESULT(attachmentImage, canvasEntityId, LyShine::RenderToTextureRequestBus, GetRenderTarget, m_attachmentImageId); + // Render the element and its children to a render target { // we always clear to transparent black - the accumulation of alpha in the render target requires it AZ::Color clearColor(0.0f, 0.0f, 0.0f, 0.0f); // Start building the render to texture node in the render graph - renderGraph->BeginRenderToTexture(m_renderTargetHandle, m_renderTargetDepthSurface, - m_viewportTopLeft, m_viewportSize, clearColor); + LyShine::RenderGraph* lyRenderGraph = dynamic_cast(renderGraph); + lyRenderGraph->BeginRenderToTexture(attachmentImage, m_viewportTopLeft, m_viewportSize, clearColor); // We don't want this fader or parent faders to affect what is rendered to the render target since we will // apply those fades when we render from the render target. @@ -624,14 +599,13 @@ void UiFaderComponent::RenderRttFader(LyShine::IRenderGraph* renderGraph, UiElem float desiredAlpha = renderGraph->GetAlphaFade() * m_fade; uint8 desiredPackedAlpha = static_cast(desiredAlpha * 255.0f); - UCol desiredPackedColor; - // This is a special case. We have an input texture that already has premultiplied alpha. - // So we tell the shader not to premultiply the output colors and we premultiply the alpha - // into the vertex colors so that they are premultiplied too. - desiredPackedColor.r = desiredPackedColor.g = desiredPackedColor.b = desiredPackedColor.a = desiredPackedAlpha; - if (m_cachedPrimitive.m_vertices[0].color.dcolor != desiredPackedColor.dcolor) + // If the fade value has changed we need to update the alpha values in the vertex colors but we do + // not want to touch or recompute the RGB values + if (m_cachedPrimitive.m_vertices[0].color.a != desiredPackedAlpha) { - // go through the cached vertices and update the color values + // go through all the cached vertices and update the alpha values + UCol desiredPackedColor = m_cachedPrimitive.m_vertices[0].color; + desiredPackedColor.a = desiredPackedAlpha; for (int i = 0; i < m_cachedPrimitive.m_numVertices; ++i) { m_cachedPrimitive.m_vertices[i].color = desiredPackedColor; @@ -639,21 +613,20 @@ void UiFaderComponent::RenderRttFader(LyShine::IRenderGraph* renderGraph, UiElem } } -#ifdef LYSHINE_ATOM_TODO // [LYN-3359] Support RTT using Atom // Add a primitive to render a quad using the render target we have created { - // Set the texture and other render state required - ITexture* texture = gEnv->pRenderer->EF_GetTextureByID(m_renderTargetHandle); - bool isClampTextureMode = true; - bool isTextureSRGB = true; - bool isTexturePremultipliedAlpha = true; - LyShine::BlendMode blendMode = LyShine::BlendMode::Normal; - - // add a render node to render from the render target texture to the current target - renderGraph->AddPrimitive(&m_cachedPrimitive, texture, - isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, blendMode); + LyShine::RenderGraph* lyRenderGraph = dynamic_cast(renderGraph); + if (lyRenderGraph) + { + // Set the texture and other render state required + AZ::Data::Instance image = attachmentImage; + bool isClampTextureMode = true; + bool isTextureSRGB = true; + bool isTexturePremultipliedAlpha = true; + LyShine::BlendMode blendMode = LyShine::BlendMode::Normal; + lyRenderGraph->AddPrimitiveAtom(&m_cachedPrimitive, image, isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, blendMode); + } } -#endif } } diff --git a/Gems/LyShine/Code/Source/UiFaderComponent.h b/Gems/LyShine/Code/Source/UiFaderComponent.h index a6960a5e36..560c1beaaa 100644 --- a/Gems/LyShine/Code/Source/UiFaderComponent.h +++ b/Gems/LyShine/Code/Source/UiFaderComponent.h @@ -18,6 +18,7 @@ #include #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// class UiFaderComponent @@ -156,11 +157,8 @@ private: // data //! This is generated from the entity ID and cached AZStd::string m_renderTargetName; - //! When rendering to a texture this is the texture ID of the render target - int m_renderTargetHandle = -1; - - //! When rendering to a texture this is our depth surface - SDepthTexture* m_renderTargetDepthSurface = nullptr; + //! When rendering to a texture this is the attachment image for the render target + AZ::RHI::AttachmentId m_attachmentImageId; //! The positions used for the render to texture viewport and to render the render target to the screen AZ::Vector2 m_viewportTopLeft; diff --git a/Gems/LyShine/Code/Source/UiMaskComponent.cpp b/Gems/LyShine/Code/Source/UiMaskComponent.cpp index 4ecb558b2b..2c1763e4ec 100644 --- a/Gems/LyShine/Code/Source/UiMaskComponent.cpp +++ b/Gems/LyShine/Code/Source/UiMaskComponent.cpp @@ -14,12 +14,17 @@ #include #include "IRenderer.h" +#include "RenderToTextureBus.h" +#include "RenderGraph.h" #include #include #include #include #include +#include +#include + //////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -79,7 +84,7 @@ void UiMaskComponent::Render(LyShine::IRenderGraph* renderGraph, UiElementInterf AZ::Vector2 renderTargetSize = pixelAlignedBottomRight - pixelAlignedTopLeft; bool needsResize = static_cast(renderTargetSize.GetX()) != m_renderTargetWidth || static_cast(renderTargetSize.GetY()) != m_renderTargetHeight; - if (m_contentRenderTargetHandle == -1 || needsResize) + if (m_contentAttachmentImageId.IsEmpty() || needsResize) { // Need to create or resize the render target CreateOrResizeRenderTarget(pixelAlignedTopLeft, pixelAlignedBottomRight); @@ -89,7 +94,7 @@ void UiMaskComponent::Render(LyShine::IRenderGraph* renderGraph, UiElementInterf // in theory the child mask element could still be non-zero size and could reveal things. But the way gradient masks // currently work is that the size of the render target is defined by the size of this element, therefore nothing would // be revealed by the mask if it is zero sized. - if (m_contentRenderTargetHandle == -1) + if (m_contentAttachmentImageId.IsEmpty()) { return; } @@ -101,7 +106,7 @@ void UiMaskComponent::Render(LyShine::IRenderGraph* renderGraph, UiElementInterf else { // using stencil mask, not going to use render targets, destroy previous render target, if exists - if (m_contentRenderTargetHandle != -1) + if (!m_contentAttachmentImageId.IsEmpty()) { DestroyRenderTarget(); } @@ -113,7 +118,7 @@ void UiMaskComponent::Render(LyShine::IRenderGraph* renderGraph, UiElementInterf else { // masking disabled, not going to use render targets, destroy previous render target, if exists - if (m_contentRenderTargetHandle != -1) + if (!m_contentAttachmentImageId.IsEmpty()) { DestroyRenderTarget(); } @@ -553,77 +558,30 @@ void UiMaskComponent::CreateOrResizeRenderTarget(const AZ::Vector2& pixelAligned m_viewportTopLeft = pixelAlignedTopLeft; m_viewportSize = renderTargetSize; -#ifdef LYSHINE_ATOM_TODO // [LYN-3359] Support RTT using Atom - // Check if the render target already exists - if (m_contentRenderTargetHandle != -1) - { - // Render target exists, resize it to the given size - if (!gEnv->pRenderer->ResizeRenderTarget(m_contentRenderTargetHandle, static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY()))) - { - AZ_Warning("UI", false, "Failed to resize content render target for UiMaskComponent"); - DestroyRenderTarget(); - } - } - else - { - // Create a render target that this element and its children will be rendered to. - m_contentRenderTargetHandle = gEnv->pRenderer->CreateRenderTarget(m_renderTargetName.c_str(), - static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY()), Clr_Transparent, eTF_R8G8B8A8); + // LYSHINE_ATOM_TODO: optimize by reusing/resizing targets + DestroyRenderTarget(); - if (m_contentRenderTargetHandle == -1) - { - AZ_Warning("UI", false, "Failed to create content render target for UiMaskComponent"); - } + // Create a render target that this element and its children will be rendered to + AZ::EntityId canvasEntityId; + EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); + AZ::RHI::Size imageSize(renderTargetSize.GetX(), renderTargetSize.GetY(), 1); + EBUS_EVENT_ID_RESULT(m_contentAttachmentImageId, canvasEntityId, LyShine::RenderToTextureRequestBus, UseRenderTarget, AZ::Name(m_renderTargetName.c_str()), imageSize); + if (m_contentAttachmentImageId.IsEmpty()) + { + AZ_Warning("UI", false, "Failed to create content render target for UiMaskComponent"); } - // if depth surface already exists then destroy it - if (m_renderTargetDepthSurface) + // Create separate render target for the mask texture + EBUS_EVENT_ID_RESULT(m_maskAttachmentImageId, canvasEntityId, LyShine::RenderToTextureRequestBus, UseRenderTarget, AZ::Name(m_maskRenderTargetName.c_str()), imageSize); + if (m_maskAttachmentImageId.IsEmpty()) { - gEnv->pRenderer->DestroyDepthSurface(m_renderTargetDepthSurface); - m_renderTargetDepthSurface = nullptr; + AZ_Warning("UI", false, "Failed to create mask render target for UiMaskComponent"); + DestroyRenderTarget(); } - if (m_contentRenderTargetHandle != -1) - { - // Also create a depth surface to render the canvas to, we need depth for masking - // since that uses the stencil buffer. We support any combination of nesting faders and masks - m_renderTargetDepthSurface = gEnv->pRenderer->CreateDepthSurface( - static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY())); - - if (!m_renderTargetDepthSurface) - { - AZ_Warning("UI", false, "Failed to create depth surface for UiMaskComponent"); - DestroyRenderTarget(); - } - } - - // Check if the mask render target already exists - if (m_maskRenderTargetHandle != -1) - { - // Render target exists, resize it to the given size - if (!gEnv->pRenderer->ResizeRenderTarget(m_maskRenderTargetHandle, static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY()))) - { - AZ_Warning("UI", false, "Failed to resize mask render target for UiMaskComponent"); - DestroyRenderTarget(); - } - } - else - { - // create separate render target for the mask texture - m_maskRenderTargetHandle = gEnv->pRenderer->CreateRenderTarget(m_maskRenderTargetName.c_str(), - static_cast(renderTargetSize.GetX()), static_cast(renderTargetSize.GetY()), Clr_Transparent, eTF_R8G8B8A8); - - if (m_maskRenderTargetHandle == -1) - { - AZ_Warning("UI", false, "Failed to create mask render target for UiMaskComponent"); - DestroyRenderTarget(); - } - } -#endif - // at this point either all render targets and depth surfaces are created or none are. // If all succeeded then update the render target size - if (m_contentRenderTargetHandle != -1) + if (!m_contentAttachmentImageId.IsEmpty()) { m_renderTargetWidth = static_cast(renderTargetSize.GetX()); m_renderTargetHeight = static_cast(renderTargetSize.GetY()); @@ -635,22 +593,22 @@ void UiMaskComponent::CreateOrResizeRenderTarget(const AZ::Vector2& pixelAligned //////////////////////////////////////////////////////////////////////////////////////////////////// void UiMaskComponent::DestroyRenderTarget() { - if (m_contentRenderTargetHandle != -1) + if (!m_contentAttachmentImageId.IsEmpty()) { - gEnv->pRenderer->DestroyRenderTarget(m_contentRenderTargetHandle); - m_contentRenderTargetHandle = -1; + AZ::EntityId canvasEntityId; + EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); + EBUS_EVENT_ID(canvasEntityId, LyShine::RenderToTextureRequestBus, ReleaseRenderTarget, m_contentAttachmentImageId); + + m_contentAttachmentImageId = AZ::RHI::AttachmentId{}; } - if (m_renderTargetDepthSurface) + if (!m_maskAttachmentImageId.IsEmpty()) { - gEnv->pRenderer->DestroyDepthSurface(m_renderTargetDepthSurface); - m_renderTargetDepthSurface = nullptr; - } + AZ::EntityId canvasEntityId; + EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); + EBUS_EVENT_ID(canvasEntityId, LyShine::RenderToTextureRequestBus, ReleaseRenderTarget, m_maskAttachmentImageId); - if (m_maskRenderTargetHandle != -1) - { - gEnv->pRenderer->DestroyRenderTarget(m_maskRenderTargetHandle); - m_maskRenderTargetHandle = -1; + m_maskAttachmentImageId = AZ::RHI::AttachmentId{}; } } @@ -747,6 +705,14 @@ void UiMaskComponent::RenderUsingGradientMask(LyShine::IRenderGraph* renderGraph // we always clear to transparent black - the accumulation of alpha in the render target requires it AZ::Color clearColor(0.0f, 0.0f, 0.0f, 0.0f); + // Get the render targets + AZ::Data::Instance contentAttachmentImage; + AZ::Data::Instance maskAttachmentImage; + AZ::EntityId canvasEntityId; + EBUS_EVENT_ID_RESULT(canvasEntityId, GetEntityId(), UiElementBus, GetCanvasEntityId); + EBUS_EVENT_ID_RESULT(contentAttachmentImage, canvasEntityId, LyShine::RenderToTextureRequestBus, GetRenderTarget, m_contentAttachmentImageId); + EBUS_EVENT_ID_RESULT(maskAttachmentImage, canvasEntityId, LyShine::RenderToTextureRequestBus, GetRenderTarget, m_maskAttachmentImageId); + // We don't want parent faders to affect what is rendered to the render target since we will // apply those fades when we render from the render target. // Note that this means that, if there are parent (no render to texture) faders, we get a "free" @@ -756,8 +722,8 @@ void UiMaskComponent::RenderUsingGradientMask(LyShine::IRenderGraph* renderGraph // mask render target { // Start building the render to texture node in the render graph - renderGraph->BeginRenderToTexture(m_maskRenderTargetHandle, m_renderTargetDepthSurface, - m_viewportTopLeft, m_viewportSize, clearColor); + LyShine::RenderGraph* lyRenderGraph = dynamic_cast(renderGraph); + lyRenderGraph->BeginRenderToTexture(maskAttachmentImage, m_viewportTopLeft, m_viewportSize, clearColor); // Render the visual component for this element (if there is one) plus the child mask element (if there is one) RenderMaskPrimitives(renderGraph, renderInterface, childMaskElementInterface, isInGame); @@ -769,8 +735,8 @@ void UiMaskComponent::RenderUsingGradientMask(LyShine::IRenderGraph* renderGraph // content render target { // Start building the render to texture node for the content render target in the render graph - renderGraph->BeginRenderToTexture(m_contentRenderTargetHandle, m_renderTargetDepthSurface, - m_viewportTopLeft, m_viewportSize, clearColor); + LyShine::RenderGraph* lyRenderGraph = dynamic_cast(renderGraph); + lyRenderGraph->BeginRenderToTexture(contentAttachmentImage, m_viewportTopLeft, m_viewportSize, clearColor); // Render the "content" - the child elements excluding the child mask element (if any) RenderContentPrimitives(renderGraph, elementInterface, childMaskElementInterface, numChildren, isInGame); @@ -790,14 +756,13 @@ void UiMaskComponent::RenderUsingGradientMask(LyShine::IRenderGraph* renderGraph float desiredAlpha = renderGraph->GetAlphaFade(); uint32 desiredPackedAlpha = static_cast(desiredAlpha * 255.0f); - UCol desiredPackedColor; - // This is a special case. We have an input texture that already has premultiplied alpha. - // So we tell the shader not to premultiply the output colors and we premultiply the alpha - // into the vertex colors so that they are premultiplied too. - desiredPackedColor.r = desiredPackedColor.g = desiredPackedColor.b = desiredPackedColor.a = desiredPackedAlpha; - if (m_cachedPrimitive.m_vertices[0].color.dcolor != desiredPackedColor.dcolor) + // If the fade value has changed we need to update the alpha values in the vertex colors but we do + // not want to touch or recompute the RGB values + if (m_cachedPrimitive.m_vertices[0].color.a != desiredPackedAlpha) { - // go through the cached vertices and update the color values + // go through all the cached vertices and update the alpha values + UCol desiredPackedColor = m_cachedPrimitive.m_vertices[0].color; + desiredPackedColor.a = desiredPackedAlpha; for (int i = 0; i < m_cachedPrimitive.m_numVertices; ++i) { m_cachedPrimitive.m_vertices[i].color = desiredPackedColor; @@ -805,22 +770,29 @@ void UiMaskComponent::RenderUsingGradientMask(LyShine::IRenderGraph* renderGraph } } -#ifdef LYSHINE_ATOM_TODO // [LYN-3359] Support RTT using Atom // Add a primitive to do the alpha mask { - // Set the texture and other render state required - ITexture* texture = gEnv->pRenderer->EF_GetTextureByID(m_contentRenderTargetHandle); - ITexture* maskTexture = gEnv->pRenderer->EF_GetTextureByID(m_maskRenderTargetHandle); - bool isClampTextureMode = true; - bool isTextureSRGB = true; - bool isTexturePremultipliedAlpha = true; - LyShine::BlendMode blendMode = LyShine::BlendMode::Normal; + LyShine::RenderGraph* lyRenderGraph = dynamic_cast(renderGraph); + if (lyRenderGraph) + { + // Set the texture and other render state required + AZ::Data::Instance contentImage = contentAttachmentImage; + AZ::Data::Instance maskImage = maskAttachmentImage; + bool isClampTextureMode = true; + bool isTextureSRGB = true; + bool isTexturePremultipliedAlpha = false; + LyShine::BlendMode blendMode = LyShine::BlendMode::Normal; - // add a render node to render using the two render targets, one as an alpha mask of the other - renderGraph->AddAlphaMaskPrimitive(&m_cachedPrimitive, texture, maskTexture, - isClampTextureMode, isTextureSRGB, isTexturePremultipliedAlpha, blendMode); + // add a render node to render using the two render targets, one as an alpha mask of the other + lyRenderGraph->AddAlphaMaskPrimitiveAtom(&m_cachedPrimitive, + contentAttachmentImage, + maskAttachmentImage, + isClampTextureMode, + isTextureSRGB, + isTexturePremultipliedAlpha, + blendMode); + } } -#endif } } diff --git a/Gems/LyShine/Code/Source/UiMaskComponent.h b/Gems/LyShine/Code/Source/UiMaskComponent.h index ce0068ca97..8635f048f5 100644 --- a/Gems/LyShine/Code/Source/UiMaskComponent.h +++ b/Gems/LyShine/Code/Source/UiMaskComponent.h @@ -15,6 +15,7 @@ #include #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// class UiMaskComponent @@ -184,15 +185,16 @@ private: // data //! This is generated from the entity ID and cached AZStd::string m_maskRenderTargetName; - //! When rendering to a texture this is the texture ID of the render target - int m_contentRenderTargetHandle = -1; + //! When rendering to a texture this is the attachment image for the render target + AZ::RHI::AttachmentId m_contentAttachmentImageId; //! When rendering to a texture this is our depth surface, we use the same one for rendering the mask elements //! and the content elements - it is cleared in between. SDepthTexture* m_renderTargetDepthSurface = nullptr; //! When rendering to a texture this is the texture ID of the render target - int m_maskRenderTargetHandle = -1; + //! When rendering to a texture this is the attachment image for the render target + AZ::RHI::AttachmentId m_maskAttachmentImageId; //! The positions used for the render to texture viewport and to render the render target to the screen AZ::Vector2 m_viewportTopLeft = AZ::Vector2::CreateZero(); diff --git a/Gems/LyShine/Code/Source/UiRenderer.cpp b/Gems/LyShine/Code/Source/UiRenderer.cpp index 56374d1152..357431c80a 100644 --- a/Gems/LyShine/Code/Source/UiRenderer.cpp +++ b/Gems/LyShine/Code/Source/UiRenderer.cpp @@ -6,6 +6,7 @@ * */ #include "UiRenderer.h" +#include "LyShinePassDataBus.h" #include #include @@ -60,25 +61,32 @@ void UiRenderer::OnBootstrapSceneReady([[maybe_unused]] AZ::RPI::Scene* bootstra AZ::Data::Instance uiShader = AZ::RPI::LoadShader(uiShaderFilepath); // Create scene to be used by the dynamic draw context - AZ::RPI::ScenePtr scene; if (m_viewportContext) { // Create a new scene based on the user specified viewport context - scene = CreateScene(m_viewportContext); + m_scene = CreateScene(m_viewportContext); } else { // No viewport context specified, use default scene - scene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene(); + m_scene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene(); } // Create a dynamic draw context for UI Canvas drawing for the scene - CreateDynamicDrawContext(scene, uiShader); + m_dynamicDraw = CreateDynamicDrawContext(m_scene, uiShader); - // Cache shader data such as input indices for later use - CacheShaderData(m_dynamicDraw); + if (m_dynamicDraw) + { + // Cache shader data such as input indices for later use + CacheShaderData(m_dynamicDraw); - m_isRPIReady = true; + m_isRPIReady = true; + } + else + { + AZ_Error(LogName, false, "Failed to create a dynamic draw context for LyShine. \ + This can happen if the LyShine pass hasn't been added to the main render pipeline."); + } } AZ::RPI::ScenePtr UiRenderer::CreateScene(AZStd::shared_ptr viewportContext) @@ -107,22 +115,40 @@ AZ::RPI::ScenePtr UiRenderer::CreateScene(AZStd::shared_ptr uiShader) +AZ::RHI::Ptr UiRenderer::CreateDynamicDrawContext( + AZ::RPI::ScenePtr scene, + AZ::Data::Instance uiShader) { - m_dynamicDraw = AZ::RPI::DynamicDrawInterface::Get()->CreateDynamicDrawContext(); + // Find the pass that renders the UI canvases after the rtt passes + AZ::RPI::RasterPass* uiCanvasPass = nullptr; + AZ::RPI::SceneId sceneId = m_scene->GetId(); + LyShinePassRequestBus::EventResult(uiCanvasPass, sceneId, &LyShinePassRequestBus::Events::GetUiCanvasPass); + + AZ::RHI::Ptr dynamicDraw = AZ::RPI::DynamicDrawInterface::Get()->CreateDynamicDrawContext(); // Initialize the dynamic draw context - m_dynamicDraw->InitShader(uiShader); - m_dynamicDraw->InitVertexFormat( + dynamicDraw->InitShader(uiShader); + dynamicDraw->InitVertexFormat( { { "POSITION", AZ::RHI::Format::R32G32_FLOAT }, { "COLOR", AZ::RHI::Format::B8G8R8A8_UNORM }, { "TEXCOORD", AZ::RHI::Format::R32G32_FLOAT }, { "BLENDINDICES", AZ::RHI::Format::R16G16_UINT } } ); - m_dynamicDraw->AddDrawStateOptions(AZ::RPI::DynamicDrawContext::DrawStateOptions::StencilState + dynamicDraw->AddDrawStateOptions(AZ::RPI::DynamicDrawContext::DrawStateOptions::StencilState | AZ::RPI::DynamicDrawContext::DrawStateOptions::BlendMode); - m_dynamicDraw->SetOutputScope(scene.get()); - m_dynamicDraw->EndInit(); + + if (uiCanvasPass) + { + dynamicDraw->SetOutputScope(uiCanvasPass); + } + else + { + // Render target support is disabled + dynamicDraw->SetOutputScope(m_scene.get()); + } + dynamicDraw->EndInit(); + + return dynamicDraw; } AZStd::shared_ptr UiRenderer::GetViewportContext() @@ -158,19 +184,26 @@ void UiRenderer::CacheShaderData(const AZ::RHI::Ptr isClampIndexName); // Cache shader variants that will be used - // LYSHINE_ATOM_TODO - more variants will be used in future phase (masks/render target support) - AZ::RPI::ShaderOptionList shaderOptionsDefault; - shaderOptionsDefault.push_back(AZ::RPI::ShaderOption(AZ::Name("o_preMultiplyAlpha"), AZ::Name("false"))); - shaderOptionsDefault.push_back(AZ::RPI::ShaderOption(AZ::Name("o_alphaTest"), AZ::Name("false"))); - shaderOptionsDefault.push_back(AZ::RPI::ShaderOption(AZ::Name("o_srgbWrite"), AZ::Name("true"))); - shaderOptionsDefault.push_back(AZ::RPI::ShaderOption(AZ::Name("o_modulate"), AZ::Name("Modulate::None"))); - m_uiShaderData.m_shaderVariantDefault = dynamicDraw->UseShaderVariant(shaderOptionsDefault); - AZ::RPI::ShaderOptionList shaderOptionsAlphaTest; - shaderOptionsAlphaTest.push_back(AZ::RPI::ShaderOption(AZ::Name("o_preMultiplyAlpha"), AZ::Name("false"))); - shaderOptionsAlphaTest.push_back(AZ::RPI::ShaderOption(AZ::Name("o_alphaTest"), AZ::Name("true"))); - shaderOptionsAlphaTest.push_back(AZ::RPI::ShaderOption(AZ::Name("o_srgbWrite"), AZ::Name("true"))); - shaderOptionsAlphaTest.push_back(AZ::RPI::ShaderOption(AZ::Name("o_modulate"), AZ::Name("Modulate::None"))); - m_uiShaderData.m_shaderVariantAlphaTest = dynamicDraw->UseShaderVariant(shaderOptionsAlphaTest); + AZ::RPI::ShaderOptionList shaderOptionsTextureLinear; + shaderOptionsTextureLinear.push_back(AZ::RPI::ShaderOption(AZ::Name("o_alphaTest"), AZ::Name("false"))); + shaderOptionsTextureLinear.push_back(AZ::RPI::ShaderOption(AZ::Name("o_srgbWrite"), AZ::Name("true"))); + shaderOptionsTextureLinear.push_back(AZ::RPI::ShaderOption(AZ::Name("o_modulate"), AZ::Name("Modulate::None"))); + m_uiShaderData.m_shaderVariantTextureLinear = dynamicDraw->UseShaderVariant(shaderOptionsTextureLinear); + AZ::RPI::ShaderOptionList shaderOptionsTextureSrgb; + shaderOptionsTextureSrgb.push_back(AZ::RPI::ShaderOption(AZ::Name("o_alphaTest"), AZ::Name("false"))); + shaderOptionsTextureSrgb.push_back(AZ::RPI::ShaderOption(AZ::Name("o_srgbWrite"), AZ::Name("false"))); + shaderOptionsTextureSrgb.push_back(AZ::RPI::ShaderOption(AZ::Name("o_modulate"), AZ::Name("Modulate::None"))); + m_uiShaderData.m_shaderVariantTextureSrgb = dynamicDraw->UseShaderVariant(shaderOptionsTextureSrgb); + AZ::RPI::ShaderOptionList shaderVariantAlphaTestMask; + shaderVariantAlphaTestMask.push_back(AZ::RPI::ShaderOption(AZ::Name("o_alphaTest"), AZ::Name("true"))); + shaderVariantAlphaTestMask.push_back(AZ::RPI::ShaderOption(AZ::Name("o_srgbWrite"), AZ::Name("false"))); + shaderVariantAlphaTestMask.push_back(AZ::RPI::ShaderOption(AZ::Name("o_modulate"), AZ::Name("Modulate::None"))); + m_uiShaderData.m_shaderVariantAlphaTestMask = dynamicDraw->UseShaderVariant(shaderVariantAlphaTestMask); + AZ::RPI::ShaderOptionList shaderVariantGradientMask; + shaderVariantGradientMask.push_back(AZ::RPI::ShaderOption(AZ::Name("o_alphaTest"), AZ::Name("false"))); + shaderVariantGradientMask.push_back(AZ::RPI::ShaderOption(AZ::Name("o_srgbWrite"), AZ::Name("false"))); + shaderVariantGradientMask.push_back(AZ::RPI::ShaderOption(AZ::Name("o_modulate"), AZ::Name("Modulate::Alpha"))); + m_uiShaderData.m_shaderVariantGradientMask = dynamicDraw->UseShaderVariant(shaderVariantGradientMask); } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -215,6 +248,38 @@ AZ::RHI::Ptr UiRenderer::GetDynamicDrawContext() return m_dynamicDraw; } +//////////////////////////////////////////////////////////////////////////////////////////////////// +AZ::RHI::Ptr UiRenderer::CreateDynamicDrawContextForRTT(const AZStd::string& rttName) +{ + // find the rtt pass with the specified name + AZ::RPI::RasterPass* rttPass = nullptr; + AZ::RPI::SceneId sceneId = m_scene->GetId(); + LyShinePassRequestBus::EventResult(rttPass, sceneId, &LyShinePassRequestBus::Events::GetRttPass, rttName); + if (!rttPass) + { + return nullptr; + } + + AZ::RHI::Ptr dynamicDraw = AZ::RPI::DynamicDrawInterface::Get()->CreateDynamicDrawContext(); + + // Initialize the dynamic draw context + dynamicDraw->InitShader(m_dynamicDraw->GetShader()); + dynamicDraw->InitVertexFormat( + { { "POSITION", AZ::RHI::Format::R32G32_FLOAT }, + { "COLOR", AZ::RHI::Format::B8G8R8A8_UNORM }, + { "TEXCOORD", AZ::RHI::Format::R32G32_FLOAT }, + { "BLENDINDICES", AZ::RHI::Format::R16G16_UINT } } + ); + dynamicDraw->AddDrawStateOptions(AZ::RPI::DynamicDrawContext::DrawStateOptions::StencilState + | AZ::RPI::DynamicDrawContext::DrawStateOptions::BlendMode); + + dynamicDraw->SetOutputScope(rttPass); + + dynamicDraw->EndInit(); + + return dynamicDraw; +} + //////////////////////////////////////////////////////////////////////////////////////////////////// const UiRenderer::UiShaderData& UiRenderer::GetUiShaderData() { @@ -270,11 +335,27 @@ void UiRenderer::SetBaseState(BaseState state) //////////////////////////////////////////////////////////////////////////////////////////////////// AZ::RPI::ShaderVariantId UiRenderer::GetCurrentShaderVariant() { - AZ::RPI::ShaderVariantId variantId = m_uiShaderData.m_shaderVariantDefault; + AZ::RPI::ShaderVariantId variantId = m_uiShaderData.m_shaderVariantTextureLinear; if (m_baseState.m_useAlphaTest) { - variantId = m_uiShaderData.m_shaderVariantAlphaTest; + variantId = m_uiShaderData.m_shaderVariantAlphaTestMask; + } + else if (m_baseState.m_modulateAlpha) + { + variantId = m_uiShaderData.m_shaderVariantGradientMask; + } + else if (!m_baseState.m_useAlphaTest && m_baseState.m_srgbWrite) + { + variantId = m_uiShaderData.m_shaderVariantTextureLinear; + } + else if (!m_baseState.m_useAlphaTest && !m_baseState.m_srgbWrite) + { + variantId = m_uiShaderData.m_shaderVariantTextureSrgb; + } + else + { + AZ_Error(LogName, 0, "Unsupported shader variant."); } return variantId; diff --git a/Gems/LyShine/Code/Source/UiRenderer.h b/Gems/LyShine/Code/Source/UiRenderer.h index d05261c2d6..14fc67fc6b 100644 --- a/Gems/LyShine/Code/Source/UiRenderer.h +++ b/Gems/LyShine/Code/Source/UiRenderer.h @@ -36,8 +36,10 @@ public: // types AZ::RHI::ShaderInputConstantIndex m_viewProjInputIndex; AZ::RHI::ShaderInputConstantIndex m_isClampInputIndex; - AZ::RPI::ShaderVariantId m_shaderVariantDefault; - AZ::RPI::ShaderVariantId m_shaderVariantAlphaTest; + AZ::RPI::ShaderVariantId m_shaderVariantTextureLinear; + AZ::RPI::ShaderVariantId m_shaderVariantTextureSrgb; + AZ::RPI::ShaderVariantId m_shaderVariantAlphaTestMask; + AZ::RPI::ShaderVariantId m_shaderVariantGradientMask; }; // Base state @@ -56,17 +58,23 @@ public: // types m_blendState.m_blendSource = AZ::RHI::BlendFactor::AlphaSource; m_blendState.m_blendDest = AZ::RHI::BlendFactor::AlphaSourceInverse; m_blendState.m_blendOp = AZ::RHI::BlendOp::Add; + m_blendState.m_blendAlphaSource = AZ::RHI::BlendFactor::One; + m_blendState.m_blendAlphaDest = AZ::RHI::BlendFactor::Zero; + m_blendState.m_blendAlphaOp = AZ::RHI::BlendOp::Add; // Disable stencil m_stencilState = AZ::RHI::StencilState(); m_stencilState.m_enable = 0; m_useAlphaTest = false; + m_modulateAlpha = false; } AZ::RHI::TargetBlendState m_blendState; AZ::RHI::StencilState m_stencilState; bool m_useAlphaTest = false; + bool m_modulateAlpha = false; + bool m_srgbWrite = true; }; public: // member functions @@ -93,6 +101,8 @@ public: // member functions //! Return the dynamic draw context associated with this UI renderer AZ::RHI::Ptr GetDynamicDrawContext(); + AZ::RHI::Ptr CreateDynamicDrawContextForRTT(const AZStd::string& rttName); + //! Return the shader data for the ui shader const UiShaderData& GetUiShaderData(); @@ -123,6 +133,9 @@ public: // member functions //! Decrement the current stencil reference value void DecrementStencilRef(); + //! Return the viewport context set by the user, or the default if not set + AZStd::shared_ptr GetViewportContext(); + #ifndef _RELEASE //! Setup to record debug texture data before rendering void DebugSetRecordingOptionForTextureData(int recordingOption); @@ -143,10 +156,9 @@ private: // member functions AZ::RPI::ScenePtr CreateScene(AZStd::shared_ptr viewportContext); //! Create a dynamic draw context for this renderer - void CreateDynamicDrawContext(AZ::RPI::ScenePtr scene, AZ::Data::Instance); - - //! Return the viewport context set by the user, or the default if not set - AZStd::shared_ptr GetViewportContext(); + AZ::RHI::Ptr CreateDynamicDrawContext( + AZ::RPI::ScenePtr scene, + AZ::Data::Instance uiShader); //! Bind the global white texture for all the texture units we use void BindNullTexture(); @@ -168,6 +180,8 @@ protected: // attributes // Set by user when viewport context is not the main/default viewport AZStd::shared_ptr m_viewportContext; + AZ::RPI::ScenePtr m_scene; + #ifndef _RELEASE int m_debugTextureDataRecordLevel = 0; AZStd::unordered_set m_texturesUsedInFrame; // LYSHINE_ATOM_TODO - convert to RPI::Image diff --git a/Gems/LyShine/Code/Tests/UiTooltipComponentTest.cpp b/Gems/LyShine/Code/Tests/UiTooltipComponentTest.cpp index 17eb2c081f..65ca1ec280 100644 --- a/Gems/LyShine/Code/Tests/UiTooltipComponentTest.cpp +++ b/Gems/LyShine/Code/Tests/UiTooltipComponentTest.cpp @@ -163,11 +163,9 @@ namespace UnitTest SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; gEnv->pTimer = &m_timer; + gEnv->pLyShine = nullptr; - UiCanvasComponent* uiCanvasComponent; - UiTooltipDisplayComponent* uiTooltipDisplayComponent; - UiTooltipComponent* uiTooltipComponent; - std::tie(uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent) = CreateUiCanvasWithTooltip(); + auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); uiTooltipDisplayComponent->SetTriggerMode(UiTooltipDisplayInterface::TriggerMode::OnHover); AZ::Entity* uiTooltipEntity = uiTooltipComponent->GetEntity(); @@ -193,11 +191,9 @@ namespace UnitTest SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; gEnv->pTimer = &m_timer; + gEnv->pLyShine = nullptr; - UiCanvasComponent* uiCanvasComponent; - UiTooltipDisplayComponent* uiTooltipDisplayComponent; - UiTooltipComponent* uiTooltipComponent; - std::tie(uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent) = CreateUiCanvasWithTooltip(); + auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); uiTooltipDisplayComponent->SetTriggerMode(UiTooltipDisplayInterface::TriggerMode::OnHover); AZ::Entity* uiTooltipEntity = uiTooltipComponent->GetEntity(); @@ -221,11 +217,9 @@ namespace UnitTest SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; gEnv->pTimer = &m_timer; + gEnv->pLyShine = nullptr; - UiCanvasComponent* uiCanvasComponent; - UiTooltipDisplayComponent* uiTooltipDisplayComponent; - UiTooltipComponent* uiTooltipComponent; - std::tie(uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent) = CreateUiCanvasWithTooltip(); + auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); uiTooltipDisplayComponent->SetTriggerMode(UiTooltipDisplayInterface::TriggerMode::OnPress); AZ::Entity* uiTooltipEntity = uiTooltipComponent->GetEntity(); @@ -249,11 +243,9 @@ namespace UnitTest SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; gEnv->pTimer = &m_timer; + gEnv->pLyShine = nullptr; - UiCanvasComponent* uiCanvasComponent; - UiTooltipDisplayComponent* uiTooltipDisplayComponent; - UiTooltipComponent* uiTooltipComponent; - std::tie(uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent) = CreateUiCanvasWithTooltip(); + auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); uiTooltipDisplayComponent->SetTriggerMode(UiTooltipDisplayInterface::TriggerMode::OnPress); AZ::Entity* uiTooltipEntity = uiTooltipComponent->GetEntity(); @@ -277,11 +269,9 @@ namespace UnitTest SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; gEnv->pTimer = &m_timer; + gEnv->pLyShine = nullptr; - UiCanvasComponent* uiCanvasComponent; - UiTooltipDisplayComponent* uiTooltipDisplayComponent; - UiTooltipComponent* uiTooltipComponent; - std::tie(uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent) = CreateUiCanvasWithTooltip(); + auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); uiTooltipDisplayComponent->SetTriggerMode(UiTooltipDisplayInterface::TriggerMode::OnClick); AZ::Entity* uiTooltipEntity = uiTooltipComponent->GetEntity(); diff --git a/Gems/LyShine/Code/lyshine_static_files.cmake b/Gems/LyShine/Code/lyshine_static_files.cmake index 7fdac831b6..0c934eb057 100644 --- a/Gems/LyShine/Code/lyshine_static_files.cmake +++ b/Gems/LyShine/Code/lyshine_static_files.cmake @@ -11,8 +11,11 @@ set(FILES Include/LyShine/Draw2d.h Source/LyShine.cpp Source/LyShine.h + Source/LyShinePassDataBus.h Source/LyShineDebug.cpp Source/LyShineDebug.h + Source/LyShinePass.cpp + Source/LyShinePass.h Source/StringUtfUtils.h Source/UiImageComponent.cpp Source/UiImageComponent.h @@ -28,6 +31,7 @@ set(FILES Source/LyShineLoadScreen.h Source/RenderGraph.cpp Source/RenderGraph.h + Source/RenderToTextureBus.h Source/TextMarkup.cpp Source/TextMarkup.h Source/UiButtonComponent.cpp diff --git a/Gems/LyShine/LyShineScript/LyShinePass.data b/Gems/LyShine/LyShineScript/LyShinePass.data new file mode 100644 index 0000000000..af44db91ed --- /dev/null +++ b/Gems/LyShine/LyShineScript/LyShinePass.data @@ -0,0 +1,20 @@ + { + "Name": "LyShinePass", + "TemplateName": "LyShineParentTemplate", + "Connections": [ + { + "LocalSlot": "ColorInputOutput", + "AttachmentRef": { + "Pass": "DebugOverlayPass", + "Attachment": "InputOutput" + } + }, + { + "LocalSlot": "DepthInputOutput", + "AttachmentRef": { + "Pass": "DepthPrePass", + "Attachment": "Depth" + } + } + ] + } \ No newline at end of file diff --git a/Gems/LyShine/LyShineScript/PatchRenderPipeline.py b/Gems/LyShine/LyShineScript/PatchRenderPipeline.py new file mode 100644 index 0000000000..09a0049e81 --- /dev/null +++ b/Gems/LyShine/LyShineScript/PatchRenderPipeline.py @@ -0,0 +1,71 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +""" + +import os +import sys + +# Parse arguments +if len(sys.argv) != 3: + print('Incorrect number of args') + exit() + +engine_path = sys.argv[1] +if not os.path.exists(engine_path): + print(f'Given path {engine_path} does not exist') + exit() + +project_path = sys.argv[2] +if not os.path.exists(project_path): + print(f'Given path {project_path} does not exist') + exit() + +sys.path.insert(0, os.path.join(engine_path, 'Gems/Atom/RPI/Tools/')) + +from atom_rpi_tools.pass_data import PassTemplate +import atom_rpi_tools.utils as utils + +# Folder of this py file +dir_name = os.path.dirname(os.path.realpath(__file__)) + +# Patch render pipeline to insert a custom LyShine parent pass + +# Gem::Atom_Feature_Common gem's path since default render pipeline is comming from this gem +gem_assets_path = os.path.join(engine_path,'Gems/Atom/feature/Common/Assets/') + +pipeline_relatvie_path = 'Passes/MainPipeline.pass' +srcRenderPipeline = os.path.join(gem_assets_path, pipeline_relatvie_path) +destRenderPipeline = os.path.join(project_path, pipeline_relatvie_path) +# If the project doesn't have a customized main pipeline +# copy the default render pipeline from Atom_Common_Feature gem to same path in project folder +utils.find_or_copy_file(destRenderPipeline, srcRenderPipeline) + +# Load project render pipeline +renderPipeline = PassTemplate(destRenderPipeline) + +# Skip if LyShinePass already exist +newPassName = 'LyShinePass' +if renderPipeline.find_pass(newPassName)>-1: + print('Skip merging. LyShinePass already exists') + exit() + +# Insert LyShinePass between DebugOverlayPass and UIPass +refPass = 'DebugOverlayPass' +# The data file for new pass request is in the same folder of the py file +newPassRequestFilePath = os.path.join(dir_name, 'LyShinePass.data') +newPassRequestData = utils.load_json_file(newPassRequestFilePath) +insertIndex = renderPipeline.find_pass(refPass) + 1 +if insertIndex>-1: + renderPipeline.insert_pass_request(insertIndex, newPassRequestData) +else: + print('Failed to find ', refPass) + exit() + +# Update attachment references for the passes following LyShinePass +renderPipeline.replace_references_after(newPassName, 'DebugOverlayPass', 'InputOutput', 'LyShinePass', 'ColorInputOutput') + +# Save the updated render pipeline +renderPipeline.save() diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h index d1eac73a65..16aa8157aa 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/NetworkTransformComponent.h @@ -36,6 +36,8 @@ namespace Multiplayer void OnScaleChangedEvent(float scale); void OnResetCountChangedEvent(); + void UpdateTargetHostFrameId(); + AZ::Transform m_previousTransform = AZ::Transform::CreateIdentity(); AZ::Transform m_targetTransform = AZ::Transform::CreateIdentity(); @@ -45,6 +47,8 @@ namespace Multiplayer AZ::Event::Handler m_resetCountEventHandler; EntityPreRenderEvent::Handler m_entityPreRenderEventHandler; + + Multiplayer::HostFrameId m_targetHostFrameId = HostFrameId(0); }; class NetworkTransformComponentController diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index e5b1a5adfc..4f714068db 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -122,6 +122,11 @@ namespace Multiplayer //! @return the current server time in milliseconds virtual AZ::TimeMs GetCurrentHostTimeMs() const = 0; + //! Returns the current blend factor for client side interpolation + //! This value is only relevant on the client and is used to smooth between host frames + //! @return the current blend factor + virtual float GetCurrentBlendFactor() const = 0; + //! Returns the network time instance bound to this multiplayer instance. //! @return pointer to the network time instance bound to this multiplayer instance virtual INetworkTime* GetNetworkTime() = 0; @@ -182,23 +187,27 @@ namespace Multiplayer class ScopedAlterTime final { public: - inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId connectionId) + inline ScopedAlterTime(HostFrameId frameId, AZ::TimeMs timeMs, float blendFactor, AzNetworking::ConnectionId connectionId) { INetworkTime* time = GetNetworkTime(); m_previousHostFrameId = time->GetHostFrameId(); m_previousHostTimeMs = time->GetHostTimeMs(); m_previousRewindConnectionId = time->GetRewindingConnectionId(); time->AlterTime(frameId, timeMs, connectionId); + m_previousBlendFactor = time->GetHostBlendFactor(); + time->AlterBlendFactor(blendFactor); } inline ~ScopedAlterTime() { INetworkTime* time = GetNetworkTime(); time->AlterTime(m_previousHostFrameId, m_previousHostTimeMs, m_previousRewindConnectionId); + time->AlterBlendFactor(m_previousBlendFactor); } private: HostFrameId m_previousHostFrameId = InvalidHostFrameId; AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; + float m_previousBlendFactor = DefaultBlendFactor; }; inline const char* GetEnumString(MultiplayerAgentType value) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h index ab7bbaa8c6..704e9d2734 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerTypes.h @@ -22,6 +22,9 @@ namespace Multiplayer //! The default number of rewindable samples for us to store. static constexpr uint32_t RewindHistorySize = 128; + //! The default blend factor for ScopedAlterTime + static constexpr float DefaultBlendFactor = 1.f; + AZ_TYPE_SAFE_INTEGRAL(HostId, uint32_t); static constexpr HostId InvalidHostId = static_cast(-1); diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput/NetworkInput.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput/NetworkInput.h index 3ef4258060..1e02d6bf56 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput/NetworkInput.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput/NetworkInput.h @@ -45,6 +45,9 @@ namespace Multiplayer AZ::TimeMs GetHostTimeMs() const; AZ::TimeMs& ModifyHostTimeMs(); + void SetHostBlendFactor(float hostBlendFactor); + float GetHostBlendFactor() const; + void AttachNetBindComponent(NetBindComponent* netBindComponent); bool Serialize(AzNetworking::ISerializer& serializer); @@ -73,6 +76,7 @@ namespace Multiplayer ClientInputId m_inputId = ClientInputId{ 0 }; HostFrameId m_hostFrameId = InvalidHostFrameId; AZ::TimeMs m_hostTimeMs = AZ::TimeMs{ 0 }; + float m_hostBlendFactor = 0.f; ConstNetworkEntityHandle m_owner; bool m_wasAttached = false; }; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/INetworkTime.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/INetworkTime.h index 35ea317f62..43bcf5404e 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/INetworkTime.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/INetworkTime.h @@ -43,6 +43,10 @@ namespace Multiplayer //! @return the hosts current timeMs virtual AZ::TimeMs GetHostTimeMs() const = 0; + //! Retrieves the hosts current blend factor (may be rewound on the server during backward reconciliation). + //! @return the hosts current blend factor + virtual float GetHostBlendFactor() const = 0; + //! Get the controlling connection that may be currently altering global game time. //! Note this abstraction is required at a relatively high level to allow for 'don't rewind the shooter' semantics //! @return the ConnectionId of the connection requesting the rewind operation @@ -60,6 +64,10 @@ namespace Multiplayer //! @param rewindConnectionId the rewinding ConnectionId virtual void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) = 0; + //! Alters the current Host blend factor. Used to drive interpolation in rewound states. + //! @param blendFactor the blend factor to use + virtual void AlterBlendFactor(float blendFactor) = 0; + //! Syncs all entities contained within a volume to the current rewind state. //! @param rewindVolume the volume to rewind entities within (needed for physics entities) virtual void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) = 0; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h index 056404693f..a8af564c15 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.h @@ -60,6 +60,10 @@ namespace Multiplayer //! @return value in const base type form const BASE_TYPE& Get() const; + //! Const base type retriever for one host frame behind Get(). Only intended for use in SyncRewind contexts. + //! @return value in const base type form + const BASE_TYPE& GetPrevious() const; + //! Base type retriever. //! @return value in base type form BASE_TYPE& Modify(); diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.inl b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.inl index b3a14e698b..69283c496d 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.inl +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkTime/RewindableObject.inl @@ -66,6 +66,12 @@ namespace Multiplayer return GetValueForTime(GetCurrentTimeForProperty()); } + template + inline const BASE_TYPE& RewindableObject::GetPrevious() const + { + return GetValueForTime(GetCurrentTimeForProperty() - HostFrameId(1)); + } + template inline BASE_TYPE& RewindableObject::Modify() { diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index df0d84c427..23578e5c18 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -155,9 +155,12 @@ namespace Multiplayer // Discard move input events, client may be speed hacking if (m_clientBankedTime < sv_MaxBankTimeWindowSec) { + // Client blends from previous frame to target so here we subtract blend factor to get to that state + const float blendFactor = AZStd::min(AZStd::max(0.f, input.GetHostBlendFactor()), 1.f); + const AZ::TimeMs blendMs = AZ::TimeMs(static_cast(static_cast(cl_InputRateMs)) * (1.f - blendFactor)); m_clientBankedTime = AZStd::min(m_clientBankedTime + clientInputRateSec, (double)sv_MaxBankTimeWindowSec); // clamp to boundary { - ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), invokingConnection->GetConnectionId()); + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs() - blendMs, input.GetHostBlendFactor(), invokingConnection->GetConnectionId()); GetNetBindComponent()->ProcessInput(input, static_cast(clientInputRateSec)); } @@ -311,7 +314,7 @@ namespace Multiplayer ++ModifyLastInputId(); input.SetClientInputId(GetLastInputId()); - ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), invokingConnection->GetConnectionId()); + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), input.GetHostBlendFactor(), invokingConnection->GetConnectionId()); GetNetBindComponent()->ProcessInput(input, clientInputRateSec); AZLOG @@ -391,7 +394,7 @@ namespace Multiplayer { // Reprocess the input for this frame NetworkInput& input = m_inputHistory[replayIndex]; - ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), invokingConnection->GetConnectionId()); + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), input.GetHostBlendFactor(), invokingConnection->GetConnectionId()); GetNetBindComponent()->ProcessInput(input, clientInputRateSec); AZLOG @@ -499,6 +502,7 @@ namespace Multiplayer input.SetClientInputId(m_clientInputId); input.SetHostFrameId(networkTime->GetHostFrameId()); input.SetHostTimeMs(multiplayer->GetCurrentHostTimeMs()); + input.SetHostBlendFactor(multiplayer->GetCurrentBlendFactor()); // Allow components to form the input for this frame GetNetBindComponent()->CreateInput(input, inputRate); @@ -573,7 +577,7 @@ namespace Multiplayer NetworkInput& input = m_lastInputReceived[0]; { - ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), AzNetworking::InvalidConnectionId); + ScopedAlterTime scopedTime(input.GetHostFrameId(), input.GetHostTimeMs(), DefaultBlendFactor, AzNetworking::InvalidConnectionId); GetNetBindComponent()->ProcessInput(input, inputRate); } diff --git a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp index 1038ec48ef..df4d7618fa 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetworkTransformComponent.cpp @@ -61,18 +61,21 @@ namespace Multiplayer { m_previousTransform.SetRotation(m_targetTransform.GetRotation()); m_targetTransform.SetRotation(rotation); + UpdateTargetHostFrameId(); } void NetworkTransformComponent::OnTranslationChangedEvent(const AZ::Vector3& translation) { m_previousTransform.SetTranslation(m_targetTransform.GetTranslation()); m_targetTransform.SetTranslation(translation); + UpdateTargetHostFrameId(); } void NetworkTransformComponent::OnScaleChangedEvent(float scale) { m_previousTransform.SetUniformScale(m_targetTransform.GetUniformScale()); m_targetTransform.SetUniformScale(scale); + UpdateTargetHostFrameId(); } void NetworkTransformComponent::OnResetCountChangedEvent() @@ -83,14 +86,31 @@ namespace Multiplayer m_previousTransform = m_targetTransform; } + void NetworkTransformComponent::UpdateTargetHostFrameId() + { + HostFrameId currentHostFrameId = Multiplayer::GetNetworkTime()->GetHostFrameId(); + if (currentHostFrameId > m_targetHostFrameId) + { + m_targetHostFrameId = currentHostFrameId; + } + } + void NetworkTransformComponent::OnPreRender([[maybe_unused]] float deltaTime, float blendFactor) { if (!HasController()) { AZ::Transform blendTransform; - blendTransform.SetRotation(m_previousTransform.GetRotation().Slerp(m_targetTransform.GetRotation(), blendFactor)); - blendTransform.SetTranslation(m_previousTransform.GetTranslation().Lerp(m_targetTransform.GetTranslation(), blendFactor)); - blendTransform.SetUniformScale(AZ::Lerp(m_previousTransform.GetUniformScale(), m_targetTransform.GetUniformScale(), blendFactor)); + if (Multiplayer::GetNetworkTime() && Multiplayer::GetNetworkTime()->GetHostFrameId() > m_targetHostFrameId) + { + m_previousTransform = m_targetTransform; + blendTransform = m_targetTransform; + } + else + { + blendTransform.SetRotation(m_previousTransform.GetRotation().Slerp(m_targetTransform.GetRotation(), blendFactor)); + blendTransform.SetTranslation(m_previousTransform.GetTranslation().Lerp(m_targetTransform.GetTranslation(), blendFactor)); + blendTransform.SetUniformScale(AZ::Lerp(m_previousTransform.GetUniformScale(), m_targetTransform.GetUniformScale(), blendFactor)); + } if (!GetTransformComponent()->GetWorldTM().IsClose(blendTransform)) { diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp index deb53bacab..fc398182ef 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp @@ -32,6 +32,7 @@ namespace Multiplayer { m_networkEditorInterface = AZ::Interface::Get()->CreateNetworkInterface( AZ::Name(MPEditorInterfaceName), ProtocolType::Tcp, TrustZone::ExternalClientToServer, *this); + m_networkEditorInterface->SetTimeoutEnabled(false); if (editorsv_isDedicated) { uint16_t editorServerPort = DefaultServerEditorPort; diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp index 9030b150e6..d557c65215 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorSystemComponent.cpp @@ -147,13 +147,9 @@ namespace Multiplayer processLaunchInfo.m_showWindow = true; processLaunchInfo.m_processPriority = AzFramework::ProcessPriority::PROCESSPRIORITY_NORMAL; - // Launch the Server and give it a few seconds to boot up + // Launch the Server AzFramework::ProcessWatcher* outProcess = AzFramework::ProcessWatcher::LaunchProcess( processLaunchInfo, AzFramework::ProcessCommunicationType::COMMUNICATOR_TYPE_NONE); - if (outProcess) - { - AZStd::this_thread::sleep_for(AZStd::chrono::milliseconds(15000)); - } return outProcess; } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp index 21c7ce80d6..893e53fbf6 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.cpp @@ -809,6 +809,11 @@ namespace Multiplayer } } + float MultiplayerSystemComponent::GetCurrentBlendFactor() const + { + return m_renderBlendFactor; + } + INetworkTime* MultiplayerSystemComponent::GetNetworkTime() { return &m_networkTime; @@ -856,12 +861,12 @@ namespace Multiplayer { m_tickFactor += deltaTime / serverRateSeconds; // Linear close to the origin, but asymptote at y = 1 - const float renderBlendFactor = AZStd::clamp(1.0f - (std::pow(cl_renderTickBlendBase, m_tickFactor)), 0.0f, 1.0f); + m_renderBlendFactor = AZStd::clamp(1.0f - (std::pow(cl_renderTickBlendBase, m_tickFactor)), 0.0f, 1.0f); AZLOG ( NET_Blending, "Computed blend factor of %0.3f using a tick factor of %0.3f, a frametime of %0.3f and a serverTickRate of %0.3f", - renderBlendFactor, + m_renderBlendFactor, m_tickFactor, deltaTime, serverRateSeconds @@ -908,7 +913,7 @@ namespace Multiplayer for (NetBindComponent* netBindComponent : gatheredEntities) { - netBindComponent->NotifyPreRender(deltaTime, renderBlendFactor); + netBindComponent->NotifyPreRender(deltaTime, m_renderBlendFactor); } } else @@ -920,7 +925,7 @@ namespace Multiplayer NetBindComponent* netBindComponent = entity->FindComponent(); if (netBindComponent != nullptr) { - netBindComponent->NotifyPreRender(deltaTime, renderBlendFactor); + netBindComponent->NotifyPreRender(deltaTime, m_renderBlendFactor); } } } diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index ab37958962..e2fb7deacc 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -113,6 +113,7 @@ namespace Multiplayer void Terminate(AzNetworking::DisconnectReason reason) override; void SendReadyForEntityUpdates(bool readyForEntityUpdates) override; AZ::TimeMs GetCurrentHostTimeMs() const override; + float GetCurrentBlendFactor() const override; INetworkTime* GetNetworkTime() override; INetworkEntityManager* GetNetworkEntityManager() override; void SetFilterEntityManager(IFilterEntityManager* entityFilter) override; @@ -155,6 +156,7 @@ namespace Multiplayer HostFrameId m_lastReplicatedHostFrameId = HostFrameId(0); double m_serverSendAccumulator = 0.0; + float m_renderBlendFactor = 0.0f; float m_tickFactor = 0.0f; #if !defined(AZ_RELEASE_BUILD) diff --git a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp index a1d8ab6a68..35ca02bfba 100644 --- a/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkInput/NetworkInput.cpp @@ -76,6 +76,16 @@ namespace Multiplayer return m_hostTimeMs; } + void NetworkInput::SetHostBlendFactor(float hostBlendFactor) + { + m_hostBlendFactor = hostBlendFactor; + } + + float NetworkInput::GetHostBlendFactor() const + { + return m_hostBlendFactor; + } + void NetworkInput::AttachNetBindComponent(NetBindComponent* netBindComponent) { m_wasAttached = true; @@ -91,7 +101,8 @@ namespace Multiplayer { if (!serializer.Serialize(m_inputId, "InputId") || !serializer.Serialize(m_hostTimeMs, "HostTimeMs") - || !serializer.Serialize(m_hostFrameId, "HostFrameId")) + || !serializer.Serialize(m_hostFrameId, "HostFrameId") + || !serializer.Serialize(m_hostBlendFactor, "HostBlendFactor")) { return false; } @@ -164,6 +175,7 @@ namespace Multiplayer m_inputId = rhs.m_inputId; m_hostFrameId = rhs.m_hostFrameId; m_hostTimeMs = rhs.m_hostTimeMs; + m_hostBlendFactor = rhs.m_hostBlendFactor; m_componentInputs.resize(rhs.m_componentInputs.size()); for (int32_t i = 0; i < rhs.m_componentInputs.size(); ++i) { diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp index 645ce1fc00..7c19546fb6 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.cpp @@ -55,6 +55,11 @@ namespace Multiplayer return m_hostTimeMs; } + float NetworkTime::GetHostBlendFactor() const + { + return m_hostBlendFactor; + } + AzNetworking::ConnectionId NetworkTime::GetRewindingConnectionId() const { return m_rewindingConnectionId; @@ -72,6 +77,11 @@ namespace Multiplayer m_rewindingConnectionId = rewindConnectionId; } + void NetworkTime::AlterBlendFactor(float blendFactor) + { + m_hostBlendFactor = blendFactor; + } + void NetworkTime::SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) { // Since the vis system doesn't support rewound queries, first query with an expanded volume to catch any fast moving entities @@ -95,6 +105,7 @@ namespace Multiplayer if (networkTransform != nullptr) { + // We're not presently factoring in interpolated position here const AZ::Vector3 rewindCenter = networkTransform->GetTranslation(); // Get the rewound position const AZ::Vector3 rewindOffset = rewindCenter - currentCenter; // Compute offset between rewound and current positions const AZ::Aabb rewoundAabb = currentBounds.GetTranslated(rewindOffset); // Apply offset to the entity aabb diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 4d568f40d9..6c211c816d 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -30,9 +30,11 @@ namespace Multiplayer HostFrameId GetUnalteredHostFrameId() const override; void IncrementHostFrameId() override; AZ::TimeMs GetHostTimeMs() const override; + float GetHostBlendFactor() const override; AzNetworking::ConnectionId GetRewindingConnectionId() const override; HostFrameId GetHostFrameIdForRewindingConnection(AzNetworking::ConnectionId rewindConnectionId) const override; void AlterTime(HostFrameId frameId, AZ::TimeMs timeMs, AzNetworking::ConnectionId rewindConnectionId) override; + void AlterBlendFactor(float blendFactor) override; void SyncEntitiesToRewindState(const AZ::Aabb& rewindVolume) override; void ClearRewoundEntities() override; //! @} @@ -44,6 +46,7 @@ namespace Multiplayer HostFrameId m_hostFrameId = HostFrameId{ 0 }; HostFrameId m_unalteredFrameId = HostFrameId{ 0 }; AZ::TimeMs m_hostTimeMs = AZ::TimeMs{ 0 }; + float m_hostBlendFactor = DefaultBlendFactor; AzNetworking::ConnectionId m_rewindingConnectionId = AzNetworking::InvalidConnectionId; }; } diff --git a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp index 5ed4f4d591..f6e5d82703 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp @@ -43,7 +43,7 @@ namespace UnitTest // Test rewind for all pushed values and overall size for (uint32_t idx = 0; idx < RewindableContainerSize; ++idx) { - Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(idx + 1, test.size()); EXPECT_EQ(idx, test.back()); } @@ -70,9 +70,9 @@ namespace UnitTest EXPECT_TRUE(test.empty()); // Test rewind for pop_back and clear - Multiplayer::ScopedAlterTime pop_time(static_cast(RewindableContainerSize), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime pop_time(static_cast(RewindableContainerSize), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(RewindableContainerSize - 1, test.size()); - Multiplayer::ScopedAlterTime clear_time(static_cast(RewindableContainerSize + 1), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime clear_time(static_cast(RewindableContainerSize + 1), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(0, test.size()); // Test copy_values and resize_no_construct @@ -100,7 +100,7 @@ namespace UnitTest // Test rewind for all values and overall size for (uint32_t idx = 1; idx <= RewindableContainerSize; ++idx) { - Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); for (uint32_t testIdx = 0; testIdx < RewindableContainerSize; ++testIdx) { if (testIdx < idx) diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index d80082baa9..b8d60a94e8 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -39,7 +39,7 @@ namespace UnitTest for (uint32_t i = 0; i < 16; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(i, test); } @@ -52,7 +52,7 @@ namespace UnitTest for (uint32_t i = 16; i < 48; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(i, test); } } @@ -70,7 +70,7 @@ namespace UnitTest { // Note that we didn't actually set any value for time rewindableBufferFrames, so we're testing fetching a value past the last time set - Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(RewindableBufferFrames - 1, test); } } @@ -93,7 +93,7 @@ namespace UnitTest for (uint32_t i = 0; i < RewindableBufferFrames; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); const Object& value = test; EXPECT_EQ(value.value, i); } @@ -102,19 +102,19 @@ namespace UnitTest TEST_F(RewindableObjectTests, TestBackfillOnLargeTimestep) { Multiplayer::RewindableObject test(0); - Multiplayer::ScopedAlterTime time1(static_cast(0), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time1(static_cast(0), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); test = 1; - Multiplayer::ScopedAlterTime time2(static_cast(31), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time2(static_cast(31), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); test = 2; for (uint32_t i = 0; i < 31; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(1, test); } - Multiplayer::ScopedAlterTime time3(static_cast(31), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time3(static_cast(31), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(2, test); } @@ -130,7 +130,7 @@ namespace UnitTest for (uint32_t i = 0; i < 1000; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(1000 - i), AZ::TimeMs{ 0 }, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(1000 - i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(1000, test); } } diff --git a/Gems/NvCloth/Code/Source/Pipeline/SceneAPIExt/ClothRule.cpp b/Gems/NvCloth/Code/Source/Pipeline/SceneAPIExt/ClothRule.cpp index 383ea9e5f6..a2683be2ab 100644 --- a/Gems/NvCloth/Code/Source/Pipeline/SceneAPIExt/ClothRule.cpp +++ b/Gems/NvCloth/Code/Source/Pipeline/SceneAPIExt/ClothRule.cpp @@ -37,7 +37,15 @@ namespace NvCloth const AZ::SceneAPI::Containers::SceneGraph& graph, const size_t numVertices) const { - const auto meshNodeIndex = graph.Find(GetMeshNodeName()); + const AZ::SceneAPI::Containers::SceneGraph::NodeIndex meshNodeIndex = [this, &graph]() + { + if (const auto index = graph.Find(GetMeshNodeName() + AZStd::string(AZ::SceneAPI::Utilities::OptimizedMeshSuffix)); index.IsValid()) + { + return index; + } + return graph.Find(GetMeshNodeName()); + }(); + if (!meshNodeIndex.IsValid()) { return {}; diff --git a/Gems/PhysX/Code/Source/Scene/PhysXSceneSimulationFilterCallback.cpp b/Gems/PhysX/Code/Source/Scene/PhysXSceneSimulationFilterCallback.cpp index d902fb91ca..e103913cdf 100644 --- a/Gems/PhysX/Code/Source/Scene/PhysXSceneSimulationFilterCallback.cpp +++ b/Gems/PhysX/Code/Source/Scene/PhysXSceneSimulationFilterCallback.cpp @@ -55,7 +55,9 @@ namespace PhysX size_t SceneSimulationFilterCallback::CollisionPairHasher::operator()(const CollisionActorPair& collisionPair) const { size_t hash{ 0 }; - AZStd::hash_combine(hash, collisionPair.m_actorA, collisionPair.m_actorB); + // Order elements so {1,2} and {2,1} would generate the same hash + auto [smallerVal, biggerVal] = AZStd::minmax(collisionPair.m_actorA, collisionPair.m_actorB); + AZStd::hash_combine(hash, smallerVal, biggerVal); return hash; } diff --git a/Gems/ScriptCanvas/.gitignore b/Gems/ScriptCanvas/.gitignore new file mode 100644 index 0000000000..7ae9da2d7f --- /dev/null +++ b/Gems/ScriptCanvas/.gitignore @@ -0,0 +1 @@ +Assets/Logs/ \ No newline at end of file diff --git a/Gems/Vegetation/Code/Source/Editor/EditorSpawnerComponent.h b/Gems/Vegetation/Code/Source/Editor/EditorSpawnerComponent.h index 709b645ea2..6563a8f8b9 100644 --- a/Gems/Vegetation/Code/Source/Editor/EditorSpawnerComponent.h +++ b/Gems/Vegetation/Code/Source/Editor/EditorSpawnerComponent.h @@ -29,6 +29,6 @@ namespace Vegetation static constexpr const char* const s_componentDescription = "Creates dynamic vegetation in a specified area"; static constexpr const char* const s_icon = "Editor/Icons/Components/Vegetation.svg"; static constexpr const char* const s_viewportIcon = "Editor/Icons/Components/Viewport/Vegetation.svg"; - static constexpr const char* const s_helpUrl = "https://o3de.org/docs/user-guide/components/reference/vegetation-layer-spawner/"; + static constexpr const char* const s_helpUrl = "https://o3de.org/docs/user-guide/components/reference/vegetation/layer-spawner/"; }; } diff --git a/Gems/WhiteBox/Code/Source/Rendering/Atom/WhiteBoxAtomRenderMesh.cpp b/Gems/WhiteBox/Code/Source/Rendering/Atom/WhiteBoxAtomRenderMesh.cpp index 3f089a8639..daa0ad59f8 100644 --- a/Gems/WhiteBox/Code/Source/Rendering/Atom/WhiteBoxAtomRenderMesh.cpp +++ b/Gems/WhiteBox/Code/Source/Rendering/Atom/WhiteBoxAtomRenderMesh.cpp @@ -112,17 +112,8 @@ namespace WhiteBox AddLodBuffers(modelLodCreator); modelLodCreator.BeginMesh(); modelLodCreator.SetMeshAabb(meshData.GetAabb()); - - // set the default material - if (auto materialAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath(TexturedMaterialPath.data())) - { - modelLodCreator.SetMeshMaterialAsset(materialAsset); - } - else - { - AZ_Error("CreateLodAsset", false, "Could not load material."); - return false; - } + + modelLodCreator.SetMeshMaterialSlot(OneMaterialSlotId); AddMeshBuffers(modelLodCreator); modelLodCreator.EndMesh(); @@ -154,6 +145,20 @@ namespace WhiteBox modelCreator.Begin(AZ::Data::AssetId(AZ::Uuid::CreateRandom())); modelCreator.SetName(ModelName); modelCreator.AddLodAsset(AZStd::move(m_lodAsset)); + + if (auto materialAsset = AZ::RPI::AssetUtils::LoadAssetByProductPath(TexturedMaterialPath.data())) + { + AZ::RPI::ModelMaterialSlot materialSlot; + materialSlot.m_stableId = OneMaterialSlotId; + materialSlot.m_defaultMaterialAsset = materialAsset; + modelCreator.AddMaterialSlot(materialSlot); + } + else + { + AZ_Error("CreateLodAsset", false, "Could not load material."); + return; + } + modelCreator.End(m_modelAsset); } diff --git a/Gems/WhiteBox/Code/Source/Rendering/Atom/WhiteBoxAtomRenderMesh.h b/Gems/WhiteBox/Code/Source/Rendering/Atom/WhiteBoxAtomRenderMesh.h index 00179f196d..63aca62051 100644 --- a/Gems/WhiteBox/Code/Source/Rendering/Atom/WhiteBoxAtomRenderMesh.h +++ b/Gems/WhiteBox/Code/Source/Rendering/Atom/WhiteBoxAtomRenderMesh.h @@ -91,6 +91,7 @@ namespace WhiteBox // TODO: LYN-784 static constexpr AZStd::string_view TexturedMaterialPath = "materials/defaultpbr.azmaterial"; static constexpr AZStd::string_view SolidMaterialPath = "materials/defaultpbr.azmaterial"; + static constexpr AZ::RPI::ModelMaterialSlot::StableId OneMaterialSlotId = 0; //! White box model name. static constexpr AZStd::string_view ModelName = "WhiteBoxMesh"; diff --git a/Registry/AssetProcessorPlatformConfig.setreg b/Registry/AssetProcessorPlatformConfig.setreg index 26aa5b2663..f1cb49c9cf 100644 --- a/Registry/AssetProcessorPlatformConfig.setreg +++ b/Registry/AssetProcessorPlatformConfig.setreg @@ -142,9 +142,6 @@ "Exclude TempFiles": { "pattern": ".*\\\\/\\\\$tmp[0-9]*_.*" }, - "Exclude AlembicCompressionTemplates": { - "pattern": ".*\\\\/Presets\\\\/GeomCache\\\\/.*" - }, "Exclude TmpAnimationCompression": { "pattern": ".*\\\\/Editor\\\\/Tmp\\\\/AnimationCompression\\\\/.*" }, diff --git a/Templates/DefaultProject/Template/.gitignore b/Templates/DefaultProject/Template/.gitignore index f21f551ce4..28b4b330f5 100644 --- a/Templates/DefaultProject/Template/.gitignore +++ b/Templates/DefaultProject/Template/.gitignore @@ -1,4 +1,5 @@ [Bb]uild/ [Cc]ache/ [Uu]ser/ -[Uu]ser_test*/ \ No newline at end of file +[Uu]ser_test*/ +_savebackup/ \ No newline at end of file diff --git a/Templates/MinimalProject/Template/.gitignore b/Templates/MinimalProject/Template/.gitignore index 9a6d119b1b..a3c776304c 100644 --- a/Templates/MinimalProject/Template/.gitignore +++ b/Templates/MinimalProject/Template/.gitignore @@ -1,3 +1,4 @@ [Bb]uild/ [Cc]ache/ -[Uu]ser/ \ No newline at end of file +[Uu]ser/ +_savebackup/ \ No newline at end of file diff --git a/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py b/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py index 50021080fe..57454930eb 100644 --- a/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py +++ b/Tools/LyTestTools/ly_test_tools/o3de/asset_processor.py @@ -594,7 +594,7 @@ class AssetProcessor(object): output_list = None if capture_output: if decode: - output_list = run_result.stdout.decode('utf-8').splitlines() + output_list = run_result.stdout.decode('utf-8', errors="replace").splitlines() else: output_list = run_result.stdout.splitlines() diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 209ae9b062..7bb2c61774 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -10,7 +10,6 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARGETS zlib PACKAGE_HASH e6f34b8ac16acf881e3d666ef9fd0c1aee94c3f69283fb6524d35d6f858eebbb) ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) -ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index f7884fae46..bdffbd5dc7 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -10,7 +10,6 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARGETS zlib PACKAGE_HASH e6f34b8ac16acf881e3d666ef9fd0c1aee94c3f69283fb6524d35d6f858eebbb) ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) -ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index 2b6e1da9ab..0134a45565 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -10,7 +10,6 @@ ly_associate_package(PACKAGE_NAME zlib-1.2.8-rev2-multiplatform TARGETS zlib PACKAGE_HASH e6f34b8ac16acf881e3d666ef9fd0c1aee94c3f69283fb6524d35d6f858eebbb) ly_associate_package(PACKAGE_NAME ilmbase-2.3.0-rev4-multiplatform TARGETS ilmbase PACKAGE_HASH 97547fdf1fbc4d81b8ccf382261f8c25514ed3b3c4f8fd493f0a4fa873bba348) ly_associate_package(PACKAGE_NAME hdf5-1.0.11-rev2-multiplatform TARGETS hdf5 PACKAGE_HASH 11d5e04df8a93f8c52a5684a4cacbf0d9003056360983ce34f8d7b601082c6bd) -ly_associate_package(PACKAGE_NAME alembic-1.7.11-rev3-multiplatform TARGETS alembic PACKAGE_HASH ba7a7d4943dd752f5a662374f6c48b93493df1d8e2c5f6a8d101f3b50700dd25) ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform TARGETS assimplib PACKAGE_HASH 1a9113788b893ef4a2ee63ac01eb71b981a92894a5a51175703fa225f5804dec) ly_associate_package(PACKAGE_NAME squish-ccr-20150601-rev3-multiplatform TARGETS squish-ccr PACKAGE_HASH c878c6c0c705e78403c397d03f5aa7bc87e5978298710e14d09c9daf951a83b3) ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) diff --git a/Code/Framework/AzAutoGen/AzAutoGen.py b/cmake/AzAutoGen.py similarity index 100% rename from Code/Framework/AzAutoGen/AzAutoGen.py rename to cmake/AzAutoGen.py diff --git a/cmake/LyAutoGen.cmake b/cmake/LyAutoGen.cmake index 64cb73a453..4aec0f9726 100644 --- a/cmake/LyAutoGen.cmake +++ b/cmake/LyAutoGen.cmake @@ -25,17 +25,17 @@ function(ly_add_autogen) list(FILTER AZCG_INPUTFILES INCLUDE REGEX ".*\.(xml|json|jinja)$") target_include_directories(${ly_add_autogen_NAME} PUBLIC "${CMAKE_CURRENT_BINARY_DIR}/Azcg/Generated") execute_process( - COMMAND ${LY_PYTHON_CMD} "${LY_ROOT_FOLDER}/Code/Framework/AzAutoGen/AzAutoGen.py" "${CMAKE_BINARY_DIR}/Azcg/TemplateCache/" "${CMAKE_CURRENT_BINARY_DIR}/Azcg/Generated/" "${CMAKE_CURRENT_SOURCE_DIR}" "${AZCG_INPUTFILES}" "${ly_add_autogen_AUTOGEN_RULES}" "-n" + COMMAND ${LY_PYTHON_CMD} "${LY_ROOT_FOLDER}/cmake/AzAutoGen.py" "${CMAKE_BINARY_DIR}/Azcg/TemplateCache/" "${CMAKE_CURRENT_BINARY_DIR}/Azcg/Generated/" "${CMAKE_CURRENT_SOURCE_DIR}" "${AZCG_INPUTFILES}" "${ly_add_autogen_AUTOGEN_RULES}" "-n" OUTPUT_VARIABLE AUTOGEN_OUTPUTS ) string(STRIP "${AUTOGEN_OUTPUTS}" AUTOGEN_OUTPUTS) set(AZCG_DEPENDENCIES ${AZCG_INPUTFILES}) - list(APPEND AZCG_DEPENDENCIES "${LY_ROOT_FOLDER}/Code/Framework/AzAutoGen/AzAutoGen.py") + list(APPEND AZCG_DEPENDENCIES "${LY_ROOT_FOLDER}/cmake/AzAutoGen.py") add_custom_command( OUTPUT ${AUTOGEN_OUTPUTS} DEPENDS ${AZCG_DEPENDENCIES} COMMAND ${CMAKE_COMMAND} -E echo "Running AutoGen for ${ly_add_autogen_NAME}" - COMMAND ${LY_PYTHON_CMD} "${LY_ROOT_FOLDER}/Code/Framework/AzAutoGen/AzAutoGen.py" "${CMAKE_BINARY_DIR}/Azcg/TemplateCache/" "${CMAKE_CURRENT_BINARY_DIR}/Azcg/Generated/" "${CMAKE_CURRENT_SOURCE_DIR}" "${AZCG_INPUTFILES}" "${ly_add_autogen_AUTOGEN_RULES}" + COMMAND ${LY_PYTHON_CMD} "${LY_ROOT_FOLDER}/cmake/AzAutoGen.py" "${CMAKE_BINARY_DIR}/Azcg/TemplateCache/" "${CMAKE_CURRENT_BINARY_DIR}/Azcg/Generated/" "${CMAKE_CURRENT_SOURCE_DIR}" "${AZCG_INPUTFILES}" "${ly_add_autogen_AUTOGEN_RULES}" VERBATIM ) set_target_properties(${ly_add_autogen_NAME} PROPERTIES AUTOGEN_INPUT_FILES "${AZCG_INPUTFILES}") diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 612358f938..353c015fd3 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -45,7 +45,6 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar # we need to set the PUBLIC_HEADER property of the target for all the headers we are exporting. After doing that, installing the # headers end up in one folder instead of duplicating the folder structure of the public/interface include directory. # Instead, we install them with install(DIRECTORY) - set(include_location "include") get_target_property(include_directories ${TARGET_NAME} INTERFACE_INCLUDE_DIRECTORIES) if (include_directories) unset(public_headers) @@ -63,9 +62,10 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar continue() endif() + unset(rel_include_dir) cmake_path(RELATIVE_PATH include_directory BASE_DIRECTORY ${LY_ROOT_FOLDER} OUTPUT_VARIABLE rel_include_dir) - cmake_path(APPEND include_location "${rel_include_dir}" ".." OUTPUT_VARIABLE destination_dir) - cmake_path(NORMAL_PATH destination_dir) + cmake_path(APPEND rel_include_dir "..") + cmake_path(NORMAL_PATH rel_include_dir OUTPUT_VARIABLE destination_dir) install(DIRECTORY ${include_directory} DESTINATION ${destination_dir} @@ -75,6 +75,7 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar PATTERN *.hpp PATTERN *.inl PATTERN *.hxx + PATTERN *.jinja # LyAutoGen files ) endif() endforeach() @@ -156,10 +157,9 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar foreach(include ${include_directories}) string(GENEX_STRIP ${include} include_genex_expr) if(include_genex_expr STREQUAL include) # only for cases where there are no generation expressions - cmake_path(RELATIVE_PATH include BASE_DIRECTORY ${LY_ROOT_FOLDER} OUTPUT_VARIABLE target_include) - cmake_path(NORMAL_PATH target_include) - # Escape the LY_ROOT_FOLDER variable so that it isn't resolved during the install step - string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "\${LY_ROOT_FOLDER}/${include_location}/${target_include}\n") + # Make the include path relative to the source dir where the target will be declared + cmake_path(RELATIVE_PATH include BASE_DIRECTORY ${absolute_target_source_dir} OUTPUT_VARIABLE target_include) + string(APPEND INCLUDE_DIRECTORIES_PLACEHOLDER "${target_include}\n") endif() endforeach() endif() @@ -204,7 +204,7 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar set(TARGET_RUN_HELPER "add_custom_target(${RUN_TARGET_NAME}) set_target_properties(${RUN_TARGET_NAME} PROPERTIES - FOLDER \"CMakePredefinedTargets/SDK\" + FOLDER \"O3DE_SDK\" VS_DEBUGGER_COMMAND \$> VS_DEBUGGER_COMMAND_ARGUMENTS \"--project-path=\${LY_DEFAULT_PROJECT_PATH}\" )" diff --git a/cmake/cmake_files.cmake b/cmake/cmake_files.cmake index 490817d625..aa275b634a 100644 --- a/cmake/cmake_files.cmake +++ b/cmake/cmake_files.cmake @@ -9,6 +9,7 @@ set(FILES 3rdParty.cmake 3rdPartyPackages.cmake + AzAutoGen.py CMakeFiles.cmake CommandExecution.cmake Configurations.cmake