leopoldo-zugasti
3 年前
当前提交
d017dd97
共有 99 个文件被更改,包括 10281 次插入 和 2157 次删除
-
19README.md
-
14TestProjects/PerceptionHDRP/Packages/packages-lock.json
-
1TestProjects/PerceptionURP/Assets/Tests/Editor/PerceptionCameraEditorUrpTests.cs
-
14TestProjects/PerceptionURP/Packages/packages-lock.json
-
43com.unity.perception/CHANGELOG.md
-
1com.unity.perception/Documentation~/Schema/Synthetic_Dataset_Schema.md
-
999com.unity.perception/Documentation~/Schema/image_0.png
-
9com.unity.perception/Documentation~/HPTutorial/TUTORIAL.md
-
999com.unity.perception/Documentation~/Tutorial/Images/di_usim_2.png
-
589com.unity.perception/Documentation~/Tutorial/Images/build_uploaded.png
-
597com.unity.perception/Documentation~/Tutorial/Images/runinusim.png
-
13com.unity.perception/Documentation~/Tutorial/Phase3.md
-
5com.unity.perception/Documentation~/Tutorial/Phase1.md
-
34com.unity.perception/Documentation~/Tutorial/Phase2.md
-
12com.unity.perception/Editor/GroundTruth/IdLabelConfigEditor.cs
-
43com.unity.perception/Editor/GroundTruth/PerceptionCameraEditor.cs
-
13com.unity.perception/Editor/Randomization/Utilities/UIElementsEditorUtilities.cs
-
5com.unity.perception/Editor/Randomization/Utilities/StaticData.cs
-
2com.unity.perception/Editor/Randomization/Uxml/Sampler/SamplerInterfaceElement.uxml
-
7com.unity.perception/Editor/Randomization/Uxml/ScenarioBaseElement.uxml
-
8com.unity.perception/Editor/Randomization/Uxml/RunInUnitySimulationWindow.uxml
-
16com.unity.perception/Editor/Randomization/VisualElements/Parameter/ParameterElement.cs
-
15com.unity.perception/Editor/Randomization/VisualElements/Sampler/SamplerInterfaceElement.cs
-
2com.unity.perception/Editor/Randomization/VisualElements/Basic/UIntField.cs
-
2com.unity.perception/Editor/Randomization/VisualElements/Basic/UxmlUIntAttributeDescription.cs
-
191com.unity.perception/Editor/Randomization/Editors/RunInUnitySimulationWindow.cs
-
14com.unity.perception/Editor/Randomization/Editors/ScenarioBaseEditor.cs
-
6com.unity.perception/Runtime/GroundTruth/Labelers/ObjectCountLabeler.cs
-
51com.unity.perception/Runtime/GroundTruth/Labelers/CameraLabeler.cs
-
2com.unity.perception/Runtime/GroundTruth/Labelers/BoundingBox3DLabeler.cs
-
8com.unity.perception/Runtime/GroundTruth/Labelers/KeypointLabeler.cs
-
20com.unity.perception/Runtime/GroundTruth/SimulationState.cs
-
10com.unity.perception/Runtime/Randomization/Parameters/CategoricalParameter.cs
-
109com.unity.perception/Runtime/Randomization/Randomizers/RandomizerExamples/Utilities/GameObjectOneWayCache.cs
-
117com.unity.perception/Runtime/Randomization/Scenarios/ScenarioBase.cs
-
3com.unity.perception/Runtime/Randomization/Scenarios/Serialization/SerializationStructures.cs
-
5com.unity.perception/Runtime/Randomization/Scenarios/Serialization/ScenarioSerializer.cs
-
18com.unity.perception/Runtime/Randomization/Scenarios/UnitySimulationScenario.cs
-
4com.unity.perception/Tests/Editor/PerceptionCameraEditorTests.cs
-
2com.unity.perception/Tests/Runtime/GroundTruthTests/DatasetJsonUtilityTests.cs
-
2com.unity.perception/Tests/Runtime/GroundTruthTests/VisualizationTests.cs
-
4com.unity.perception/Tests/Runtime/Randomization/ScenarioTests/ScenarioTests.cs
-
15com.unity.perception/Tests/Runtime/Randomization/ScenarioTests/Resources/SampleScenarioConfiguration.json
-
6com.unity.perception/package.json
-
15TestProjects/PerceptionURP/ProjectSettings/BurstAotSettings_StandaloneOSX.json
-
8com.unity.perception/Editor/Pyrception.meta
-
11com.unity.perception/Editor/Randomization/PropertyDrawers/AssetSourceDrawer.cs.meta
-
26com.unity.perception/Editor/Randomization/PropertyDrawers/AssetSourceDrawer.cs
-
22com.unity.perception/Editor/Randomization/Utilities/AssetLoadingUtilities.cs
-
11com.unity.perception/Editor/Randomization/Utilities/AssetLoadingUtilities.cs.meta
-
8com.unity.perception/Editor/Randomization/Uxml/AssetSource.meta
-
8com.unity.perception/Editor/Randomization/VisualElements/AssetSource.meta
-
8com.unity.perception/Runtime/Randomization/Randomizers/AssetSources.meta
-
8com.unity.perception/Tests/Runtime/Randomization/AssetSourceTests.meta
-
1001com.unity.perception/Documentation~/FAQ/images/inner_objects.png
-
1001com.unity.perception/Documentation~/FAQ/images/inner_labels.gif
-
229com.unity.perception/Documentation~/FAQ/images/cluster_randomizer.png
-
199com.unity.perception/Documentation~/FAQ/images/prefab_cluster.png
-
1001com.unity.perception/Documentation~/FAQ/images/hdrp.png
-
1001com.unity.perception/Documentation~/FAQ/images/hdrp_pt_128_samples.png
-
1001com.unity.perception/Documentation~/FAQ/images/hdrp_pt_4096_samples.png
-
1001com.unity.perception/Documentation~/FAQ/images/hdrp_rt_gi.png
-
419com.unity.perception/Documentation~/FAQ/images/volume.png
-
609com.unity.perception/Documentation~/FAQ/FAQ.md
-
8com.unity.perception/Editor/Pyrception/pyrception-utils.meta
-
10com.unity.perception/Editor/Randomization/Uxml/AssetSource/AssetListElement.uxml
-
10com.unity.perception/Editor/Randomization/Uxml/AssetSource/AssetListElement.uxml.meta
-
7com.unity.perception/Editor/Randomization/Uxml/AssetSource/AssetListItemElement.uxml
-
10com.unity.perception/Editor/Randomization/Uxml/AssetSource/AssetListItemElement.uxml.meta
-
10com.unity.perception/Editor/Randomization/Uxml/AssetSource/AssetSourceElement.uxml.meta
-
26com.unity.perception/Editor/Randomization/Uxml/AssetSource/AssetSourceElement.uxml
-
11com.unity.perception/Editor/Randomization/VisualElements/AssetSource/AssetListElement.cs.meta
-
39com.unity.perception/Editor/Randomization/VisualElements/AssetSource/AssetListItemElement.cs
-
11com.unity.perception/Editor/Randomization/VisualElements/AssetSource/AssetListItemElement.cs.meta
-
11com.unity.perception/Editor/Randomization/VisualElements/AssetSource/AssetSourceElement.cs.meta
-
93com.unity.perception/Editor/Randomization/VisualElements/AssetSource/AssetListElement.cs
-
153com.unity.perception/Editor/Randomization/VisualElements/AssetSource/AssetSourceElement.cs
-
3com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/AssetSource.cs.meta
-
35com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/AssetSourceLocation.cs
-
3com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/AssetSourceLocation.cs.meta
-
3com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/LocalAssetSourceLocation.cs.meta
-
22com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/AssetRole.cs
-
11com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/AssetRole.cs.meta
-
152com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/AssetSource.cs
-
34com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/LocalAssetSourceLocation.cs
-
24com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/AssetSourceEditorDescriptionAttribute.cs
-
11com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/AssetSourceEditorDescriptionAttribute.cs.meta
-
11com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/IAssetRoleBase.cs.meta
-
20com.unity.perception/Runtime/Randomization/Randomizers/AssetSources/IAssetRoleBase.cs
-
11com.unity.perception/Tests/Runtime/Randomization/AssetSourceTests/LocalAssetSourceTests.cs.meta
-
63com.unity.perception/Tests/Runtime/Randomization/AssetSourceTests/LocalAssetSourceTests.cs
999
com.unity.perception/Documentation~/Schema/image_0.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
999
com.unity.perception/Documentation~/Tutorial/Images/di_usim_2.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
|
|||
{ |
|||
"MonoBehaviour": { |
|||
"Version": 3, |
|||
"EnableBurstCompilation": true, |
|||
"EnableOptimisations": true, |
|||
"EnableSafetyChecks": false, |
|||
"EnableDebugInAllBuilds": false, |
|||
"UsePlatformSDKLinker": false, |
|||
"CpuMinTargetX32": 0, |
|||
"CpuMaxTargetX32": 0, |
|||
"CpuMinTargetX64": 0, |
|||
"CpuMaxTargetX64": 0, |
|||
"CpuTargetsX64": 72 |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 5000b0088702b4f589e73939e27aa132 |
|||
folderAsset: yes |
|||
DefaultImporter: |
|||
externalObjects: {} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
fileFormatVersion: 2 |
|||
guid: 5be7d531a18f32b4f93a73b173259337 |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using Editor.Randomization.VisualElements.AssetSource; |
|||
using UnityEngine; |
|||
using UnityEngine.Perception.Randomization; |
|||
using UnityEngine.UIElements; |
|||
|
|||
namespace UnityEditor.Perception.Randomization.PropertyDrawers |
|||
{ |
|||
[CustomPropertyDrawer(typeof(AssetSource<>))] |
|||
class AssetSourceDrawer : PropertyDrawer |
|||
{ |
|||
public override VisualElement CreatePropertyGUI(SerializedProperty property) |
|||
{ |
|||
return new AssetSourceElement(property, fieldInfo); |
|||
} |
|||
|
|||
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) |
|||
{ |
|||
EditorGUI.PropertyField(position, property, label, true); |
|||
} |
|||
|
|||
public override float GetPropertyHeight(SerializedProperty property, GUIContent label) |
|||
{ |
|||
return EditorGUI.GetPropertyHeight(property); |
|||
} |
|||
} |
|||
} |
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using UnityEngine; |
|||
using Object = UnityEngine.Object; |
|||
|
|||
namespace UnityEditor.Perception.Randomization |
|||
{ |
|||
static class AssetLoadingUtilities |
|||
{ |
|||
public static List<Object> LoadAssetsFromFolder(string folderPath, Type assetType) |
|||
{ |
|||
if (!folderPath.StartsWith(Application.dataPath)) |
|||
throw new ApplicationException("Selected folder is not an asset folder in this project"); |
|||
var assetsPath = "Assets" + folderPath.Remove(0, Application.dataPath.Length); |
|||
var assetIds = AssetDatabase.FindAssets($"t:{assetType.Name}", new[] { assetsPath }); |
|||
var assets = new List<Object>(); |
|||
foreach (var guid in assetIds) |
|||
assets.Add(AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), assetType)); |
|||
return assets; |
|||
} |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 30b11971d353ad648b466b3f7763859e |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
fileFormatVersion: 2 |
|||
guid: 7e7eabbe9ff71e64291989566ea6ec83 |
|||
folderAsset: yes |
|||
DefaultImporter: |
|||
externalObjects: {} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
fileFormatVersion: 2 |
|||
guid: 29370b0293eb9a046b454ffdd7b1c372 |
|||
folderAsset: yes |
|||
DefaultImporter: |
|||
externalObjects: {} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
fileFormatVersion: 2 |
|||
guid: c3b723ce8e6a50141834747972131766 |
|||
folderAsset: yes |
|||
DefaultImporter: |
|||
externalObjects: {} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
fileFormatVersion: 2 |
|||
guid: ea8713402c0e1a946ac6af555b908641 |
|||
folderAsset: yes |
|||
DefaultImporter: |
|||
externalObjects: {} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
1001
com.unity.perception/Documentation~/FAQ/images/inner_objects.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
1001
com.unity.perception/Documentation~/FAQ/images/inner_labels.gif
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
1001
com.unity.perception/Documentation~/FAQ/images/hdrp.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
1001
com.unity.perception/Documentation~/FAQ/images/hdrp_pt_128_samples.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
1001
com.unity.perception/Documentation~/FAQ/images/hdrp_pt_4096_samples.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
1001
com.unity.perception/Documentation~/FAQ/images/hdrp_rt_gi.png
文件差异内容过多而无法显示
查看文件
文件差异内容过多而无法显示
查看文件
|
|||
# FAQ and Code Samples |
|||
|
|||
This page covers a variety of topics, including common questions and issues that may arise while using the Perception package, as well as code samples and recommendations for a number of popular workflows and use-cases. |
|||
|
|||
## <a name="labeling">Labeling</a> |
|||
|
|||
|
|||
<details> |
|||
<summary><strong>Q: How can I disable or enable labeling on an object at runtime?</strong></summary> |
|||
<br> |
|||
|
|||
You can turn labeling on and off on a GameObject by switching the enabled state of its `Labeling` component. For example: |
|||
|
|||
```C# |
|||
gameObject.GetComponent<Labeling>().enabled = false; |
|||
``` |
|||
|
|||
--- |
|||
|
|||
|
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: How can I remove or add new labels to objects at runtime?</strong></summary><br> |
|||
|
|||
This can be achieved through modifying the `labels` list of the `Labeling` component. The key is to call `RefreshLabeling()` on the component after making any changes to the labels. Example: |
|||
|
|||
```C# |
|||
var labeling = gameObject.GetComponent<Labeling>(); |
|||
labeling.labels.Clear(); |
|||
labeling.labels.Add("new-label"); |
|||
labeling.RefreshLabeling(); |
|||
``` |
|||
Keep in mind that any new label added with this method should already be present in the Label Config attached to the Labeler that is supposed to label this object. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: Is it possible to label only parts of an object or assign different labels to different parts of objects?</strong></summary><br> |
|||
|
|||
Labeling works on the GameObject level, so to achieve the scenarios described here, you will need to break down your main object into multiple GameObjects parented to the same root object, and add `Labeling` components to each of the inner objects, as shown below. |
|||
|
|||
<p align="center"> |
|||
<img src="images/inner_objects.png" width="800"/> |
|||
</p> |
|||
|
|||
Alternatively, in cases where parts of the surface of the object need to be labeled (e.g. decals on objects), you can add labeled invisible surfaces on top of these sections. These invisible surfaces need to have a fully transparent material. To create an invisible material: |
|||
|
|||
* Create a new material (***Assets -> Create -> Material***) and name it `TransparentMaterial` |
|||
* Set the **Surface Type** for the material to **Transparent**, and set the alpha channel of the **Base Map** color to 0. |
|||
* For HDRP: In addition to the above, disable **Preserve specular lighting** |
|||
|
|||
An example labeled output for an object with separate labels on inner objects and decals is shown below: |
|||
|
|||
<p align="center"> |
|||
<img src="images/inner_labels.gif" width="600"/> |
|||
</p> |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: When visible surfaces of two objects are fully aligned, the bounding boxes seem to blink in and out of existence from one frame to another. Why is that?</strong></summary><br> |
|||
|
|||
This is due to a common graphics problem called *z-fighting*. This occurs when the shader can't decide which of the two surfaces to draw on top of the other, since they both have the exact same distance from the camera. To fix this, simply move one of the objects slightly so that the two problematic surfaces do not fully align. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
|
|||
## <a name="randomization">Randomization</a> |
|||
|
|||
<details> |
|||
<summary><strong>Q: How can I have multiple sets of prefabs in a foreground placement Randomizer, and on every Iteration select one from each set?</strong> |
|||
</summary><br> |
|||
|
|||
This question is an example of more complex functionality that can be achieved by applying slight modifications to the provided sample Randomizers, or by creating completely custom ones by extending the `Randomizer` class. |
|||
|
|||
Here, we have a variety of options toward achieving the described outcome. One simple method could be to add several more `GameObjectParameter` fields inside of the provided sample `ForegroundObjectPlacementRandomizer`. Each of these Parameters could hold one of our object lists. Then, on each iteration, we would fetch one prefab from each of the lists using the `Sample()` function of each Parameter. |
|||
|
|||
The above solution can work but it is not modular enough, with the lists of prefabs not being reusable in other Randomizers. |
|||
|
|||
A better approach can be to define each prefab list separately as a scriptable object asset, and then just reference those scriptable objects inside of our foreground Randomizer. To do this, we first define a `PrefabCluster` class to hold a list of prefabs. |
|||
|
|||
```C# |
|||
using UnityEngine; |
|||
using UnityEngine.Perception.Randomization.Parameters; |
|||
|
|||
[CreateAssetMenu(fileName="NewPrefabCluster", menuName="Test/PrefabCluster")] |
|||
public class PrefabCluster : ScriptableObject |
|||
{ |
|||
public GameObjectParameter clusterPrefabs; |
|||
} |
|||
``` |
|||
|
|||
We can now create a cluster asset using the ***Assets -> Create -> Test -> PrefabCluster*** menu option and populate its list of prefabs. Each cluster contains one `GameObjectParameter`, which will hold the list of prefabs and provide us with a `Sample()` function. |
|||
|
|||
To be able to edit these clusters with the same editor UI available for Randomizers, you will also need to add an empty custom editor for the `PrefabCluster` class that extends our bespoke `ParameterUIElementsEditor` class: |
|||
|
|||
```C# |
|||
using UnityEditor; |
|||
using UnityEditor.Perception.Randomization; |
|||
|
|||
[CustomEditor(typeof(PrefabCluster))] |
|||
public class PrefabClusterEditor : ParameterUIElementsEditor { } |
|||
``` |
|||
|
|||
Note that any editor scripts must be placed inside a folder named "Editor" within your project. "Editor" is a special folder name in Unity that prevents editor code from compiling into a player during the build process. For example, the file path for the `PrefabClusterEditor` script above could be `.../Assets/Scripts/Editor/PrefabClusterEditor`. |
|||
|
|||
The ***Inspector*** view of a prefab cluster asset looks like below: |
|||
|
|||
<p align="center"> |
|||
<img src="images/prefab_cluster.png" width="400"/> |
|||
</p> |
|||
|
|||
Now all that is left is to use our prefab clusters inside a Randomizer. Here is some sample code: |
|||
|
|||
```C# |
|||
using System; |
|||
using UnityEngine; |
|||
|
|||
[Serializable] |
|||
[UnityEngine.Perception.Randomization.Randomizers.AddRandomizerMenu("My Randomizers/Cluster Randomizer")] |
|||
public class ClusterRandomizer : UnityEngine.Perception.Randomization.Randomizers.Randomizer |
|||
{ |
|||
public PrefabCluster[] clusters; |
|||
protected override void OnIterationStart() |
|||
{ |
|||
//select a random prefab from each cluster |
|||
foreach (var cluster in clusters) |
|||
{ |
|||
var prefab = cluster.clusterPrefabs.Sample(); |
|||
//do things with this prefab, e.g. create instances of it, etc. |
|||
} |
|||
} |
|||
} |
|||
``` |
|||
This Randomizer takes a list of `PrefabCluster` assets, then, on each Iteration, it goes through all the provided clusters and samples one prefab from each. The ***Inspector*** view for this Randomizer looks like this: |
|||
|
|||
<p align="center"> |
|||
<img src="images/cluster_randomizer.png" width="400"/> |
|||
</p> |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: How can I specify an exact number of objects to place using the sample foreground object placement Randomizer?</strong> </summary><br> |
|||
|
|||
The provided `ForegroundObjectPlacementRandomizer` uses Poisson Disk sampling to find randomly positioned points in the space denoted by the provided `Width` and `Height` values. The lower bound on the distance between the sampled points will be `Separation Distance`. The number of sampled points will be the maximum number of points in the given area that match these criteria. |
|||
|
|||
Thus, to limit the number of spawned objects, you can simply introduce a hard limit in the `for` loop that iterates over the Poisson Disk samples, to break out of the loop if the limit is reached. Additionally, we will need to shuffle the list of points retrieved from the Poisson Disk sampling in order to remove any selection bias when building our subset of points. This is because Poisson Disk points are sampled in sequence and relative to the points already sampled, therefore, the initial points in the list are likely to be closer to each other. We will use a `FloatParameter` to perform this shuffle, so that we can guarantee that our simulation is deterministic and reproducible. |
|||
```C# |
|||
FloatParameter m_IndexShuffleParameter = new FloatParameter { value = new UniformSampler(0, 1) }; |
|||
|
|||
protected override void OnIterationStart() |
|||
{ |
|||
var seed = SamplerState.NextRandomState(); |
|||
var placementSamples = PoissonDiskSampling.GenerateSamples( |
|||
placementArea.x, placementArea.y, separationDistance, seed); |
|||
var offset = new Vector3(placementArea.x, placementArea.y, 0f) * -0.5f; |
|||
|
|||
//shuffle retrieved points |
|||
var indexes = Enumerable.Range(0, placementSamples.Length).ToList(); |
|||
indexes = indexes.OrderBy(item => m_IndexShuffleParameter.Sample()).ToList(); |
|||
|
|||
//maximum number of objects to place |
|||
var limit = 50; |
|||
|
|||
var instantiatedCount = 0; |
|||
//iterate over all points |
|||
foreach (var index in indexes) |
|||
{ |
|||
instantiatedCount ++; |
|||
|
|||
if (instantiatedCount == limit) |
|||
break; |
|||
|
|||
var instance = m_GameObjectOneWayCache.GetOrInstantiate(prefabs.Sample()); |
|||
instance.transform.position = new Vector3(placementSamples[index].x, placementSamples[index].y, depth) + offset; |
|||
} |
|||
placementSamples.Dispose(); |
|||
} |
|||
``` |
|||
|
|||
This will guarantee an upper limit of 50 on the number of objects. To have exactly 50 objects, we need to make sure the `Separation Distance` is small enough for the given area, so that there are always at least 50 point samples found. Experiment with different values for the distance until you find one that produces the minimum number of points required. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: How can I avoid object overlap with the sample foreground object placement Randomizer?</strong></summary><br> |
|||
|
|||
There are a number of ways for procedurally placing objects while avoiding any overlap between them, and most of these methods can be rather complex and need to place objects in a sequence. All the modifications to the objects (like scale, rotation, etc.) would also need to happen before the next object is placed, so that the state of the world is fully known before each placement. |
|||
|
|||
Here, we are going to introduce a rather simple modification in the sample foreground placement code provided with the package. In each Iteration, a random scale factor is chosen, and then a desirable separation distance is calculated based on this scale factor and the list of given prefabs. We also scale the objects here to introduce additional randomization, due to the fact that once we have placed the objects we can no longer scale them. |
|||
|
|||
Based on the value given for `Non Overlap Guarantee`, this Randomizer can either reduce the amount of overlap or completely remove overlap. |
|||
|
|||
```C# |
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.Linq; |
|||
using UnityEngine; |
|||
using UnityEngine.Perception.Randomization.Parameters; |
|||
using UnityEngine.Perception.Randomization.Randomizers; |
|||
using UnityEngine.Perception.Randomization.Randomizers.Utilities; |
|||
using UnityEngine.Perception.Randomization.Samplers; |
|||
|
|||
[Serializable] |
|||
[AddRandomizerMenu("Example/No Overlap Foreground Object Placement Randomizer")] |
|||
public class NoOverlapForegroundObjectPlacementRandomizer : Randomizer |
|||
{ |
|||
public float depth; |
|||
[Tooltip("Range of scales used for objects. All objects in each frame will use the same scale.")] |
|||
public FloatParameter scaleParameter = new FloatParameter { value = new UniformSampler(4, 8) }; |
|||
public Vector2 placementArea; |
|||
public GameObjectParameter prefabs; |
|||
|
|||
[Tooltip("Degree to which we can guarantee that no objects will overlap. Use 1 for no overlap and smaller values (down to 0) for more dense placement with a possibility of some overlap.")] |
|||
public float nonOverlapGuarantee = 1; |
|||
|
|||
float m_ScaleFactor = 1f; |
|||
GameObject m_Container; |
|||
GameObjectOneWayCache m_GameObjectOneWayCache; |
|||
Dictionary<GameObject, float> m_GameObjectBoundsSizeCache; |
|||
List<GameObject> m_SelectedPrefabs; |
|||
int m_SelectionPoolSizePerFrame = 1; |
|||
FloatParameter m_IndexSelector = new FloatParameter { value = new UniformSampler(0, 1) }; |
|||
|
|||
protected override void OnAwake() |
|||
{ |
|||
m_Container = new GameObject("Foreground Objects"); |
|||
m_Container.transform.parent = scenario.transform; |
|||
m_GameObjectOneWayCache = new GameObjectOneWayCache( |
|||
m_Container.transform, prefabs.categories.Select(element => element.Item1).ToArray()); |
|||
m_GameObjectBoundsSizeCache = new Dictionary<GameObject, float>(); |
|||
m_SelectedPrefabs = new List<GameObject>(); |
|||
|
|||
//Calculate the average bounds size for the prefabs included in this categorical parameter |
|||
var averageBoundsSize = CalculateAverageBoundsSize(); |
|||
|
|||
//Calculate average scale based on the scale range given |
|||
var averageScale = 1f; |
|||
var sampler = (UniformSampler)scaleParameter.value; |
|||
if (sampler != null) |
|||
{ |
|||
averageScale = (sampler.range.minimum + sampler.range.maximum) / 2; |
|||
} |
|||
|
|||
//Use average bounds size and average scale to guess the maximum number of objects that can be placed without having them overlap. |
|||
//This is a heuristic to help us start the placement process. The actual number of items placed will usually be much smaller. |
|||
m_SelectionPoolSizePerFrame = (int)(placementArea.x * placementArea.y / (averageBoundsSize * averageScale)); |
|||
} |
|||
|
|||
protected override void OnIterationStart() |
|||
{ |
|||
m_ScaleFactor = scaleParameter.Sample(); |
|||
m_SelectedPrefabs.Clear(); |
|||
|
|||
//Select a random number of prefabs for this frame. Placement calculations will be done based on this subset. |
|||
for (var i = 0; i < m_SelectionPoolSizePerFrame; i++) |
|||
{ |
|||
var randIndex = (int)Mathf.Round((m_IndexSelector.Sample() * prefabs.categories.Count) - 0.5f); |
|||
m_SelectedPrefabs.Add(prefabs.categories[randIndex].Item1); |
|||
} |
|||
|
|||
//Calculate the minimum separation distance needed for the selected prefabs to not overlap. |
|||
var separationDistance = CalculateMaxSeparationDistance(m_SelectedPrefabs); |
|||
var seed = SamplerState.NextRandomState(); |
|||
var placementSamples = PoissonDiskSampling.GenerateSamples( |
|||
placementArea.x, placementArea.y, separationDistance, seed); |
|||
var offset = new Vector3(placementArea.x, placementArea.y, 0f) * -0.5f; |
|||
foreach (var sample in placementSamples) |
|||
{ |
|||
//Pick a random prefab from the selected subset and instantiate it. |
|||
var randIndex = (int)Mathf.Round((m_IndexSelector.Sample() * m_SelectedPrefabs.Count) - 0.5f); |
|||
var instance = m_GameObjectOneWayCache.GetOrInstantiate(m_SelectedPrefabs[randIndex]); |
|||
instance.transform.position = new Vector3(sample.x, sample.y, depth) + offset; |
|||
instance.transform.localScale = Vector3.one * m_ScaleFactor; |
|||
} |
|||
|
|||
placementSamples.Dispose(); |
|||
} |
|||
|
|||
protected override void OnIterationEnd() |
|||
{ |
|||
m_GameObjectOneWayCache.ResetAllObjects(); |
|||
} |
|||
|
|||
/// <summary> |
|||
/// Calculates the separation distance needed between placed objects to be sure that no two objects will overlap |
|||
/// </summary><br> |
|||
/// <returns>The max separation distance</returns> |
|||
float CalculateMaxSeparationDistance(ICollection<GameObject> categories) |
|||
{ |
|||
var maxBoundsSize = m_GameObjectBoundsSizeCache.Where(item => categories.Contains(item.Key)).Max(pair => pair.Value); |
|||
return maxBoundsSize * m_ScaleFactor * nonOverlapGuarantee; |
|||
} |
|||
|
|||
float CalculateAverageBoundsSize() |
|||
{ |
|||
foreach (var category in prefabs.categories) |
|||
{ |
|||
var prefab = category.Item1; |
|||
|
|||
prefab.transform.localScale = Vector3.one; |
|||
var renderers = prefab.GetComponentsInChildren<Renderer>(); |
|||
var totalBounds = new Bounds(); |
|||
foreach (var renderer in renderers) |
|||
{ |
|||
totalBounds.Encapsulate(renderer.bounds); |
|||
} |
|||
|
|||
var boundsSize = totalBounds.size.magnitude; |
|||
m_GameObjectBoundsSizeCache.Add(prefab, boundsSize); |
|||
} |
|||
|
|||
return m_GameObjectBoundsSizeCache.Values.Average(); |
|||
} |
|||
} |
|||
|
|||
``` |
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: What if I don't want randomized object placement? Can I move my objects in a non-randomized deterministic manner on each frame?</strong> </summary><br> |
|||
|
|||
Even though we call them Randomizers, you can use a Randomizer to perform any task through-out the execution lifecycle of your Scenario. The power of the Randomizers comes from the lifecycle hooks that they have into the Iteration and the Scenario, making it easy to know and guarantee when and in which order in the life of your simulation each piece of code runs. These functions include: |
|||
* `OnEnable` |
|||
* `OnAwake` |
|||
* `OnUpdate` |
|||
* `OnIterationStart` |
|||
* `OnIterationEnd` |
|||
* `OnScenarioStart` |
|||
* `OnScenarioComplete` |
|||
* `OnDisable` |
|||
|
|||
So, in order to have deliberate non-random object movement, you will just need to put your object movement code inside of one of the recurrent lifecycle functions. `OnUpdate()` runs on every frame of the simulation, and `OnIterationStart()` runs every Iteration (which can be the same as each frame if you have only 1 frame per Iteration of your Scenario). For example, the code below moves all objects tagged with the component `ForwardMoverTag` along their forward axis by 1 unit, on every Iteration. |
|||
|
|||
```C# |
|||
protected override void OnIterationStart() |
|||
{ |
|||
var tags = tagManager.Query<ForwardMoverTag>(); |
|||
foreach (var tag in tags) |
|||
{ |
|||
tag.transform.Translate(Vector3.forward); |
|||
} |
|||
} |
|||
``` |
|||
Additionally, keep in mind that you can use Perception Samplers (and therefore Parameters) to generate constant values, not just random ones. The `ConstantSampler` class provides this functionality. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: The objects instantiated using the sample foreground placement Randomizer are floating in the air. How can I use this Randomizer to place objects on a horizontal surface instead?</strong> </summary><br> |
|||
|
|||
The objects instantiated by the sample foreground Randomizer are all parented to an object named `Foreground Objects` at the root of the Scene Hierarchy. To modify the orientation of the objects, you can simply rotate this parent object at the beginning of the Scenario. |
|||
|
|||
Alternatively, you could also place `Foreground Objects` inside another GameObject in the Scene using the `Transform.SetParent()` method, and then modify the local position and rotation of `Foreground Objects` in such a way that makes the objects appear on the surface of the parent GameObject. |
|||
|
|||
In addition, if you'd like to have horizontal placement without touching the parent object, you can modify the Randomizer's code to place objects horizontally instead of vertically. The lines responsible for placement are: |
|||
```C# |
|||
var offset = new Vector3(placementArea.x, placementArea.y, 0) * -0.5f; |
|||
``` |
|||
```C# |
|||
instance.transform.position = new Vector3(sample.x, sample.y, depth) + offset; |
|||
``` |
|||
|
|||
The first line builds an offset vector that is later used to center the points retrieved from Poisson Disk sampling around the center of the coordinate system. The second line is executed in a loop, and each time, places one object at one of the sampled points at the depth (along Z axis) provided by the user. |
|||
|
|||
To make this placement horizontal, you would just need to change these two lines to swap Y for Z. The resulting lines would be: |
|||
|
|||
```C# |
|||
var offset = new Vector3(placementArea.x, 0, placementArea.y) * -0.5f; |
|||
``` |
|||
```C# |
|||
instance.transform.position = new Vector3(sample.x, depth, sample.y) + offset; |
|||
``` |
|||
|
|||
Note that the variable `depth` is in fact playing the role of a height variable now. |
|||
|
|||
Finally, to achieve more natural placement, you could also use Unity's physics engine to drop the objects on a surface, let them settle, and then capture an image. To achieve this, you would just need to have sufficient frames in each Iteration of the Scenario (instead of the default 1 frame per iteration), and set your Perception Camera's capture interval to a large enough number that would make it capture each Iteration once after the objects have settled. This example is explained in more detail in the [Perception Camera](#perception-camera) section of this FAQ. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: Does using the same Random Seed value in two runs of the same Scenario guarantee that the generated datasets are identical?</strong></summary><br> |
|||
|
|||
If you only use the Samplers (and Parameters, which internally use Samplers) provided in the Perception package to generate random values throughout the Scenario's lifecycle and keep the `Random Seed` value unchanged, an identical sequence of random numbers will be generated every time the Scenario is run. This is because the Samplers obtain their seeds through continually mutating the provided global `Random Seed` in the Scenario. |
|||
|
|||
Keep in mind that any change in the order of sampling or the number of samples obtained can lead to different outcomes. For example, if you change the order of Randomizers in the Scenario, the Samplers inside of these Randomizers will now execute in the new order, and thus, they will operate based on different seeds than before and generate different numbers. The same can happen if you add additional calls to a Sampler inside a Randomizer, causing the Samplers in later Randomizers to now use different seeds, since the global seed has been mutated more times than before. |
|||
|
|||
One more thing to keep in mind is that certain systems and components of Unity are not deterministic and can produce different outcomes in consecutive runs. Examples of this are the physics engine and the film grain post processing. Hence, if you need to guarantee that your simulation always produces the exact same dataset, make sure to research the various systems that you use to make sure they behave deterministically. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
## <a name="perception-camera">Perception Camera</a> |
|||
|
|||
<details> |
|||
<summary><strong>Q: What is the relationship between the Scenario's lifecycle properties (Iterations and Frames per Iteration) and the Perception Camera's timing properties (Simulation Delta Time, Start at Frame, and Frames Between Captures)?</strong> </summary><br> |
|||
|
|||
Each Iteration of the Scenario resets the Perception Camera's timing variables. Thus, you can think of each Iteration of the Scenario as one separate Perception Camera sequence, in which the camera's internal timing properties come into play. For instance, if you have 10 `Frames Per Iteration` on your Scenario, and your Perception Camera's `Start at Frame` value is set to 8, you will get two captures from the camera at the 9th and 10th frames of each Iteration (note that `Start at Frame` starts from 0). Similarly, you can use the `Frames Between Captures` to introduce intervals between captures. A value of 0 leads to all frames being captured. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: I want to simulate physics (or other accumulative behaviors such as auto-exposure) for a number of frames and let things settle before capturing the Scene. Is this possible with the Perception package?</strong></summary><br> |
|||
|
|||
Yes. The Perception Camera can be set to capture at specific frame intervals, rather than every frame. The `Frames Between Captures` value is set to 0 by default, which causes the camera to capture all frames; however, you can change this to 1 to capture every other frame, or larger numbers to allow more time between captures. You can also have the camera start capturing at a certain frame rather than the first frame, by setting the `Start at Frame` value to a value other than 0. All of this timing happens within each Iteration of the Scenario, and gets reset when you advance to the next Iteration. Therefore, the combination of these properties and the Scenario's `Frames Per Iteration` property allows you to randomize the state of your Scene at the start of each Iteration, let things run for a number of frames, and then capture the Scene at the end of the Iteration. |
|||
|
|||
Suppose we need to drop a few objects into the Scene, let them interact physically and settle after a number of frames, and then capture their final state once. Afterwards, we want to repeat this cycle by randomizing the initial positions of the objects, dropping them, and capturing the final state again. We will set the Scenario's `Frames Per Iteration` to 300, which should be sufficient for the objects to get close to a settled position (this depends on the value you use for `Simulation Delta Time` in Perception Camera and the physical properties of the engine and objects, and can be found through experimentation). We also set the `Start at Frame` value of the Perception Camera to 290, and the `Frames Between Captures` to a sufficiently large number (like 100), so that we only get one capture per Iteration of the Scenario. The results look like below. Note how the bounding boxes only appear after the objects are fairly settled. These are the timestamps at which captures are happening. |
|||
|
|||
|
|||
<p align="center"> |
|||
<img src="images/object_drop.gif" width="700"/> |
|||
</p> |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: I do not want the Perception Camera to control the delta time of my simulation or capture on a scheduled basis. Can I have a Perception Camera in my Scene that does not affect timings and trigger captures manually from other scripts?</strong></summary><br> |
|||
|
|||
Yes. The Perception Camera offers two trigger modes, `Scheduled` and `Manual`, and these can be chosen in the editor UI for the Perception Camera component. If you select the `Manual` mode, you will be able to trigger captures by calling the `RequestCapture()` method of `PerceptionCamera`. In this mode, you have the option to not have this camera dictate your simulation delta time. This is controlled using the `Affect Simulation Timing` checkbox. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
|
|||
<details> |
|||
<summary><strong>Q: Can I have multiple Perception Cameras active in my Scene simultaneously?</strong></summary><br> |
|||
|
|||
No, at this time the Perception package only supports one active Perception Camera. This is something that is on our roadmap and we hope to support soon. |
|||
|
|||
However, the package does support having more than one Perception Camera in the Scene, as long as only one is active when the simulation starts. Therefore, one possible workaround, if your simulation is fully deterministic from one run to the next, would be to run the simulation more than once, each time with one of the cameras active. While not ideal, this will at least let you generate matching datasets. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: My RGB images look darker than what I see in Unity Editor, when I render the Perception Camera to a texture. How can I fix this?</strong> |
|||
</summary><br> |
|||
|
|||
This issue is caused by the color format of the texture. In the ***Inspector*** view of the render texture, set color format to `R8G8B8A8_SRGB`. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: How do I report additional custom information in my output dataset for each frame or the whole simulation (e.g. 3D position of objects at the start of each Iteration, intensity of lights, etc.)?</strong> |
|||
</summary><br> |
|||
|
|||
This can be done by adding custom annotations to your dataset. Have a look at [this](https://github.com/Unity-Technologies/com.unity.perception/blob/master/com.unity.perception/Documentation%7E/DatasetCapture.md) page for an explanation, as well as an example for how to do this. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
## <a name="miscellaneous">Miscellaneous</a> |
|||
|
|||
<details> |
|||
<summary><strong>Q: Objects in my captured images have jagged edges, how can I fix this?</strong> |
|||
</summary><br> |
|||
|
|||
This is a common issue with rendering graphics into raster images (digital images), when the resolution of the raster is not high enough to perfectly display slanting lines. The common solution to this issue is the use of anti-aliasing methods, and Unity offers a number of these in both URP and HDRP. To experiment with anti-aliasing, go to the ***Inspector*** view of your Perception Camera object and in the Camera component, change `Anti-aliasing` from `None` to another option. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: I am using an HDRP Unity project with Perception and my images have significant blurring around most objects. How can I remove this blur?</strong> |
|||
</summary><br> |
|||
|
|||
The effect you are observing here is motion blur, which happens because the placement Randomizers used in the Perception tutorial cache their instantiated objects from one Iteration to the next, and move them to new locations on each Iteration instead of destroying them and creating new ones. This "motion" of the objects causes the motion blur effect to kick in. |
|||
|
|||
|
|||
HDRP projects have motion blur and a number of other post processing effects enabled by default. To disable motion blur or any other effect, follow these steps: |
|||
1. Create an empty GameObject in your Scene and add a Volume component to it. |
|||
2. Set the Volume's profile to the **Volume Global** asset. |
|||
3. Uncheck the **Motion Blur** option. |
|||
|
|||
|
|||
<p align="center"> |
|||
<img src="images/volume.png" width="500"/> |
|||
</p> |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: Are all post processing effects provided by Unity safe to use in synthetic datasets?</strong> |
|||
</summary><br> |
|||
|
|||
No. When using post processing effects, you need to be careful about issues regarding randomness and determinism: |
|||
|
|||
* There are certain post processing effects that need randomization internally, e.g. film grain. The film grain effect provided by Unity is not sufficiently randomized for model training and can thus mislead your CV model to look for a specific noise pattern during prediction. |
|||
* Even if such an effect is properly randomized, using a randomized effect would make your overall randomization strategy non-deterministic, meaning you would not be able to reproduce your datasets. This is because the effect would internally use random number generators outside of the Samplers provided by the Perception package. If you have access to the source code for a randomized effect, you can modify it to only use Perception Samplers for random number generation, which would make its behavior deterministic and thus appropriate for use in synthetic datasets that need to be reproducible. |
|||
|
|||
To make sure you do not run into insufficient randomization or non-determinism, it would be best to implement effects such as film grain yourself or modify existing code to make sure no random number generators are used except for the Samplers provided in the Perception package. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: What post processing effects can help improve model performance?</strong> |
|||
</summary><br> |
|||
|
|||
Based on our experiments, randomizing contrast, saturation, lens blur, and lens distortion can help significantly improve the performance of your CV model. We recommend experimenting with these as well as other effects to determine those that work best for your use-case. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: Can I debug my C# code?</strong> |
|||
</summary><br> |
|||
|
|||
Unity projects can be debugged using external editors such as Visual Studio or JetBrains Rider. For local development and debugging, you will first need to clone the Perception repository to disk and add the Perception package from this cloned repository to your Unity project. Then, in Unity Editor, go to ***Edit (or "Unity" on OSX) -> Preferences -> External Tools***. Select your preferred editor as the External Script Editor, and enable |
|||
**General .csproj files** for at least **Embedded packages** and **Local packages**. This will allow you to quickly navigate through the code-base for the Perception package and internal Unity Editor packages. |
|||
|
|||
All you need to do now is to double click any of the Perception package's C# script files from inside Unity Editor's **Project** window. The files are located in `Assets/Perception`. Double clicking will open them in your external editor of choice, and you will be able to attach the debugger to Unity. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
|
|||
<details> |
|||
<summary><strong>Q: What kind of synthetic environment will be best for my use-case?</strong> |
|||
</summary><br> |
|||
|
|||
It is difficult to say what type of synthetic environment would lead to the best model performance. It is best to carry out small and quick experiments with both random unstructured environments (such as the [SynthDet](https://github.com/Unity-Technologies/SynthDet) project) and more structured ones that may resemble real environments in which prediction will need to happen. This will help identify the types of environments and randomizations that work best for each specific use-case. The beauty of synthetic data is that you can try these experiments fairly quickly. |
|||
|
|||
Here are a few blog posts to give you some ideas: [1](https://blog.unity.com/technology/synthetic-data-simulating-myriad-possibilities-to-train-robust-machine-learning-models), [2](https://blog.unity.com/technology/use-unitys-perception-tools-to-generate-and-analyze-synthetic-data-at-scale-to-train), [3](https://blog.unity.com/technology/training-a-performant-object-detection-ml-model-on-synthetic-data-using-unity-perception), [4](https://blog.unity.com/technology/supercharge-your-computer-vision-models-with-synthetic-datasets-built-by-unity), [5](https://blog.unity.com/technology/boosting-computer-vision-performance-with-synthetic-data). |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
|
|||
<details> |
|||
<summary><strong>Q: Can I have more realistic rendering in my Scene?</strong> |
|||
</summary><br> |
|||
|
|||
A project's lighting configuration typically has the greatest influence over the final rendered output over any other simulation property. Unity has many lighting options, each of which is designed as a different trade-off between performance and realism/capability. The 3 most pertinent options that you will likely be interested in are: |
|||
|
|||
* URP baked lighting: The Universal Render Pipeline offers the most performant lighting configurations by using an offline baking process to generate realistic bounce lighting within a static scene and then using simple shadow mapped dynamic lights in conjunctions with light probes to make dynamic (or randomized) objects "fit" into the baked scene. This option provides high performance, but lacks the visual fidelity needed for interior environments and is geared toward more outdoor-like settings. Also, depending on scene randomization complexity, light baking might not be the best option. Randomly generated scenes will often place objects and adjust lighting in ways that make the new scene incompatible with the original baked lighting configuration. |
|||
|
|||
* HDRP lighting: A default HDRP scene offers a step toward more realistic environments with a much larger array of lighting settings (soft shadows, multiple dynamic lights, etc.) and a host of additional real-time effects like camera exposure and screen space ambient occlusion. A warning though: real time screen space effects may make your scene "look better", but the way these effects are calculated is not based on how light works in the real world, so realism may vary. Another huge advantage of HDRP is the potential to have moderately realistic lighting without baking your lighting configuration (though you can integrate light baking if you want to). However, there is no real-time global illumination option in default HDRP, meaning that your scene will not simulate complex real world light behavior such as light bouncing, light bleeding, or realistic shadows for dynamic scenes. This can result in unrealistically dark scenes when only using directional lights and windows (without extra interior lights to brighten things up). Overall though, HDRP offers a good compromise between performance and realism for some use cases. |
|||
|
|||
* HDRP DXR (DirectX Raytracing): Unity offers some preview ray tracing features in its latest editor versions that can be used to drastically improve the realism of your scene. Here are the pros and cons of DXR: |
|||
* Pros: |
|||
* Can simulate more realistic light behaviors (light bouncing, light color bleeding, and realistic shadows) |
|||
* No light baking required |
|||
* Cons: |
|||
* Requires special hardware to run (Nvidia RTX graphics cards) |
|||
* Time consuming to render (relative to default HDRP). Some lighting options (Global Illumination) are less expensive than others (Path Tracing). |
|||
* More complicated to configure |
|||
* These features are still in preview and subject to change |
|||
|
|||
A visual comparison of the different lighting configurations in HDRP is shown below. The Scene includes one directional light and one dim point light on the ceiling. |
|||
|
|||
Default HDRP: |
|||
|
|||
<p align="center"> |
|||
<img src="images/hdrp.png" width="700"/> |
|||
</p> |
|||
|
|||
HDRP with Global Illumination (notice how much brighter the scene is with ray traced light bouncing): |
|||
|
|||
<p align="center"> |
|||
<img src="images/hdrp_rt_gi.png" width="700"/> |
|||
</p> |
|||
|
|||
HDRP with Path Tracing (128 samples) (notice the red light bleeding from the cube onto the floor and the increased shadow quality): |
|||
|
|||
<p align="center"> |
|||
<img src="images/hdrp_pt_128_samples.png" width="700"/> |
|||
</p> |
|||
|
|||
HDRP with Path Tracing (4096 samples) (more samples leads to less ray tracing noise but also a longer time to render): |
|||
|
|||
<p align="center"> |
|||
<img src="images/hdrp_pt_4096_samples.png" width="700"/> |
|||
</p> |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: I am randomizing my Scene every frame and using ray casting to detect the position of objects, but my ray casts are returning incorrect results. What is the issue here?</strong> |
|||
</summary><br> |
|||
|
|||
The physics engine needs to catch up with the position and rotation of your objects and is typically a frame behind. When you randomize things every frame, the physics engine can never catch up. To fix this, call `Physics.SyncTransforms` just before calling any ray casting methods. |
|||
|
|||
--- |
|||
</details> |
|||
|
|||
<details> |
|||
<summary><strong>Q: Where can I get humanoid models and animations?</strong> |
|||
</summary><br> |
|||
|
|||
One useful resource for humanoid characters and animations is [Mixamo](https://www.mixamo.com/#/?page=1&type=Motion%2CMotionPack). |
|||
|
|||
--- |
|||
</details> |
|
|||
fileFormatVersion: 2 |
|||
guid: 6c8dccf3511434d2aadb672239c0c571 |
|||
folderAsset: yes |
|||
DefaultImporter: |
|||
externalObjects: {} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements"> |
|||
<VisualElement class="parameter__categorical-options-list"> |
|||
<ListView name="assets"/> |
|||
</VisualElement> |
|||
<VisualElement style="flex-direction: row; justify-content: flex-end;"> |
|||
<Button name="add-asset" text="Add Asset" class="parameter__categorical-options-list-button"/> |
|||
<Button name="add-folder" text="Add Folder" class="parameter__categorical-options-list-button"/> |
|||
<Button name="clear-assets" text="Clear Assets" class="parameter__categorical-options-list-button"/> |
|||
</VisualElement> |
|||
</UXML> |
|
|||
fileFormatVersion: 2 |
|||
guid: e4915dfbbc1de39478264a8f5d168ca0 |
|||
ScriptedImporter: |
|||
internalIDToNameTable: [] |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|||
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0} |
|
|||
<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements"> |
|||
<VisualElement class="parameter__categorical-option"> |
|||
<Button name="remove" class="randomization__remove-item-button"/> |
|||
<Label name="index-label" text="[0]" style="min-width: 50px;"/> |
|||
<editor:ObjectField name="item" class="parameter__categorical-option-property-field"/> |
|||
</VisualElement> |
|||
</UXML> |
|
|||
fileFormatVersion: 2 |
|||
guid: d710875a5224e1b4186c4334f791ca19 |
|||
ScriptedImporter: |
|||
internalIDToNameTable: [] |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|||
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0} |
|
|||
fileFormatVersion: 2 |
|||
guid: e6fba9b826939224fac37b7ead85df2a |
|||
ScriptedImporter: |
|||
internalIDToNameTable: [] |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|||
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0} |
|
|||
<UXML xmlns="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements"> |
|||
<VisualElement style="margin-bottom: 4px;"> |
|||
<Style src="../../Uss/Styles.uss"/> |
|||
<Label name="name" text="Field Name" class="unity-base-field__label"/> |
|||
<VisualElement style="margin-left: 18px;"> |
|||
<VisualElement style="flex-direction: row; align-items: center;"> |
|||
<Label |
|||
text="Location" |
|||
class="unity-base-field__label" |
|||
tooltip="The asset source location to load assets from"/> |
|||
<editor:ToolbarMenu name="location-dropdown" text="Type" class="sampler__type-menu"/> |
|||
</VisualElement> |
|||
<VisualElement style="margin-left: 18px;"> |
|||
<VisualElement name="fields-container" style="flex-grow: 1;"/> |
|||
<TextElement name="location-notes" class="scenario__info-box"/> |
|||
</VisualElement> |
|||
<VisualElement style="flex-direction: row; align-items: center;"> |
|||
<Label |
|||
text="Asset Role" |
|||
class="unity-base-field__label" |
|||
tooltip="Asset Roles preprocess assets loaded from the selected asset source location"/> |
|||
<editor:ToolbarMenu name="asset-role-dropdown" text="Type" class="sampler__type-menu"/> |
|||
</VisualElement> |
|||
</VisualElement> |
|||
</VisualElement> |
|||
</UXML> |
|
|||
fileFormatVersion: 2 |
|||
guid: 7c9fc5cac7e306247a669a3f33479736 |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using System; |
|||
using UnityEditor; |
|||
using UnityEditor.Perception.Randomization; |
|||
using UnityEditor.UIElements; |
|||
using UnityEngine.UIElements; |
|||
|
|||
namespace Editor.Randomization.VisualElements.AssetSource |
|||
{ |
|||
class AssetListItemElement : VisualElement |
|||
{ |
|||
int m_Index; |
|||
Type m_ItemType; |
|||
SerializedProperty m_Property; |
|||
|
|||
public AssetListItemElement(SerializedProperty property, Type itemType) |
|||
{ |
|||
m_Property = property; |
|||
m_ItemType = itemType; |
|||
} |
|||
|
|||
public void BindProperties(int i) |
|||
{ |
|||
Clear(); |
|||
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>( |
|||
$"{StaticData.uxmlDir}/AssetSource/{nameof(AssetListItemElement)}.uxml"); |
|||
template.CloneTree(this); |
|||
|
|||
m_Index = i; |
|||
var indexLabel = this.Q<Label>("index-label"); |
|||
indexLabel.text = $"[{m_Index}]"; |
|||
|
|||
var optionProperty = m_Property.GetArrayElementAtIndex(i); |
|||
var option = this.Q<ObjectField>("item"); |
|||
option.BindProperty(optionProperty); |
|||
option.objectType = m_ItemType; |
|||
option.allowSceneObjects = false; |
|||
} |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 5fd946360906cd5449f8d54f3c65e41c |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
fileFormatVersion: 2 |
|||
guid: 43a7574956bc88b45a6597e2c94c9cb6 |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using System; |
|||
using System.Collections; |
|||
using UnityEditor; |
|||
using UnityEditor.Perception.Randomization; |
|||
using UnityEngine; |
|||
using UnityEngine.UIElements; |
|||
|
|||
namespace Editor.Randomization.VisualElements.AssetSource |
|||
{ |
|||
class AssetListElement : VisualElement |
|||
{ |
|||
SerializedProperty m_Property; |
|||
IList list => (IList)StaticData.GetManagedReferenceValue(m_Property); |
|||
|
|||
public AssetListElement(SerializedProperty property, Type itemType) |
|||
{ |
|||
m_Property = property; |
|||
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>( |
|||
$"{StaticData.uxmlDir}/AssetSource/AssetListElement.uxml"); |
|||
template.CloneTree(this); |
|||
|
|||
var listView = this.Q<ListView>("assets"); |
|||
listView.itemsSource = list; |
|||
listView.itemHeight = 22; |
|||
listView.selectionType = SelectionType.None; |
|||
listView.style.flexGrow = 1.0f; |
|||
listView.style.height = new StyleLength(listView.itemHeight * 4); |
|||
listView.makeItem = () => |
|||
{ |
|||
return new AssetListItemElement(m_Property, itemType); |
|||
}; |
|||
listView.bindItem = (element, i) => |
|||
{ |
|||
var optionElement = (AssetListItemElement)element; |
|||
optionElement.BindProperties(i); |
|||
var removeButton = optionElement.Q<Button>("remove"); |
|||
removeButton.clicked += () => |
|||
{ |
|||
// First delete sets option to null, second delete removes option
|
|||
var numOptions = m_Property.arraySize; |
|||
m_Property.DeleteArrayElementAtIndex(i); |
|||
if (numOptions == m_Property.arraySize) |
|||
m_Property.DeleteArrayElementAtIndex(i); |
|||
|
|||
m_Property.serializedObject.ApplyModifiedProperties(); |
|||
listView.itemsSource = list; |
|||
listView.Refresh(); |
|||
}; |
|||
}; |
|||
|
|||
var addOptionButton = this.Q<Button>("add-asset"); |
|||
addOptionButton.clicked += () => |
|||
{ |
|||
m_Property.arraySize++; |
|||
m_Property.serializedObject.ApplyModifiedProperties(); |
|||
listView.itemsSource = list; |
|||
listView.Refresh(); |
|||
listView.ScrollToItem(m_Property.arraySize); |
|||
}; |
|||
|
|||
var addFolderButton = this.Q<Button>("add-folder"); |
|||
addFolderButton.clicked += () => |
|||
{ |
|||
var folderPath = EditorUtility.OpenFolderPanel( |
|||
"Add Assets From Folder", Application.dataPath, string.Empty); |
|||
if (folderPath == string.Empty) |
|||
return; |
|||
|
|||
var assets = AssetLoadingUtilities.LoadAssetsFromFolder(folderPath, itemType); |
|||
var optionsIndex = m_Property.arraySize; |
|||
m_Property.arraySize += assets.Count; |
|||
for (var i = 0; i < assets.Count; i++) |
|||
{ |
|||
var optionProperty = m_Property.GetArrayElementAtIndex(optionsIndex + i); |
|||
optionProperty.objectReferenceValue = assets[i]; |
|||
} |
|||
|
|||
m_Property.serializedObject.ApplyModifiedProperties(); |
|||
listView.itemsSource = list; |
|||
listView.Refresh(); |
|||
}; |
|||
|
|||
var clearOptionsButton = this.Q<Button>("clear-assets"); |
|||
clearOptionsButton.clicked += () => |
|||
{ |
|||
m_Property.arraySize = 0; |
|||
m_Property.serializedObject.ApplyModifiedProperties(); |
|||
listView.itemsSource = list; |
|||
listView.Refresh(); |
|||
}; |
|||
} |
|||
} |
|||
} |
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.ComponentModel; |
|||
using System.Reflection; |
|||
using UnityEditor; |
|||
using UnityEditor.Perception.Randomization; |
|||
using UnityEditor.UIElements; |
|||
using UnityEngine; |
|||
using UnityEngine.Perception.Randomization; |
|||
using UnityEngine.UIElements; |
|||
|
|||
namespace Editor.Randomization.VisualElements.AssetSource |
|||
{ |
|||
class AssetSourceElement : VisualElement |
|||
{ |
|||
SerializedProperty m_AssetRoleProperty; |
|||
SerializedProperty m_LocationProperty; |
|||
ToolbarMenu m_AssetRoleToolbarMenu; |
|||
ToolbarMenu m_LocationToolbarMenu; |
|||
VisualElement m_FieldsContainer; |
|||
TextElement m_LocationNotes; |
|||
Type m_AssetType; |
|||
Dictionary<string, Type> m_AssetRoleLabelsToTypes = new Dictionary<string, Type>(); |
|||
|
|||
IAssetRoleBase assetRole => |
|||
(IAssetRoleBase)StaticData.GetManagedReferenceValue(m_AssetRoleProperty); |
|||
AssetSourceLocation assetSourceLocation => |
|||
(AssetSourceLocation)StaticData.GetManagedReferenceValue(m_LocationProperty); |
|||
|
|||
public AssetSourceElement(SerializedProperty property, FieldInfo fieldInfo) |
|||
{ |
|||
m_AssetType = fieldInfo.FieldType.GetGenericArguments()[0]; |
|||
m_AssetRoleProperty = property.FindPropertyRelative("m_AssetRoleBase"); |
|||
m_LocationProperty = property.FindPropertyRelative(nameof(AssetSource<GameObject>.assetSourceLocation)); |
|||
var template = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>( |
|||
$"{StaticData.uxmlDir}/AssetSource/AssetSourceElement.uxml"); |
|||
template.CloneTree(this); |
|||
|
|||
var nameLabel = this.Q<Label>("name"); |
|||
nameLabel.text = property.displayName; |
|||
|
|||
m_FieldsContainer = this.Q<VisualElement>("fields-container"); |
|||
|
|||
m_AssetRoleToolbarMenu = this.Q<ToolbarMenu>("asset-role-dropdown"); |
|||
var storedAssetRole = assetRole; |
|||
m_AssetRoleToolbarMenu.text = storedAssetRole != null |
|||
? GetAssetRoleDisplayName(assetRole.GetType()) : "None"; |
|||
|
|||
// ReSharper disable once PossibleNullReferenceException
|
|||
var baseType = fieldInfo.FieldType.GetProperty("assetRole").PropertyType; |
|||
m_AssetRoleToolbarMenu.menu.AppendAction( |
|||
"None", |
|||
a => ReplaceAssetRole(null), |
|||
a => DropdownMenuAction.Status.Normal); |
|||
m_AssetRoleLabelsToTypes.Clear(); |
|||
foreach (var type in StaticData.assetRoleTypes) |
|||
{ |
|||
if (!type.IsSubclassOf(baseType)) |
|||
continue; |
|||
var label = GetAssetRoleDisplayName(type); |
|||
|
|||
if (m_AssetRoleLabelsToTypes.ContainsKey(label)) |
|||
Debug.LogError($"The asset role classes {type.Name} && {m_AssetRoleLabelsToTypes[label].Name} have an identical label: \"{label}\". Asset role labels should be unique."); |
|||
else |
|||
m_AssetRoleLabelsToTypes.Add(label, type); |
|||
|
|||
m_AssetRoleToolbarMenu.menu.AppendAction( |
|||
label, |
|||
a => ReplaceAssetRole(type), |
|||
a => DropdownMenuAction.Status.Normal); |
|||
} |
|||
|
|||
m_LocationNotes = this.Q<TextElement>("location-notes"); |
|||
m_LocationToolbarMenu = this.Q<ToolbarMenu>("location-dropdown"); |
|||
foreach (var type in StaticData.assetSourceLocationTypes) |
|||
{ |
|||
m_LocationToolbarMenu.menu.AppendAction( |
|||
GetDisplayName(type), |
|||
a => ReplaceLocation(type), |
|||
a => DropdownMenuAction.Status.Normal); |
|||
} |
|||
if (assetSourceLocation == null) |
|||
CreateAssetSourceLocation(typeof(LocalAssetSourceLocation)); |
|||
UpdateLocationUI(assetSourceLocation.GetType()); |
|||
} |
|||
|
|||
void ReplaceAssetRole(Type type) |
|||
{ |
|||
if (type == null) |
|||
{ |
|||
m_AssetRoleToolbarMenu.text = "None"; |
|||
m_AssetRoleProperty.managedReferenceValue = null; |
|||
} |
|||
else |
|||
{ |
|||
m_AssetRoleToolbarMenu.text = GetAssetRoleDisplayName(type); |
|||
var newAssetRole = (IAssetRoleBase)Activator.CreateInstance(type); |
|||
m_AssetRoleProperty.managedReferenceValue = newAssetRole; |
|||
} |
|||
m_AssetRoleProperty.serializedObject.ApplyModifiedProperties(); |
|||
} |
|||
|
|||
void CreateAssetSourceLocation(Type type) |
|||
{ |
|||
var newLocation = (AssetSourceLocation)Activator.CreateInstance(type); |
|||
m_LocationProperty.managedReferenceValue = newLocation; |
|||
m_LocationProperty.serializedObject.ApplyModifiedProperties(); |
|||
} |
|||
|
|||
void ReplaceLocation(Type type) |
|||
{ |
|||
CreateAssetSourceLocation(type); |
|||
UpdateLocationUI(type); |
|||
} |
|||
|
|||
void UpdateLocationUI(Type type) |
|||
{ |
|||
m_LocationToolbarMenu.text = GetDisplayName(type); |
|||
var notesAttribute = (AssetSourceEditorDescriptionAttribute)Attribute.GetCustomAttribute(type, typeof(AssetSourceEditorDescriptionAttribute)); |
|||
if (notesAttribute != null) |
|||
{ |
|||
m_LocationNotes.text = notesAttribute.notes; |
|||
m_LocationNotes.style.display = new StyleEnum<DisplayStyle>(DisplayStyle.Flex); |
|||
} |
|||
else |
|||
{ |
|||
m_LocationNotes.style.display = new StyleEnum<DisplayStyle>(DisplayStyle.None); |
|||
} |
|||
CreatePropertyFields(); |
|||
} |
|||
|
|||
void CreatePropertyFields() |
|||
{ |
|||
m_FieldsContainer.Clear(); |
|||
if (m_LocationProperty.type == $"managedReference<{nameof(LocalAssetSourceLocation)}>") |
|||
m_FieldsContainer.Add( |
|||
new AssetListElement(m_LocationProperty.FindPropertyRelative("assets"), m_AssetType)); |
|||
else |
|||
UIElementsEditorUtilities.CreatePropertyFields(m_LocationProperty, m_FieldsContainer); |
|||
} |
|||
|
|||
static string GetDisplayName(Type type) |
|||
{ |
|||
var attribute = (DisplayNameAttribute)Attribute.GetCustomAttribute(type, typeof(DisplayNameAttribute)); |
|||
return attribute != null ? attribute.DisplayName : type.Name; |
|||
} |
|||
|
|||
static string GetAssetRoleDisplayName(Type type) |
|||
{ |
|||
return $"{((IAssetRoleBase)Activator.CreateInstance(type)).label} ({type.Name})"; |
|||
} |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 27aa08b82cf94015adc22309c8f3bc48 |
|||
timeCreated: 1618977151 |
|
|||
using UnityEngine; |
|||
|
|||
namespace UnityEngine.Perception.Randomization |
|||
{ |
|||
/// <summary>
|
|||
/// Derive this class to load Unity assets from a specific location
|
|||
/// </summary>
|
|||
public abstract class AssetSourceLocation |
|||
{ |
|||
/// <summary>
|
|||
/// The number of assets available at this location
|
|||
/// </summary>
|
|||
public abstract int count { get; } |
|||
|
|||
/// <summary>
|
|||
/// Execute setup steps before accessing assets at this location
|
|||
/// </summary>
|
|||
/// <param name="assetRole">The asset role that will be used to preprocess assets from this location</param>
|
|||
/// <typeparam name="T">The type of assets that will be loaded from this location</typeparam>
|
|||
public abstract void Initialize<T>(AssetRole<T> assetRole) where T : Object; |
|||
|
|||
/// <summary>
|
|||
/// Unload all assets loaded from this location
|
|||
/// </summary>
|
|||
public abstract void ReleaseAssets(); |
|||
|
|||
/// <summary>
|
|||
/// Retrieves an asset from this location using the provided index
|
|||
/// </summary>
|
|||
/// <param name="index">The index to load the asset from</param>
|
|||
/// <typeparam name="T">The type of asset to load</typeparam>
|
|||
/// <returns>The loaded asset</returns>
|
|||
public abstract T LoadAsset<T>(int index) where T : Object; |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 9f2e99decdb94c7c898d7702e10cbce5 |
|||
timeCreated: 1619732135 |
|
|||
fileFormatVersion: 2 |
|||
guid: 20f161f5e56247c280fc1b56b567f49a |
|||
timeCreated: 1618983500 |
|
|||
namespace UnityEngine.Perception.Randomization |
|||
{ |
|||
/// <summary>
|
|||
/// Derive this class to create a typed asset role.
|
|||
/// Typed asset roles are used to apply preprocessing steps to assets loaded from an <see cref="AssetSource{T}"/>.
|
|||
/// </summary>
|
|||
/// <typeparam name="T">The type of asset to preprocess</typeparam>
|
|||
public abstract class AssetRole<T> : IAssetRoleBase where T : Object |
|||
{ |
|||
/// <inheritdoc/>
|
|||
public abstract string label { get; } |
|||
|
|||
/// <inheritdoc/>
|
|||
public abstract string description { get; } |
|||
|
|||
/// <summary>
|
|||
/// Perform preprocessing operations on an asset loaded from an <see cref="AssetSource{T}"/>.
|
|||
/// </summary>
|
|||
/// <param name="asset">The asset to preprocess</param>
|
|||
public abstract void Preprocess(T asset); |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 3fce529b432e45f45bee917a2c4205b6 |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using System; |
|||
using UnityEngine.Perception.Randomization.Samplers; |
|||
|
|||
namespace UnityEngine.Perception.Randomization |
|||
{ |
|||
/// <summary>
|
|||
/// AssetSources are used to load assets from a generically within a <see cref="Randomizers.Randomizer"/>
|
|||
/// </summary>
|
|||
/// <typeparam name="T">The type of asset to load</typeparam>
|
|||
[Serializable] |
|||
public sealed class AssetSource<T> where T : Object |
|||
{ |
|||
[SerializeReference] IAssetRoleBase m_AssetRoleBase; |
|||
|
|||
/// <summary>
|
|||
/// The location to load assets from
|
|||
/// </summary>
|
|||
[SerializeReference] public AssetSourceLocation assetSourceLocation = new LocalAssetSourceLocation(); |
|||
|
|||
bool m_Initialized; |
|||
UniformSampler m_Sampler = new UniformSampler(); |
|||
|
|||
/// <summary>
|
|||
/// The asset role used to preprocess assets from this source
|
|||
/// </summary>
|
|||
public AssetRole<T> assetRole |
|||
{ |
|||
get => (AssetRole<T>)m_AssetRoleBase; |
|||
set => m_AssetRoleBase = value; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// The number of assets available within this asset source
|
|||
/// </summary>
|
|||
public int count |
|||
{ |
|||
get |
|||
{ |
|||
CheckIfInitialized(); |
|||
return assetSourceLocation.count; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Execute setup steps for this AssetSource. It is often unnecessary to call this API directly since all other
|
|||
/// relevant APIs in this class will Initialize() this AssetSource if it hasn't been already.
|
|||
/// </summary>
|
|||
public void Initialize() |
|||
{ |
|||
if (!m_Initialized) |
|||
{ |
|||
assetSourceLocation.Initialize(assetRole); |
|||
m_Initialized = true; |
|||
} |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Returns the unprocessed asset loaded from the provided index
|
|||
/// </summary>
|
|||
/// <param name="index">The index of the asset to load</param>
|
|||
/// <returns>The asset loaded at the provided index</returns>
|
|||
public T LoadRawAsset(int index) |
|||
{ |
|||
CheckIfInitialized(); |
|||
return assetSourceLocation.LoadAsset<T>(index); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Returns all unprocessed assets that can be loaded from this AssetSource
|
|||
/// </summary>
|
|||
/// <returns>All assets that can be loaded from this AssetSource</returns>
|
|||
public T[] LoadAllRawAssets() |
|||
{ |
|||
CheckIfInitialized(); |
|||
var array = new T[count]; |
|||
for (var i = 0; i < count; i++) |
|||
array[i] = LoadRawAsset(i); |
|||
return array; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Creates an instance of the asset loaded from the provided index and preprocesses it using the asset role
|
|||
/// assigned to this asset source
|
|||
/// </summary>
|
|||
/// <param name="index">The index of the asset to load</param>
|
|||
/// <returns>The instantiated instance</returns>
|
|||
public T CreateProcessedInstance(int index) |
|||
{ |
|||
CheckIfInitialized(); |
|||
return CreateProcessedInstance(LoadRawAsset(index)); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Instantiates, preprocesses, and returns all assets that can be loaded from this asset source
|
|||
/// </summary>
|
|||
/// <returns>Instantiated instances from every loadable asset</returns>
|
|||
public T[] CreateProcessedInstances() |
|||
{ |
|||
CheckIfInitialized(); |
|||
var array = new T[count]; |
|||
for (var i = 0; i < count; i++) |
|||
array[i] = CreateProcessedInstance(i); |
|||
return array; |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Returns a uniformly random sampled asset from this AssetSource
|
|||
/// </summary>
|
|||
/// <returns>The randomly sampled asset</returns>
|
|||
public T SampleAsset() |
|||
{ |
|||
CheckIfInitialized(); |
|||
return count == 0 ? null : assetSourceLocation.LoadAsset<T>((int)(m_Sampler.Sample() * count)); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Instantiates and preprocesses a uniformly random sampled asset from this AssetSource
|
|||
/// </summary>
|
|||
/// <returns>The generated random instance</returns>
|
|||
public T SampleInstance() |
|||
{ |
|||
CheckIfInitialized(); |
|||
return CreateProcessedInstance(SampleAsset()); |
|||
} |
|||
|
|||
/// <summary>
|
|||
/// Unloads all assets that have been loaded from this AssetSource
|
|||
/// </summary>
|
|||
public void ReleaseAssets() |
|||
{ |
|||
CheckIfInitialized(); |
|||
assetSourceLocation.ReleaseAssets(); |
|||
} |
|||
|
|||
void CheckIfInitialized() |
|||
{ |
|||
if (!m_Initialized) |
|||
Initialize(); |
|||
} |
|||
|
|||
T CreateProcessedInstance(T asset) |
|||
{ |
|||
if (asset == null) |
|||
return null; |
|||
|
|||
var instance = Object.Instantiate(asset); |
|||
if (assetRole != null) |
|||
assetRole.Preprocess(instance); |
|||
return instance; |
|||
} |
|||
} |
|||
} |
|
|||
using System; |
|||
using System.Collections.Generic; |
|||
using System.ComponentModel; |
|||
|
|||
namespace UnityEngine.Perception.Randomization |
|||
{ |
|||
/// <summary>
|
|||
/// A basic <see cref="AssetSourceLocation"/> for loading local project assets
|
|||
/// </summary>
|
|||
[Serializable] |
|||
[DisplayName("Assets In Project")] |
|||
public class LocalAssetSourceLocation : AssetSourceLocation |
|||
{ |
|||
/// <summary>
|
|||
/// The list of local assets available from this source
|
|||
/// </summary>
|
|||
public List<Object> assets = new List<Object>(); |
|||
|
|||
/// <inheritdoc/>
|
|||
public override int count => assets.Count; |
|||
|
|||
/// <inheritdoc/>
|
|||
public override void Initialize<T>(AssetRole<T> assetRole) { } |
|||
|
|||
/// <inheritdoc/>
|
|||
public override void ReleaseAssets() { } |
|||
|
|||
/// <inheritdoc/>
|
|||
public override T LoadAsset<T>(int index) |
|||
{ |
|||
return (T)assets[index]; |
|||
} |
|||
} |
|||
} |
|
|||
using System; |
|||
|
|||
namespace UnityEngine.Perception.Randomization |
|||
{ |
|||
/// <summary>
|
|||
/// Used to annotate an AssetSourceLocation with description notes within the inspector UI
|
|||
/// </summary>
|
|||
public class AssetSourceEditorDescriptionAttribute : Attribute |
|||
{ |
|||
/// <summary>
|
|||
/// The text notes to display in the AssetSourceLocation's UI.
|
|||
/// </summary>
|
|||
public string notes; |
|||
|
|||
/// <summary>
|
|||
/// Constructs a new AssetSourceLocationNotes attribute
|
|||
/// </summary>
|
|||
/// <param name="notes">The text notes to display in the inspector</param>
|
|||
public AssetSourceEditorDescriptionAttribute(string notes) |
|||
{ |
|||
this.notes = notes; |
|||
} |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: 2aa6aeb2e6318114fb5ac0829edcac00 |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
fileFormatVersion: 2 |
|||
guid: 7c335d3150918dc49be9cf2eddb144d2 |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using UnityEngine; |
|||
|
|||
namespace UnityEngine.Perception.Randomization |
|||
{ |
|||
/// <summary>
|
|||
/// The base asset role class. Derive from <see cref="AssetRole{T}"/> instead to create a new asset role.
|
|||
/// </summary>
|
|||
interface IAssetRoleBase |
|||
{ |
|||
/// <summary>
|
|||
/// The string label uniquely associated with this asset role
|
|||
/// </summary>
|
|||
string label { get; } |
|||
|
|||
/// <summary>
|
|||
/// A description for this asset role
|
|||
/// </summary>
|
|||
string description { get; } |
|||
} |
|||
} |
|
|||
fileFormatVersion: 2 |
|||
guid: c7b5bdabb856bb5469fd4033fb6bda01 |
|||
MonoImporter: |
|||
externalObjects: {} |
|||
serializedVersion: 2 |
|||
defaultReferences: [] |
|||
executionOrder: 0 |
|||
icon: {instanceID: 0} |
|||
userData: |
|||
assetBundleName: |
|||
assetBundleVariant: |
|
|||
using NUnit.Framework; |
|||
using UnityEngine; |
|||
using UnityEngine.Perception.Randomization; |
|||
using UnityEngine.Perception.Randomization.Randomizers.SampleRandomizers.Tags; |
|||
|
|||
namespace RandomizationTests.AssetSourceTests |
|||
{ |
|||
[TestFixture] |
|||
public class LocalAssetSourceTests |
|||
{ |
|||
GameObject m_TestObject; |
|||
TestBehaviour m_Behaviour; |
|||
|
|||
class TestAssetRole : AssetRole<GameObject> |
|||
{ |
|||
public override string label => "test"; |
|||
public override string description => ""; |
|||
|
|||
public override void Preprocess(GameObject asset) |
|||
{ |
|||
asset.AddComponent<RotationRandomizerTag>(); |
|||
} |
|||
} |
|||
|
|||
class TestBehaviour : MonoBehaviour |
|||
{ |
|||
public AssetSource<GameObject> gameObjectSource = new AssetSource<GameObject> |
|||
{ |
|||
assetRole = new TestAssetRole(), |
|||
assetSourceLocation = new LocalAssetSourceLocation() |
|||
}; |
|||
} |
|||
|
|||
[SetUp] |
|||
public void Setup() |
|||
{ |
|||
m_TestObject = new GameObject(); |
|||
m_Behaviour = m_TestObject.AddComponent<TestBehaviour>(); |
|||
} |
|||
|
|||
[TearDown] |
|||
public void TearDown() |
|||
{ |
|||
Object.DestroyImmediate(m_TestObject); |
|||
} |
|||
|
|||
[Test] |
|||
public void GetZeroCountWithoutThrowingException() |
|||
{ |
|||
Assert.DoesNotThrow(() => |
|||
{ |
|||
var count = m_Behaviour.gameObjectSource.count; |
|||
}); |
|||
} |
|||
|
|||
[Test] |
|||
public void SampleFromEmptySourceReturnsNull() |
|||
{ |
|||
Assert.IsNull(m_Behaviour.gameObjectSource.SampleAsset()); |
|||
Assert.IsNull(m_Behaviour.gameObjectSource.SampleInstance()); |
|||
} |
|||
} |
|||
} |
部分文件因为文件数量过多而无法显示
撰写
预览
正在加载...
取消
保存
Reference in new issue