浏览代码

removed entities dependency

/main
sleal-unity 4 年前
当前提交
fec66d94
共有 21 个文件被更改,包括 212 次插入288 次删除
  1. 9
      com.unity.perception/Runtime/GroundTruth/GroundTruthCrossPipelinePass.cs
  2. 11
      com.unity.perception/Runtime/GroundTruth/GroundTruthPass.cs
  3. 20
      com.unity.perception/Runtime/GroundTruth/Labelers/BoundingBox3DLabeler.cs
  4. 18
      com.unity.perception/Runtime/GroundTruth/Labelers/KeypointLabeler.cs
  5. 17
      com.unity.perception/Runtime/GroundTruth/Labeling/LabelEntryMatchCache.cs
  6. 34
      com.unity.perception/Runtime/GroundTruth/Labeling/Labeling.cs
  7. 1
      com.unity.perception/Runtime/Randomization/Randomizers/Randomizer.cs
  8. 1
      com.unity.perception/Runtime/Randomization/Randomizers/RandomizerExamples/Utilities/PoissonDiskSampling.cs
  9. 1
      com.unity.perception/Tests/Runtime/GroundTruthTests/LabelEntryMatchCacheTests.cs
  10. 1
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTagTests.cs
  11. 14
      com.unity.perception/package.json
  12. 141
      com.unity.perception/Runtime/GroundTruth/LabeledObjectsManager.cs
  13. 3
      com.unity.perception/Runtime/GroundTruth/LabeledObjectsManager.cs.meta
  14. 24
      com.unity.perception/Runtime/GroundTruth/PerceptionUpdater.cs
  15. 3
      com.unity.perception/Runtime/GroundTruth/PerceptionUpdater.cs.meta
  16. 15
      com.unity.perception/Runtime/GroundTruth/GroundTruthInfo.cs
  17. 11
      com.unity.perception/Runtime/GroundTruth/GroundTruthInfo.cs.meta
  18. 11
      com.unity.perception/Runtime/GroundTruth/GroundTruthLabelSetupSystem.cs.meta
  19. 13
      com.unity.perception/Runtime/GroundTruth/SimulationManagementComponentSystem.cs
  20. 11
      com.unity.perception/Runtime/GroundTruth/SimulationManagementComponentSystem.cs.meta
  21. 141
      com.unity.perception/Runtime/GroundTruth/GroundTruthLabelSetupSystem.cs

9
com.unity.perception/Runtime/GroundTruth/GroundTruthCrossPipelinePass.cs


using System;
using Unity.Entities;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;

internal abstract class GroundTruthCrossPipelinePass : IGroundTruthGenerator
abstract class GroundTruthCrossPipelinePass : IGroundTruthGenerator
{
public Camera targetCamera;

{
if (!m_IsActivated)
{
var labelSetupSystem = World.DefaultGameObjectInjectionWorld?.GetExistingSystem<GroundTruthLabelSetupSystem>();
labelSetupSystem?.Activate(this);
LabeledObjectsManager.singleton.Activate(this);
m_IsActivated = true;
}
}

var labelSetupSystem = World.DefaultGameObjectInjectionWorld?.GetExistingSystem<GroundTruthLabelSetupSystem>();
labelSetupSystem?.Deactivate(this);
LabeledObjectsManager.singleton.Deactivate(this);
}
protected RendererListDesc CreateRendererListDesc(Camera camera, CullingResults cullingResult, string overrideMaterialPassName, int overrideMaterialPassIndex, Material overrideMaterial, LayerMask layerMask /*, PerObjectData perObjectData*/)

11
com.unity.perception/Runtime/GroundTruth/GroundTruthPass.cs


#if HDRP_PRESENT
using System;
using Unity.Entities;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;

// If we are forced to activate here we will get zeroes in the first frame.
EnsureActivated();
this.targetColorBuffer = TargetBuffer.Custom;
this.targetDepthBuffer = TargetBuffer.Custom;
targetColorBuffer = TargetBuffer.Custom;
targetDepthBuffer = TargetBuffer.Custom;
}
protected sealed override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult)

