浏览代码

Merge branch 'randomizers' into tutorial_sample_project

/main
Mohsen Kamalzadeh 4 年前
当前提交
5efef524
共有 6 个文件被更改,包括 67 次插入33 次删除
  1. 38
      com.unity.perception/Editor/Randomization/Editors/RunInUSimWindow.cs
  2. 23
      com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTagManager.cs
  3. 3
      com.unity.perception/Runtime/Randomization/Randomizers/SampleRandomizers/Randomizers/BackgroundObjectPlacementRandomizer.cs
  4. 6
      com.unity.perception/Runtime/Randomization/Randomizers/SampleRandomizers/Randomizers/SunAngleRandomizer.cs
  5. 25
      com.unity.perception/Runtime/Randomization/Randomizers/SampleRandomizers/Utilities/PoissonDiskSampling.cs
  6. 5
      com.unity.perception/Tests/Runtime/Randomization/RandomizerTests/RandomizerTagTests.cs

38
com.unity.perception/Editor/Randomization/Editors/RunInUSimWindow.cs


using Unity.Simulation.Client;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
using ZipUtility;

{
string m_BuildDirectory;
string m_BuildZipPath;
SysParamDefinition m_SysParam;

void OnEnable()
{
m_BuildDirectory = Application.dataPath + "/../Build";
Project.Activate();
Project.clientReadyStateChanged += CreateEstablishingConnectionUI;
CreateEstablishingConnectionUI(Project.projectIdState);

/// <summary>
/// Enables a visual element to remember values between editor sessions
/// </summary>
/// <param name="element">The visual element to enable view data for</param>
static void SetViewDataKey(VisualElement element)
{
element.viewDataKey = $"RunInUSim_{element.name}";

m_MainSceneField = root.Q<ObjectField>("main-scene");
m_MainSceneField.objectType = typeof(SceneAsset);
if (SceneManager.sceneCount > 0)
{
var path = SceneManager.GetSceneAt(0).path;
var asset = AssetDatabase.LoadAssetAtPath<SceneAsset>(path);
m_MainSceneField.value = asset;
}
m_ScenarioField.value = FindObjectOfType<ScenarioBase>();
sysParamMenu.menu.AppendAction(definition.description, action => m_SysParam = definition);
{
sysParamMenu.menu.AppendAction(
definition.description,
action =>
{
m_SysParam = definition;
sysParamMenu.text = definition.description;
});
}
sysParamMenu.text = sysParamDefinitions[0].description;
m_SysParam = sysParamDefinitions[0];

void CreateLinuxBuildAndZip()
{
// Create build directory
var pathToProjectBuild = Application.dataPath + "/../" + "Build/";
if (!Directory.Exists(pathToProjectBuild + m_RunNameField.value))
Directory.CreateDirectory(pathToProjectBuild + m_RunNameField.value);
pathToProjectBuild = pathToProjectBuild + m_RunNameField.value + "/";
var projectBuildDirectory = $"{m_BuildDirectory}/{m_RunNameField.value}";
if (!Directory.Exists(projectBuildDirectory))
Directory.CreateDirectory(projectBuildDirectory);
// Create Linux build
Debug.Log("Creating Linux build...");

locationPathName = Path.Combine(pathToProjectBuild, m_RunNameField.value + ".x86_64"),
locationPathName = Path.Combine(projectBuildDirectory, $"{m_RunNameField.value}.x86_64"),
target = BuildTarget.StandaloneLinux64
};
var report = BuildPipeline.BuildPlayer(buildPlayerOptions);

// Zip the build
Debug.Log("Starting to zip...");
var buildFolder = Application.dataPath + "/../" + "Build/" + m_RunNameField.value;
Zip.DirectoryContents(buildFolder, m_RunNameField.value);
m_BuildZipPath = buildFolder + ".zip";
Zip.DirectoryContents(projectBuildDirectory, m_RunNameField.value);
m_BuildZipPath = projectBuildDirectory + ".zip";
Debug.Log("Created build zip");
}

23
com.unity.perception/Runtime/Randomization/Randomizers/RandomizerTagManager.cs


Dictionary<Type, HashSet<GameObject>> m_TagMap = new Dictionary<Type, HashSet<GameObject>>();
/// <summary>
/// Returns a list of all GameObjects in the scene that have a RandomizerTag of the given type
/// Enumerates all GameObjects in the scene that have a RandomizerTag of the given type
/// <returns>A list of GameObjects with the given RandomizerTag</returns>
public GameObject[] Query<T>() where T : RandomizerTag
/// <returns>GameObjects with the given RandomizerTag</returns>
public IEnumerable<GameObject> Query<T>() where T : RandomizerTag
return m_TagMap.ContainsKey(type) ? m_TagMap[type].ToArray() : new GameObject[0];
if (!m_TagMap.ContainsKey(type))
yield break;
foreach (var taggedObject in m_TagMap[type])
yield return taggedObject;
if (m_TagMap.ContainsKey(tagType))
{
m_TagMap[tagType].Add(obj);
}
else
{
var newSet = new HashSet<GameObject> { obj };
m_TagMap.Add(tagType, newSet);
}
if (!m_TagMap.ContainsKey(tagType))
m_TagMap[tagType] = new HashSet<GameObject>();
m_TagMap[tagType].Add(obj);
}
internal void RemoveTag(Type tagType, GameObject obj)

3
com.unity.perception/Runtime/Randomization/Randomizers/SampleRandomizers/Randomizers/BackgroundObjectPlacementRandomizer.cs


/// </summary>
protected override void OnIterationStart()
{
if (m_SpawnedObjects == null)
m_SpawnedObjects = new List<GameObject>();
m_SpawnedObjects ??= new List<GameObject>();
for (var i = 0; i < layerCount; i++)
{

6
com.unity.perception/Runtime/Randomization/Randomizers/SampleRandomizers/Randomizers/SunAngleRandomizer.cs


public FloatParameter hour = new FloatParameter { value = new UniformSampler(0, 24)};
/// <summary>
/// The time of the year (0 being Jan 1st and 1 being December 31st)
/// The day of the year (0 being Jan 1st and 364 being December 31st)
public FloatParameter timeOfYear = new FloatParameter { value = new UniformSampler(0, 1)};
public FloatParameter dayOfTheYear = new FloatParameter { value = new UniformSampler(0, 365)};
/// <summary>
/// The earth's latitude (-90 is the south pole, 0 is the equator, and +90 is the north pole)

foreach (var lightObject in lightObjects)
{
var earthSpin = Quaternion.AngleAxis((hour.Sample() + 12f) / 24f * 360f, Vector3.down);
var timeOfYearRads = timeOfYear.Sample() * Mathf.PI * 2f;
var timeOfYearRads = dayOfTheYear.Sample() / 365f * Mathf.PI * 2f;
var earthTilt = Quaternion.Euler(Mathf.Cos(timeOfYearRads) * 23.5f, 0, Mathf.Sin(timeOfYearRads) * 23.5f);
var earthLat = Quaternion.AngleAxis(latitude.Sample(), Vector3.right);
var lightRotation = earthTilt * earthSpin * earthLat;

25
com.unity.perception/Runtime/Randomization/Randomizers/SampleRandomizers/Utilities/PoissonDiskSampling.cs


{
const int k_DefaultSamplingResolution = 30;
// Algorithm sourced from Robert Bridson's paper "Fast Poisson Disk Sampling in Arbitrary Dimensions"
// https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf
/// <summary>
/// Returns a list of poisson disc sampled points for a given area and density
/// </summary>

}
}
// Algorithm sourced from Robert Bridson's paper "Fast Poisson Disk Sampling in Arbitrary Dimensions"
// https://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf
/// <summary>
/// Returns a list of poisson disc sampled points for a given area and density
/// </summary>
/// <param name="width">Width of the sampling area</param>
/// <param name="height">Height of the sampling area</param>
/// <param name="minimumRadius">The minimum distance required between each sampled point</param>
/// <param name="seed">The random seed used to initialize the algorithm state</param>
/// <param name="samplingResolution">The number of potential points sampled around every valid point</param>
/// <param name="allocator">The allocator type of the generated native container</param>
/// <returns>The list of generated poisson points</returns>
static NativeList<float2> Sample(
float width,
float height,

{
var samples = new NativeList<float2>(allocator);
// Calculate occupancy grid dimensions
var random = new Unity.Mathematics.Random(seed);
var cellSize = minimumRadius / math.sqrt(2);
var rows = Mathf.FloorToInt(height / cellSize);

return samples;
// Initialize a few constants
var samplingArc = (math.PI * 2) / samplingResolution;
var samplingArc = math.PI * 2 / samplingResolution;
// Initialize a hash array that maps a sample's grid position to it's index
// This list will track all points that may still have space around them for generating new points
// Randomly place a seed point in a central location within the generation space to kick off the algorithm
var firstPoint = new float2(
random.NextFloat(0.4f, 0.6f) * width,
random.NextFloat(0.4f, 0.6f) * height);

var length = random.NextFloat(minimumRadius, minimumRadius * 2);
var angle = samplingArc * i + random.NextFloat(-halfSamplingArc, halfSamplingArc);
// Generate a new point within the circular placement region around the active point
var newPoint = activePoint + new float2(
math.cos(angle) * length,
math.sin(angle) * length);

if (row < 0 || row >= rows || col < 0 || col >= cols)
continue;
// Iterate over the 8 surrounding grid locations to check if the newly generated point is too close
// to an existing point
var tooCloseToAnotherPoint = false;
for (var x = -2; x <= 2; x++)
{

if (tooCloseToAnotherPoint)
continue;
// If the new point is accepted, add it to the occupancy grid and the list of generated samples
nextPointFound = true;
activePoints.Add(newPoint);
samples.Add(newPoint);

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


using NUnit.Framework;
using System.Linq;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.Experimental.Perception.Randomization.Scenarios;
using Assert = Unity.Assertions.Assert;

for (var i = 0; i < copyCount - 1; i++)
Object.Instantiate(gameObject);
var queriedObjects = m_Scenario.tagManager.Query<ExampleTag>();
var queriedObjects = m_Scenario.tagManager.Query<ExampleTag>().ToArray();
Assert.AreEqual(queriedObjects.Length, copyCount);
}
}
正在加载...
取消
保存