{
if (!m_IsActivated)
{
var labelSetupSystem = World.DefaultGameObjectInjectionWorld?.GetExistingSystem<GroundTruthLabelSetupSystem>();
labelSetupSystem?.Activate(this);
LabeledObjectsManager.singleton.Activate(this);
m_IsActivated = true;
}
}

var labelSetupSystem = World.DefaultGameObjectInjectionWorld?.GetExistingSystem<GroundTruthLabelSetupSystem>();
labelSetupSystem?.Deactivate(this);
LabeledObjectsManager.singleton.Deactivate(this);
}
}
}

20
com.unity.perception/Runtime/GroundTruth/Labelers/BoundingBox3DLabeler.cs


using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Unity.Collections;
using Unity.Entities;
using Unity.Profiling;
namespace UnityEngine.Perception.GroundTruth

/// </summary>
public class BoundingBox3DLabeler : CameraLabeler
{
EntityQuery m_EntityQuery;
///<inheritdoc/>
public override string description
{

/// <param name="labelConfig">The label config for resolving the label for each object.</param>
public BoundingBox3DLabeler(IdLabelConfig labelConfig)
{
this.idLabelConfig = labelConfig;
idLabelConfig = labelConfig;
}
/// <inheritdoc/>

"Bounding box for each labeled object visible to the sensor", id: new Guid(annotationId));
perceptionCamera.RenderedObjectInfosCalculated += OnRenderObjectInfosCalculated;
m_EntityQuery = World.DefaultGameObjectInjectionWorld.EntityManager.CreateEntityQuery(typeof(Labeling), typeof(GroundTruthInfo));
m_AsyncAnnotations = new Dictionary<int, AsyncAnnotation>();
m_BoundingBoxValues = new Dictionary<int, Dictionary<uint, BoxData>>();

m_AsyncAnnotations[m_CurrentFrame] = perceptionCamera.SensorHandle.ReportAnnotationAsync(m_AnnotationDefinition);
var entities = m_EntityQuery.ToEntityArray(Allocator.TempJob);
var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
foreach (var entity in entities)
{
ProcessEntity(entityManager.GetComponentObject<Labeling>(entity));
}
entities.Dispose();
foreach (var label in LabeledObjectsManager.singleton.registeredLabels)
ProcessLabel(label);
}
void OnRenderObjectInfosCalculated(int frameCount, NativeArray<RenderedObjectInfo> renderedObjectInfos)

}
}
void ProcessEntity(Labeling labeledEntity)
void ProcessLabel(Labeling labeledEntity)
{
using (s_BoundingBoxCallback.Auto())
{

18
com.unity.perception/Runtime/GroundTruth/Labelers/KeypointLabeler.cs


using System.Collections.Generic;
using System.Linq;
using Unity.Collections;
using Unity.Entities;
using UnityEngine.Serialization;
namespace UnityEngine.Perception.GroundTruth
{

// ReSharper restore MemberCanBePrivate.Global
AnnotationDefinition m_AnnotationDefinition;
EntityQuery m_EntityQuery;
Texture2D m_MissingTexture;
Dictionary<int, (AsyncAnnotation annotation, Dictionary<uint, KeypointEntry> keypoints)> m_AsyncAnnotations;

m_AnnotationDefinition = DatasetCapture.RegisterAnnotationDefinition("keypoints", new []{TemplateToJson(activeTemplate)},
"pixel coordinates of keypoints in a model, along with skeletal connectivity data", id: new Guid(annotationId));
m_EntityQuery = World.DefaultGameObjectInjectionWorld.EntityManager.CreateEntityQuery(typeof(Labeling), typeof(GroundTruthInfo));
// Texture to use in case the template does not contain a texture for the joints or the skeletal connections
m_MissingTexture = new Texture2D(1, 1);

m_AsyncAnnotations[m_CurrentFrame] = (annotation, keypoints);
var entities = m_EntityQuery.ToEntityArray(Allocator.TempJob);
var entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
foreach (var entity in entities)
{
ProcessEntity(entityManager.GetComponentObject<Labeling>(entity));
}
entities.Dispose();
foreach (var label in LabeledObjectsManager.singleton.registeredLabels)
ProcessLabel(label);
}
// ReSharper disable InconsistentNaming

return false;
}
void ProcessEntity(Labeling labeledEntity)
void ProcessLabel(Labeling labeledEntity)
{
// Cache out the data of a labeled game object the first time we see it, this will
// save performance each frame. Also checks to see if a labeled game object can be annotated.

17
com.unity.perception/Runtime/GroundTruth/Labeling/LabelEntryMatchCache.cs


using System;
using Unity.Collections;
using Unity.Entities;
namespace UnityEngine.Perception.GroundTruth
{

const int k_StartingObjectCount = 1 << 8;
NativeList<ushort> m_InstanceIdToLabelEntryIndexLookup;
IdLabelConfig m_IdLabelConfig;
ushort m_DefaultValue = ushort.MaxValue;
const ushort k_DefaultValue = ushort.MaxValue;
World.DefaultGameObjectInjectionWorld.GetOrCreateSystem<GroundTruthLabelSetupSystem>().Activate(this);
LabeledObjectsManager.singleton.Activate(this);
}
public bool TryGetLabelEntryFromInstanceId(uint instanceId, out IdLabelEntry labelEntry, out int index)

if (m_InstanceIdToLabelEntryIndexLookup.Length <= instanceId || m_InstanceIdToLabelEntryIndexLookup[(int)instanceId] == m_DefaultValue)
if (m_InstanceIdToLabelEntryIndexLookup.Length <= instanceId || m_InstanceIdToLabelEntryIndexLookup[(int)instanceId] == k_DefaultValue)
return false;
index = m_InstanceIdToLabelEntryIndexLookup[(int)instanceId];

{
if (m_IdLabelConfig.TryGetMatchingConfigurationEntry(labeling, out _, out var index))
{
Debug.Assert(index < m_DefaultValue, "Too many entries in the label config");
Debug.Assert(index < k_DefaultValue, "Too many entries in the label config");
for (int i = oldLength; i < instanceId; i++)
m_InstanceIdToLabelEntryIndexLookup[i] = m_DefaultValue;
for (var i = oldLength; i < instanceId; i++)
m_InstanceIdToLabelEntryIndexLookup[i] = k_DefaultValue;
m_InstanceIdToLabelEntryIndexLookup[(int)instanceId] = m_DefaultValue;
m_InstanceIdToLabelEntryIndexLookup[(int)instanceId] = k_DefaultValue;
World.DefaultGameObjectInjectionWorld?.GetExistingSystem<GroundTruthLabelSetupSystem>()?.Deactivate(this);
LabeledObjectsManager.singleton.Deactivate(this);
m_InstanceIdToLabelEntryIndexLookup.Dispose();
}
}

34
com.unity.perception/Runtime/GroundTruth/Labeling/Labeling.cs


using System.Collections.Generic;
using Unity.Entities;
using UnityEditor;
using UnityEngine.Serialization;

[AddComponentMenu("Perception/Labeling/Labeling")]
public class Labeling : MonoBehaviour
{
static LabeledObjectsManager labeledObjectManager => LabeledObjectsManager.singleton;
[FormerlySerializedAs("classes")] public List<string> labels = new List<string>();
// /// <summary>
// /// A list for backing up the asset's manually added labels, so that if the user switches to auto labeling and back, the previously added labels can be revived
// /// </summary>
// public List<string> manualLabelsBackup = new List<string>();
[FormerlySerializedAs("classes")]
public List<string> labels = new List<string>();
/// <summary>
/// The specific subtype of AssetLabelingScheme that this component is using, if useAutoLabeling is enabled.

/// </summary>
public uint instanceId { get; private set; }
Entity m_Entity;
internal void SetInstanceId(uint instanceId)
{
this.instanceId = instanceId;
}
m_Entity = World.DefaultGameObjectInjectionWorld.EntityManager.CreateEntity();
World.DefaultGameObjectInjectionWorld.EntityManager.AddComponentObject(m_Entity, this);
labeledObjectManager.Register(this);
if (World.DefaultGameObjectInjectionWorld != null)
World.DefaultGameObjectInjectionWorld.EntityManager.DestroyEntity(m_Entity);
labeledObjectManager.Unregister(this);
}
void Reset()

EditorUtility.SetDirty(gameObject);
#endif
}
/// <summary>
/// Refresh ground truth generation for the labeling of the attached GameObject. This is necessary when the

{
World.DefaultGameObjectInjectionWorld.GetOrCreateSystem<GroundTruthLabelSetupSystem>()
.RefreshLabeling(m_Entity);
labeledObjectManager.RefreshLabeling(this);
}
internal void SetInstanceId(uint id)
{
instanceId = id;
}
}
}

1
com.unity.perception/Runtime/Randomization/Randomizers/Randomizer.cs


using System;
using System.Collections.Generic;
using Unity.Entities;
using UnityEngine.Perception.Randomization.Parameters;
using UnityEngine.Perception.Randomization.Scenarios;

1
com.unity.perception/Runtime/Randomization/Randomizers/RandomizerExamples/Utilities/PoissonDiskSampling.cs


using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Perception.Randomization.Randomizers.Utilities
{

1
com.unity.perception/Tests/Runtime/GroundTruthTests/LabelEntryMatchCacheTests.cs


using System.Collections;
using NUnit.Framework;
using Unity.Entities;
using UnityEngine;
using UnityEngine.Perception.GroundTruth;
using UnityEngine.TestTools;

1
com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTagTests.cs


using NUnit.Framework;
using UnityEngine;
using UnityEngine.Perception.Randomization.Randomizers;
using Assert = Unity.Assertions.Assert;
namespace RandomizationTests.RandomizerTests
{

14
com.unity.perception/package.json


{
"dependencies": {
"com.unity.burst": "1.4.6",
"com.unity.collections": "0.15.0-preview.21",
"com.unity.burst": "1.3.9",
"com.unity.entities": "0.8.0-preview.8",
"com.unity.simulation.capture": "0.0.10-preview.19",
"com.unity.simulation.capture": "0.0.10-preview.19",
"com.unity.simulation.core": "0.0.10-preview.22"
},
"description": "Tools for generating large-scale data sets for perception-based machine learning training and validation",

"version": "0.7.0-preview.2",
"samples":[
"samples": [
"path" : "Samples~/Tutorial Files"
"path": "Samples~/Tutorial Files"
"path" : "Samples~/Human Pose Labeling and Randomization"
"path": "Samples~/Human Pose Labeling and Randomization"
}
}

141
com.unity.perception/Runtime/GroundTruth/LabeledObjectsManager.cs


using System.Collections.Generic;
using UnityEngine.Perception.Randomization.Randomizers;
namespace UnityEngine.Perception.GroundTruth
{
class LabeledObjectsManager
{
public static LabeledObjectsManager singleton { get; } = new LabeledObjectsManager();
const uint k_StartingIndex = 1;
uint m_CurrentObjectIndex = k_StartingIndex;
List<IGroundTruthGenerator> m_ActiveGenerators = new List<IGroundTruthGenerator>();
LinkedHashSet<Labeling> m_UnregisteredLabels = new LinkedHashSet<Labeling>();
LinkedHashSet<Labeling> m_RegisteredLabels = new LinkedHashSet<Labeling>();
public IEnumerable<Labeling> registeredLabels => m_RegisteredLabels;
public void Update()
{
if (m_RegisteredLabels.Count == 0)
m_CurrentObjectIndex = k_StartingIndex;
foreach (var unregisteredLabel in m_UnregisteredLabels)
{
if (m_RegisteredLabels.Contains(unregisteredLabel))
continue;
var instanceId = m_CurrentObjectIndex++;
InitGameObjectRecursive(
unregisteredLabel.gameObject,
new MaterialPropertyBlock(),
unregisteredLabel,
instanceId);
unregisteredLabel.SetInstanceId(instanceId);
m_RegisteredLabels.Add(unregisteredLabel);
}
m_UnregisteredLabels.Clear();
}
/// <summary>
/// Activates the given <see cref="IGroundTruthGenerator"/>. <see cref="IGroundTruthGenerator.SetupMaterialProperties"/>
/// will be called for all <see cref="MeshRenderer"/> instances under each object containing a <see cref="Labeling"/> component.
/// </summary>
/// <param name="generator">The generator to register</param>
public void Activate(IGroundTruthGenerator generator)
{
m_ActiveGenerators.Add(generator);
foreach (var label in m_RegisteredLabels)
InitGameObjectRecursive(label.gameObject, new MaterialPropertyBlock(), label, label.instanceId);
}
/// <summary>
/// Deactivates the given <see cref="IGroundTruthGenerator"/>. It will no longer receive calls when <see cref="Labeling"/> instances are created.
/// </summary>
/// <param name="generator">The generator to deactivate</param>
/// <returns>True if the <see cref="generator"/> was successfully removed. False if <see cref="generator"/> was not active.</returns>
public bool Deactivate(IGroundTruthGenerator generator)
{
return m_ActiveGenerators.Remove(generator);
}
/// <summary>
/// Registers a labeling component
/// </summary>
/// <param name="labeledObject">the component to register</param>
public void Register(Labeling labeledObject)
{
m_UnregisteredLabels.Add(labeledObject);
}
/// <summary>
/// Unregisters a labeling component
/// </summary>
/// <param name="labeledObject">the component to unregister</param>
public void Unregister(Labeling labeledObject)
{
m_UnregisteredLabels.Remove(labeledObject);
m_RegisteredLabels.Remove(labeledObject);
}
/// <summary>
/// Refresh ground truth generation for the labeling of a particular GameObject. This is necessary when the
/// list of labels changes or when renderers or materials change on objects in the hierarchy.
/// </summary>
/// <param name="labeledObject">the component to refresh</param>
public void RefreshLabeling(Labeling labeledObject)
{
m_RegisteredLabels.Remove(labeledObject);
m_UnregisteredLabels.Add(labeledObject);
}
void InitGameObjectRecursive(
GameObject gameObject, MaterialPropertyBlock mpb, Labeling labeling, uint instanceId)
{
var terrain = gameObject.GetComponent<Terrain>();
if (terrain != null)
{
terrain.GetSplatMaterialPropertyBlock(mpb);
foreach (var pass in m_ActiveGenerators)
pass.SetupMaterialProperties(mpb, null, labeling, instanceId);
terrain.SetSplatMaterialPropertyBlock(mpb);
}
var renderer = gameObject.GetComponent<Renderer>();
if (renderer != null)
{
renderer.GetPropertyBlock(mpb);
foreach (var pass in m_ActiveGenerators)
pass.SetupMaterialProperties(mpb, renderer, labeling, instanceId);
renderer.SetPropertyBlock(mpb);
var materialCount = renderer.materials.Length;
for (var i = 0; i < materialCount; i++)
{
renderer.GetPropertyBlock(mpb, i);
//Only apply to individual materials if there is already a MaterialPropertyBlock on it
if (!mpb.isEmpty)
{
foreach (var pass in m_ActiveGenerators)
pass.SetupMaterialProperties(mpb, renderer, labeling, instanceId);
renderer.SetPropertyBlock(mpb, i);
}
}
}
for (var i = 0; i < gameObject.transform.childCount; i++)
{
var child = gameObject.transform.GetChild(i).gameObject;
if (child.GetComponent<Labeling>() != null)
continue;
InitGameObjectRecursive(child, mpb, labeling, instanceId);
}
}
}
}

3
com.unity.perception/Runtime/GroundTruth/LabeledObjectsManager.cs.meta


fileFormatVersion: 2
guid: d138f786c7d94325962fec6fa091edbb
timeCreated: 1614980066

24
com.unity.perception/Runtime/GroundTruth/PerceptionUpdater.cs


namespace UnityEngine.Perception.GroundTruth
{
/// <summary>
/// PerceptionUpdater is automatically spawned when the player starts and is used to coordinate and maintain
/// static perception lifecycle behaviours.
/// </summary>
class PerceptionUpdater : MonoBehaviour
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void Initialize()
{
var updaterObject = new GameObject("PerceptionUpdater");
updaterObject.AddComponent<PerceptionUpdater>();
// updaterObject.hideFlags = HideFlags.HideAndDontSave;
DontDestroyOnLoad(updaterObject);
}
void LateUpdate()
{
LabeledObjectsManager.singleton.Update();
DatasetCapture.SimulationState?.Update();
}
}
}

3
com.unity.perception/Runtime/GroundTruth/PerceptionUpdater.cs.meta


fileFormatVersion: 2
guid: ea65959b27da42a2a364b2ae9a3dc65a
timeCreated: 1614983032

15
com.unity.perception/Runtime/GroundTruth/GroundTruthInfo.cs


using Unity.Entities;
namespace UnityEngine.Perception.GroundTruth
{
/// <summary>
/// Information regarding a Labeling instance. Generated by <see cref="GroundTruthLabelSetupSystem"/>
/// </summary>
public struct GroundTruthInfo : IComponentData
{
/// <summary>
/// The instanceId assigned to the <see cref="Labeling"/>
/// </summary>
public uint instanceId;
}
}

11
com.unity.perception/Runtime/GroundTruth/GroundTruthInfo.cs.meta


fileFormatVersion: 2
guid: 013782ed5fce31d46b9849bbb3cc3da8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
com.unity.perception/Runtime/GroundTruth/GroundTruthLabelSetupSystem.cs.meta


fileFormatVersion: 2
guid: 67ff3a1956c5bb14487beccf559cdd49
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

13
com.unity.perception/Runtime/GroundTruth/SimulationManagementComponentSystem.cs


using System;
using Unity.Entities;
namespace UnityEngine.Perception.GroundTruth
{
class SimulationManagementComponentSystem : ComponentSystem
{
protected override void OnUpdate()
{
DatasetCapture.SimulationState?.Update();
}
}
}

11
com.unity.perception/Runtime/GroundTruth/SimulationManagementComponentSystem.cs.meta


fileFormatVersion: 2
guid: 8dfdda78cfa74c6991ac2d757d8e7019
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

141
com.unity.perception/Runtime/GroundTruth/GroundTruthLabelSetupSystem.cs


using System.Collections.Generic;
using System.Threading;
using Unity.Entities;
namespace UnityEngine.Perception.GroundTruth
{
struct IdAssignmentParameters : IComponentData
{
public uint idStart;
public uint idStep;
}
/// <summary>
/// System which notifies the registered <see cref="IGroundTruthGenerator"/> about <see cref="Labeling"/> additions.
/// </summary>
public class GroundTruthLabelSetupSystem : ComponentSystem
{
List<IGroundTruthGenerator> m_ActiveGenerators = new List<IGroundTruthGenerator>();
ThreadLocal<MaterialPropertyBlock> m_MaterialPropertyBlocks = new ThreadLocal<MaterialPropertyBlock>();
int m_CurrentObjectIndex = -1;
/// <inheritdoc/>
protected override void OnCreate()
{
//These are here to inform the system runner the queries we are interested in. Without these calls, OnUpdate() might not be called
GetEntityQuery(ComponentType.Exclude<GroundTruthInfo>(), ComponentType.ReadOnly<Labeling>());
GetEntityQuery(ComponentType.ReadOnly<GroundTruthInfo>(), ComponentType.ReadOnly<Labeling>());
}
/// <inheritdoc/>
protected override void OnUpdate()
{
var entityQuery = Entities.WithAll<IdAssignmentParameters>().ToEntityQuery();
IdAssignmentParameters idAssignmentParameters;
if (entityQuery.CalculateEntityCount() == 1)
idAssignmentParameters = entityQuery.GetSingleton<IdAssignmentParameters>();
else
idAssignmentParameters = new IdAssignmentParameters {idStart = 1, idStep = 1};
var entityCount = Entities.WithAll<Labeling, GroundTruthInfo>().ToEntityQuery().CalculateEntityCount();
if (entityCount == 0)
m_CurrentObjectIndex = -1;
Entities.WithNone<GroundTruthInfo>().ForEach((Entity e, Labeling labeling) =>
{
var objectIndex = (uint)Interlocked.Increment(ref m_CurrentObjectIndex);
var instanceId = idAssignmentParameters.idStart + objectIndex * idAssignmentParameters.idStep;
var gameObject = labeling.gameObject;
if (!m_MaterialPropertyBlocks.IsValueCreated)
m_MaterialPropertyBlocks.Value = new MaterialPropertyBlock();
InitGameObjectRecursive(gameObject, m_MaterialPropertyBlocks.Value, labeling, instanceId);
EntityManager.AddComponentData(e, new GroundTruthInfo
{
instanceId = instanceId
});
labeling.SetInstanceId(instanceId);
});
}
void InitGameObjectRecursive(GameObject gameObject, MaterialPropertyBlock mpb, Labeling labeling, uint instanceId)
{
var terrain = gameObject.GetComponent<Terrain>();
if (terrain != null)
{
terrain.GetSplatMaterialPropertyBlock(mpb);
foreach (var pass in m_ActiveGenerators)
pass.SetupMaterialProperties(mpb, null, labeling, instanceId);
terrain.SetSplatMaterialPropertyBlock(mpb);
}
var renderer = (Renderer)gameObject.GetComponent<MeshRenderer>();
if (renderer == null)
renderer = gameObject.GetComponent<SkinnedMeshRenderer>();
if (renderer != null)
{
renderer.GetPropertyBlock(mpb);
foreach (var pass in m_ActiveGenerators)
pass.SetupMaterialProperties(mpb, renderer, labeling, instanceId);
renderer.SetPropertyBlock(mpb);
var materialCount = renderer.materials.Length;
for (int i = 0; i < materialCount; i++)
{
renderer.GetPropertyBlock(mpb, i);
//Only apply to individual materials if there is already a MaterialPropertyBlock on it
if (!mpb.isEmpty)
{
foreach (var pass in m_ActiveGenerators)
pass.SetupMaterialProperties(mpb, renderer, labeling, instanceId);
renderer.SetPropertyBlock(mpb, i);
}
}
}
for (var i = 0; i < gameObject.transform.childCount; i++)
{
var child = gameObject.transform.GetChild(i).gameObject;
if (child.GetComponent<Labeling>() != null)
continue;
InitGameObjectRecursive(child, mpb, labeling, instanceId);
}
}
/// <summary>
/// Activates the given <see cref="IGroundTruthGenerator"/>. <see cref="IGroundTruthGenerator.SetupMaterialProperties"/>
/// will be called for all <see cref="MeshRenderer"/> instances under each object containing a <see cref="Labeling"/> component.
/// </summary>
/// <param name="generator">The generator to register</param>
public void Activate(IGroundTruthGenerator generator)
{
m_ActiveGenerators.Add(generator);
Entities.ForEach((Labeling labeling, ref GroundTruthInfo info) =>
{
var gameObject = labeling.gameObject;
InitGameObjectRecursive(gameObject, m_MaterialPropertyBlocks.Value, labeling, info.instanceId);
});
}
/// <summary>
/// Deactivates the given <see cref="IGroundTruthGenerator"/>. It will no longer receive calls when <see cref="Labeling"/> instances are created.
/// </summary>
/// <param name="generator">The generator to deactivate</param>
/// <returns>True if the <see cref="generator"/> was successfully removed. False if <see cref="generator"/> was not active.</returns>
public bool Deactivate(IGroundTruthGenerator generator)
{
return m_ActiveGenerators.Remove(generator);
}
internal void RefreshLabeling(Entity labelingEntity)
{
EntityManager.RemoveComponent<GroundTruthInfo>(labelingEntity);
}
}
}
正在加载...
取消
保存